diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 533c2f9151..6140babecd 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -10,6 +10,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](acorn/acorn.d.ts) [Acorn](https://github.com/marijnh/acorn) by [RReverser](https://github.com/RReverser) * [:link:](rails-actioncable/rails-actioncable.d.ts) [ActionCable](https://github.com/rails/rails/tree/master/actioncable) by [Vincent Zhu](https://github.com/zhu1230) * [:link:](cordova-plugin-ms-adal/cordova-plugin-ms-adal.d.ts) [Active Directory Authentication Library plugin for Apache Cordova](https://github.com/AzureAD/azure-activedirectory-library-for-cordova) by [Kai Walter](https://github.com/KaiWalter) +* [:link:](adal-angular/adal-angular.d.ts) [ADAL.JS](https://github.com/AzureAD/azure-activedirectory-library-for-js) by [mmaitre314](https://github.com/mmaitre314) +* [:link:](adal-angular/adal.d.ts) [ADAL.JS](https://github.com/AzureAD/azure-activedirectory-library-for-js) by [mmaitre314](https://github.com/mmaitre314) * [:link:](add2home/add2home.d.ts) [add2home](http://cubiq.org/add-to-home-screen) by [James Wilkins](http://www.codeplex.com/site/users/view/jamesnw) * [:link:](adm-zip/adm-zip.d.ts) [adm-zip](https://github.com/cthackers/adm-zip) by [John Vilk](https://github.com/jvilk), [Abner Oliveira](https://github.com/abner) * [:link:](ag-grid/ag-grid.d.ts) [ag-grid](http://www.ag-grid.com) by [Niall Crosby](https://github.com/ceolter) @@ -38,6 +40,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](angularjs/angular-component-router.d.ts) [Angular JS 1.5 component router](http://angularjs.org) by [David Reher](http://github.com/davidreher) * [:link:](angular-meteor/angular-meteor.d.ts) [Angular JS Meteor (angular.meteor module)](https://github.com/Urigo/angular-meteor) by [Peter Grman](https://github.com/pgrm) * [:link:](angular-locker/angular-locker.d.ts) [Angular Locker](https://github.com/tymondesigns/angular-locker) by [Niko Kovačič](https://github.com/nkovacic) +* [:link:](angular-media-queries/match-media.d.ts) [Angular matchMedia (angular.matchMedia module)](https://github.com/jacopotarantino/angular-match-media) by [Joao Monteiro](https://github.com/jpmnteiro) * [:link:](angular-material/angular-material.d.ts) [Angular Material (angular.material module)](https://github.com/angular/material) by [Matt Traynham](https://github.com/mtraynham) * [:link:](angular-protractor/angular-protractor.d.ts) [Angular Protractor](https://github.com/angular/protractor) by [Bill Armstrong](https://github.com/BillArmstrong) * [:link:](angular-scenario/angular-scenario.d.ts) [Angular Scenario Testing (ngScenario module)](http://angularjs.org) by [RomanoLindano](https://github.com/RomanoLindano) @@ -55,8 +58,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](angular-environment/angular-environment.d.ts) [angular-environment](https://github.com/juanpablob/angular-environment) by [Matt Wheatley](https://github.com/terrawheat) * [:link:](angular-formly/angular-formly.d.ts) [angular-formly](https://github.com/formly-js/angular-formly) by [Scott Hatcher](https://github.com/scatcher) * [:link:](angular-gettext/angular-gettext.d.ts) [angular-gettext](https://angular-gettext.rocketeer.be) by [Ákos Lukács](https://github.com/AkosLukacs) -* [:link:](angular-google-analytics/angular-google-analytics-service.d.ts) [angular-google-analytics](https://github.com/revolunet/angular-google-analytics) by [Matt Wheatley](https://github.com/terrawheat) * [:link:](angular-google-analytics/angular-google-analytics.d.ts) [angular-google-analytics](https://github.com/revolunet/angular-google-analytics) by [Cyril Schumacher](https://github.com/cyrilschumacher) +* [:link:](angular-google-analytics/angular-google-analytics-service.d.ts) [angular-google-analytics](https://github.com/revolunet/angular-google-analytics) by [Matt Wheatley](https://github.com/terrawheat) * [:link:](angular-hotkeys/angular-hotkeys.d.ts) [angular-hotkeys](https://github.com/chieffancypants/angular-hotkeys) by [Jason Zhao](https://github.com/jlz27), [Stefan Steinhart](https://github.com/reppners) * [:link:](angular-http-auth/angular-http-auth.d.ts) [angular-http-auth](https://github.com/witoldsz/angular-http-auth) by [vvakame](https://github.com/vvakame) * [:link:](angular-httpi/angular-httpi.d.ts) [angular-httpi](https://github.com/bennadel/httpi) by [Andrew Camilleri](https://github.com/Kukks) @@ -68,6 +71,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](angular-modal/angular-modal.d.ts) [angular-modal](https://github.com/btford/angular-modal) by [Paul Lessing](https://github.com/paullessing) * [:link:](angular-notifications/angular-notifications.d.ts) [angular-notifications](https://github.com/DerekRies/angular-notifications) by [Tomasz Ducin](https://github.com/ducin/DefinitelyTyped) * [:link:](angular-notify/angular-notify.d.ts) [angular-notify](https://github.com/cgross/angular-notify) by [Suwato](https://github.com/Suwato/DefinitelyTyped) +* [:link:](angular-permission/angular-permission.d.ts) [angular-permission](https://github.com/Narzerus/angular-permission) by [Voislav Mishevski](https://github.com/vmishevski) * [:link:](angular-scroll/angular-scroll.d.ts) [angular-scroll](https://github.com/oblador/angular-scroll) by [Sam Herrmann](https://github.com/samherrmann) * [:link:](angular-signalr-hub/angular-signalr-hub.d.ts) [angular-signalr-hub](https://github.com/JustMaier/angular-signalr-hub) by [Adam Santaniello](https://github.com/AdamSantaniello) * [:link:](angular-spinner/angular-spinner.d.ts) [angular-spinner.js](https://github.com/urish/angular-spinner) by [Marcin Biegała](https://github.com/Biegal) @@ -86,11 +90,12 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](animation-frame/animation-frame.d.ts) [animation-frame](https://github.com/kof/animation-frame) by [Qinfeng Chen](https://github.com/qinfchen) * [:link:](ansi-styles/ansi-styles.d.ts) [ansi-styles](https://github.com/sindresorhus/ansi-styles) by [bryn austin bellomy](https://github.com/brynbellomy) * [:link:](ansicolors/ansicolors.d.ts) [ansicolors](https://github.com/thlorenz/ansicolors) by [rogierschouten](https://github.com/rogierschouten) -* [:link:](antd/antd.d.ts) [Antd](http://ant.design) by [bang88](https://github.com/bang88) +* [:link:](antd/antd.d.ts) [Antd](http://ant.design) by [bang88](https://github.com/bang88), [Bruce Mitchener](https://github.com/waywardmonkeys) * [:link:](any-db/any-db.d.ts) [any-db](https://github.com/grncdr/node-any-db) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](any-db-transaction/any-db-transaction.d.ts) [any-db-transaction](https://github.com/grncdr/node-any-db-transaction) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](anydb-sql/anydb-sql.d.ts) [anydb-sql](https://github.com/doxout/anydb-sql) by [Gorgi Kosev](https://github.com/spion) * [:link:](anydb-sql-migrations/anydb-sql-migrations.d.ts) [anydb-sql-migrations](https://github.com/spion/anydb-sql-migrations) by [Gorgi Kosev](https://github.com/spion) +* [:link:](cordova-plugin-background-mode/cordova-plugin-background-mode.d.ts) [Apache Background Mode plugin](https://github.com/katzer/cordova-plugin-background-mode) by [Paul Thiel](https://github.com/Lordnoname) * [:link:](cordova/cordova.d.ts) [Apache Cordova](http://cordova.apache.org) by [Microsoft Open Technologies Inc.](http://msopentech.com) * [:link:](cordova-plugin-email-composer/cordova-plugin-email-composer.d.ts) [Apache Cordova Email Composer plugin](https://github.com/katzer/cordova-plugin-email-composer) by [Dave Taylor](http://davetayls.me) * [:link:](api-error-handler/api-error-handler.d.ts) [api-error-handler](https://github.com/expressjs/api-error-handler) by [Tanguy Krotoff](https://github.com/tkrotoff) @@ -244,19 +249,20 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](circular-json/circular-json.d.ts) [circular-json](https://github.com/WebReflection/circular-json) by [Jonathan Pevarnek](https://github.com/jpevarnek) * [:link:](ckeditor/ckeditor.d.ts) [CKEditor](http://ckeditor.com) by [Ondrej Sevcik](https://github.com/ondrejsevcik) * [:link:](classnames/classnames.d.ts) [classnames](https://github.com/JedWatson/classnames) by [Dave Keen](http://www.keendevelopment.ch), [Adi Dahiya](https://github.com/adidahiya), [Jason Killian](https://github.com/JKillian) +* [:link:](cldr.js/cldr.js-event.d.ts) [Cldr.js](https://github.com/rxaviers/cldrjs) by [Raman But-Husaim](https://github.com/RamanBut-Husaim) * [:link:](cldr.js/cldr.js-supplemental.d.ts) [Cldr.js](https://github.com/rxaviers/cldrjs) by [Raman But-Husaim](https://github.com/RamanBut-Husaim) * [:link:](cldr.js/cldr.js.d.ts) [Cldr.js](https://github.com/rxaviers/cldrjs) by [Raman But-Husaim](https://github.com/RamanBut-Husaim), [Grégoire Castre](https://github.com/gcastre) -* [:link:](cldr.js/cldr.js-event.d.ts) [Cldr.js](https://github.com/rxaviers/cldrjs) by [Raman But-Husaim](https://github.com/RamanBut-Husaim) * [:link:](clean-css/clean-css.d.ts) [clean-css](https://github.com/jakubpawlowicz/clean-css) by [Tanguy Krotoff](https://github.com/tkrotoff) +* [:link:](cli/cli.d.ts) [cli](https://www.npmjs.com/package/cli) by [Klaus Reimer](https://github.com/kayahr) * [:link:](cli-color/cli-color.d.ts) [cli-color](https://github.com/medikoo/cli-color) by [Joel Spadin](https://github.com/ChaosinaCan) * [:link:](clipboard/clipboard.d.ts) [clipboard.js](https://github.com/zenorocha/clipboard.js) by [Andrei Kurosh](https://github.com/impworks) * [:link:](clone/clone.d.ts) [clone](https://github.com/pvorb/node-clone) by [Kieran Simpson](https://github.com/kierans/DefinitelyTyped) * [:link:](closure-compiler/closure-compiler.d.ts) [closure-compiler](https://github.com/tim-smart/node-closure) by [Martin Probst](https://github.com/mprobst) +* [:link:](codemirror/codemirror-showhint.d.ts) [CodeMirror](https://github.com/marijnh/CodeMirror) by [jacqt](https://github.com/jacqt), [basarat](https://github.com/basarat) +* [:link:](codemirror/codemirror-matchbrackets.d.ts) [CodeMirror](https://github.com/marijnh/CodeMirror) by [Sixin Li](https://github.com/sixinli) * [:link:](codemirror/codemirror-runmode.d.ts) [CodeMirror](https://github.com/marijnh/CodeMirror) by [Joseph Vaughan](https://github.com/Joev-) * [:link:](codemirror/searchcursor.d.ts) [CodeMirror](https://github.com/marijnh/CodeMirror) by [jacqt](https://github.com/jacqt) * [:link:](codemirror/codemirror.d.ts) [CodeMirror](https://github.com/marijnh/CodeMirror) by [mihailik](https://github.com/mihailik) -* [:link:](codemirror/codemirror-showhint.d.ts) [CodeMirror](https://github.com/marijnh/CodeMirror) by [jacqt](https://github.com/jacqt), [basarat](https://github.com/basarat) -* [:link:](codemirror/codemirror-matchbrackets.d.ts) [CodeMirror](https://github.com/marijnh/CodeMirror) by [Sixin Li](https://github.com/sixinli) * [:link:](coffeeify/coffeeify.d.ts) [coffeeify](https://github.com/jnordberg/coffeeify) by [Qubo](https://github.com/tkQubo) * [:link:](colorbrewer/colorbrewer.d.ts) [colorbrewer](https://github.com/jeanlauliac/colorbrewer) by [Matt Traynham](https://github.com/mtraynham) * [:link:](colors/colors.d.ts) [Colors.js 0.6.0-1](https://github.com/Marak/colors.js) by [Bart van der Schoor](https://github.com/Bartvds) @@ -308,6 +314,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](createjs/createjs.d.ts) [CreateJS](http://www.createjs.com) by [Pedro Ferreira](https://bitbucket.org/drk4), [Chris Smith](https://github.com/evilangelist), [Satoru Kimura](https://github.com/gyohk) * [:link:](credential/credential.d.ts) [credential](https://github.com/ericelliott/credential) by [Phú](https://github.com/phuvo) * [:link:](cron/cron.d.ts) [cron](https://www.npmjs.com/package/cron) by [Hiroki Horiuchi](https://github.com/horiuchi) +* [:link:](cropperjs/cropperjs.d.ts) [cropperjs](https://github.com/fengyuanchen/cropperjs) by [Stepan Mikhaylyuk](https://github.com/stepancar) * [:link:](cross-storage/cross-storage.d.ts) [cross-storage](https://github.com/zendesk/cross-storage) by [Daniel Chao](http://dchao.co) * [:link:](crossfilter/crossfilter.d.ts) [CrossFilter](https://github.com/square/crossfilter) by [Schmulik Raskin](https://github.com/schmuli) * [:link:](crossroads/crossroads.d.ts) [Crossroads.js](http://millermedeiros.github.io/crossroads.js) by [Diullei Gomes](https://github.com/diullei) @@ -369,13 +376,14 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](dot-case/dot-case.d.ts) [dot-case](https://github.com/blakeembrey/dot-case) by [Sam Saint-Pettersen](https://github.com/stpettersens) * [:link:](dot-prop/dot-prop.d.ts) [dot-prop](https://github.com/sindresorhus/dot-prop) by [Sam Verschueren](https://github.com/samverschueren) * [:link:](dotdotdot/dotdotdot.d.ts) [dotdotdot](http://dotdotdot.frebsite.nl) by [Milan Jaros](https://github.com/milanjaros) +* [:link:](dotenv/dotenv.d.ts) [dotenv](https://github.com/motdotla/dotenv) by [Jussi Kinnula](https://github.com/jussikinnula) * [:link:](doublearray/doublearray.d.ts) [doublearray](https://github.com/takuyaa/doublearray) by [MIZUSHIMA Junki](https://github.com/mzsm) * [:link:](draft-js/draft-js.d.ts) [draft-js](https://github.com/facebook/draft-js) by [Pavel Evsegneev](https://github.com/Ahineya) -* [:link:](hystrixjs/hystrixjs.d.ts) [dragula](https://bitbucket.org/igor_sechyn/hystrixjs) by [Igor Sechyn](https://github.com/igorsechyn) * [:link:](dragula/dragula.d.ts) [dragula](http://bevacqua.github.io/dragula) by [Paul Welter](https://github.com/pwelter34) +* [:link:](hystrixjs/hystrixjs.d.ts) [dragula](https://bitbucket.org/igor_sechyn/hystrixjs) by [Igor Sechyn](https://github.com/igorsechyn) * [:link:](drop/drop.d.ts) [Drop](http://github.hubspot.com/drop) by [Adi Dahiya](https://github.com/adidahiya) * [:link:](dropboxjs/dropboxjs.d.ts) [dropbox-js](https://github.com/dropbox/dropbox-js) by [Steve Fenton](https://github.com/Steve-Fenton), [Pedro Casaubon](https://github.com/xperiments) -* [:link:](dropzone/dropzone.d.ts) [Dropzone](http://www.dropzonejs.com) by [Natan Vivo](https://github.com/nvivo), [Andy Hawkins](https://github.com/a904guy/,http://a904guy.com/,http://www.bmbsqd.com), [Vasya Aksyonov](https://github.com/outring) +* [:link:](dropzone/dropzone.d.ts) [Dropzone](http://www.dropzonejs.com) by [Natan Vivo](https://github.com/nvivo), [Andy Hawkins](https://github.com/a904guy/,http://a904guy.com/,http://www.bmbsqd.com), [Vasya Aksyonov](https://github.com/outring), [Simon Huber](https://github.com/renuo) * [:link:](dsv/dsv.d.ts) [dsv](https://www.npmjs.com/package/dsv) by [Jason Swearingen](https://jasonswearingen.github.io) * [:link:](dts-bundle/dts-bundle.d.ts) [dts-bundle](https://github.com/TypeStrong/dts-bundle) by [Asana](https://asana.com) * [:link:](durandal/durandal.d.ts) [Durandal](http://durandaljs.com) by [Blue Spire](https://github.com/BlueSpire) @@ -394,8 +402,9 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000) * [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped) * [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan) -* [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io) +* [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak) * [:link:](electron-builder/electron-builder.d.ts) [electron-builder](https://github.com/loopline-systems/electron-builder) by [Maxime LUCE](https://github.com/SomaticIT) +* [:link:](electron-json-storage/electron-json-storage.d.ts) [electron-json-storage](https://github.com/jviotti/electron-json-storage) by [Sam Saint-Pettersen](https://github.com/stpettersens) * [:link:](electron-packager/electron-packager.d.ts) [electron-packager](https://github.com/maxogden/electron-packager) by [Maxime LUCE](https://github.com/SomaticIT) * [:link:](github-electron/electron-prebuilt.d.ts) [electron-prebuilt](https://github.com/mafintosh/electron-prebuilt) by [rhysd](https://github.com/rhysd) * [:link:](electron-window-state/electron-window-state.d.ts) [electron-window-state](https://github.com/mawie81/electron-window-state) by [rhysd](https://github.com/rhysd) @@ -407,19 +416,23 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](emissary/emissary.d.ts) [emissary](https://github.com/atom/emissary) by [vvakame](https://github.com/vvakame) * [:link:](empower/empower.d.ts) [empower](https://github.com/twada/empower) by [vvakame](https://github.com/vvakame) * [:link:](emscripten/emscripten.d.ts) [Emscripten](http://kripken.github.io/emscripten-site/index.html) by [Kensuke Matsuzaki](https://github.com/zakki) +* [:link:](encoding-japanese/encoding-japanese.d.ts) [encoding-japanese](https://github.com/polygonplanet/encoding.js) by [rhysd](https://rhysd.github.io) * [:link:](envify/envify.d.ts) [envify](https://github.com/hughsk/envify) by [Qubo](https://github.com/tkQubo) * [:link:](enzyme/enzyme.d.ts) [Enzyme](https://github.com/airbnb/enzyme) by [Marian Palkus](https://github.com/MarianPalkus), [Cap3](http://www.cap3.de) * [:link:](epiceditor/epiceditor.d.ts) [EpicEditor](http://epiceditor.com) by [Boris Yankov](https://github.com/borisyankov) * [:link:](eq.js/eq.js.d.ts) [eq.js](https://github.com/Snugug/eq.js) by [Stephen Lautier](https://github.com/stephenlautier) * [:link:](errorhandler/errorhandler.d.ts) [errorhandler](https://github.com/expressjs/errorhandler) by [Santi Albo](https://github.com/santialbo) +* [:link:](error-stack-parser/error-stack-parser.d.ts) [ErrorStackParser](https://github.com/stacktracejs/error-stack-parser) by [Eric Wendelin](https://www.eriwen.com) * [:link:](es6-collections/es6-collections.d.ts) [es6-collections](https://github.com/WebReflection/es6-collections) by [Ron Buckton](http://github.com/rbuckton) * [:link:](es6-promise/es6-promise.d.ts) [es6-promise](https://github.com/jakearchibald/ES6-Promise) by [François de Campredon](https://github.com/fdecampredon), [vvakame](https://github.com/vvakame) * [:link:](es6-shim/es6-shim.d.ts) [es6-shim](https://github.com/paulmillr/es6-shim) by [Ron Buckton](http://github.com/rbuckton) +* [:link:](escape-html/escape-html.d.ts) [escape-html](https://github.com/component/escape-html) by [Elisée MAURER](https://github.com/elisee) * [:link:](escape-latex/escape-latex.d.ts) [escape-latex](https://github.com/dangmai/escape-latex) by [Oliver Schneider](https://github.com/olsio) * [:link:](escape-string-regexp/escape-string-regexp.d.ts) [escape-string-regexp](https://github.com/sindresorhus/escape-string-regexp) by [kruncher](https://github.com/kruncher) * [:link:](esprima/esprima.d.ts) [Esprima](http://esprima.org) by [teppeis](https://github.com/teppeis), [RReverser](https://github.com/RReverser) * [:link:](estree/flow.d.ts) [ESTree AST extensions for Facebook Flow](https://github.com/estree/estree) by [RReverser](https://github.com/RReverser) * [:link:](estree/estree.d.ts) [ESTree AST specification](https://github.com/estree/estree) by [RReverser](https://github.com/RReverser) +* [:link:](evaporate/evaporate.d.ts) [EvaporateJS](https://github.com/TTLabs/EvaporateJS) by [Andrew Kuklewicz](https://github.com/kookster), [Chris Rhoden](https://github.com/chrisrhoden) * [:link:](event-kit/event-kit.d.ts) [event-kit](https://github.com/atom/event-kit) by [Vadim Macagon](https://github.com/enlight) * [:link:](event-loop-lag/event-loop-lag.d.ts) [event-loop-lag](https://github.com/pebble/event-loop-lag) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](event-stream/event-stream.d.ts) [event-stream](https://github.com/dominictarr/event-stream) by [David Gardiner](https://github.com/flcdrg) @@ -430,8 +443,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](expect/expect.d.ts) [Expect](https://github.com/mjackson/expect) by [Justin Reidy](https://github.com/jmreidy) * [:link:](expect.js/expect.js.d.ts) [expect.js](https://github.com/Automattic/expect.js) by [Teppei Sato](https://github.com/teppeis) * [:link:](expectations/expectations.d.ts) [expectations.js](https://github.com/spmason/expectations) by [vvakame](https://github.com/vvakame) -* [:link:](express/express.d.ts) [Express 4.x](http://expressjs.com) by [Boris Yankov](https://github.com/borisyankov) * [:link:](express-serve-static-core/express-serve-static-core.d.ts) [Express 4.x](http://expressjs.com) by [Boris Yankov](https://github.com/borisyankov) +* [:link:](express/express.d.ts) [Express 4.x](http://expressjs.com) by [Boris Yankov](https://github.com/borisyankov) * [:link:](express-brute/express-brute.d.ts) [express-brute](https://github.com/AdamPflug/express-brute) by [Cyril Schumacher](https://github.com/cyrilschumacher) * [:link:](express-brute-memcached/express-brute-memcached.d.ts) [express-brute-memcached](https://github.com/AdamPflug/express-brute-memcached) by [Cyril Schumacher](https://github.com/cyrilschumacher) * [:link:](express-brute-mongo/express-brute-mongo.d.ts) [express-brute-mongo](https://github.com/auth0/express-brute-mongo) by [Cyril Schumacher](https://github.com/cyrilschumacher) @@ -447,6 +460,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](express-route-fs/express-route-fs.d.ts) [express-route-fs](https://github.com/kripod/express-route-fs) by [Kristóf Poduszló](https://github.com/kripod) * [:link:](express-session/express-session.d.ts) [express-session](https://www.npmjs.org/package/express-session) by [Hiroki Horiuchi](https://github.com/horiuchi) * [:link:](express-unless/express-unless.d.ts) [express-unless](https://www.npmjs.org/package/express-unless) by [Wonshik Kim](https://github.com/wokim) +* [:link:](express-useragent/express-useragent.d.ts) [express-useragent](https://www.npmjs.org/package/express-useragent) by [Isman Usoh](https://github.com/isman-usoh) * [:link:](express-validator/express-validator.d.ts) [express-validator](https://github.com/ctavan/express-validator) by [Nathan Ridley](https://github.com/axefrog), [Jonathan Häberle](http://dreampulse.de) * [:link:](extend/extend.d.ts) [extend](https://www.npmjs.com/package/extend) by [Stefan Steinhart](https://github.com/reppners) * [:link:](wiiu/wiiu.d.ts) [Extended Functionality of Wii U Internet Browser](https://www.nintendo.co.jp/wiiu/hardware/internetbrowser/extended_functionality.html) by [MIZUSHIMA Junki](https://github.com/mzsm) @@ -457,6 +471,12 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](fbsdk/fbsdk.d.ts) [Facebook Javascript SDK](https://developers.facebook.com/docs/javascript) by [Joshua Strobl](https://github.com/JoshStrobl) * [:link:](fbemitter/fbemitter.d.ts) [Facebook's EventEmitter](https://github.com/facebook/emitter) by [kmxz](https://github.com/kmxz) * [:link:](faker/faker.d.ts) [faker](http://marak.com/faker.js) by [Bas Pennings](https://github.com/basp), [Yuki Kokubun](https://github.com/Kuniwak) +* [:link:](falcor/falcor-browser.d.ts) [falcor](http://netflix.github.io/falcor) by [Quramy](https://github.com/Quramy) +* [:link:](falcor/falcor.d.ts) [falcor](http://netflix.github.io/falcor) by [Quramy](https://github.com/Quramy) +* [:link:](falcor-express/falcor-express.d.ts) [falcor-express](https://github.com/Netflix/falcor-express) by [Quramy](https://github.com/Quramy) +* [:link:](falcor-http-datasource/falcor-http-datasource.d.ts) [falcor-http-datasource](https://github.com/Netflix/falcor-http-datasource) by [Quramy](https://github.com/Quramy) +* [:link:](falcor-json-graph/falcor-json-graph.d.ts) [falcor-json-graph](https://github.com/Netflix/falcor-json-graph) by [Quramy](https://github.com/Quramy) +* [:link:](falcor-router/falcor-router.d.ts) [falcor-router](https://github.com/Netflix/falcor-router) by [Quramy](https://github.com/Quramy) * [:link:](famous/famous.d.ts) [Famous Engine](http://famous.org) by [Boris Vasilenko](https://github.com/borisvasilenko) * [:link:](fancybox/fancybox.d.ts) [fancyBox](https://github.com/fancyapps/fancyBox) by [Boris Yankov](https://github.com/borisyankov) * [:link:](farbtastic/farbtastic.d.ts) [Farbtastic: jQuery Color Wheel](http://mattfarina.github.io/farbtastic) by [Matt Brooks](https://github.com/EnableSoftware) @@ -472,6 +492,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](filesystem/filesystem.d.ts) [File System API](http://www.w3.org/TR/file-system-api) by [Kon](http://phyzkit.net) * [:link:](file-url/file-url.d.ts) [file-url](https://github.com/sindresorhus/file-url) by [MEDIA CHECK s.r.o.](http://www.mediacheck.cz) * [:link:](FileSaver/FileSaver.d.ts) [FileSaver.js](https://github.com/eligrey/FileSaver.js) by [Cyril Schumacher](https://github.com/cyrilschumacher) +* [:link:](filesize/filesize.d.ts) [filesize](https://github.com/avoidwork/filesize.js) by [Giedrius Grabauskas](https://github.com/GiedriusGrabauskas) * [:link:](finalhandler/finalhandler.d.ts) [finalhandler](https://github.com/pillarjs/finalhandler) by [Ilya Mochalov](https://github.com/chrootsu) * [:link:](Finch/Finch.d.ts) [Finch](https://github.com/stoodder/finchjs) by [David Sichau](https://github.com/DavidSichau) * [:link:](findup-sync/findup-sync.d.ts) [findup-sync](https://github.com/cowboy/node-findup-sync) by [Bart van der Schoor](https://github.com/Bartvds), [Nathan Brown](https://github.com/ngbrown) @@ -507,8 +528,9 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](foundation-sites/foundation-sites.d.ts) [Foundation Sites](http://foundation.zurb.com) by [Sam Vloeberghs](https://github.com/samvloeberghs) * [:link:](fpsmeter/FPSMeter.d.ts) [FPSmeter](http://darsa.in/fpsmeter) by [Aaron Lampros](http://github.com/alampros) * [:link:](freedom/freedom-core-env.d.ts) [freedom](https://github.com/freedomjs/freedom) by [Jonathan Pevarnek](https://github.com/jpevarnek) -* [:link:](freedom/freedom-module-env.d.ts) [freedom](https://github.com/freedomjs/freedom) by [Jonathan Pevarnek](https://github.com/jpevarnek) * [:link:](freedom/freedom.d.ts) [freedom](https://github.com/freedomjs/freedom) by [Jonathan Pevarnek](https://github.com/jpevarnek) +* [:link:](freedom/freedom-module-env.d.ts) [freedom](https://github.com/freedomjs/freedom) by [Jonathan Pevarnek](https://github.com/jpevarnek) +* [:link:](freeport/freeport.d.ts) [freeport](https://github.com/daaku/nodejs-freeport) by [Arne Schubert](https://github.com/atd-schubert) * [:link:](from/from.d.ts) [from](https://github.com/dominictarr/from) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](fromjs/fromjs.d.ts) [fromjs](https://github.com/suckgamony/fromjs) by [Glenn Dierckx](https://github.com/glenndierckx) * [:link:](fromnow/fromnow.d.ts) [fromnow](https://github.com/lukeed/fromNow) by [Martin Bukovics](https://github.com/marinewater) @@ -544,33 +566,33 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](goJS/goJS.d.ts) [GoJS](http://gojs.net) by [Northwoods Software](https://github.com/NorthwoodsSoftware) * [:link:](google.analytics/ga.d.ts) [Google Analytics (Classic and Universal)](https://developers.google.com/analytics/devguides/collection/gajs) by [Ronnie Haakon Hegelund](http://ronniehegelund.blogspot.dk), [Pat Kujawa](http://patkujawa.com) * [:link:](gapi/gapi.d.ts) [Google API Client](https://code.google.com/p/google-api-javascript-client) by [Frank M](https://github.com/sgtfrankieboy) -* [:link:](google-apps-script/google-apps-script.document.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) * [:link:](google-apps-script/google-apps-script.content.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.maps.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.mail.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.lock.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.language.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) * [:link:](google-apps-script/google-apps-script.contacts.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) * [:link:](google-apps-script/google-apps-script.charts.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.optimization.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.maps.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.calendar.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.cache.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.base.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.script.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.jdbc.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.gmail.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.forms.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.html.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.xml-service.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) * [:link:](google-apps-script/google-apps-script.utilities.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) * [:link:](google-apps-script/google-apps-script.url-fetch.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.script.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) * [:link:](google-apps-script/google-apps-script.ui.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.jdbc.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.drive.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.spreadsheet.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.mail.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.html.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.groups.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.gmail.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) * [:link:](google-apps-script/google-apps-script.types.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.properties.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.language.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.forms.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.spreadsheet.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) * [:link:](google-apps-script/google-apps-script.sites.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.xml-service.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.base.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.cache.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.calendar.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) -* [:link:](google-apps-script/google-apps-script.lock.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.properties.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.document.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.optimization.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.groups.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) +* [:link:](google-apps-script/google-apps-script.drive.d.ts) [Google Apps Script 2015-11-12](https://developers.google.com/apps-script) by [motemen](https://github.com/motemen) * [:link:](google.feeds/google.feed.api.d.ts) [Google Feed Apis](https://developers.google.com/feed) by [RodneyJT](https://github.com/RodneyJT) * [:link:](google.geolocation/google.geolocation.d.ts) [Google Geolocation](https://code.google.com/p/geo-location-javascript) by [Vincent Bortone](https://github.com/vbortone) * [:link:](googlemaps/google.maps.d.ts) [Google Maps JavaScript API](https://developers.google.com/maps) by [Folia A/S](http://www.folia.dk), [Chris Wrench](https://github.com/cgwrench) @@ -583,6 +605,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](gapi.translate/gapi.translate.d.ts) [Google Translate API](https://developers.google.com/translate) by [Frank M](https://github.com/sgtfrankieboy) * [:link:](gapi.urlshortener/gapi.urlshortener.d.ts) [Google Url Shortener API](https://developers.google.com/url-shortener) by [Frank M](https://github.com/sgtfrankieboy) * [:link:](google.visualization/google.visualization.d.ts) [Google Visualisation Apis](https://developers.google.com/chart) by [Dan Ludwig](https://github.com/danludwig) +* [:link:](google-closure-compiler/google-closure-compiler.d.ts) [google-closure-compiler](https://github.com/chadkillingsworth/closure-compiler-npm) by [Evan Martin](http://neugierig.org) * [:link:](google-maps/google-maps.d.ts) [google-maps](https://www.npmjs.com/package/google-maps) by [Deividas Bakanas](https://github.com/DeividasBakanas), [Giedrius Grabauskas](https://github.com/GiedriusGrabauskas) * [:link:](gae.channel.api/gae.channel.api.d.ts) [GoogleAppEngine's Channel API](https://developers.google.com/appengine/docs/java/channel/javascript) by [vvakame](https://github.com/vvakame) * [:link:](graceful-fs/graceful-fs.d.ts) [graceful-fs](https://github.com/cowboy/graceful-fs) by [Bart van der Schoor](https://github.com/Bartvds) @@ -590,13 +613,14 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](graphene-pk11/graphene-pk11.d.ts) [graphene-pk11](https://github.com/PeculiarVentures/graphene) by [Stepan Miroshin](https://github.com/microshine) * [:link:](graphviz/graphviz.d.ts) [Graphviz](https://github.com/glejeune/node-graphviz) by [Matt Frantz](https://github.com/mhfrantz) * [:link:](gravatar/gravatar.d.ts) [gravatar](https://github.com/emerleite/node-gravatar) by [Denis Sokolov](https://github.com/denis-sokolov) +* [:link:](qrcode-generator/qrcode-generator.d.ts) [grcode-generator](https://github.com/kazuhikoarase/qrcode-generator) by [Stefan Huber](https://github.com/stefanhuber) * [:link:](greasemonkey/greasemonkey.d.ts) [Greasemonkey](http://www.greasespot.net) by [Kota Saito](https://github.com/kotas) * [:link:](greensock/greensock.d.ts) [GreenSock Animation Platform](http://www.greensock.com/get-started-js) by [Robert S](https://github.com/codebelt) * [:link:](gridfs-stream/gridfs-stream.d.ts) [gridfs-stream](https://github.com/aheckmann/gridfs-stream) by [Lior Mualem](https://github.com/liorm) * [:link:](gridstack/gridstack.d.ts) [Gridstack](http://troolee.github.io/gridstack.js) by [Pascal Senn](https://github.com/PascalSenn) * [:link:](gruntjs/gruntjs.d.ts) [Grunt 0.4.x](http://gruntjs.com) by [Jeff May](https://github.com/jeffmay), [Basarat Ali Syed](https://github.com/basarat) -* [:link:](gsap/Core.d.ts) [GSAP](http://greensock.com) by [VILIC VANE](https://vilic.github.io) * [:link:](gsap/Ease.d.ts) [GSAP](http://greensock.com) by [VILIC VANE](https://vilic.github.io) +* [:link:](gsap/Core.d.ts) [GSAP](http://greensock.com) by [VILIC VANE](https://vilic.github.io) * [:link:](gsap/TweenLite.d.ts) [GSAP](http://greensock.com) by [VILIC VANE](https://vilic.github.io) * [:link:](gulp/gulp.d.ts) [Gulp v3.8.x](http://gulpjs.com) by [Drew Noakes](https://drewnoakes.com) * [:link:](gulp-autoprefixer/gulp-autoprefixer.d.ts) [gulp-autoprefixer](https://github.com/sindresorhus/gulp-autoprefixer) by [Asana](https://asana.com) @@ -660,6 +684,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](gulp-watch/gulp-watch.d.ts) [gulp-watch](https://github.com/floatdrop/gulp-watch) by [Tanguy Krotoff](https://github.com/tkrotoff) * [:link:](hammerjs/hammerjs.d.ts) [Hammer.js](http://hammerjs.github.io) by [Philip Bulley](https://github.com/milkisevil), [Han Lin Yap](https://github.com/codler) * [:link:](handlebars/handlebars.d.ts) [Handlebars](http://handlebarsjs.com) by [Boris Yankov](https://github.com/borisyankov) +* [:link:](handsontable/handsontable.d.ts) [Handsontable](https://handsontable.com) by [Handsoncode sp. z o.o.](http://handsoncode.net) * [:link:](hapi/hapi.d.ts) [hapi](http://github.com/spumko/hapi) by [Jason Swearingen](http://github.com/jasonswearingen) * [:link:](harmony-proxy/harmony-proxy.d.ts) [harmony-proxy](https://www.npmjs.com/package/harmony-proxy) by [Remo Jansen](https://github.com/remojansen) * [:link:](hasher/hasher.d.ts) [Hasher.js](https://github.com/millermedeiros/hasher) by [flyfishMT](https://github.com/flyfishMT) @@ -681,6 +706,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](hopscotch/hopscotch.d.ts) [Hopscotch](http://linkedin.github.io/hopscotch) by [Tim Perry](https://github.com/pimterry) * [:link:](howlerjs/howler.d.ts) [howler.js](https://github.com/goldfire/howler.js) by [Pedro Casaubon](https://github.com/xperiments) * [:link:](touch-events/touch-events.d.ts) [HTML Touch Events](http://www.w3.org/TR/touch-events) by [Kevin Barabash](https://github.com/kevinb7) +* [:link:](html-entities/html-entities.d.ts) [html-entities](https://www.npmjs.com/package/html-entities) by [Xavier Stouder](https://github.com/xstoudi) * [:link:](html-to-text/html-to-text.d.ts) [html-to-text](https://github.com/werk85/node-html-to-text) by [Eryk Warren](https://github.com/erykwarren) * [:link:](html2canvas/html2canvas.d.ts) [html2canvas.js](https://github.com/niklasvh/html2canvas) by [Richard Hepburn](https://github.com/rwhepburn) * [:link:](html-minifier/html-minifier.d.ts) [HTMLMinifier](https://github.com/kangax/html-minifier) by [Tanguy Krotoff](https://github.com/tkrotoff) @@ -693,8 +719,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](humane/humane.d.ts) [Humane](http://wavded.github.com/humane-js) by [jmvrbanac](https://github.com/jmvrbanac) * [:link:](hypertext-application-language/hypertext-application-language.d.ts) [Hypertext Application Language Draft 6](https://tools.ietf.org/html/draft-kelly-json-hal-06) by [Maks3w](https://github.com/maks3w) * [:link:](i18n-node/i18n-node.d.ts) [i18n-node](https://github.com/mashpie/i18n-node) by [Maxime LUCE](https://github.com/SomaticIT) +* [:link:](i18next/i18next.d.ts) [i18next](http://i18next.com) by [Michael Ledin](https://github.com/mxl) * [:link:](ng-i18next/ng-i18next.d.ts) [i18next](https://github.com/i18next/ng-i18next) by [Cyril Schumacher](https://github.com/cyrilschumacher) -* [:link:](i18next/i18next.d.ts) [i18next](http://i18next.com) by [Maarten Docter](https://github.com/mdocter) * [:link:](i18next-browser-languagedetector/i18next-browser-languagedetector.d.ts) [i18next-browser-languagedetector](http://i18next.com) by [Cyril Schumacher](https://github.com/cyrilschumacher) * [:link:](i18next-express-middleware/i18next-express-middleware.d.ts) [i18next-express-middleware](http://i18next.com) by [Cyril Schumacher](https://github.com/cyrilschumacher) * [:link:](i18next-node-fs-backend/i18next-node-fs-backend.d.ts) [i18next-node-fs-backend](https://github.com/i18next/i18next-node-fs-backend) by [Cyril Schumacher](https://github.com/cyrilschumacher) @@ -703,14 +729,16 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](ibm-mobilefirst/ibm-mobilefirst.d.ts) [IBM MobileFirst Platform Foundation](http://www.ibm.com/software/products/en/mobilefirstfoundation) by [Guillermo Ignacio Enriquez Gutierrez](https://github.com/nacho4d) * [:link:](icepick/icepick.d.ts) [icepick](https://github.com/aearly/icepick) by [Nathan Brown](https://github.com/ngbrown) * [:link:](icheck/icheck.d.ts) [iCheck](http://damirfoy.com/iCheck) by [Dániel Tar](https://github.com/qcz) +* [:link:](iconv/iconv.d.ts) [iconv](https://github.com/bnoordhuis/node-iconv) by [delphinus](https://github.com/delphinus35) * [:link:](image-size/image-size.d.ts) [image-size](https://github.com/image-size/image-size) by [Elisée MAURER](https://github.com/elisee) * [:link:](imagemagick/imagemagick.d.ts) [imagemagick](http://github.com/rsms/node-imagemagick) by [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](imagemagick-native/imagemagick-native.d.ts) [imagemagick-native](https://www.npmjs.org/package/imagemagick-native) by [Hiroki Horiuchi](https://github.com/horiuchi) * [:link:](imagesloaded/imagesloaded.d.ts) [imagesLoaded](https://github.com/desandro/imagesloaded) by [Chris Charabaruk](http://github.com/coldacid) * [:link:](imap/imap.d.ts) [imap](https://www.npmjs.com/package/imap) by [Peter Snider](https://github.com/psnider) * [:link:](imgur-rest-api/imgur-rest-api.d.ts) [Imgur REST API v3](https://api.imgur.com) by [Luke William Westby](http://github.com/lukewestby) +* [:link:](immutability-helper/immutability-helper.d.ts) [immutability-helper](https://github.com/kolodny/immutability-helper) by [Sean Kelley](https://github.com/seansfkelley) * [:link:](impress/impress.d.ts) [Impress.js](https://github.com/bartaz/impress.js) by [Boris Yankov](https://github.com/borisyankov) -* [:link:](incremental-dom/incremental-dom.d.ts) [Incremetal DOM](https://github.com/google/incremental-dom) by [Basarat Ali Syed](https://github.com/basarat) +* [:link:](incremental-dom/incremental-dom.d.ts) [Incremetal DOM](https://github.com/google/incremental-dom) by [Basarat Ali Syed](https://github.com/basarat), [Markus Lanthaler](https://github.com/lanthaler) * [:link:](inflected/inflected.d.ts) [inflected](https://github.com/martinandert/inflected) by [Daniel Schmidt](https://github.com/dsci) * [:link:](inflection/inflection.d.ts) [inflection](https://github.com/dreamerslab/node.inflection) by [Shogo Iwano](https://github.com/shiwano) * [:link:](inherits/inherits.d.ts) [inherits](https://github.com/isaacs/inherits) by [Ilya Mochalov](https://github.com/chrootsu) @@ -727,6 +755,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](inversify/inversify.d.ts) [inversify](https://github.com/inversify/InversifyJS) by [inversify](https://github.com/inversify) * [:link:](ionic/ionic.d.ts) [Ionic](http://ionicframework.com) by [Spencer Williams](https://github.com/spencerwi) * [:link:](cordova-ionic/cordova-ionic.d.ts) [Ionic Cordova plugins](https://github.com/driftyco) by [Hendrik Maus](https://github.com/hendrikmaus) +* [:link:](ioredis/ioredis.d.ts) [ioredis](https://github.com/luin/ioredis) by [York Yao](https://github.com/plantain-00) * [:link:](irc/irc.d.ts) [irc](https://github.com/martynsmith/node-irc) by [phillips1012](https://github.com/phillips1012) * [:link:](is-lower-case/is-lower-case.d.ts) [is-lower-case](https://github.com/blakeembrey/is-lower-case) by [Sam Saint-Pettersen](https://github.com/stpettersens) * [:link:](is-my-json-valid/is-my-json-valid.d.ts) [is-my-json-valid](https://github.com/mafintosh/is-my-json-valid) by [kruncher](https://github.com/kruncher) @@ -877,6 +906,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](js-data-angular/js-data-angular.d.ts) [JSDataAngular](https://github.com/js-data/js-data-angular) by [Stefan Steinhart](https://github.com/reppners) * [:link:](jsdeferred/jsdeferred.d.ts) [JSDeferred](https://github.com/cho45/jsdeferred) by [Daisuke Mino](https://github.com/minodisk) * [:link:](jsdom/jsdom.d.ts) [jsdom](https://github.com/tmpvar/jsdom) by [Asana](https://asana.com) +* [:link:](jsen/jsen.d.ts) [jsen (JSON Sentinel)](https://github.com/bugventure/jsen) by [Vladimir Đokić](https://github.com/vladeck) * [:link:](jsend/jsend.d.ts) [jsend](https://github.com/Prestaul/jsend) by [Federico Caselli](https://github.com/CaselIT) * [:link:](jsesc/jsesc.d.ts) [jsesc](https://github.com/mathiasbynens/jsesc) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](jsfl/jsfl.d.ts) [JSFL](https://adobe.com) by [soywiz](https://github.com/soywiz) @@ -888,6 +918,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](jsnox/jsnox.d.ts) [JSnoX](https://github.com/af/jsnox) by [Steve Baker](https://github.com/stkb) * [:link:](json-patch/json-patch.d.ts) [json-patch](https://github.com/bruth/jsonpatch-js) by [vvakame](https://github.com/vvakame) * [:link:](json-pointer/json-pointer.d.ts) [json-pointer 1.0 l](https://www.npmjs.org/package/json-pointer) by [Bart van der Schoor](https://github.com/Bartvds) +* [:link:](json-socket/json-socket.d.ts) [json-socket](https://github.com/sebastianseilund/node-json-socket) by [Sven Reglitzki](https://github.com/svi3c) * [:link:](json-stable-stringify/json-stable-stringify.d.ts) [json-stable-stringify](https://github.com/substack/json-stable-stringify) by [Matt Frantz](https://github.com/mhfrantz) * [:link:](json5/json5.d.ts) [JSON5](http://json5.org) by [Jason Swearingen](https://jasonswearingen.github.io) * [:link:](jsoneditoronline/jsoneditoronline.d.ts) [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) by [Vincent Bortone](https://github.com/vbortone) @@ -904,6 +935,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](jsts/jsts.d.ts) [jsts](https://github.com/bjornharrtell/jsts) by [Stephane Alie](https://github.com/StephaneAlie) * [:link:](jsuri/jsuri.d.ts) [jsUri](https://github.com/derek-watson/jsUri) by [Chris Charabaruk](http://github.com/coldacid), [Florian Wagner](http://github.com/flqw) * [:link:](jsurl/jsurl.d.ts) [jsurl](https://github.com/Mikhus/jsurl) by [Alexey Gorshkov](https://github.com/agorshkov23) +* [:link:](jsx-chai/jsx-chai.d.ts) [jsx-chai](https://github.com/bkonkle/jsx-chai) by [Philipp Holzer](https://github.com/nupplaphil) * [:link:](jszip/jszip.d.ts) [JSZip](http://stuk.github.com/jszip) by [mzeiher](https://github.com/mzeiher) * [:link:](jug/jug.d.ts) [jug](https://github.com/kaiquewdev/Graph) by [yevt](https://github.com/yevt) * [:link:](jwplayer/jwplayer.d.ts) [JW Player](http://developer.longtailvideo.com/trac) by [Martin Duparc](https://github.com/martinduparc) @@ -947,17 +979,22 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](ko.plus/ko.plus.d.ts) [ko.plus](https://github.com/stevegreatrex/ko.plus) by [Howard Richards](https://github.com/conficient) * [:link:](koa-compose/koa-compose.d.ts) [koa](https://github.com/koajs/compose) by [jKey Lu](https://github.com/jkeylu) * [:link:](koa/koa.d.ts) [Koa 2.x](http://koajs.com) by [DavidCai1993](https://github.com/DavidCai1993) +* [:link:](koa-bodyparser/koa-bodyparser.d.ts) [koa-bodyparser v3.x](https://github.com/koajs/bodyparser) by [Jerry Chin](https://github.com/hellopao) +* [:link:](koa-favicon/koa-favicon.d.ts) [koa-favicon v2.x](https://github.com/koajs/favicon) by [Jerry Chin](https://github.com/hellopao) +* [:link:](koa-json/koa-json.d.ts) [koa-json v2.x](https://github.com/koajs/json) by [Alex Friedman](https://github.com/brooklyndev) * [:link:](koa-router/koa-router.d.ts) [koa-router v7.x](https://github.com/alexmingoia/koa-router) by [Jerry Chin](https://github.com/hellopao) -* [:link:](kolite/knockout.dirtyFlag.d.ts) [KoLite](https://github.com/CodeSeven/kolite) by [Boris Yankov](https://github.com/borisyankov) -* [:link:](kolite/knockout.command.d.ts) [KoLite](https://github.com/CodeSeven/kolite) by [Boris Yankov](https://github.com/borisyankov) -* [:link:](kolite/knockout.activity.d.ts) [KoLite](https://github.com/CodeSeven/kolite) by [Boris Yankov](https://github.com/borisyankov) +* [:link:](koa-static/koa-static.d.ts) [koa-static v2.x](https://github.com/koajs/static) by [Jerry Chin](https://github.com/hellopao) * [:link:](kolite/kolite.d.ts) [KoLite](https://github.com/CodeSeven/kolite) by [Boris Yankov](https://github.com/borisyankov) +* [:link:](kolite/knockout.activity.d.ts) [KoLite](https://github.com/CodeSeven/kolite) by [Boris Yankov](https://github.com/borisyankov) +* [:link:](kolite/knockout.command.d.ts) [KoLite](https://github.com/CodeSeven/kolite) by [Boris Yankov](https://github.com/borisyankov) +* [:link:](kolite/knockout.dirtyFlag.d.ts) [KoLite](https://github.com/CodeSeven/kolite) by [Boris Yankov](https://github.com/borisyankov) * [:link:](konami.js/konami.d.ts) [Konami-js](https://github.com/snaptortoise/konami-js) by [Matthieu Mourisson](https://github.com/mareek) * [:link:](kue/kue.d.ts) [kue 0.9.x](https://github.com/Automattic/kue) by [Nicholas Penree](http://github.com/drudge) * [:link:](kuromoji/kuromoji.d.ts) [kuromoji.js](https://github.com/takuyaa/kuromoji.js) by [MIZUSHIMA Junki](https://github.com/mzsm) * [:link:](ladda/ladda.d.ts) [Ladda](https://github.com/hakimel/Ladda) by [Danil Flores](https://github.com/dflor003), [Michael Lee](https://github.com/leemicw) * [:link:](lls/lls.d.ts) [LargeLocalStorage](https://github.com/tantaman/LargeLocalStorage) by [Borislav Zhivkov](https://github.com/borislavjivkov) * [:link:](later/later.d.ts) [LaterJS](http://bunkat.github.io/later) by [Jason D Dryhurst-Smith](http://jasonds.co.uk) +* [:link:](latinize/latinize.d.ts) [latinize](https://github.com/dundalek/latinize) by [Giedrius Grabauskas](https://github.com/GiedriusGrabauskas) * [:link:](lazy.js/lazy.js.d.ts) [Lazy.js](https://github.com/dtao/lazy.js) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](lazypipe/lazypipe.d.ts) [lazypipe](https://github.com/OverZealous/lazypipe) by [Thomas Corbière](https://github.com/tomc974) * [:link:](leaflet-curve/leaflet-curve.d.ts) [leaflet-curve](https://github.com/onikiienko/Leaflet.curve) by [Onikiienko](https://github.com/onikiienko) @@ -992,7 +1029,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](log4js/log4js.d.ts) [log4js](https://github.com/nomiddlename/log4js-node) by [Kentaro Okuno](http://github.com/armorik83) * [:link:](logg/logg.d.ts) [logg](https://github.com/dpup/node-logg) by [Bret Little](https://github.com/blittle) * [:link:](loggly/loggly.d.ts) [loggly](https://github.com/nodejitsu/node-loggly) by [Ray Martone](https://github.com/rmartone) -* [:link:](loglevel/loglevel.d.ts) [loglevel](https://github.com/pimterry/loglevel) by [Stefan Profanter](https://github.com/Pro), [Florian Wagner](https://github.com/flqw) +* [:link:](loglevel/loglevel.d.ts) [loglevel](https://github.com/pimterry/loglevel) by [Stefan Profanter](https://github.com/Pro), [Florian Wagner](https://github.com/flqw), [Gabor Szmetanko](https://github.com/szmeti) * [:link:](logrotate-stream/logrotate-stream.d.ts) [logrotate-stream](https://github.com/dstokes/logrotate-stream) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](lokijs/lokijs.d.ts) [lokijs](https://github.com/techfort/LokiJS) by [TeamworkGuy2](https://github.com/TeamworkGuy2) * [:link:](lolex/lolex.d.ts) [lolex](https://github.com/sinonjs/lolex) by [Wim Looman](https://github.com/Nemo157) @@ -1044,6 +1081,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](node-mysql-wrapper/my-meteor.d.ts) [meteorjs for node-mysql-wrapper which helps in development](https://github.com/nodets/node-mysql-wrapper) by [Makis Maropoulos](https://github.com/kataras) * [:link:](method-override/method-override.d.ts) [method-override](https://github.com/expressjs/method-override) by [Santi Albo](https://github.com/santialbo) * [:link:](metismenu/metismenu.d.ts) [metisMenu](http://github.com/onokumus/metisMenu) by [onokums](https://github.com/onokumus) +* [:link:](microgears/microgears.d.ts) [microgears](http://github.com/marcusdb/microgears) by [Marcus David Bronstein](https://github.com/marcusdb) * [:link:](micromatch/micromatch.d.ts) [micromatch](https://github.com/jonschlinkert/micromatch) by [glen-84](https://github.com/glen-84) * [:link:](microsoft-ajax/microsoft.ajax.d.ts) [Microsoft ASP.NET Ajax client side library](http://msdn.microsoft.com/en-us/library/ee341002(v=vs.100).aspx) by [Patrick Magee](https://github.com/pjmagee) * [:link:](xrm/xrm.d.ts) [Microsoft Dynamics xRM API](http://www.microsoft.com/en-us/download/details.aspx?id=44567) by [David Berry](https://github.com/6ix4our), [Matt Ngan](https://github.com/mattngan), [Markus Mauch](https://github.com/markusmauch) @@ -1072,8 +1110,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](mkpath/mkpath.d.ts) [mkpath](https://www.npmjs.com/package/mkpath) by [Jared Klopper](https://github.com/optical) * [:link:](mmmagic/mmmagic.d.ts) [mmmagic](https://github.com/mscdex/mmmagic) by [Andrei Sebastian Cîmpean](http://andreime.com) * [:link:](mobile-detect/mobile-detect.d.ts) [mobile-detect](http://hgoebl.github.io/mobile-detect.js) by [Martin McWhorter](https://github.com/martinmcwhorter) -* [:link:](mobservable-react/mobservable-react.d.ts) [mobservable](https://github.com/mweststrate/mobservable-react) by [Michel Weststrate](https://github.com/mweststrate) * [:link:](mobservable/mobservable.d.ts) [mobservable](https://mweststrate.github.io/mobservable) by [Michel Weststrate](https://github.com/mweststrate) +* [:link:](mobservable-react/mobservable-react.d.ts) [mobservable](https://github.com/mweststrate/mobservable-react) by [Michel Weststrate](https://github.com/mweststrate) * [:link:](mocha/mocha-node.d.ts) [mocha](http://mochajs.org) by [Vadim Macagon](https://github.com/enlight), [vvakame](https://github.com/vvakame) * [:link:](mocha/mocha.d.ts) [mocha](http://mochajs.org) by [Kazi Manzur Rashid](https://github.com/kazimanzurrashid), [otiai10](https://github.com/otiai10), [jt000](https://github.com/jt000), [Vadim Macagon](https://github.com/enlight) * [:link:](mocha-phantomjs/mocha-phantomjs.d.ts) [mocha-phantomjs](http://metaskills.net/mocha-phantomjs) by [Erik Schierboom](https://github.com/ErikSchierboom) @@ -1081,9 +1119,9 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](mockery/mockery.d.ts) [mockery](https://github.com/mfncooper/mockery) by [jt000](https://github.com/jt000) * [:link:](modernizr/modernizr.d.ts) [Modernizr](http://modernizr.com) by [Boris Yankov](https://github.com/borisyankov), [Theodore Brown](https://github.com/theodorejb), [Leon Yu](https://github.com/leonyu) * [:link:](moment-timezone/moment-timezone.d.ts) [moment-timezone.js](http://momentjs.com/timezone) by [Michel Salib](https://github.com/michelsalib) -* [:link:](moment-range/moment-range.d.ts) [Moment.js](https://github.com/gf3/moment-range) by [Bart van den Burg](https://github.com/Burgov), [Wilgert Velinga](https://github.com/wilgert) -* [:link:](moment/moment.d.ts) [Moment.js](https://github.com/timrwood/moment) by [Michael Lakerveld](https://github.com/Lakerfield), [Aaron King](https://github.com/kingdango), [Hiroki Horiuchi](https://github.com/horiuchi), [Dick van den Brink](https://github.com/DickvdBrink), [Adi Dahiya](https://github.com/adidahiya), [Matt Brooks](https://github.com/EnableSoftware) * [:link:](moment/moment-node.d.ts) [Moment.js](https://github.com/timrwood/moment) by [Michael Lakerveld](https://github.com/Lakerfield), [Aaron King](https://github.com/kingdango), [Hiroki Horiuchi](https://github.com/horiuchi), [Dick van den Brink](https://github.com/DickvdBrink), [Adi Dahiya](https://github.com/adidahiya), [Matt Brooks](https://github.com/EnableSoftware), [Gal Talmor](https://github.com/galtalmor) +* [:link:](moment/moment.d.ts) [Moment.js](https://github.com/timrwood/moment) by [Michael Lakerveld](https://github.com/Lakerfield), [Aaron King](https://github.com/kingdango), [Hiroki Horiuchi](https://github.com/horiuchi), [Dick van den Brink](https://github.com/DickvdBrink), [Adi Dahiya](https://github.com/adidahiya), [Matt Brooks](https://github.com/EnableSoftware) +* [:link:](moment-range/moment-range.d.ts) [Moment.js](https://github.com/gf3/moment-range) by [Bart van den Burg](https://github.com/Burgov), [Wilgert Velinga](https://github.com/wilgert) * [:link:](mongodb/mongodb.d.ts) [MongoDB](https://github.com/mongodb/node-mongodb-native/tree/2.1) by [Federico Caselli](https://github.com/CaselIT) * [:link:](mongoose/mongoose.d.ts) [Mongoose](http://mongoosejs.com) by [horiuchi](https://github.com/horiuchi) * [:link:](mongoose-auto-increment/mongoose-auto-increment.d.ts) [mongoose-auto-increment](https://github.com/codetunnel/mongoose-auto-increment) by [Aya Morisawa](https://github.com/AyaMorisawa) @@ -1101,7 +1139,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](msgpack/msgpack.d.ts) [msgpack.js - MessagePack JavaScript Implementation](https://github.com/uupaa/msgpack.js) by [Shinya Mochizuki](https://github.com/enrapt-mochizuki) * [:link:](msnodesql/msnodesql.d.ts) [msnodesql](https://github.com/WindowsAzure/node-sqlserver) by [Boris Yankov](https://github.com/borisyankov), [Maxime LUCE](https://github.com/SomaticIT) * [:link:](msportalfx-test/msportalfx-test.d.ts) [msportalfx-test](https://msazure.visualstudio.com/DefaultCollection/AzureUX/_git/portalfx-msportalfx-test) by [Julio Casal](https://github.com/julioct) -* [:link:](mssql/mssql.d.ts) [mssql](https://www.npmjs.com/package/mssql) by [COLSA Corporation](http://www.colsa.com), [Ben Farr](https://github.com/jaminfarr) +* [:link:](mssql/mssql.d.ts) [mssql](https://www.npmjs.com/package/mssql) by [COLSA Corporation](http://www.colsa.com), [Ben Farr](https://github.com/jaminfarr), [Vitor Buzinaro](https://github.com/buzinas) * [:link:](mu2/mu2.d.ts) [mu2](http://github.com/raycmorgan/mu) by [Jeff Goddard](https://github.com/jedigo) * [:link:](multer/multer.d.ts) [multer](https://github.com/expressjs/multer) by [jt000](https://github.com/jt000), [vilicvane](https://vilic.github.io), [David Broder-Rodgers](https://github.com/DavidBR-SW) * [:link:](multiplexjs/multiplexjs.d.ts) [Multiplex.js](http://github.com/multiplex/multiplex.js) by [Kamyar Nazeri](http://github.com/KamyarNazeri) @@ -1109,6 +1147,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](mz/mz.d.ts) [mz](https://github.com/normalize/mz) by [Thomas Hickman](https://github.com/ThomasHickman) * [:link:](nanoajax/nanoajax.d.ts) [nanoajax](https://github.com/yanatan16/nanoajax) by [Nathan Cahill](https://github.com/nathancahill) * [:link:](natural/natural.d.ts) [Natural](https://github.com/NaturalNode/natural) by [Dylan R. E. Moonfire](https://github.com/dmoonfire) +* [:link:](natural-sort/natural-sort.d.ts) [NaturalSort](https://github.com/studio-b12/natural-sort) by [Antonio Morales](https://github.com/a-morales) * [:link:](navigation/navigation.d.ts) [Navigation](http://grahammendick.github.io/navigation) by [Graham Mendick](https://github.com/grahammendick) * [:link:](nconf/nconf.d.ts) [nconf](https://github.com/flatiron/nconf) by [Jeff Goddard](https://github.com/jedigo), [Jean-Martin Thibault](https://github.com/jmthibault) * [:link:](ncp/ncp.d.ts) [ncp](https://github.com/AvianFlu/ncp) by [Bart van der Schoor](https://github.com/bartvds) @@ -1117,6 +1156,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](netmask/netmask.d.ts) [Netmask](https://github.com/rs/node-netmask) by [Matt Frantz](https://github.com/mhfrantz) * [:link:](nexpect/nexpect.d.ts) [nexpect](https://github.com/nodejitsu/nexpect) by [vvakame](http://github.com/vvakame) * [:link:](ng-command/ng-command.d.ts) [ng-command](https://github.com/stephenlautier/ng-command) by [Stephen Lautier](https://github.com/stephenlautier) +* [:link:](ng-facebook/ng-facebook.d.ts) [ng-facebook](https://github.com/GoDisco/ngFacebook) by [Crevil](https://github.com/Crevil) * [:link:](ng-flow/ng-flow.d.ts) [ng-flow](https://github.com/flowjs/ng-flow) by [Ryan McNamara](https://github.com/ryan10132) * [:link:](ng-grid/ng-grid.d.ts) [ng-grid](http://angular-ui.github.io/ng-grid) by [Ken Smith](https://github.com/smithkl42), [Roland Zwaga](https://github.com/rolandzwaga), [Kent Cooper](https://github.com/kentcooper) * [:link:](angular-idle/angular-idle.d.ts) [ng-idle](http://hackedbychinese.github.io/ng-idle) by [mthamil](https://github.com/mthamil) @@ -1147,7 +1187,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](ng-stomp/ng-stomp.d.ts) [ngStomp](https://github.com/beevelop/ng-stomp) by [Lukasz Potapczuk](https://github.com/lpotapczuk) * [:link:](ngstorage/ngstorage.d.ts) [ngstorage](https://github.com/gsklee/ngStorage) by [Jakub Pistek](https://github.com/kubiq) * [:link:](nightmare/nightmare.d.ts) [Nightmare](https://github.com/segmentio/nightmare) by [horiuchi](https://github.com/horiuchi) -* [:link:](noble/noble.d.ts) [noble](https://github.com/sandeepmistry/noble) by [Seon-Wook Park](https://github.com/swook) +* [:link:](noble/noble.d.ts) [noble](https://github.com/sandeepmistry/noble) by [Seon-Wook Park](https://github.com/swook), [Hans Bakker](https://github.com/wind-rider) * [:link:](nock/nock.d.ts) [nock](https://github.com/pgte/nock) by [bonnici](https://github.com/bonnici) * [:link:](node-imap/imap.d.ts) [node imap](https://github.com/mscdex/node-imap) by [Steve Fenton](https://github.com/Steve-Fenton) * [:link:](oauth2-server/oauth2-server.d.ts) [Node OAuth2 Server](https://github.com/thomseddon/node-oauth2-server) by [Robbie Van Gorkom](https://github.com/vangorra) @@ -1189,12 +1229,13 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](node-sass-middleware/node-sass-middleware.d.ts) [node-sass-middleware](https://github.com/sass/node-sass-middleware) by [Pascal Garber](http://www.jumplink.eu) * [:link:](node-schedule/node-schedule.d.ts) [node-schedule](https://github.com/tejasmanohar/node-schedule) by [Cyril Schumacher](https://github.com/cyrilschumacher) * [:link:](node-slack/node-slack.d.ts) [node-slack](https://github.com/xoxco/node-slack) by [Qubo](https://github.com/tkQubo) +* [:link:](node-snap7/node-snap7.d.ts) [node-snap7](https://github.com/mathiask88/node-snap7) by [Heilingbrunner](https://github.com/heilingbrunner) * [:link:](srp/srp.d.ts) [node-srp](https://github.com/mozilla/node-srp) by [Pat Smuk](https://github.com/Patman64) * [:link:](stack-trace/stack-trace.d.ts) [node-stack-trace](https://github.com/felixge/node-stack-trace) by [Exceptionless](https://github.com/exceptionless) * [:link:](node-uuid/node-uuid-global.d.ts) [node-uuid.js](https://github.com/broofa/node-uuid) by [Jeff May](https://github.com/jeffmay) -* [:link:](node-uuid/node-uuid.d.ts) [node-uuid.js](https://github.com/broofa/node-uuid) by [Jeff May](https://github.com/jeffmay) -* [:link:](node-uuid/node-uuid-base.d.ts) [node-uuid.js](https://github.com/broofa/node-uuid) by [Jeff May](https://github.com/jeffmay) * [:link:](node-uuid/node-uuid-cjs.d.ts) [node-uuid.js](https://github.com/broofa/node-uuid) by [Jeff May](https://github.com/jeffmay) +* [:link:](node-uuid/node-uuid-base.d.ts) [node-uuid.js](https://github.com/broofa/node-uuid) by [Jeff May](https://github.com/jeffmay) +* [:link:](node-uuid/node-uuid.d.ts) [node-uuid.js](https://github.com/broofa/node-uuid) by [Jeff May](https://github.com/jeffmay) * [:link:](node-validator/node-validator.d.ts) [node-validator](https://www.npmjs.com/package/node-validator) by [Ken Gorab](https://github.com/kengorab) * [:link:](node-webkit/node-webkit.d.ts) [node-webkit](https://github.com/rogerwang/node-webkit) by [Pedro Casaubon](https://github.com/xperiments) * [:link:](xml2js/xml2js.d.ts) [node-xml2js](https://github.com/Leonidas-from-XIV/node-xml2js) by [Michel Salib](https://github.com/michelsalib), [Jason McNeil](https://github.com/jasonrm), [Christopher Currens](https://github.com/ccurrens) @@ -1242,8 +1283,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](once/once.d.ts) [once](https://github.com/isaacs/once) by [Denis Sokolov](https://github.com/denis-sokolov) * [:link:](onoff/onoff.d.ts) [onoff](https://github.com/fivdi/onoff) by [Marcel Ernst](https://github.com/marcel-ernst) * [:link:](onsenui/onsenui.d.ts) [Onsen UI](http://onsen.io) by [Fran Dios](https://github.com/frankdiox) -* [:link:](deep-extend/deep-extend.d.ts) [open](https://github.com/unclechu/node-deep-extend) by [rhysd](https://github.com/rhysd) * [:link:](open/open.d.ts) [open](https://github.com/jjrdn/node-open) by [Bart van der Schoor](https://github.com/Bartvds) +* [:link:](deep-extend/deep-extend.d.ts) [open](https://github.com/unclechu/node-deep-extend) by [rhysd](https://github.com/rhysd) * [:link:](OpenJsCad/openjscad.d.ts) [OpenJsCad.js](https://github.com/joostn/OpenJsCad) by [Dan Marshall](https://github.com/danmarshall) * [:link:](openlayers/openlayers.d.ts) [OpenLayers](http://openlayers.org) by [Wouter Goedhart](https://github.com/woutergd) * [:link:](openpgp/openpgp.d.ts) [openpgpjs](http://openpgpjs.org) by [Guillaume Lacasa](https://blog.lacasa.fr) @@ -1271,12 +1312,14 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](pascal-case/pascal-case.d.ts) [pascal-case](https://github.com/blakeembrey/pascal-case) by [Sam Saint-Pettersen](https://github.com/stpettersens) * [:link:](passport/passport.d.ts) [Passport](http://passportjs.org) by [Horiuchi_H](https://github.com/horiuchi) * [:link:](passport-strategy/passport-strategy.d.ts) [Passport Strategy module](https://github.com/jaredhanson/passport-strategy) by [Lior Mualem](https://github.com/liorm) -* [:link:](passport-twitter/passport-twitter.d.ts) [passport-facebook](https://github.com/jaredhanson/passport-facebook) by [James Roland Cabresos](https://github.com/staticfunction) * [:link:](passport-facebook/passport-facebook.d.ts) [passport-facebook](https://github.com/jaredhanson/passport-facebook) by [James Roland Cabresos](https://github.com/staticfunction) * [:link:](passport-google-oauth/passport-google-oauth.d.ts) [passport-facebook](https://github.com/jaredhanson/passport-facebook) by [James Roland Cabresos](https://github.com/staticfunction) +* [:link:](passport-twitter/passport-twitter.d.ts) [passport-facebook](https://github.com/jaredhanson/passport-facebook) by [James Roland Cabresos](https://github.com/staticfunction) * [:link:](passport-facebook-token/passport-facebook-token.d.ts) [passport-facebook-token](https://github.com/drudge/passport-facebook-token) by [Ray Martone](https://github.com/rmartone) * [:link:](passport-http-bearer/passport-http-bearer.d.ts) [passport-http-bearer](https://github.com/jaredhanson/passport-http-bearer) by [Isman Usoh](https://github.com/isman-usoh) +* [:link:](passport-jwt/passport-jwt.d.ts) [passport-jwt](https://github.com/themikenicholson/passport-jwt) by [TANAKA Koichi](https://github.com/mugeso) * [:link:](passport-local/passport-local.d.ts) [passport-local](https://github.com/jaredhanson/passport-local) by [Maxime LUCE](https://github.com/SomaticIT) +* [:link:](password-hash/password-hash.d.ts) [password-hash 1.2.x](https://github.com/davidwood/node-password-hash) by [TANAKA Koichi](https://github.com/mugeso) * [:link:](path-case/path-case.d.ts) [path-case](https://github.com/blakeembrey/path-case) by [Sam Saint-Pettersen](https://github.com/stpettersens) * [:link:](path-exists/path-exists.d.ts) [path-exists](https://github.com/sindresorhus/path-exists) by [Shogo Iwano](https://github.com/shiwano) * [:link:](path-parse/path-parse.d.ts) [path-parse](https://github.com/jbgutierrez/path-parse) by [Dan Chao](http://dchao.co) @@ -1291,7 +1334,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](pegjs/pegjs.d.ts) [PEG.js](http://pegjs.org) by [vvakame](https://github.com/vvakame), [Tobias Kahlert](https://github.com/SrTobi) * [:link:](persona/persona.d.ts) [Persona](http://www.mozilla.org/en-US/persona) by [James Frasca](https://github.com/Nycto) * [:link:](pg/pg.d.ts) [pg](https://github.com/brianc/node-postgres) by [Phips Peter](http://pspeter3.com) -* [:link:](pg-promise/pg-promise.d.ts) [pg-promise](https://github.com/vitaly-t/pg-promise) by [Jörg Dotzki](https://github.com/ISO50) +* [:link:](pg-promise/pg-promise.d.ts) [pg-promise](https://github.com/vitaly-t/pg-promise) by [vvakame](https://github.com/vvakame) * [:link:](pgwmodal/pgwmodal.d.ts) [PgwModal](http://pgwjs.com/pgwmodal) by [Pine Mizune](https://github.com/pine613) * [:link:](phantomcss/phantomcss.d.ts) [PhantomCSS](https://github.com/Huddle/PhantomCSS) by [Amaury Bauzac](https://github.com/abauzac) * [:link:](phantom/phantom.d.ts) [PhantomJS bridge for NodeJS](https://github.com/sgentle/phantomjs-node) by [horiuchi](https://github.com/horiuchi), [Random](https://github.com/llRandom) @@ -1336,9 +1379,11 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](prelude-ls/prelude-ls.d.ts) [prelude.ls](http://www.preludels.com) by [Aya Morisawa](https://github.com/AyaMorisawa) * [:link:](prettyjson/prettyjson.d.ts) [prettyjson](https://github.com/rafeca/prettyjson) by [Wael BEN ZID EL GUEBSI](https://github.com/benzid-wael) * [:link:](meteor-prime8consulting-oauth2/meteor-prime8consulting-oauth2.d.ts) [prime8consulting:meteor-oauth2](https://github.com/prime-8-consulting/meteor-oauth2) by [Robbie Van Gorkom](https://github.com/vangorra) +* [:link:](prismjs/prism.d.ts) [prism](http://prismjs.com) by [Erik Lieben](https://github.com/eriklieben) * [:link:](progressjs/progress.d.ts) [ProgressJs](http://usablica.github.io/progress.js) by [Shunsuke Ohtani](https://github.com/zaneli) * [:link:](project-oxford/project-oxford.d.ts) [project-oxford](https://github.com/felixrieseberg/project-oxford) by [Scott Southwood](https://github.com/scsouthw) * [:link:](promise/promise.d.ts) [promise](https://www.promisejs.org) by [Manuel Rueda](https://github.com/ManRueda) +* [:link:](promise-pg/promise-pg.d.ts) [promise-pg](https://bitbucket.org/lplabs/promise-pg) by [Chris Charabaruk](http://github.com/coldacid) * [:link:](promise-pool/promise-pool.d.ts) [promise-pool](https://github.com/vilic/promise-pool) by [VILIC VANE](https://github.com/vilic) * [:link:](promises-a-plus/promises-a-plus.d.ts) [promises-a-plus](http://promisesaplus.com) by [Igor Oleinikov](https://github.com/Igorbek) * [:link:](promisify-supertest/promisify-supertest.d.ts) [promisify-supertest](https://www.npmjs.com/package/promisify-supertest) by [Leo Liang](https://github.com/aleung) @@ -1364,6 +1409,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](qwest/qwest.d.ts) [qwest](https://github.com/pyrsmk/qwest) by [Lindsay Evans](https://github.com/lindsayevans) * [:link:](rabbit.js/rabbit.js.d.ts) [rabbit.js](https://github.com/squaremo/rabbit.js) by [Wonshik Kim](https://github.com/wokim) * [:link:](ractive/ractive.d.ts) [Ractive](http://ractivejs.org) by [Han Lin Yap](http://yap.nu) +* [:link:](radium/radium.d.ts) [radium](https://github.com/formidablelabs/radium) by [Alex Gorbatchev](https://github.com/alexgorbatchev), [Philipp Holzer](https://github.com/nupplaphil) * [:link:](random-js/random-js.d.ts) [random-js](https://github.com/ckknight/random-js) by [Gustavo Di Pietro](https://github.com/pistacchio) * [:link:](random-string/random-string.d.ts) [random-string](https://github.com/valiton/node-random-string) by [Sam Saint-Pettersen](https://github.com/stpettersens) * [:link:](rangy/rangy.d.ts) [Rangy](https://github.com/timdown/rangy) by [Rudolph Gottesheim](http://www.midnight-design.at) @@ -1390,6 +1436,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](rc-select/rc-select.d.ts) [React Select](https://github.com/react-component/select) by [Denis Tirilis](https://github.com/DenisTirilis) * [:link:](react-bootstrap/react-bootstrap.d.ts) [react-bootstrap](https://github.com/react-bootstrap/react-bootstrap) by [Walker Burgin](https://github.com/walkerburgin), [Vincent Siao](https://github.com/vsiao) * [:link:](react-bootstrap-table/react-bootstrap-table.d.ts) [react-bootstrap-table](https://github.com/AllenFang/react-bootstrap-table) by [Frank Laub](https://github.com/flaub) +* [:link:](react-cropper/react-cropper.d.ts) [react-cropper](https://github.com/roadmanfong/react-cropper) by [Stepan Mikhaylyuk](https://github.com/stepancar) * [:link:](react-datagrid/react-datagrid.d.ts) [react-datagrid](https://github.com/zippyui/react-datagrid.git) by [Stephen Jelfs](https://github.com/stephenjelfs) * [:link:](react-day-picker/react-day-picker.d.ts) [react-day-picker](https://github.com/gpbl/react-day-picker) by [Giampaolo Bellavite](https://github.com/gpbl), [Jason Killian](https://github.com/jkillian) * [:link:](react-dropzone/react-dropzone.d.ts) [react-dropzone](https://github.com/paramaggarwal/react-dropzone) by [Mathieu Larouche Dube](https://github.com/matdube) @@ -1400,9 +1447,10 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](react-input-calendar/react-input-calendar.d.ts) [react-input-calendar](https://github.com/Rudeg/react-input-calendar) by [Stepan Mikhaylyuk](https://github.com/stepancar) * [:link:](react-intl/react-intl.d.ts) [react-intl](http://formatjs.io/react) by [Bruno Grieder](https://github.com/bgrieder), [Christian Droulers](https://github.com/cdroulers) * [:link:](react-mixin/react-mixin.d.ts) [react-mixin](https://github.com/brigand/react-mixin) by [Qubo](https://github.com/tkqubo) +* [:link:](react-motion/react-motion.d.ts) [react-motion](https://github.com/chenglou/react-motion) by [Stepan Mikhaylyuk](https://github.com/stepancar) * [:link:](react-native/react-native.d.ts) [react-native](https://github.com/facebook/react-native) by [Bruno Grieder](https://github.com/bgrieder) * [:link:](react-props-decorators/react-props-decorators.d.ts) [react-props-decorators](https://github.com/popkirby/react-props-decorators) by [Qubo](https://github.com/tkqubo) -* [:link:](react-redux/react-redux.d.ts) [react-redux](https://github.com/rackt/react-redux) by [Qubo](https://github.com/tkqubo) +* [:link:](react-redux/react-redux.d.ts) [react-redux](https://github.com/rackt/react-redux) by [Qubo](https://github.com/tkqubo), [Sean Kelley](https://github.com/seansfkelley) * [:link:](react-router/react-router.d.ts) [react-router](https://github.com/rackt/react-router) by [Sergey Buturlakin](https://github.com/sergey-buturlakin), [Yuichi Murata](https://github.com/mrk21), [Václav Ostrožlík](https://github.com/vasek17), [Nathan Brown](https://github.com/ngbrown) * [:link:](react-router-bootstrap/react-router-bootstrap.d.ts) [react-router-bootstrap](https://github.com/react-bootstrap/react-router-bootstrap) by [Vincent Lesierse](https://github.com/vlesierse) * [:link:](react-router-redux/react-router-redux.d.ts) [react-router-redux](https://github.com/rackt/react-router-redux) by [Isman Usoh](http://github.com/isman-usoh), [Noah Shipley](https://github.com/noah79), [Dimitri Rosenberg](https://github.com/rosendi) @@ -1411,15 +1459,20 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](react-spinkit/react-spinkit.d.ts) [react-spinkit](https://github.com/KyleAMathews/react-spinkit) by [Qubo](https://github.com/tkqubo) * [:link:](react-swf/react-swf.d.ts) [react-swf](https://github.com/syranide/react-swf) by [Stepan Mikhaylyuk](https://github.com/stepancar) * [:link:](react-swipeable-views/react-swipeable-views.d.ts) [react-swipeable-views](https://github.com/oliviertassinari/react-swipeable-views) by [Michael Ledin](https://github.com/mxl) +* [:link:](react-tabs/react-tabs.d.ts) [react-tabs](https://github.com/reactjs/react-tabs) by [Yuu Igarashi](https://github.com/yu-i9) +* [:link:](react-tagcloud/react-tagcloud.d.ts) [react-tagcloud](https://github.com/madox2/react-tagcloud) by [wassname](https://github.com/wassname) * [:link:](react-tap-event-plugin/react-tap-event-plugin.d.ts) [react-tap-event-plugin](https://github.com/zilverline/react-tap-event-plugin) by [Michael Ledin](https://github.com/mxl) +* [:link:](react-widgets/react-widgets.d.ts) [react-widgets](https://github.com/jquense/react-widgets) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](read/read.d.ts) [read](https://github.com/isaacs/read) by [Tim JK](https://github.com/timjk) * [:link:](readdir-stream/readdir-stream.d.ts) [readdir-stream](https://github.com/logicalparadox/readdir-stream) by [Bart van der Schoor](https://github.com/Bartvds) +* [:link:](rebass/rebass.d.ts) [Rebass](https://github.com/jxnblk/rebass) by [rhysd](https://rhysd.github.io) * [:link:](recursive-readdir/recursive-readdir.d.ts) [recursive-readdir](https://github.com/jergason/recursive-readdir) by [Elisée Maurer](https://github.com/elisee) * [:link:](redis/redis.d.ts) [redis](https://github.com/mranney/node_redis) by [Carlos Ballesteros Velasco](https://github.com/soywiz), [Peter Harris](https://github.com/CodeAnimal), [TANAKA Koichi](https://github.com/MugeSo) * [:link:](redlock/redlock.d.ts) [Redlock](https://github.com/mike-marcacci/node-redlock) by [Ilya Mochalov](https://github.com/chrootsu) * [:link:](redux/redux.d.ts) [Redux](https://github.com/rackt/redux) by [William Buchwalter](https://github.com/wbuchwalter), [Vincent Prouillet](https://github.com/Keats) * [:link:](redux-action-utils/redux-action-utils.d.ts) [redux-action-utils](https://github.com/insin/redux-action-utils) by [Qubo](https://github.com/tkqubo) * [:link:](redux-actions/redux-actions.d.ts) [redux-actions](https://github.com/acdlite/redux-actions) by [Jack Hsu](https://github.com/jaysoo) +* [:link:](redux-debounced/redux-debounced.d.ts) [redux-debounced](https://github.com/ryanseddon/redux-debounced) by [Sean Kelley](https://github.com/seansfkelley) * [:link:](redux-devtools/redux-devtools.d.ts) [redux-devtools](https://github.com/gaearon/redux-devtools) by [Petryshyn Sergii](https://github.com/mc-petry) * [:link:](redux-devtools-dock-monitor/redux-devtools-dock-monitor.d.ts) [redux-devtools-dock-monitor](https://github.com/gaearon/redux-devtools-dock-monitor) by [Petryshyn Sergii](https://github.com/mc-petry) * [:link:](redux-devtools-log-monitor/redux-devtools-log-monitor.d.ts) [redux-devtools-log-monitor](https://github.com/gaearon/redux-devtools-log-monitor) by [Petryshyn Sergii](https://github.com/mc-petry) @@ -1427,6 +1480,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](react-scroll/react-scroll.d.ts) [redux-immutable](https://github.com/fisshy/react-scroll) by [Pedro Pereira](https://github.com/oizie) * [:link:](redux-immutable/redux-immutable.d.ts) [redux-immutable](https://github.com/gajus/redux-immutable) by [Pedro Pereira](https://github.com/oizie) * [:link:](redux-logger/redux-logger.d.ts) [redux-logger](https://github.com/fcomb/redux-logger) by [Alexander Rusakov](https://github.com/arusakov) +* [:link:](redux-promise/redux-promise.d.ts) [redux-promise](https://github.com/acdlite/redux-promise) by [Rogelio Morrell Caballero](https://github.com/molekilla) * [:link:](redux-router/redux-router.d.ts) [redux-router](https://github.com/rackt/redux-router) by [Stepan Mikhaylyuk](http://github.com/stepancar) * [:link:](redux-saga/redux-saga.d.ts) [redux-saga](https://github.com/yelouafi/redux-saga) by [Daniel Lytkin](https://github.com/aikoven), [Dimitri Rosenberg](https://github.com/rosendi) * [:link:](redux-thunk/redux-thunk.d.ts) [redux-thunk](https://github.com/gaearon/redux-thunk) by [Qubo](https://github.com/tkqubo) @@ -1443,6 +1497,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](requirejs/require.d.ts) [RequireJS](http://requirejs.org) by [Josh Baldwin](https://github.com/jbaldwin) * [:link:](reselect/reselect.d.ts) [reselect](https://github.com/rackt/reselect) by [Ian Ker-Seymer](https://github.com/ianks) * [:link:](resemblejs/resemblejs.d.ts) [Resemble.js](http://huddle.github.io/Resemble.js) by [Tim Perry](https://github.com/pimterry) +* [:link:](resolve-from/resolve-from.d.ts) [resolve-from](https://github.com/sindresorhus/resolve-from) by [unional](https://github.com/unional) * [:link:](response-time/response-time.d.ts) [response-time](https://github.com/expressjs/response-time) by [Uros Smolnik](https://github.com/urossmolnik) * [:link:](rest-io/rest-io.d.ts) [rest-io](https://github.com/EnoF/rest-io) by [Andy Tang](https://github.com/EnoF), [Stefan Schacherl](https://github.com/TheBay0r) * [:link:](rest/rest.d.ts) [rest.js](https://github.com/cujojs/rest) by [Wim Looman](https://github.com/Nemo157) @@ -1469,6 +1524,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](rtree/rtree.d.ts) [rtree](https://github.com/leaflet-extras/RTree) by [Omede Firouz](https://github.com/oefirouz) * [:link:](run-sequence/run-sequence.d.ts) [run-sequence](https://github.com/OverZealous/run-sequence) by [Keita Kagurazaka](https://github.com/k-kagurazaka) * [:link:](rx/rx.d.ts) [RxJS](http://rx.codeplex.com) by [gsino](http://www.codeplex.com/site/users/view/gsino), [Igor Oleinikov](https://github.com/Igorbek) +* [:link:](rx-dom/rx-dom.d.ts) [RxJS](https://github.com/Reactive-Extensions/RxJS-DOM) by [oliver Weichhold](https://github.com/oliverw) * [:link:](rx/rx.aggregates.d.ts) [RxJS-Aggregates](http://rx.codeplex.com) by [Carl de Billy](http://carl.debilly.net), [Igor Oleinikov](https://github.com/Igorbek) * [:link:](rx/rx.all.d.ts) [RxJS-All](http://rx.codeplex.com) by [Carl de Billy](http://carl.debilly.net), [Igor Oleinikov](https://github.com/Igorbek) * [:link:](rx/rx.async.d.ts) [RxJS-Async](http://rx.codeplex.com) by [zoetrope](https://github.com/zoetrope), [Igor Oleinikov](https://github.com/Igorbek) @@ -1511,8 +1567,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](sentence-case/sentence-case.d.ts) [sentence-case](https://github.com/blakeembrey/sentence-case) by [Sam Saint-Pettersen](https://github.com/stpettersens) * [:link:](sequelize/sequelize.d.ts) [Sequelize](http://sequelizejs.com) by [samuelneff](https://github.com/samuelneff), [Peter Harris](https://github.com/codeanimal), [Ivan Drinchev](https://github.com/drinchev) * [:link:](sequelize-fixtures/sequelize-fixtures.d.ts) [Sequelize-Fixtures](https://github.com/domasx2/sequelize-fixtures) by [Christian Schwarz](https://github.com/cschwarz) -* [:link:](serve-favicon/serve-favicon.d.ts) [serve-favicon](https://github.com/expressjs/serve-favicon) by [Uros Smolnik](https://github.com/urossmolnik) * [:link:](on-headers/on-headers.d.ts) [serve-favicon](https://github.com/jshttp/on-headers) by [John Jeffery](https://github.com/jjeffery) +* [:link:](serve-favicon/serve-favicon.d.ts) [serve-favicon](https://github.com/expressjs/serve-favicon) by [Uros Smolnik](https://github.com/urossmolnik) * [:link:](serve-index/serve-index.d.ts) [serve-index](https://github.com/expressjs/serve-index) by [Tanguy Krotoff](https://github.com/tkrotoff) * [:link:](serve-static/serve-static.d.ts) [serve-static](https://github.com/expressjs/serve-static) by [Uros Smolnik](https://github.com/urossmolnik) * [:link:](ss-utils/ss-utils.d.ts) [ServiceStack Utils](https://servicestack.net) by [Demis Bellot](https://github.com/mythz) @@ -1546,13 +1602,16 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](slickgrid/slick.autotooltips.d.ts) [SlickGrid AutoToolTips Plugin](https://github.com/mleibman/SlickGrid) by [Ryo Iwamoto](https://github.com/ryiwamoto) * [:link:](slickgrid/slick.headerbuttons.d.ts) [SlickGrid HeaderButtons Plugin](https://github.com/mleibman/SlickGrid) by [Derek Cicerone](https://github.com/derekcicerone) * [:link:](slickgrid/slick.rowselectionmodel.d.ts) [SlickGrid RowSelectionModel Plugin](https://github.com/mleibman/SlickGrid) by [Derek Cicerone](https://github.com/derekcicerone) +* [:link:](slideout/slideout.d.ts) [Slideout](https://github.com/mango/slideout) by [Markus Peloso](https://github.com/ToastHawaii) * [:link:](smoothie/smoothie.d.ts) [Smoothie Charts](https://github.com/joewalnes/smoothie) by [Drew Noakes](https://drewnoakes.com), [Mike H. Hawley](https://github.com/mikehhawley) * [:link:](smtpapi/smtpapi.d.ts) [smtpapi-nodejs](https://github.com/sendgrid/smtpapi-nodejs) by [Antonio Morales](https://github.com/a-morales) * [:link:](snake-case/snake-case.d.ts) [snake-case](https://github.com/blakeembrey/snake-case) by [Sam Saint-Pettersen](https://github.com/stpettersens) * [:link:](snapsvg/snapsvg.d.ts) [Snap-SVG](https://github.com/adobe-webplatform/Snap.svg) by [Lars Klein](https://github.com/lhk), [Mattanja Kern](https://github.com/mattanja) * [:link:](soap/soap.d.ts) [soap](https://www.npmjs.com/package/soap) by [Nicole Wang](https://github.com/nicoleWjie) +* [:link:](cordova-plugin-x-socialsharing/cordova-plugin-x-socialsharing.d.ts) [SocialSharing-PhoneGap-Plugin](https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin) by [Markus Wagner](https://github.com/Ritzlgrmft) * [:link:](socket.io/socket.io.d.ts) [socket.io](http://socket.io) by [PROGRE](https://github.com/progre), [Damian Connolly](https://github.com/divillysausages), [Florent Poujol](https://github.com/florentpoujol) * [:link:](socket.io-client/socket.io-client.d.ts) [socket.io-client](http://socket.io) by [PROGRE](https://github.com/progre), [Damian Connolly](https://github.com/divillysausages), [Florent Poujol](https://github.com/florentpoujol) +* [:link:](socket.io-redis/socket.io-redis.d.ts) [socket.io-redis](https://github.com/socketio/socket.io-redis) by [Philipp Holzer](https://github.com/nupplaphil) * [:link:](socket.io.users/socket.io.users.d.ts) [socket.io.users](https://github.com/nodets/socket.io.users) by [Makis Maropoulos](https://github.com/kataras) * [:link:](socketty/socketty.d.ts) [Socketty](https://www.npmjs.com/package/socketty) by [Nax](https://github.com/Nax) * [:link:](sockjs/sockjs.d.ts) [SockJS 0.3.x](https://github.com/sockjs/sockjs-client) by [Emil Ivanov](https://github.com/vladev) @@ -1586,6 +1645,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](steam/steam.d.ts) [steam](https://github.com/seishun/node-steam) by [Andrey Kurdyumov](https://github.com/kant2002) * [:link:](slick-carousel/slick-carousel.d.ts) [stick](http://kenwheeler.github.io/slick) by [John Gouigouix](https://github.com/orchestra-ts/DefinitelyTyped) * [:link:](storejs/storejs.d.ts) [store.js](https://github.com/marcuswestin/store.js) by [Vincent Bortone](https://github.com/vbortone) +* [:link:](stream-meter/stream-meter.d.ts) [stream-meter](https://github.com/brycebaril/node-stream-meter) by [TANAKA Koichi](https://github.com/mugeso) * [:link:](stream-series/stream-series.d.ts) [stream-series](https://github.com/rschmukler/stream-series) by [Keita Kagurazaka](https://github.com/k-kagurazaka) * [:link:](stream-to-array/stream-to-array.d.ts) [stream-to-array](https://github.com/stream-utils/stream-to-array) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](streamjs/streamjs.d.ts) [streamjs](http://winterbe.github.io/streamjs) by [Bence Eros](https://github.com/erosb) @@ -1594,7 +1654,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](strip-json-comments/strip-json-comments.d.ts) [strip-json-comments](https://github.com/sindresorhus/strip-json-comments) by [Dylan R. E. Moonfire](https://github.com/dmoonfire) * [:link:](stripe/stripe.d.ts) [stripe](https://stripe.com) by [Andy Hawkins](https://github.com/a904guy/,http://a904guy.com), [Eric J. Smith](https://github.com/ejsmith), [Amrit Kahlon](https://github.com/amritk) * [:link:](stripe-checkout/stripe-checkout.d.ts) [Stripe Checkout](https://stripe.com/checkout) by [Chris Wrench](https://github.com/cgwrench) -* [:link:](stripe/stripe-node.d.ts) [stripe-node](https://github.com/stripe/stripe-node) by [William Johnston](https://github.com/wjohnsto) +* [:link:](stripe/stripe-node.d.ts) [stripe-node](https://github.com/stripe/stripe-node) by [William Johnston](https://github.com/wjohnsto), [Peter Harris](https://github.com/codeanimal) * [:link:](strophe/strophe.d.ts) [Strophe.js](http://strophe.im/strophejs) by [David Deutsch](https://github.com/DavidKDeutsch) * [:link:](stylus/stylus.d.ts) [stylus](https://github.com/LearnBoost/stylus) by [Maxime LUCE](https://github.com/SomaticIT) * [:link:](sugar/sugar.d.ts) [Sugar](http://sugarjs.com) by [Josh Baldwin](https://github.com/jbaldwin) @@ -1637,6 +1697,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](text-buffer/text-buffer.d.ts) [text-buffer](https://github.com/atom/text-buffer) by [vvakame](https://github.com/vvakame) * [:link:](text-encoding/text-encoding.d.ts) [text-encoding](https://github.com/inexorabletash/text-encoding) by [MIZUNE Pine](https://github.com/pine613) * [:link:](facebook-js-sdk/facebook-js-sdk.d.ts) [the Facebook Javascript SDK](https://developers.facebook.com/docs/javascript) by [Amrit Kahlon](https://github.com/amritk) +* [:link:](facebook-pixel/facebook-pixel.d.ts) [the Facebook Pixel Tag API](https://developers.facebook.com/docs/ads-for-websites/tag-api) by [Noctis Hsu](https://github.com/noctishsu) * [:link:](spotify-api/spotify-api.d.ts) [The Spotify Web API](https://developer.spotify.com/web-api) by [Niels Kristian Hansen Skovmand](https://github.com/skovmand) * [:link:](threejs/three-FirstPersonControls.d.ts) [three.js](http://mrdoob.github.com/three.js) by [Poul Kjeldager Sørensen](https://github.com/s093294) * [:link:](threejs/three-canvasrenderer.d.ts) [three.js (CanvasRenderer.js)](https://github.com/mrdoob/three.js/blob/master/examples/js/renderers/CanvasRenderer.js) by [Satoru Kimura](https://github.com/gyohk) @@ -1655,7 +1716,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](threejs/three-transformcontrols.d.ts) [three.js (TransformControls.js)](https://github.com/mrdoob/three.js/blob/master/examples/js/controls/TransformControls.js) by [Stefan Profanter](https://github.com/Pro) * [:link:](threejs/three-vrcontrols.d.ts) [three.js (VRControls.js)](https://github.com/mrdoob/three.js/blob/master/examples/js/controls/VRControls.js) by [Toshiya Nakakura](https://github.com/nakakura) * [:link:](threejs/three-vreffect.d.ts) [three.js (VREffect.js)](https://github.com/mrdoob/three.js/blob/master/examples/js/effects/VREffect.js) by [Toshiya Nakakura](https://github.com/nakakura) -* [:link:](threejs/three.d.ts) [three.js r73](http://mrdoob.github.com/three.js) by [Kon](http://phyzkit.net), [Satoru Kimura](https://github.com/gyohk) +* [:link:](threejs/three.d.ts) [three.js r75](http://mrdoob.github.com/three.js) by [Kon](http://phyzkit.net), [Satoru Kimura](https://github.com/gyohk), [Florent Poujol](https://github.com/florentpoujol), [SereznoKot](https://github.com/SereznoKot) * [:link:](thrift/thrift.d.ts) [thrift](https://www.npmjs.com/package/thrift) by [Zachary Collins](https://github.com/corps) * [:link:](through/through.d.ts) [through](https://github.com/dominictarr/through) by [Andrew Gaspar](https://github.com/AndrewGaspar) * [:link:](through2/through2.d.ts) [through2 v](https://github.com/rvagg/through2) by [Bart van der Schoor](https://github.com/Bartvds), [jedmao](https://github.com/jedmao), [Georgios Valotasios](https://github.com/valotas) @@ -1684,14 +1745,15 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](twig/twig.d.ts) [twig](https://github.com/justjohn/twig.js) by [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](twitter/twitter.d.ts) [Twitter for Websites](https://dev.twitter.com/web) by [Chitoku](https://github.com/chitoku-k) * [:link:](jquery.bootstrap.wizard/jquery.bootstrap.wizard.d.ts) [twitter-bootstrap-wizard](https://github.com/VinceG/twitter-bootstrap-wizard) by [Blake Niemyjski](https://github.com/niemyjski) +* [:link:](twitter-text/twitter-text.d.ts) [twitter-text](https://github.com/twitter/twitter-text) by [rhysd](https://rhysd.github.io) * [:link:](twix/twix.d.ts) [twix.js](https://github.com/icambron/twix.js) by [j3ko](https://github.com/j3ko) * [:link:](type-check/type-check.d.ts) [type-check](https://github.com/gkz/type-check) by [Hans Windhoff](https://github.com/hansrwindhoff) * [:link:](type-detect/type-detect.d.ts) [type-detect](https://github.com/chaijs/type-detect) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](type-name/type-name.d.ts) [type-name](https://github.com/twada/type-name) by [OKUNOKENTARO](https://github.com/armorik83) * [:link:](typeahead/typeahead.d.ts) [typeahead.js](http://twitter.github.io/typeahead.js) by [Ivaylo Gochkov](https://github.com/igochkov), [Gidon Junge](https://github.com/gjunge) * [:link:](webfontloader/webfontloader.d.ts) [typekit-webfontloader](https://github.com/typekit/webfontloader) by [doskallemaskin](https://github.com/doskallemaskin) -* [:link:](typescript/typescript.d.ts) [TypeScript API](http://www.typescriptlang.org) by [Microsoft TypeScript](http://typescriptlang.org) * [:link:](typescript-services/typescriptServices.d.ts) [TypeScript API](http://www.typescriptlang.org) by [Microsoft TypeScript](http://typescriptlang.org) +* [:link:](typescript/typescript.d.ts) [TypeScript API](http://www.typescriptlang.org) by [Microsoft TypeScript](http://typescriptlang.org) * [:link:](typescript-deferred/typescript-deferred.d.ts) [typescript-deferred](https://github.com/DirtyHairy/typescript-deferred) by [Christian Speckner](https://github.com/DirtyHairy) * [:link:](meteor-persistent-session/meteor-persistent-session.d.ts) [u2622:persistent-session](https://github.com/okgrow/meteor-persistent-session) by [Robbie Van Gorkom](https://github.com/vangorra) * [:link:](ua-parser-js/ua-parser-js.d.ts) [ua-parser-js](https://github.com/faisalman/ua-parser-js) by [Viktor Miroshnikov](https://github.com/superduper), [Lucas Woo](https://github.com/legendecas) @@ -1701,8 +1763,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](ui-router-extras/ui-router-extras.d.ts) [UI-Router Extras (ct.ui.router.extras module)](https://github.com/christopherthielen/ui-router-extras) by [Michael Putters](https://github.com/mputters), [Marcel van de Kamp](https://github.com/marcel-k) * [:link:](ui-select/ui-select.d.ts) [ui-select](https://github.com/angular-ui/ui-select) by [Niko Kovačič](https://github.com/nkovacic) * [:link:](uikit/uikit.d.ts) [uikit](http://getuikit.org) by [Giovanni Silva](https://github.com/giovannicandido) -* [:link:](umbraco/umbraco-services.d.ts) [Umbraco](https://github.com/umbraco) by [DeCareSystemsIreland](https://github.com/DeCareSystemsIreland) * [:link:](umbraco/umbraco-resources.d.ts) [Umbraco](https://github.com/umbraco) by [DeCareSystemsIreland](https://github.com/DeCareSystemsIreland) +* [:link:](umbraco/umbraco-services.d.ts) [Umbraco](https://github.com/umbraco) by [DeCareSystemsIreland](https://github.com/DeCareSystemsIreland) * [:link:](umbraco/umbraco.d.ts) [Umbraco](https://github.com/umbraco) by [DeCareSystemsIreland](https://github.com/DeCareSystemsIreland) * [:link:](umzug/umzug.d.ts) [Umzug](https://github.com/sequelize/umzug) by [Ivan Drinchev](https://github.com/drinchev) * [:link:](underscore/underscore.d.ts) [Underscore](http://underscorejs.org) by [Boris Yankov](https://github.com/borisyankov), [Josh Baldwin](https://github.com/jbaldwin), [Christopher Currens](https://github.com/ccurrens) @@ -1727,6 +1789,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](usage/usage.d.ts) [usage](https://github.com/arunoda/node-usage) by [Pascal Vomhoff](https://github.com/pvomhoff) * [:link:](username/username.d.ts) [username](https://www.npmjs.com/package/username) by [Klaus Reimer](https://github.com/kayahr) * [:link:](utils-merge/utils-merge.d.ts) [utils-merge](https://github.com/jaredhanson/utils-merge) by [Ilya Mochalov](https://github.com/chrootsu) +* [:link:](uuid-1345/uuid-1345.d.ts) [uuid-1345](https://github.com/scravy/uuid-1345) by [TANAKA Koichi](https://github.com/mugeso) * [:link:](uuid/UUID.d.ts) [UUID.js](https://github.com/LiosK/UUID.js) by [Jason Jarrett](https://github.com/staxmanade) * [:link:](valerie/valerie.d.ts) [valerie](https://github.com/davewatts/valerie) by [Howard Richards](https://github.com/conficient) * [:link:](validator/validator.d.ts) [validator.js](https://github.com/chriso/validator.js) by [tgfjt](https://github.com/tgfjt), [Ilya Mochalov](https://github.com/chrootsu) @@ -1753,6 +1816,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](vue/vue.d.ts) [vuejs](https://github.com/vuejs/vue) by [odangosan](https://github.com/odangosan), [kaorun343](https://github.com/kaorun343) * [:link:](w2ui/w2ui.d.ts) [w2ui](http://w2ui.com) by [Valentin Robert](https://github.com/Ptival) * [:link:](wake_on_lan/wake_on_lan.d.ts) [wake_on_lan](https://github.com/agnat/node_wake_on_lan) by [Tobias Kahlert](https://github.com/SrTobi) +* [:link:](wampy/wampy.d.ts) [wampy.js](https://github.com/KSDaemon/wampy.js) by [Konstantin Burkalev](https://github.com/KSDaemon) * [:link:](watch/watch.d.ts) [watch](https://github.com/mikeal/watch) by [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](jquery.watermark/jquery.watermark.d.ts) [Watermark plugin for jQuery](http://jquery-watermark.googlecode.com) by [Anwar Javed](https://github.com/anwarjaved) * [:link:](webaudioapi/waa.d.ts) [Web Audio API](http://www.w3.org/TR/webaudio) by [Baruch Berger](https://github.com/bbss), [Kon](http://phyzkit.net), [kubosho](https://github.com/kubosho) @@ -1775,6 +1839,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](when/when.d.ts) [When](https://github.com/cujojs/when) by [Derek Cicerone](https://github.com/derekcicerone), [Wim Looman](https://github.com/Nemo157) * [:link:](which/which.d.ts) [which](https://github.com/isaacs/node-which) by [vvakame](https://github.com/vvakame) * [:link:](jquery.window/jquery.window.d.ts) [Window plugin for jQuery](http://fstoke.me/jquery/window) by [Ryan Graham](https://github.com/ryan-codingintrigue) +* [:link:](windows-1251/windows-1251.d.ts) [windows-1251](https://github.com/mathiasbynens/windows-1251) by [RomanGolovanov](https://github.com/RomanGolovanov) * [:link:](windows-service/windows-service.d.ts) [windows-service](https://bitbucket.org/stephenwvickers/node-windows-service) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](winjs/winjs.d.ts) [WinJS](http://try.buildwinjs.com) by [TypeScript samples](https://www.typescriptlang.org), [Adam Hewitt](https://github.com/adamhewitt627), [Craig Treasure](https://github.com/craigktreasure), [Jeff Fisher](https://github.com/xirzec) * [:link:](winreg/winreg.d.ts) [Winreg](https://github.com/fresc81/node-winreg) by [RX14](https://github.com/RX14) diff --git a/DataStream.js/DataStream.js-tests.ts b/DataStream.js/DataStream.js-tests.ts index 71bb08537e..733809254b 100644 --- a/DataStream.js/DataStream.js-tests.ts +++ b/DataStream.js/DataStream.js-tests.ts @@ -1,4 +1,4 @@ -/// + var buf = new ArrayBuffer(100); var ds = new DataStream(buf); diff --git a/DataStream.js/DataStream.js.d.ts b/DataStream.js/index.d.ts similarity index 100% rename from DataStream.js/DataStream.js.d.ts rename to DataStream.js/index.d.ts diff --git a/DataStream.js/tsconfig.json b/DataStream.js/tsconfig.json new file mode 100644 index 0000000000..33d822391f --- /dev/null +++ b/DataStream.js/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "DataStream.js-tests.ts" + ] +} \ No newline at end of file diff --git a/FileSaver/FileSaver-tests.ts b/FileSaver/FileSaver-tests.ts index 4cfae373e3..7495a85d8b 100644 --- a/FileSaver/FileSaver-tests.ts +++ b/FileSaver/FileSaver-tests.ts @@ -1,4 +1,4 @@ -/// + /** * @summary Test for "saveAs" function. diff --git a/FileSaver/FileSaver.d.ts b/FileSaver/index.d.ts similarity index 100% rename from FileSaver/FileSaver.d.ts rename to FileSaver/index.d.ts diff --git a/FileSaver/tsconfig.json b/FileSaver/tsconfig.json new file mode 100644 index 0000000000..c96374453b --- /dev/null +++ b/FileSaver/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "FileSaver-tests.ts" + ] +} \ No newline at end of file diff --git a/Finch/Finch-tests.ts b/Finch/Finch-tests.ts index ec15bcb88e..5200d3be10 100644 --- a/Finch/Finch-tests.ts +++ b/Finch/Finch-tests.ts @@ -1,4 +1,4 @@ -/// + function test_Finch() { diff --git a/Finch/Finch.d.ts b/Finch/index.d.ts similarity index 100% rename from Finch/Finch.d.ts rename to Finch/index.d.ts diff --git a/Finch/tsconfig.json b/Finch/tsconfig.json new file mode 100644 index 0000000000..0d67632f25 --- /dev/null +++ b/Finch/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "Finch-tests.ts" + ] +} \ No newline at end of file diff --git a/Headroom/headroom-tests.ts b/Headroom/headroom-tests.ts index e0e83449eb..292406b8ef 100644 --- a/Headroom/headroom-tests.ts +++ b/Headroom/headroom-tests.ts @@ -1,4 +1,4 @@ -/// + new Headroom(document.getElementById('siteHead')); diff --git a/Headroom/headroom.d.ts b/Headroom/index.d.ts similarity index 100% rename from Headroom/headroom.d.ts rename to Headroom/index.d.ts diff --git a/Headroom/tsconfig.json b/Headroom/tsconfig.json new file mode 100644 index 0000000000..7513e87fe9 --- /dev/null +++ b/Headroom/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "Headroom-tests.ts" + ] +} \ No newline at end of file diff --git a/HubSpot-pace/HubSpot-pace-tests.ts b/HubSpot-pace/HubSpot-pace-tests.ts index 1c1daa2a68..034a1e4cc9 100644 --- a/HubSpot-pace/HubSpot-pace-tests.ts +++ b/HubSpot-pace/HubSpot-pace-tests.ts @@ -1,4 +1,4 @@ -/// + pace.start({ document: false diff --git a/HubSpot-pace/HubSpot-pace.d.ts b/HubSpot-pace/index.d.ts similarity index 100% rename from HubSpot-pace/HubSpot-pace.d.ts rename to HubSpot-pace/index.d.ts diff --git a/HubSpot-pace/tsconfig.json b/HubSpot-pace/tsconfig.json new file mode 100644 index 0000000000..2df41bdaf7 --- /dev/null +++ b/HubSpot-pace/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "HubSpot-pace-tests.ts" + ] +} \ No newline at end of file diff --git a/JSONStream/JSONStream-tests.ts b/JSONStream/JSONStream-tests.ts index ea7eb64ff9..00884c8857 100644 --- a/JSONStream/JSONStream-tests.ts +++ b/JSONStream/JSONStream-tests.ts @@ -1,4 +1,3 @@ -/// import json = require('JSONStream'); diff --git a/JSONStream/JSONStream.d.ts b/JSONStream/JSONStream.d.ts deleted file mode 100644 index 029e5b8e9c..0000000000 --- a/JSONStream/JSONStream.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Type definitions for JSONStream v0.8.0 -// Project: http://github.com/dominictarr/JSONStream -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'JSONStream' { - - export interface Options { - recurse: boolean; - } - - export function parse(pattern: any): NodeJS.ReadWriteStream; - export function parse(patterns: any[]): NodeJS.ReadWriteStream; - - export function stringify(): NodeJS.ReadWriteStream; - export function stringify(open: string, sep: string, close: string): NodeJS.ReadWriteStream; - - export function stringifyObject(): NodeJS.ReadWriteStream; - export function stringifyObject(open: string, sep: string, close: string): NodeJS.ReadWriteStream; -} diff --git a/JSONStream/index.d.ts b/JSONStream/index.d.ts new file mode 100644 index 0000000000..f405e284ba --- /dev/null +++ b/JSONStream/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for JSONStream v0.8.0 +// Project: http://github.com/dominictarr/JSONStream +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + + +export interface Options { + recurse: boolean; +} + +export declare function parse(pattern: any): NodeJS.ReadWriteStream; +export declare function parse(patterns: any[]): NodeJS.ReadWriteStream; + +export declare function stringify(): NodeJS.ReadWriteStream; +export declare function stringify(open: string, sep: string, close: string): NodeJS.ReadWriteStream; + +export declare function stringifyObject(): NodeJS.ReadWriteStream; +export declare function stringifyObject(open: string, sep: string, close: string): NodeJS.ReadWriteStream; diff --git a/JSONStream/tsconfig.json b/JSONStream/tsconfig.json new file mode 100644 index 0000000000..3509029bd0 --- /dev/null +++ b/JSONStream/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "JSONStream-tests.ts" + ] +} \ No newline at end of file diff --git a/OpenJsCad/index.d.ts b/OpenJsCad/index.d.ts new file mode 100644 index 0000000000..c6cae5d5cc --- /dev/null +++ b/OpenJsCad/index.d.ts @@ -0,0 +1,917 @@ +// Type definitions for OpenJsCad.js +// Project: https://github.com/joostn/OpenJsCad +// Definitions by: Dan Marshall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace THREE { + var CSG: { + fromCSG: (csg: CSG, defaultColor: any) => { + colorMesh: Mesh; + wireframe: Mesh; + boundLen: number; + }; + getGeometryVertex: (geometry: any, vertex_position: any) => number; + }; + /* + function OrbitControls(object: any, domElement: any): void; + function SpriteCanvasMaterial(parameters?: any): void; + */ + interface ICanvasRendererOptions { + canvas?: HTMLCanvasElement; + alpha?: boolean; + } + /* + class CanvasRenderer implements Renderer { + domElement: HTMLCanvasElement; + private pixelRatio; + private autoClear; + private sortObjects; + private sortElements; + private info; + private _projector; + private _renderData; + private _elements; + private _lights; + private _canvas; + private _canvasWidth; + private _canvasHeight; + private _canvasWidthHalf; + private _canvasHeightHalf; + private _viewportX; + private _viewportY; + private _viewportWidth; + private _viewportHeight; + private _context; + private _clearColor; + private _clearAlpha; + private _contextGlobalAlpha; + private _contextGlobalCompositeOperation; + private _contextStrokeStyle; + private _camera; + private _contextFillStyle; + private _contextLineWidth; + private _contextLineCap; + private _contextLineJoin; + private _contextLineDash; + private _v1; + private _v2; + private _v3; + private _v4; + private _v5; + private _v6; + private _v1x; + private _v1y; + private _v2x; + private _v2y; + private _v3x; + private _v3y; + private _v4x; + private _v4y; + private _v5x; + private _v5y; + private _v6x; + private _v6y; + private _color; + private _color1; + private _color2; + private _color3; + private _color4; + private _diffuseColor; + private _emissiveColor; + private _lightColor; + private _patterns; + private _image; + private _uvs; + private _uv1x; + private _uv1y; + private _uv2x; + private _uv2y; + private _uv3x; + private _uv3y; + private _clipBox; + private _clearBox; + private _elemBox; + private _ambientLight; + private _directionalLights; + private _pointLights; + private _vector3; + private _centroid; + private _normal; + private _normalViewMatrix; + constructor(parameters: ICanvasRendererOptions); + supportsVertexTextures(): void; + setFaceCulling: () => void; + getPixelRatio(): number; + setPixelRatio(value: any): void; + setSize(width: any, height: any, updateStyle: any): void; + setViewport(x: any, y: any, width: any, height: any): void; + setScissor(): void; + enableScissorTest(): void; + setClearColor(color: any, alpha: any): void; + setClearColorHex(hex: any, alpha: any): void; + getClearColor(): Color; + getClearAlpha(): number; + getMaxAnisotropy(): number; + clear(): void; + clearColor(): void; + clearDepth(): void; + clearStencil(): void; + render(scene: Scene, camera: Camera, renderTarget?: RenderTarget, forceClear?: boolean): void; + calculateLights(): void; + calculateLight(position: any, normal: any, color: any): void; + renderSprite(v1: any, element: any, material: any): void; + renderLine(v1: any, v2: any, element: any, material: any): void; + renderFace3(v1: any, v2: any, v3: any, uv1: any, uv2: any, uv3: any, element: any, material: any): void; + drawTriangle(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any): void; + strokePath(color: any, linewidth: any, linecap: any, linejoin: any): void; + fillPath(color: any): void; + onTextureUpdate(event: any): void; + textureToPattern(texture: any): void; + patternPath(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any, u0: any, v0: any, u1: any, v1: any, u2: any, v2: any, texture: any): void; + clipImage(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any, u0: any, v0: any, u1: any, v1: any, u2: any, v2: any, image: any): void; + expand(v1: any, v2: any, pixels: any): void; + setOpacity(value: any): void; + setBlending(value: any): void; + setLineWidth(value: any): void; + setLineCap(value: any): void; + setLineJoin(value: any): void; + setStrokeStyle(value: any): void; + setFillStyle(value: any): void; + setLineDash(value: any): void; + } + function RenderableObject(): void; + function RenderableFace(): void; + function RenderableVertex(): void; + function RenderableLine(): void; + function RenderableSprite(): void; + function Projector(): void; + */ +} +declare namespace OpenJsCad { + interface ILog { + (x: string): void; + prevLogTime?: number; + } + var log: ILog; + interface IViewerOptions { + drawLines?: boolean; + drawFaces?: boolean; + color?: number[]; + bgColor?: number; + noWebGL?: boolean; + } + interface ProcessorOptions extends IViewerOptions { + verbose?: boolean; + viewerwidth?: number; + viewerheight?: number; + viewerheightratio?: number; + } + class Viewer { + private perspective; + private drawOptions; + private size; + private defaultColor_; + private bgColor_; + private containerElm_; + private scene_; + private camera_; + private controls_; + private renderer_; + private canvas; + private pauseRender_; + private requestID_; + constructor(containerElm: any, size: any, options: IViewerOptions); + createScene(drawAxes: any, axLen: any): void; + createCamera(): void; + createControls(canvas: any): void; + webGLAvailable(): boolean; + createRenderer(bool_noWebGL: any): void; + render(): void; + animate(): void; + cancelAnimate(): void; + refreshRenderer(bool_noWebGL: any): void; + drawAxes(axLen: any): void; + setCsg(csg: any, resetZoom: any): void; + applyDrawOptions(): void; + clear(): void; + getUserMeshes(str?: any): THREE.Object3D[]; + resetZoom(r: any): void; + parseSizeParams(): void; + handleResize(): void; + } + function makeAbsoluteUrl(url: any, baseurl: any): any; + function isChrome(): boolean; + function runMainInWorker(mainParameters: any): void; + function expandResultObjectArray(result: any): any; + function checkResult(result: any): void; + function resultToCompactBinary(resultin: any): any; + function resultFromCompactBinary(resultin: any): any; + function parseJsCadScriptSync(script: any, mainParameters: any, debugging: any): any; + function parseJsCadScriptASync(script: any, mainParameters: any, options: any, callback: any): Worker; + function getWindowURL(): URL; + function textToBlobUrl(txt: any): string; + function revokeBlobUrl(url: any): void; + function FileSystemApiErrorHandler(fileError: any, operation: any): void; + function AlertUserOfUncaughtExceptions(): void; + function getParamDefinitions(script: any): any[]; + interface EventHandler { + (ev?: Event): any; + } + /** + * options parameter: + * - drawLines: display wireframe lines + * - drawFaces: display surfaces + * - bgColor: canvas background color + * - color: object color + * - viewerwidth, viewerheight: set rendering size. Works with any css unit. + * viewerheight can also be specified as a ratio to width, ie number e (0, 1] + * - noWebGL: force render without webGL + * - verbose: show additional info (currently only time used for rendering) + */ + interface ViewerSize { + widthDefault: string; + heightDefault: string; + width: number; + height: number; + heightratio: number; + } + class Processor { + private containerdiv; + private options; + private onchange; + private static widthDefault; + private static heightDefault; + private viewerdiv; + private viewer; + private viewerSize; + private processing; + private currentObject; + private hasValidCurrentObject; + private hasOutputFile; + private worker; + private paramDefinitions; + private paramControls; + private script; + private hasError; + private debugging; + private errordiv; + private errorpre; + private statusdiv; + private controldiv; + private statusspan; + private statusbuttons; + private abortbutton; + private renderedElementDropdown; + private formatDropdown; + private generateOutputFileButton; + private downloadOutputFileLink; + private parametersdiv; + private parameterstable; + private currentFormat; + private filename; + private currentObjects; + private currentObjectIndex; + private isFirstRender_; + private outputFileDirEntry; + private outputFileBlobUrl; + constructor(containerdiv: HTMLDivElement, options?: ProcessorOptions, onchange?: EventHandler); + static convertToSolid(obj: any): any; + cleanOption(option: any, deflt: any): any; + toggleDrawOption(str: any): boolean; + setDrawOption(str: any, bool: any): void; + handleResize(): void; + createElements(): void; + getFilenameForRenderedObject(): string; + setRenderedObjects(obj: any): void; + setSelectedObjectIndex(index: number): void; + selectedFormat(): any; + selectedFormatInfo(): any; + updateDownloadLink(): void; + clearViewer(): void; + abort(): void; + enableItems(): void; + setOpenJsCadPath(path: string): void; + addLibrary(lib: any): void; + setError(txt: string): void; + setDebugging(debugging: boolean): void; + setJsCad(script: string, filename?: string): void; + getParamValues(): {}; + rebuildSolid(): void; + hasSolid(): boolean; + isProcessing(): boolean; + clearOutputFile(): void; + generateOutputFile(): void; + currentObjectToBlob(): any; + supportedFormatsForCurrentObject(): string[]; + formatInfo(format: any): any; + downloadLinkTextForCurrentObject(): string; + generateOutputFileBlobUrl(): void; + generateOutputFileFileSystem(): void; + createParamControls(): void; + } +} +interface Window { + Worker: Worker; +// URL: URL; + webkitURL: URL; + requestFileSystem: any; + webkitRequestFileSystem: any; +} +interface IAMFStringOptions { + unit: string; +} +declare class CxG { + toStlString(): string; + toStlBinary(): void; + toAMFString(AMFStringOptions?: IAMFStringOptions): void; + getBounds(): CxG[]; + transform(matrix4x4: CSG.Matrix4x4): CxG; + mirrored(plane: CSG.Plane): CxG; + mirroredX(): CxG; + mirroredY(): CxG; + mirroredZ(): CxG; + translate(v: number[]): CxG; + translate(v: CSG.Vector3D): CxG; + scale(f: CSG.Vector3D): CxG; + rotateX(deg: number): CxG; + rotateY(deg: number): CxG; + rotateZ(deg: number): CxG; + rotate(rotationCenter: CSG.Vector3D, rotationAxis: CSG.Vector3D, degrees: number): CxG; + rotateEulerAngles(alpha: number, beta: number, gamma: number, position: number[]): CxG; +} +interface ICenter { + center(cAxes: string[]): CxG; +} +declare class CSG extends CxG implements ICenter { + polygons: CSG.Polygon[]; + properties: CSG.Properties; + isCanonicalized: boolean; + isRetesselated: boolean; + cachedBoundingBox: CSG.Vector3D[]; + static defaultResolution2D: number; + static defaultResolution3D: number; + static fromPolygons(polygons: CSG.Polygon[]): CSG; + static fromSlices(options: any): CSG; + static fromObject(obj: any): CSG; + static fromCompactBinary(bin: any): CSG; + toPolygons(): CSG.Polygon[]; + union(csg: CSG[]): CSG; + union(csg: CSG): CSG; + unionSub(csg: CSG, retesselate?: boolean, canonicalize?: boolean): CSG; + unionForNonIntersecting(csg: CSG): CSG; + subtract(csg: CSG[]): CSG; + subtract(csg: CSG): CSG; + subtractSub(csg: CSG, retesselate: boolean, canonicalize: boolean): CSG; + intersect(csg: CSG[]): CSG; + intersect(csg: CSG): CSG; + intersectSub(csg: CSG, retesselate?: boolean, canonicalize?: boolean): CSG; + invert(): CSG; + transform1(matrix4x4: CSG.Matrix4x4): CSG; + transform(matrix4x4: CSG.Matrix4x4): CSG; + toString(): string; + expand(radius: number, resolution: number): CSG; + contract(radius: number, resolution: number): CSG; + stretchAtPlane(normal: number[], point: number[], length: number): CSG; + expandedShell(radius: number, resolution: number, unionWithThis: boolean): CSG; + canonicalized(): CSG; + reTesselated(): CSG; + getBounds(): CSG.Vector3D[]; + mayOverlap(csg: CSG): boolean; + cutByPlane(plane: CSG.Plane): CSG; + connectTo(myConnector: CSG.Connector, otherConnector: CSG.Connector, mirror: boolean, normalrotation: number): CSG; + setShared(shared: CSG.Polygon.Shared): CSG; + setColor(args: any): CSG; + toCompactBinary(): { + "class": string; + numPolygons: number; + numVerticesPerPolygon: Uint32Array; + polygonPlaneIndexes: Uint32Array; + polygonSharedIndexes: Uint32Array; + polygonVertices: Uint32Array; + vertexData: Float64Array; + planeData: Float64Array; + shared: CSG.Polygon.Shared[]; + }; + toPointCloud(cuberadius: any): CSG; + getTransformationAndInverseTransformationToFlatLying(): any; + getTransformationToFlatLying(): any; + lieFlat(): CSG; + projectToOrthoNormalBasis(orthobasis: CSG.OrthoNormalBasis): CAG; + sectionCut(orthobasis: CSG.OrthoNormalBasis): CAG; + fixTJunctions(): CSG; + toTriangles(): any[]; + getFeatures(features: any): any; + center(cAxes: string[]): CxG; + toX3D(): Blob; + toStlBinary(): Blob; + toStlString(): string; + toAMFString(m: IAMFStringOptions): Blob; +} +declare namespace CSG { + function fnNumberSort(a: any, b: any): number; + function parseOption(options: any, optionname: any, defaultvalue: any): any; + function parseOptionAs3DVector(options: any, optionname: any, defaultvalue: any): Vector3D; + function parseOptionAs3DVectorList(options: any, optionname: any, defaultvalue: any): any; + function parseOptionAs2DVector(options: any, optionname: any, defaultvalue: any): any; + function parseOptionAsFloat(options: any, optionname: any, defaultvalue: any): any; + function parseOptionAsInt(options: any, optionname: any, defaultvalue: any): any; + function parseOptionAsBool(options: any, optionname: any, defaultvalue: any): any; + function cube(options: any): CSG; + function sphere(options: any): CSG; + function cylinder(options: any): CSG; + function roundedCylinder(options: any): CSG; + function roundedCube(options: any): CSG; + /** + * polyhedron accepts openscad style arguments. I.e. define face vertices clockwise looking from outside + */ + function polyhedron(options: any): CSG; + function IsFloat(n: any): boolean; + function solve2Linear(a: any, b: any, c: any, d: any, u: any, v: any): number[]; + class Vector3D extends CxG { + x: number; + y: number; + z: number; + constructor(v3: Vector3D); + constructor(v2: Vector2D); + constructor(v2: number[]); + constructor(x: number, y: number); + constructor(x: number, y: number, z: number); + static Create(x: number, y: number, z: number): Vector3D; + clone(): Vector3D; + negated(): Vector3D; + abs(): Vector3D; + plus(a: Vector3D): Vector3D; + minus(a: Vector3D): Vector3D; + times(a: number): Vector3D; + dividedBy(a: number): Vector3D; + dot(a: Vector3D): number; + lerp(a: Vector3D, t: number): Vector3D; + lengthSquared(): number; + length(): number; + unit(): Vector3D; + cross(a: Vector3D): Vector3D; + distanceTo(a: Vector3D): number; + distanceToSquared(a: Vector3D): number; + equals(a: Vector3D): boolean; + multiply4x4(matrix4x4: Matrix4x4): Vector3D; + transform(matrix4x4: Matrix4x4): Vector3D; + toString(): string; + randomNonParallelVector(): Vector3D; + min(p: Vector3D): Vector3D; + max(p: Vector3D): Vector3D; + toStlString(): string; + toAMFString(): string; + } + class Vertex extends CxG { + pos: Vector3D; + tag: number; + constructor(pos: Vector3D); + static fromObject(obj: any): Vertex; + flipped(): Vertex; + getTag(): number; + interpolate(other: Vertex, t: number): Vertex; + transform(matrix4x4: Matrix4x4): Vertex; + toString(): string; + toStlString(): string; + toAMFString(): string; + } + class Plane extends CxG { + normal: Vector3D; + w: number; + tag: number; + constructor(normal: Vector3D, w: number); + static fromObject(obj: any): Plane; + static EPSILON: number; + static fromVector3Ds(a: Vector3D, b: Vector3D, c: Vector3D): Plane; + static anyPlaneFromVector3Ds(a: Vector3D, b: Vector3D, c: Vector3D): Plane; + static fromPoints(a: Vector3D, b: Vector3D, c: Vector3D): Plane; + static fromNormalAndPoint(normal: Vector3D, point: Vector3D): Plane; + static fromNormalAndPoint(normal: number[], point: number[]): Plane; + flipped(): Plane; + getTag(): number; + equals(n: Plane): boolean; + transform(matrix4x4: Matrix4x4): Plane; + splitPolygon(polygon: Polygon): { + type: any; + front: any; + back: any; + }; + splitLineBetweenPoints(p1: Vector3D, p2: Vector3D): Vector3D; + intersectWithLine(line3d: Line3D): Vector3D; + intersectWithPlane(plane: Plane): Line3D; + signedDistanceToPoint(point: Vector3D): number; + toString(): string; + mirrorPoint(point3d: Vector3D): Vector3D; + } + class Polygon extends CxG { + vertices: Vertex[]; + shared: Polygon.Shared; + plane: Plane; + cachedBoundingSphere: any; + cachedBoundingBox: Vector3D[]; + static defaultShared: CSG.Polygon.Shared; + constructor(vertices: Vector3D, shared?: Polygon.Shared, plane?: Plane); + constructor(vertices: Vertex[], shared?: Polygon.Shared, plane?: Plane); + static fromObject(obj: any): Polygon; + checkIfConvex(): void; + setColor(args: any): Polygon; + getSignedVolume(): number; + getArea(): number; + getTetraFeatures(features: any): any[]; + extrude(offsetvector: any): CSG; + boundingSphere(): any; + boundingBox(): Vector3D[]; + flipped(): Polygon; + transform(matrix4x4: Matrix4x4): Polygon; + toString(): string; + projectToOrthoNormalBasis(orthobasis: OrthoNormalBasis): CAG; + /** + * Creates solid from slices (CSG.Polygon) by generating walls + * @param {Object} options Solid generating options + * - numslices {Number} Number of slices to be generated + * - callback(t, slice) {Function} Callback function generating slices. + * arguments: t = [0..1], slice = [0..numslices - 1] + * return: CSG.Polygon or null to skip + * - loop {Boolean} no flats, only walls, it's used to generate solids like a tor + */ + solidFromSlices(options: any): CSG; + /** + * + * @param walls Array of wall polygons + * @param bottom Bottom polygon + * @param top Top polygon + */ + private _addWalls(walls, bottom, top, bFlipped); + static verticesConvex(vertices: Vertex[], planenormal: any): boolean; + static createFromPoints(points: number[][], shared?: CSG.Polygon.Shared, plane?: Plane): Polygon; + static isConvexPoint(prevpoint: any, point: any, nextpoint: any, normal: any): boolean; + static isStrictlyConvexPoint(prevpoint: any, point: any, nextpoint: any, normal: any): boolean; + toStlString(): string; + } +} +declare namespace CSG.Polygon { + class Shared { + color: any; + tag: any; + constructor(color: any); + static fromObject(obj: any): Shared; + static fromColor(args: any): Shared; + getTag(): any; + getHash(): any; + } +} +declare namespace CSG { + class PolygonTreeNode { + parent: any; + children: any; + polygon: Polygon; + removed: boolean; + constructor(); + addPolygons(polygons: any): void; + remove(): void; + isRemoved(): boolean; + isRootNode(): boolean; + invert(): void; + getPolygon(): Polygon; + getPolygons(result: Polygon[]): void; + splitByPlane(plane: any, coplanarfrontnodes: any, coplanarbacknodes: any, frontnodes: any, backnodes: any): void; + _splitByPlane(plane: any, coplanarfrontnodes: any, coplanarbacknodes: any, frontnodes: any, backnodes: any): void; + addChild(polygon: Polygon): PolygonTreeNode; + invertSub(): void; + recursivelyInvalidatePolygon(): void; + } + class Tree { + polygonTree: PolygonTreeNode; + rootnode: Node; + constructor(polygons: Polygon[]); + invert(): void; + clipTo(tree: Tree, alsoRemovecoplanarFront?: boolean): void; + allPolygons(): Polygon[]; + addPolygons(polygons: Polygon[]): void; + } + class Node { + parent: Node; + plane: Plane; + front: any; + back: any; + polygontreenodes: PolygonTreeNode[]; + constructor(parent: Node); + invert(): void; + clipPolygons(polygontreenodes: PolygonTreeNode[], alsoRemovecoplanarFront: boolean): void; + clipTo(tree: Tree, alsoRemovecoplanarFront: boolean): void; + addPolygonTreeNodes(polygontreenodes: PolygonTreeNode[]): void; + getParentPlaneNormals(normals: Vector3D[], maxdepth: number): void; + } + class Matrix4x4 { + elements: number[]; + constructor(elements?: number[]); + plus(m: Matrix4x4): Matrix4x4; + minus(m: Matrix4x4): Matrix4x4; + multiply(m: Matrix4x4): Matrix4x4; + clone(): Matrix4x4; + rightMultiply1x3Vector(v: Vector3D): Vector3D; + leftMultiply1x3Vector(v: Vector3D): Vector3D; + rightMultiply1x2Vector(v: Vector2D): Vector2D; + leftMultiply1x2Vector(v: Vector2D): Vector2D; + isMirroring(): boolean; + static unity(): Matrix4x4; + static rotationX(degrees: number): Matrix4x4; + static rotationY(degrees: number): Matrix4x4; + static rotationZ(degrees: number): Matrix4x4; + static rotation(rotationCenter: CSG.Vector3D, rotationAxis: CSG.Vector3D, degrees: number): Matrix4x4; + static translation(v: number[]): Matrix4x4; + static translation(v: Vector3D): Matrix4x4; + static mirroring(plane: Plane): Matrix4x4; + static scaling(v: number[]): Matrix4x4; + static scaling(v: Vector3D): Matrix4x4; + } + class Vector2D extends CxG { + x: number; + y: number; + constructor(x: number, y: number); + constructor(x: number[]); + constructor(x: Vector2D); + static fromAngle(radians: number): Vector2D; + static fromAngleDegrees(degrees: number): Vector2D; + static fromAngleRadians(radians: number): Vector2D; + static Create(x: number, y: number): Vector2D; + toVector3D(z: number): Vector3D; + equals(a: Vector2D): boolean; + clone(): Vector2D; + negated(): Vector2D; + plus(a: Vector2D): Vector2D; + minus(a: Vector2D): Vector2D; + times(a: number): Vector2D; + dividedBy(a: number): Vector2D; + dot(a: Vector2D): number; + lerp(a: Vector2D, t: number): Vector2D; + length(): number; + distanceTo(a: Vector2D): number; + distanceToSquared(a: Vector2D): number; + lengthSquared(): number; + unit(): Vector2D; + cross(a: Vector2D): number; + normal(): Vector2D; + multiply4x4(matrix4x4: Matrix4x4): Vector2D; + transform(matrix4x4: Matrix4x4): Vector2D; + angle(): number; + angleDegrees(): number; + angleRadians(): number; + min(p: Vector2D): Vector2D; + max(p: Vector2D): Vector2D; + toString(): string; + abs(): Vector2D; + } + class Line2D extends CxG { + normal: Vector2D; + w: number; + constructor(normal: Vector2D, w: number); + static fromPoints(p1: Vector2D, p2: Vector2D): Line2D; + reverse(): Line2D; + equals(l: Line2D): boolean; + origin(): Vector2D; + direction(): Vector2D; + xAtY(y: number): number; + absDistanceToPoint(point: Vector2D): number; + intersectWithLine(line2d: Line2D): Vector2D; + transform(matrix4x4: Matrix4x4): Line2D; + } + class Line3D extends CxG { + point: Vector3D; + direction: Vector3D; + constructor(point: Vector3D, direction: Vector3D); + static fromPoints(p1: Vector3D, p2: Vector3D): Line3D; + static fromPlanes(p1: Plane, p2: Plane): Line3D; + intersectWithPlane(plane: Plane): Vector3D; + clone(): Line3D; + reverse(): Line3D; + transform(matrix4x4: Matrix4x4): Line3D; + closestPointOnLine(point: Vector3D): Vector3D; + distanceToPoint(point: Vector3D): number; + equals(line3d: Line3D): boolean; + } + class OrthoNormalBasis extends CxG { + v: Vector3D; + u: Vector3D; + plane: Plane; + planeorigin: Vector3D; + constructor(plane: Plane, rightvector?: Vector3D); + static GetCartesian(xaxisid: string, yaxisid: string): OrthoNormalBasis; + static Z0Plane(): OrthoNormalBasis; + getProjectionMatrix(): Matrix4x4; + getInverseProjectionMatrix(): Matrix4x4; + to2D(vec3: Vector3D): Vector2D; + to3D(vec2: Vector2D): Vector3D; + line3Dto2D(line3d: Line3D): Line2D; + line2Dto3D(line2d: Line2D): Line3D; + transform(matrix4x4: Matrix4x4): OrthoNormalBasis; + } + function interpolateBetween2DPointsForY(point1: Vector2D, point2: Vector2D, y: number): number; + function reTesselateCoplanarPolygons(sourcepolygons: CSG.Polygon[], destpolygons: CSG.Polygon[]): void; + class fuzzyFactory { + multiplier: number; + lookuptable: any; + constructor(numdimensions: number, tolerance: number); + lookupOrCreate(els: any, creatorCallback: any): any; + } + class fuzzyCSGFactory { + vertexfactory: fuzzyFactory; + planefactory: fuzzyFactory; + polygonsharedfactory: any; + constructor(); + getPolygonShared(sourceshared: Polygon.Shared): Polygon.Shared; + getVertex(sourcevertex: Vertex): Vertex; + getPlane(sourceplane: Plane): Plane; + getPolygon(sourcepolygon: Polygon): Polygon; + getCSG(sourcecsg: CSG): CSG; + } + var staticTag: number; + function getTag(): number; + class Properties { + cube: Properties; + center: any; + facecenters: any[]; + roundedCube: Properties; + cylinder: Properties; + start: any; + end: any; + facepointH: any; + facepointH90: any; + sphere: Properties; + facepoint: any; + roundedCylinder: any; + _transform(matrix4x4: Matrix4x4): Properties; + _merge(otherproperties: Properties): Properties; + static transformObj(source: any, result: any, matrix4x4: Matrix4x4): void; + static cloneObj(source: any, result: any): void; + static addFrom(result: any, otherproperties: Properties): void; + } + class Connector extends CxG { + point: Vector3D; + axisvector: Vector3D; + normalvector: Vector3D; + constructor(point: number[], axisvector: Vector3D, normalvector: number[]); + constructor(point: number[], axisvector: number[], normalvector: number[]); + constructor(point: number[], axisvector: number[], normalvector: Vector3D); + constructor(point: Vector3D, axisvector: number[], normalvector: Vector3D); + constructor(point: Vector3D, axisvector: number[], normalvector: number[]); + constructor(point: Vector3D, axisvector: Vector3D, normalvector: Vector3D); + normalized(): Connector; + transform(matrix4x4: Matrix4x4): Connector; + getTransformationTo(other: Connector, mirror: boolean, normalrotation: number): Matrix4x4; + axisLine(): Line3D; + extend(distance: number): Connector; + } + class ConnectorList { + connectors_: Connector[]; + closed: boolean; + constructor(connectors: Connector[]); + static defaultNormal: number[]; + static fromPath2D(path2D: CSG.Path2D, arg1: any, arg2: any): ConnectorList; + static _fromPath2DTangents(path2D: any, start: any, end: any): ConnectorList; + static _fromPath2DExplicit(path2D: any, angleIsh: any): ConnectorList; + setClosed(bool: boolean): void; + appendConnector(conn: Connector): void; + followWith(cagish: any): CSG; + verify(): void; + } + interface IRadiusOptions { + radius?: number; + resolution?: number; + } + interface ICircleOptions extends IRadiusOptions { + center?: Vector2D | number[]; + } + interface IArcOptions extends ICircleOptions { + startangle?: number; + endangle?: number; + maketangent?: boolean; + } + interface IEllpiticalArcOptions extends IRadiusOptions { + clockwise?: boolean; + large?: boolean; + xaxisrotation?: number; + xradius?: number; + yradius?: number; + } + interface IRectangleOptions { + center?: Vector2D; + corner1?: Vector2D; + corner2?: Vector2D; + radius?: Vector2D; + } + interface IRoundRectangleOptions { + roundradius: number; + resolution?: number; + } + class Path2D extends CxG { + closed: boolean; + points: Vector2D[]; + lastBezierControlPoint: Vector2D; + constructor(points: number[], closed?: boolean); + constructor(points: Vector2D[], closed?: boolean); + static arc(options: IArcOptions): Path2D; + concat(otherpath: Path2D): Path2D; + appendPoint(point: Vector2D): Path2D; + appendPoints(points: Vector2D[]): Path2D; + close(): Path2D; + rectangularExtrude(width: number, height: number, resolution: number): CSG; + expandToCAG(pathradius: number, resolution: number): CAG; + innerToCAG(): CAG; + transform(matrix4x4: Matrix4x4): Path2D; + appendBezier(controlpoints: any, options: any): Path2D; + appendArc(endpoint: Vector2D, options: IEllpiticalArcOptions): Path2D; + } +} +declare class CAG extends CxG implements ICenter { + sides: CAG.Side[]; + isCanonicalized: boolean; + constructor(); + static fromSides(sides: CAG.Side[]): CAG; + static fromPoints(points: CSG.Vector2D[]): CAG; + static fromPointsNoCheck(points: CSG.Vector2D[]): CAG; + static fromFakeCSG(csg: CSG): CAG; + static linesIntersect(p0start: CSG.Vector2D, p0end: CSG.Vector2D, p1start: CSG.Vector2D, p1end: CSG.Vector2D): boolean; + static circle(options: CSG.ICircleOptions): CAG; + static rectangle(options: CSG.IRectangleOptions): CAG; + static roundedRectangle(options: any): CAG; + static fromCompactBinary(bin: any): CAG; + toString(): string; + _toCSGWall(z0: any, z1: any): CSG; + _toVector3DPairs(m: CSG.Matrix4x4): CSG.Vector3D[][]; + _toPlanePolygons(options: any): CSG.Polygon[]; + _toWallPolygons(options: any): any[]; + union(cag: CAG[]): CAG; + union(cag: CAG): CAG; + subtract(cag: CAG[]): CAG; + subtract(cag: CAG): CAG; + intersect(cag: CAG[]): CAG; + intersect(cag: CAG): CAG; + transform(matrix4x4: CSG.Matrix4x4): CAG; + area(): number; + flipped(): CAG; + getBounds(): CSG.Vector2D[]; + isSelfIntersecting(): boolean; + expandedShell(radius: number, resolution: number): CAG; + expand(radius: number, resolution: number): CAG; + contract(radius: number, resolution: number): CAG; + extrudeInOrthonormalBasis(orthonormalbasis: CSG.OrthoNormalBasis, depth: number, options?: any): CSG; + extrudeInPlane(axis1: any, axis2: any, depth: any, options: any): CSG; + extrude(options: CAG_extrude_options): CSG; + rotateExtrude(options: any): CSG; + check(): void; + canonicalized(): CAG; + toCompactBinary(): { + 'class': string; + sideVertexIndices: Uint32Array; + vertexData: Float64Array; + }; + getOutlinePaths(): CSG.Path2D[]; + overCutInsideCorners(cutterradius: any): CAG; + center(cAxes: string[]): CxG; + toDxf(): Blob; + static PathsToDxf(paths: CSG.Path2D[]): Blob; +} +declare namespace CAG { + class Vertex { + pos: CSG.Vector2D; + tag: number; + constructor(pos: CSG.Vector2D); + toString(): string; + getTag(): number; + } + class Side extends CxG { + vertex0: Vertex; + vertex1: Vertex; + tag: number; + constructor(vertex0: Vertex, vertex1: Vertex); + static _fromFakePolygon(polygon: CSG.Polygon): Side; + toString(): string; + toPolygon3D(z0: any, z1: any): CSG.Polygon; + transform(matrix4x4: CSG.Matrix4x4): Side; + flipped(): Side; + direction(): CSG.Vector2D; + getTag(): number; + lengthSquared(): number; + length(): number; + } + class fuzzyCAGFactory { + vertexfactory: CSG.fuzzyFactory; + constructor(); + getVertex(sourcevertex: Vertex): Vertex; + getSide(sourceside: Side): Side; + getCAG(sourcecag: CAG): CAG; + } +} +interface CAG_extrude_options { + offset?: number[]; + twistangle?: number; + twiststeps?: number; +} +declare namespace CSG { + class Polygon2D extends CAG { + constructor(points: Vector2D[]); + } +} diff --git a/OpenJsCad/openjscad-tests.ts b/OpenJsCad/openjscad-tests.ts index fd13f0dbb4..60ffefff1e 100644 --- a/OpenJsCad/openjscad-tests.ts +++ b/OpenJsCad/openjscad-tests.ts @@ -1,4 +1,4 @@ -/// + function test() { diff --git a/OpenJsCad/openjscad.d.ts b/OpenJsCad/openjscad.d.ts deleted file mode 100644 index c0bdbdc1f9..0000000000 --- a/OpenJsCad/openjscad.d.ts +++ /dev/null @@ -1,912 +0,0 @@ -// Type definitions for OpenJsCad.js -// Project: https://github.com/joostn/OpenJsCad -// Definitions by: Dan Marshall -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - -declare namespace THREE { - var CSG: { - fromCSG: (csg: CSG, defaultColor: any) => { - colorMesh: Mesh; - wireframe: Mesh; - boundLen: number; - }; - getGeometryVertex: (geometry: any, vertex_position: any) => number; - }; - function OrbitControls(object: any, domElement: any): void; - function SpriteCanvasMaterial(parameters?: any): void; - interface ICanvasRendererOptions { - canvas?: HTMLCanvasElement; - alpha?: boolean; - } - class CanvasRenderer implements Renderer { - domElement: HTMLCanvasElement; - private pixelRatio; - private autoClear; - private sortObjects; - private sortElements; - private info; - private _projector; - private _renderData; - private _elements; - private _lights; - private _canvas; - private _canvasWidth; - private _canvasHeight; - private _canvasWidthHalf; - private _canvasHeightHalf; - private _viewportX; - private _viewportY; - private _viewportWidth; - private _viewportHeight; - private _context; - private _clearColor; - private _clearAlpha; - private _contextGlobalAlpha; - private _contextGlobalCompositeOperation; - private _contextStrokeStyle; - private _camera; - private _contextFillStyle; - private _contextLineWidth; - private _contextLineCap; - private _contextLineJoin; - private _contextLineDash; - private _v1; - private _v2; - private _v3; - private _v4; - private _v5; - private _v6; - private _v1x; - private _v1y; - private _v2x; - private _v2y; - private _v3x; - private _v3y; - private _v4x; - private _v4y; - private _v5x; - private _v5y; - private _v6x; - private _v6y; - private _color; - private _color1; - private _color2; - private _color3; - private _color4; - private _diffuseColor; - private _emissiveColor; - private _lightColor; - private _patterns; - private _image; - private _uvs; - private _uv1x; - private _uv1y; - private _uv2x; - private _uv2y; - private _uv3x; - private _uv3y; - private _clipBox; - private _clearBox; - private _elemBox; - private _ambientLight; - private _directionalLights; - private _pointLights; - private _vector3; - private _centroid; - private _normal; - private _normalViewMatrix; - constructor(parameters: ICanvasRendererOptions); - supportsVertexTextures(): void; - setFaceCulling: () => void; - getPixelRatio(): number; - setPixelRatio(value: any): void; - setSize(width: any, height: any, updateStyle: any): void; - setViewport(x: any, y: any, width: any, height: any): void; - setScissor(): void; - enableScissorTest(): void; - setClearColor(color: any, alpha: any): void; - setClearColorHex(hex: any, alpha: any): void; - getClearColor(): Color; - getClearAlpha(): number; - getMaxAnisotropy(): number; - clear(): void; - clearColor(): void; - clearDepth(): void; - clearStencil(): void; - render(scene: Scene, camera: Camera, renderTarget?: RenderTarget, forceClear?: boolean): void; - calculateLights(): void; - calculateLight(position: any, normal: any, color: any): void; - renderSprite(v1: any, element: any, material: any): void; - renderLine(v1: any, v2: any, element: any, material: any): void; - renderFace3(v1: any, v2: any, v3: any, uv1: any, uv2: any, uv3: any, element: any, material: any): void; - drawTriangle(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any): void; - strokePath(color: any, linewidth: any, linecap: any, linejoin: any): void; - fillPath(color: any): void; - onTextureUpdate(event: any): void; - textureToPattern(texture: any): void; - patternPath(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any, u0: any, v0: any, u1: any, v1: any, u2: any, v2: any, texture: any): void; - clipImage(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any, u0: any, v0: any, u1: any, v1: any, u2: any, v2: any, image: any): void; - expand(v1: any, v2: any, pixels: any): void; - setOpacity(value: any): void; - setBlending(value: any): void; - setLineWidth(value: any): void; - setLineCap(value: any): void; - setLineJoin(value: any): void; - setStrokeStyle(value: any): void; - setFillStyle(value: any): void; - setLineDash(value: any): void; - } - function RenderableObject(): void; - function RenderableFace(): void; - function RenderableVertex(): void; - function RenderableLine(): void; - function RenderableSprite(): void; - function Projector(): void; -} -declare namespace OpenJsCad { - interface ILog { - (x: string): void; - prevLogTime?: number; - } - var log: ILog; - interface IViewerOptions { - drawLines?: boolean; - drawFaces?: boolean; - color?: number[]; - bgColor?: number; - noWebGL?: boolean; - } - interface ProcessorOptions extends IViewerOptions { - verbose?: boolean; - viewerwidth?: number; - viewerheight?: number; - viewerheightratio?: number; - } - class Viewer { - private perspective; - private drawOptions; - private size; - private defaultColor_; - private bgColor_; - private containerElm_; - private scene_; - private camera_; - private controls_; - private renderer_; - private canvas; - private pauseRender_; - private requestID_; - constructor(containerElm: any, size: any, options: IViewerOptions); - createScene(drawAxes: any, axLen: any): void; - createCamera(): void; - createControls(canvas: any): void; - webGLAvailable(): boolean; - createRenderer(bool_noWebGL: any): void; - render(): void; - animate(): void; - cancelAnimate(): void; - refreshRenderer(bool_noWebGL: any): void; - drawAxes(axLen: any): void; - setCsg(csg: any, resetZoom: any): void; - applyDrawOptions(): void; - clear(): void; - getUserMeshes(str?: any): THREE.Object3D[]; - resetZoom(r: any): void; - parseSizeParams(): void; - handleResize(): void; - } - function makeAbsoluteUrl(url: any, baseurl: any): any; - function isChrome(): boolean; - function runMainInWorker(mainParameters: any): void; - function expandResultObjectArray(result: any): any; - function checkResult(result: any): void; - function resultToCompactBinary(resultin: any): any; - function resultFromCompactBinary(resultin: any): any; - function parseJsCadScriptSync(script: any, mainParameters: any, debugging: any): any; - function parseJsCadScriptASync(script: any, mainParameters: any, options: any, callback: any): Worker; - function getWindowURL(): URL; - function textToBlobUrl(txt: any): string; - function revokeBlobUrl(url: any): void; - function FileSystemApiErrorHandler(fileError: any, operation: any): void; - function AlertUserOfUncaughtExceptions(): void; - function getParamDefinitions(script: any): any[]; - interface EventHandler { - (ev?: Event): any; - } - /** - * options parameter: - * - drawLines: display wireframe lines - * - drawFaces: display surfaces - * - bgColor: canvas background color - * - color: object color - * - viewerwidth, viewerheight: set rendering size. Works with any css unit. - * viewerheight can also be specified as a ratio to width, ie number e (0, 1] - * - noWebGL: force render without webGL - * - verbose: show additional info (currently only time used for rendering) - */ - interface ViewerSize { - widthDefault: string; - heightDefault: string; - width: number; - height: number; - heightratio: number; - } - class Processor { - private containerdiv; - private options; - private onchange; - private static widthDefault; - private static heightDefault; - private viewerdiv; - private viewer; - private viewerSize; - private processing; - private currentObject; - private hasValidCurrentObject; - private hasOutputFile; - private worker; - private paramDefinitions; - private paramControls; - private script; - private hasError; - private debugging; - private errordiv; - private errorpre; - private statusdiv; - private controldiv; - private statusspan; - private statusbuttons; - private abortbutton; - private renderedElementDropdown; - private formatDropdown; - private generateOutputFileButton; - private downloadOutputFileLink; - private parametersdiv; - private parameterstable; - private currentFormat; - private filename; - private currentObjects; - private currentObjectIndex; - private isFirstRender_; - private outputFileDirEntry; - private outputFileBlobUrl; - constructor(containerdiv: HTMLDivElement, options?: ProcessorOptions, onchange?: EventHandler); - static convertToSolid(obj: any): any; - cleanOption(option: any, deflt: any): any; - toggleDrawOption(str: any): boolean; - setDrawOption(str: any, bool: any): void; - handleResize(): void; - createElements(): void; - getFilenameForRenderedObject(): string; - setRenderedObjects(obj: any): void; - setSelectedObjectIndex(index: number): void; - selectedFormat(): any; - selectedFormatInfo(): any; - updateDownloadLink(): void; - clearViewer(): void; - abort(): void; - enableItems(): void; - setOpenJsCadPath(path: string): void; - addLibrary(lib: any): void; - setError(txt: string): void; - setDebugging(debugging: boolean): void; - setJsCad(script: string, filename?: string): void; - getParamValues(): {}; - rebuildSolid(): void; - hasSolid(): boolean; - isProcessing(): boolean; - clearOutputFile(): void; - generateOutputFile(): void; - currentObjectToBlob(): any; - supportedFormatsForCurrentObject(): string[]; - formatInfo(format: any): any; - downloadLinkTextForCurrentObject(): string; - generateOutputFileBlobUrl(): void; - generateOutputFileFileSystem(): void; - createParamControls(): void; - } -} -interface Window { - Worker: Worker; -// URL: URL; - webkitURL: URL; - requestFileSystem: any; - webkitRequestFileSystem: any; -} -interface IAMFStringOptions { - unit: string; -} -declare class CxG { - toStlString(): string; - toStlBinary(): void; - toAMFString(AMFStringOptions?: IAMFStringOptions): void; - getBounds(): CxG[]; - transform(matrix4x4: CSG.Matrix4x4): CxG; - mirrored(plane: CSG.Plane): CxG; - mirroredX(): CxG; - mirroredY(): CxG; - mirroredZ(): CxG; - translate(v: number[]): CxG; - translate(v: CSG.Vector3D): CxG; - scale(f: CSG.Vector3D): CxG; - rotateX(deg: number): CxG; - rotateY(deg: number): CxG; - rotateZ(deg: number): CxG; - rotate(rotationCenter: CSG.Vector3D, rotationAxis: CSG.Vector3D, degrees: number): CxG; - rotateEulerAngles(alpha: number, beta: number, gamma: number, position: number[]): CxG; -} -interface ICenter { - center(cAxes: string[]): CxG; -} -declare class CSG extends CxG implements ICenter { - polygons: CSG.Polygon[]; - properties: CSG.Properties; - isCanonicalized: boolean; - isRetesselated: boolean; - cachedBoundingBox: CSG.Vector3D[]; - static defaultResolution2D: number; - static defaultResolution3D: number; - static fromPolygons(polygons: CSG.Polygon[]): CSG; - static fromSlices(options: any): CSG; - static fromObject(obj: any): CSG; - static fromCompactBinary(bin: any): CSG; - toPolygons(): CSG.Polygon[]; - union(csg: CSG[]): CSG; - union(csg: CSG): CSG; - unionSub(csg: CSG, retesselate?: boolean, canonicalize?: boolean): CSG; - unionForNonIntersecting(csg: CSG): CSG; - subtract(csg: CSG[]): CSG; - subtract(csg: CSG): CSG; - subtractSub(csg: CSG, retesselate: boolean, canonicalize: boolean): CSG; - intersect(csg: CSG[]): CSG; - intersect(csg: CSG): CSG; - intersectSub(csg: CSG, retesselate?: boolean, canonicalize?: boolean): CSG; - invert(): CSG; - transform1(matrix4x4: CSG.Matrix4x4): CSG; - transform(matrix4x4: CSG.Matrix4x4): CSG; - toString(): string; - expand(radius: number, resolution: number): CSG; - contract(radius: number, resolution: number): CSG; - stretchAtPlane(normal: number[], point: number[], length: number): CSG; - expandedShell(radius: number, resolution: number, unionWithThis: boolean): CSG; - canonicalized(): CSG; - reTesselated(): CSG; - getBounds(): CSG.Vector3D[]; - mayOverlap(csg: CSG): boolean; - cutByPlane(plane: CSG.Plane): CSG; - connectTo(myConnector: CSG.Connector, otherConnector: CSG.Connector, mirror: boolean, normalrotation: number): CSG; - setShared(shared: CSG.Polygon.Shared): CSG; - setColor(args: any): CSG; - toCompactBinary(): { - "class": string; - numPolygons: number; - numVerticesPerPolygon: Uint32Array; - polygonPlaneIndexes: Uint32Array; - polygonSharedIndexes: Uint32Array; - polygonVertices: Uint32Array; - vertexData: Float64Array; - planeData: Float64Array; - shared: CSG.Polygon.Shared[]; - }; - toPointCloud(cuberadius: any): CSG; - getTransformationAndInverseTransformationToFlatLying(): any; - getTransformationToFlatLying(): any; - lieFlat(): CSG; - projectToOrthoNormalBasis(orthobasis: CSG.OrthoNormalBasis): CAG; - sectionCut(orthobasis: CSG.OrthoNormalBasis): CAG; - fixTJunctions(): CSG; - toTriangles(): any[]; - getFeatures(features: any): any; - center(cAxes: string[]): CxG; - toX3D(): Blob; - toStlBinary(): Blob; - toStlString(): string; - toAMFString(m: IAMFStringOptions): Blob; -} -declare namespace CSG { - function fnNumberSort(a: any, b: any): number; - function parseOption(options: any, optionname: any, defaultvalue: any): any; - function parseOptionAs3DVector(options: any, optionname: any, defaultvalue: any): Vector3D; - function parseOptionAs3DVectorList(options: any, optionname: any, defaultvalue: any): any; - function parseOptionAs2DVector(options: any, optionname: any, defaultvalue: any): any; - function parseOptionAsFloat(options: any, optionname: any, defaultvalue: any): any; - function parseOptionAsInt(options: any, optionname: any, defaultvalue: any): any; - function parseOptionAsBool(options: any, optionname: any, defaultvalue: any): any; - function cube(options: any): CSG; - function sphere(options: any): CSG; - function cylinder(options: any): CSG; - function roundedCylinder(options: any): CSG; - function roundedCube(options: any): CSG; - /** - * polyhedron accepts openscad style arguments. I.e. define face vertices clockwise looking from outside - */ - function polyhedron(options: any): CSG; - function IsFloat(n: any): boolean; - function solve2Linear(a: any, b: any, c: any, d: any, u: any, v: any): number[]; - class Vector3D extends CxG { - x: number; - y: number; - z: number; - constructor(v3: Vector3D); - constructor(v2: Vector2D); - constructor(v2: number[]); - constructor(x: number, y: number); - constructor(x: number, y: number, z: number); - static Create(x: number, y: number, z: number): Vector3D; - clone(): Vector3D; - negated(): Vector3D; - abs(): Vector3D; - plus(a: Vector3D): Vector3D; - minus(a: Vector3D): Vector3D; - times(a: number): Vector3D; - dividedBy(a: number): Vector3D; - dot(a: Vector3D): number; - lerp(a: Vector3D, t: number): Vector3D; - lengthSquared(): number; - length(): number; - unit(): Vector3D; - cross(a: Vector3D): Vector3D; - distanceTo(a: Vector3D): number; - distanceToSquared(a: Vector3D): number; - equals(a: Vector3D): boolean; - multiply4x4(matrix4x4: Matrix4x4): Vector3D; - transform(matrix4x4: Matrix4x4): Vector3D; - toString(): string; - randomNonParallelVector(): Vector3D; - min(p: Vector3D): Vector3D; - max(p: Vector3D): Vector3D; - toStlString(): string; - toAMFString(): string; - } - class Vertex extends CxG { - pos: Vector3D; - tag: number; - constructor(pos: Vector3D); - static fromObject(obj: any): Vertex; - flipped(): Vertex; - getTag(): number; - interpolate(other: Vertex, t: number): Vertex; - transform(matrix4x4: Matrix4x4): Vertex; - toString(): string; - toStlString(): string; - toAMFString(): string; - } - class Plane extends CxG { - normal: Vector3D; - w: number; - tag: number; - constructor(normal: Vector3D, w: number); - static fromObject(obj: any): Plane; - static EPSILON: number; - static fromVector3Ds(a: Vector3D, b: Vector3D, c: Vector3D): Plane; - static anyPlaneFromVector3Ds(a: Vector3D, b: Vector3D, c: Vector3D): Plane; - static fromPoints(a: Vector3D, b: Vector3D, c: Vector3D): Plane; - static fromNormalAndPoint(normal: Vector3D, point: Vector3D): Plane; - static fromNormalAndPoint(normal: number[], point: number[]): Plane; - flipped(): Plane; - getTag(): number; - equals(n: Plane): boolean; - transform(matrix4x4: Matrix4x4): Plane; - splitPolygon(polygon: Polygon): { - type: any; - front: any; - back: any; - }; - splitLineBetweenPoints(p1: Vector3D, p2: Vector3D): Vector3D; - intersectWithLine(line3d: Line3D): Vector3D; - intersectWithPlane(plane: Plane): Line3D; - signedDistanceToPoint(point: Vector3D): number; - toString(): string; - mirrorPoint(point3d: Vector3D): Vector3D; - } - class Polygon extends CxG { - vertices: Vertex[]; - shared: Polygon.Shared; - plane: Plane; - cachedBoundingSphere: any; - cachedBoundingBox: Vector3D[]; - static defaultShared: CSG.Polygon.Shared; - constructor(vertices: Vector3D, shared?: Polygon.Shared, plane?: Plane); - constructor(vertices: Vertex[], shared?: Polygon.Shared, plane?: Plane); - static fromObject(obj: any): Polygon; - checkIfConvex(): void; - setColor(args: any): Polygon; - getSignedVolume(): number; - getArea(): number; - getTetraFeatures(features: any): any[]; - extrude(offsetvector: any): CSG; - boundingSphere(): any; - boundingBox(): Vector3D[]; - flipped(): Polygon; - transform(matrix4x4: Matrix4x4): Polygon; - toString(): string; - projectToOrthoNormalBasis(orthobasis: OrthoNormalBasis): CAG; - /** - * Creates solid from slices (CSG.Polygon) by generating walls - * @param {Object} options Solid generating options - * - numslices {Number} Number of slices to be generated - * - callback(t, slice) {Function} Callback function generating slices. - * arguments: t = [0..1], slice = [0..numslices - 1] - * return: CSG.Polygon or null to skip - * - loop {Boolean} no flats, only walls, it's used to generate solids like a tor - */ - solidFromSlices(options: any): CSG; - /** - * - * @param walls Array of wall polygons - * @param bottom Bottom polygon - * @param top Top polygon - */ - private _addWalls(walls, bottom, top, bFlipped); - static verticesConvex(vertices: Vertex[], planenormal: any): boolean; - static createFromPoints(points: number[][], shared?: CSG.Polygon.Shared, plane?: Plane): Polygon; - static isConvexPoint(prevpoint: any, point: any, nextpoint: any, normal: any): boolean; - static isStrictlyConvexPoint(prevpoint: any, point: any, nextpoint: any, normal: any): boolean; - toStlString(): string; - } -} -declare namespace CSG.Polygon { - class Shared { - color: any; - tag: any; - constructor(color: any); - static fromObject(obj: any): Shared; - static fromColor(args: any): Shared; - getTag(): any; - getHash(): any; - } -} -declare namespace CSG { - class PolygonTreeNode { - parent: any; - children: any; - polygon: Polygon; - removed: boolean; - constructor(); - addPolygons(polygons: any): void; - remove(): void; - isRemoved(): boolean; - isRootNode(): boolean; - invert(): void; - getPolygon(): Polygon; - getPolygons(result: Polygon[]): void; - splitByPlane(plane: any, coplanarfrontnodes: any, coplanarbacknodes: any, frontnodes: any, backnodes: any): void; - _splitByPlane(plane: any, coplanarfrontnodes: any, coplanarbacknodes: any, frontnodes: any, backnodes: any): void; - addChild(polygon: Polygon): PolygonTreeNode; - invertSub(): void; - recursivelyInvalidatePolygon(): void; - } - class Tree { - polygonTree: PolygonTreeNode; - rootnode: Node; - constructor(polygons: Polygon[]); - invert(): void; - clipTo(tree: Tree, alsoRemovecoplanarFront?: boolean): void; - allPolygons(): Polygon[]; - addPolygons(polygons: Polygon[]): void; - } - class Node { - parent: Node; - plane: Plane; - front: any; - back: any; - polygontreenodes: PolygonTreeNode[]; - constructor(parent: Node); - invert(): void; - clipPolygons(polygontreenodes: PolygonTreeNode[], alsoRemovecoplanarFront: boolean): void; - clipTo(tree: Tree, alsoRemovecoplanarFront: boolean): void; - addPolygonTreeNodes(polygontreenodes: PolygonTreeNode[]): void; - getParentPlaneNormals(normals: Vector3D[], maxdepth: number): void; - } - class Matrix4x4 { - elements: number[]; - constructor(elements?: number[]); - plus(m: Matrix4x4): Matrix4x4; - minus(m: Matrix4x4): Matrix4x4; - multiply(m: Matrix4x4): Matrix4x4; - clone(): Matrix4x4; - rightMultiply1x3Vector(v: Vector3D): Vector3D; - leftMultiply1x3Vector(v: Vector3D): Vector3D; - rightMultiply1x2Vector(v: Vector2D): Vector2D; - leftMultiply1x2Vector(v: Vector2D): Vector2D; - isMirroring(): boolean; - static unity(): Matrix4x4; - static rotationX(degrees: number): Matrix4x4; - static rotationY(degrees: number): Matrix4x4; - static rotationZ(degrees: number): Matrix4x4; - static rotation(rotationCenter: CSG.Vector3D, rotationAxis: CSG.Vector3D, degrees: number): Matrix4x4; - static translation(v: number[]): Matrix4x4; - static translation(v: Vector3D): Matrix4x4; - static mirroring(plane: Plane): Matrix4x4; - static scaling(v: number[]): Matrix4x4; - static scaling(v: Vector3D): Matrix4x4; - } - class Vector2D extends CxG { - x: number; - y: number; - constructor(x: number, y: number); - constructor(x: number[]); - constructor(x: Vector2D); - static fromAngle(radians: number): Vector2D; - static fromAngleDegrees(degrees: number): Vector2D; - static fromAngleRadians(radians: number): Vector2D; - static Create(x: number, y: number): Vector2D; - toVector3D(z: number): Vector3D; - equals(a: Vector2D): boolean; - clone(): Vector2D; - negated(): Vector2D; - plus(a: Vector2D): Vector2D; - minus(a: Vector2D): Vector2D; - times(a: number): Vector2D; - dividedBy(a: number): Vector2D; - dot(a: Vector2D): number; - lerp(a: Vector2D, t: number): Vector2D; - length(): number; - distanceTo(a: Vector2D): number; - distanceToSquared(a: Vector2D): number; - lengthSquared(): number; - unit(): Vector2D; - cross(a: Vector2D): number; - normal(): Vector2D; - multiply4x4(matrix4x4: Matrix4x4): Vector2D; - transform(matrix4x4: Matrix4x4): Vector2D; - angle(): number; - angleDegrees(): number; - angleRadians(): number; - min(p: Vector2D): Vector2D; - max(p: Vector2D): Vector2D; - toString(): string; - abs(): Vector2D; - } - class Line2D extends CxG { - normal: Vector2D; - w: number; - constructor(normal: Vector2D, w: number); - static fromPoints(p1: Vector2D, p2: Vector2D): Line2D; - reverse(): Line2D; - equals(l: Line2D): boolean; - origin(): Vector2D; - direction(): Vector2D; - xAtY(y: number): number; - absDistanceToPoint(point: Vector2D): number; - intersectWithLine(line2d: Line2D): Vector2D; - transform(matrix4x4: Matrix4x4): Line2D; - } - class Line3D extends CxG { - point: Vector3D; - direction: Vector3D; - constructor(point: Vector3D, direction: Vector3D); - static fromPoints(p1: Vector3D, p2: Vector3D): Line3D; - static fromPlanes(p1: Plane, p2: Plane): Line3D; - intersectWithPlane(plane: Plane): Vector3D; - clone(): Line3D; - reverse(): Line3D; - transform(matrix4x4: Matrix4x4): Line3D; - closestPointOnLine(point: Vector3D): Vector3D; - distanceToPoint(point: Vector3D): number; - equals(line3d: Line3D): boolean; - } - class OrthoNormalBasis extends CxG { - v: Vector3D; - u: Vector3D; - plane: Plane; - planeorigin: Vector3D; - constructor(plane: Plane, rightvector?: Vector3D); - static GetCartesian(xaxisid: string, yaxisid: string): OrthoNormalBasis; - static Z0Plane(): OrthoNormalBasis; - getProjectionMatrix(): Matrix4x4; - getInverseProjectionMatrix(): Matrix4x4; - to2D(vec3: Vector3D): Vector2D; - to3D(vec2: Vector2D): Vector3D; - line3Dto2D(line3d: Line3D): Line2D; - line2Dto3D(line2d: Line2D): Line3D; - transform(matrix4x4: Matrix4x4): OrthoNormalBasis; - } - function interpolateBetween2DPointsForY(point1: Vector2D, point2: Vector2D, y: number): number; - function reTesselateCoplanarPolygons(sourcepolygons: CSG.Polygon[], destpolygons: CSG.Polygon[]): void; - class fuzzyFactory { - multiplier: number; - lookuptable: any; - constructor(numdimensions: number, tolerance: number); - lookupOrCreate(els: any, creatorCallback: any): any; - } - class fuzzyCSGFactory { - vertexfactory: fuzzyFactory; - planefactory: fuzzyFactory; - polygonsharedfactory: any; - constructor(); - getPolygonShared(sourceshared: Polygon.Shared): Polygon.Shared; - getVertex(sourcevertex: Vertex): Vertex; - getPlane(sourceplane: Plane): Plane; - getPolygon(sourcepolygon: Polygon): Polygon; - getCSG(sourcecsg: CSG): CSG; - } - var staticTag: number; - function getTag(): number; - class Properties { - cube: Properties; - center: any; - facecenters: any[]; - roundedCube: Properties; - cylinder: Properties; - start: any; - end: any; - facepointH: any; - facepointH90: any; - sphere: Properties; - facepoint: any; - roundedCylinder: any; - _transform(matrix4x4: Matrix4x4): Properties; - _merge(otherproperties: Properties): Properties; - static transformObj(source: any, result: any, matrix4x4: Matrix4x4): void; - static cloneObj(source: any, result: any): void; - static addFrom(result: any, otherproperties: Properties): void; - } - class Connector extends CxG { - point: Vector3D; - axisvector: Vector3D; - normalvector: Vector3D; - constructor(point: number[], axisvector: Vector3D, normalvector: number[]); - constructor(point: number[], axisvector: number[], normalvector: number[]); - constructor(point: number[], axisvector: number[], normalvector: Vector3D); - constructor(point: Vector3D, axisvector: number[], normalvector: Vector3D); - constructor(point: Vector3D, axisvector: number[], normalvector: number[]); - constructor(point: Vector3D, axisvector: Vector3D, normalvector: Vector3D); - normalized(): Connector; - transform(matrix4x4: Matrix4x4): Connector; - getTransformationTo(other: Connector, mirror: boolean, normalrotation: number): Matrix4x4; - axisLine(): Line3D; - extend(distance: number): Connector; - } - class ConnectorList { - connectors_: Connector[]; - closed: boolean; - constructor(connectors: Connector[]); - static defaultNormal: number[]; - static fromPath2D(path2D: CSG.Path2D, arg1: any, arg2: any): ConnectorList; - static _fromPath2DTangents(path2D: any, start: any, end: any): ConnectorList; - static _fromPath2DExplicit(path2D: any, angleIsh: any): ConnectorList; - setClosed(bool: boolean): void; - appendConnector(conn: Connector): void; - followWith(cagish: any): CSG; - verify(): void; - } - interface IRadiusOptions { - radius?: number; - resolution?: number; - } - interface ICircleOptions extends IRadiusOptions { - center?: Vector2D | number[]; - } - interface IArcOptions extends ICircleOptions { - startangle?: number; - endangle?: number; - maketangent?: boolean; - } - interface IEllpiticalArcOptions extends IRadiusOptions { - clockwise?: boolean; - large?: boolean; - xaxisrotation?: number; - xradius?: number; - yradius?: number; - } - interface IRectangleOptions { - center?: Vector2D; - corner1?: Vector2D; - corner2?: Vector2D; - radius?: Vector2D; - } - interface IRoundRectangleOptions { - roundradius: number; - resolution?: number; - } - class Path2D extends CxG { - closed: boolean; - points: Vector2D[]; - lastBezierControlPoint: Vector2D; - constructor(points: number[], closed?: boolean); - constructor(points: Vector2D[], closed?: boolean); - static arc(options: IArcOptions): Path2D; - concat(otherpath: Path2D): Path2D; - appendPoint(point: Vector2D): Path2D; - appendPoints(points: Vector2D[]): Path2D; - close(): Path2D; - rectangularExtrude(width: number, height: number, resolution: number): CSG; - expandToCAG(pathradius: number, resolution: number): CAG; - innerToCAG(): CAG; - transform(matrix4x4: Matrix4x4): Path2D; - appendBezier(controlpoints: any, options: any): Path2D; - appendArc(endpoint: Vector2D, options: IEllpiticalArcOptions): Path2D; - } -} -declare class CAG extends CxG implements ICenter { - sides: CAG.Side[]; - isCanonicalized: boolean; - constructor(); - static fromSides(sides: CAG.Side[]): CAG; - static fromPoints(points: CSG.Vector2D[]): CAG; - static fromPointsNoCheck(points: CSG.Vector2D[]): CAG; - static fromFakeCSG(csg: CSG): CAG; - static linesIntersect(p0start: CSG.Vector2D, p0end: CSG.Vector2D, p1start: CSG.Vector2D, p1end: CSG.Vector2D): boolean; - static circle(options: CSG.ICircleOptions): CAG; - static rectangle(options: CSG.IRectangleOptions): CAG; - static roundedRectangle(options: any): CAG; - static fromCompactBinary(bin: any): CAG; - toString(): string; - _toCSGWall(z0: any, z1: any): CSG; - _toVector3DPairs(m: CSG.Matrix4x4): CSG.Vector3D[][]; - _toPlanePolygons(options: any): CSG.Polygon[]; - _toWallPolygons(options: any): any[]; - union(cag: CAG[]): CAG; - union(cag: CAG): CAG; - subtract(cag: CAG[]): CAG; - subtract(cag: CAG): CAG; - intersect(cag: CAG[]): CAG; - intersect(cag: CAG): CAG; - transform(matrix4x4: CSG.Matrix4x4): CAG; - area(): number; - flipped(): CAG; - getBounds(): CSG.Vector2D[]; - isSelfIntersecting(): boolean; - expandedShell(radius: number, resolution: number): CAG; - expand(radius: number, resolution: number): CAG; - contract(radius: number, resolution: number): CAG; - extrudeInOrthonormalBasis(orthonormalbasis: CSG.OrthoNormalBasis, depth: number, options?: any): CSG; - extrudeInPlane(axis1: any, axis2: any, depth: any, options: any): CSG; - extrude(options: CAG_extrude_options): CSG; - rotateExtrude(options: any): CSG; - check(): void; - canonicalized(): CAG; - toCompactBinary(): { - 'class': string; - sideVertexIndices: Uint32Array; - vertexData: Float64Array; - }; - getOutlinePaths(): CSG.Path2D[]; - overCutInsideCorners(cutterradius: any): CAG; - center(cAxes: string[]): CxG; - toDxf(): Blob; - static PathsToDxf(paths: CSG.Path2D[]): Blob; -} -declare namespace CAG { - class Vertex { - pos: CSG.Vector2D; - tag: number; - constructor(pos: CSG.Vector2D); - toString(): string; - getTag(): number; - } - class Side extends CxG { - vertex0: Vertex; - vertex1: Vertex; - tag: number; - constructor(vertex0: Vertex, vertex1: Vertex); - static _fromFakePolygon(polygon: CSG.Polygon): Side; - toString(): string; - toPolygon3D(z0: any, z1: any): CSG.Polygon; - transform(matrix4x4: CSG.Matrix4x4): Side; - flipped(): Side; - direction(): CSG.Vector2D; - getTag(): number; - lengthSquared(): number; - length(): number; - } - class fuzzyCAGFactory { - vertexfactory: CSG.fuzzyFactory; - constructor(); - getVertex(sourcevertex: Vertex): Vertex; - getSide(sourceside: Side): Side; - getCAG(sourcecag: CAG): CAG; - } -} -interface CAG_extrude_options { - offset?: number[]; - twistangle?: number; - twiststeps?: number; -} -declare namespace CSG { - class Polygon2D extends CAG { - constructor(points: Vector2D[]); - } -} diff --git a/OpenJsCad/tsconfig.json b/OpenJsCad/tsconfig.json new file mode 100644 index 0000000000..bce64cbc97 --- /dev/null +++ b/OpenJsCad/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "OpenJsCad-tests.ts" + ] +} \ No newline at end of file diff --git a/PayPal-Cordova-Plugin/PayPal-Cordova-Plugin-tests.ts b/PayPal-Cordova-Plugin/PayPal-Cordova-Plugin-tests.ts index dca1f93120..e83b94ea5b 100644 --- a/PayPal-Cordova-Plugin/PayPal-Cordova-Plugin-tests.ts +++ b/PayPal-Cordova-Plugin/PayPal-Cordova-Plugin-tests.ts @@ -1,6 +1,3 @@ - -/// - var item: PayPalItem; item = new PayPalItem("name", 10, "25.00", "USD"); item = new PayPalItem("name", 10, "25.00", "USD", null); diff --git a/PayPal-Cordova-Plugin/PayPal-Cordova-Plugin.d.ts b/PayPal-Cordova-Plugin/index.d.ts similarity index 100% rename from PayPal-Cordova-Plugin/PayPal-Cordova-Plugin.d.ts rename to PayPal-Cordova-Plugin/index.d.ts diff --git a/PayPal-Cordova-Plugin/tsconfig.json b/PayPal-Cordova-Plugin/tsconfig.json new file mode 100644 index 0000000000..1cd4daf266 --- /dev/null +++ b/PayPal-Cordova-Plugin/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "PayPal-Cordova-Plugin-tests.ts" + ] +} \ No newline at end of file diff --git a/_debugger/_debugger-tests.ts b/_debugger/_debugger-tests.ts index e6d7cf9980..a44777bd9e 100644 --- a/_debugger/_debugger-tests.ts +++ b/_debugger/_debugger-tests.ts @@ -1,4 +1,3 @@ -/// import _debugger = require("_debugger"); var {Client} = _debugger; diff --git a/_debugger/_debugger.d.ts b/_debugger/_debugger.d.ts deleted file mode 100644 index 14bf5d49c7..0000000000 --- a/_debugger/_debugger.d.ts +++ /dev/null @@ -1,135 +0,0 @@ -// Type definitions for Node.js debugger API -// Project: http://nodejs.org/ -// Definitions by: Basarat Ali Syed -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace NodeJS { - export module _debugger { - export interface Packet { - raw: string; - headers: string[]; - body: Message; - } - - export interface Message { - seq: number; - type: string; - } - - export interface RequestInfo { - command: string; - arguments: any; - } - - export interface Request extends Message, RequestInfo { - } - - export interface Event extends Message { - event: string; - body?: any; - } - - export interface Response extends Message { - request_seq: number; - success: boolean; - /** Contains error message if success === false. */ - message?: string; - /** Contains message body if success === true. */ - body?: any; - } - - export interface BreakpointMessageBody { - type: string; - target: number; - line: number; - } - - export class Protocol { - res: Packet; - state: string; - execute(data: string): void; - serialize(rq: Request): string; - onResponse: (pkt: Packet) => void; - } - - export var NO_FRAME: number; - export var port: number; - - export interface ScriptDesc { - name: string; - id: number; - isNative?: boolean; - handle?: number; - type: string; - lineOffset?: number; - columnOffset?: number; - lineCount?: number; - } - - export interface Breakpoint { - id: number; - scriptId: number; - script: ScriptDesc; - line: number; - condition?: string; - scriptReq?: string; - } - - export interface RequestHandler { - (err: boolean, body: Message, res: Packet): void; - request_seq?: number; - } - - export interface ResponseBodyHandler { - (err: boolean, body?: any): void; - request_seq?: number; - } - - export interface ExceptionInfo { - text: string; - } - - export interface BreakResponse { - script?: ScriptDesc; - exception?: ExceptionInfo; - sourceLine: number; - sourceLineText: string; - sourceColumn: number; - } - - export function SourceInfo(body: BreakResponse): string; - - export interface ClientInstance extends EventEmitter { - protocol: Protocol; - scripts: ScriptDesc[]; - handles: ScriptDesc[]; - breakpoints: Breakpoint[]; - currentSourceLine: number; - currentSourceColumn: number; - currentSourceLineText: string; - currentFrame: number; - currentScript: string; - - connect(port: number, host: string): void; - req(req: any, cb: RequestHandler): void; - reqFrameEval(code: string, frame: number, cb: RequestHandler): void; - mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void; - setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void; - clearBreakpoint(rq: Request, cb: RequestHandler): void; - listbreakpoints(cb: RequestHandler): void; - reqSource(from: number, to: number, cb: RequestHandler): void; - reqScripts(cb: any): void; - reqContinue(cb: RequestHandler): void; - } - - export var Client : { - new (): ClientInstance - } - } -} - -declare module "_debugger"{ - export = NodeJS._debugger; -} diff --git a/_debugger/index.d.ts b/_debugger/index.d.ts new file mode 100644 index 0000000000..324a875eba --- /dev/null +++ b/_debugger/index.d.ts @@ -0,0 +1,135 @@ +// Type definitions for Node.js debugger API +// Project: http://nodejs.org/ +// Definitions by: Basarat Ali Syed +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace NodeJS { + export module _debugger { + export interface Packet { + raw: string; + headers: string[]; + body: Message; + } + + export interface Message { + seq: number; + type: string; + } + + export interface RequestInfo { + command: string; + arguments: any; + } + + export interface Request extends Message, RequestInfo { + } + + export interface Event extends Message { + event: string; + body?: any; + } + + export interface Response extends Message { + request_seq: number; + success: boolean; + /** Contains error message if success === false. */ + message?: string; + /** Contains message body if success === true. */ + body?: any; + } + + export interface BreakpointMessageBody { + type: string; + target: number; + line: number; + } + + export class Protocol { + res: Packet; + state: string; + execute(data: string): void; + serialize(rq: Request): string; + onResponse: (pkt: Packet) => void; + } + + export var NO_FRAME: number; + export var port: number; + + export interface ScriptDesc { + name: string; + id: number; + isNative?: boolean; + handle?: number; + type: string; + lineOffset?: number; + columnOffset?: number; + lineCount?: number; + } + + export interface Breakpoint { + id: number; + scriptId: number; + script: ScriptDesc; + line: number; + condition?: string; + scriptReq?: string; + } + + export interface RequestHandler { + (err: boolean, body: Message, res: Packet): void; + request_seq?: number; + } + + export interface ResponseBodyHandler { + (err: boolean, body?: any): void; + request_seq?: number; + } + + export interface ExceptionInfo { + text: string; + } + + export interface BreakResponse { + script?: ScriptDesc; + exception?: ExceptionInfo; + sourceLine: number; + sourceLineText: string; + sourceColumn: number; + } + + export function SourceInfo(body: BreakResponse): string; + + export interface ClientInstance extends EventEmitter { + protocol: Protocol; + scripts: ScriptDesc[]; + handles: ScriptDesc[]; + breakpoints: Breakpoint[]; + currentSourceLine: number; + currentSourceColumn: number; + currentSourceLineText: string; + currentFrame: number; + currentScript: string; + + connect(port: number, host: string): void; + req(req: any, cb: RequestHandler): void; + reqFrameEval(code: string, frame: number, cb: RequestHandler): void; + mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void; + setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void; + clearBreakpoint(rq: Request, cb: RequestHandler): void; + listbreakpoints(cb: RequestHandler): void; + reqSource(from: number, to: number, cb: RequestHandler): void; + reqScripts(cb: any): void; + reqContinue(cb: RequestHandler): void; + } + + export var Client : { + new (): ClientInstance + } + } +} + +declare module "_debugger"{ + export = NodeJS._debugger; +} diff --git a/_debugger/tsconfig.json b/_debugger/tsconfig.json new file mode 100644 index 0000000000..be1ad95ec4 --- /dev/null +++ b/_debugger/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "_debugger-tests.ts" + ] +} \ No newline at end of file diff --git a/abs/abs-tests.ts b/abs/abs-tests.ts index 80f52f8ffd..45445bbbb6 100644 --- a/abs/abs-tests.ts +++ b/abs/abs-tests.ts @@ -1,5 +1,3 @@ -/// - import Abs from 'abs'; const x: string = Abs('/foo'); diff --git a/abs/abs.d.ts b/abs/abs.d.ts deleted file mode 100644 index 58a5335283..0000000000 --- a/abs/abs.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Type definitions for abs 1.1.0 -// Project: https://github.com/IonicaBizau/node-abs -// Definitions by: Aya Morisawa -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "abs" { - /** - * Compute the absolute path of an input. - * @param input The input path. - */ - function Abs(input: string): string; - - export default Abs; -} diff --git a/abs/index.d.ts b/abs/index.d.ts new file mode 100644 index 0000000000..b5182da9e6 --- /dev/null +++ b/abs/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for abs 1.1.0 +// Project: https://github.com/IonicaBizau/node-abs +// Definitions by: Aya Morisawa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/** + * Compute the absolute path of an input. + * @param input The input path. + */ +declare function Abs(input: string): string; + +export default Abs; diff --git a/abs/tsconfig.json b/abs/tsconfig.json new file mode 100644 index 0000000000..2f5b6004be --- /dev/null +++ b/abs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "abs-tests.ts" + ] +} \ No newline at end of file diff --git a/absolute/absolute-tests.ts b/absolute/absolute-tests.ts index 5c2514450a..b2eceda474 100644 --- a/absolute/absolute-tests.ts +++ b/absolute/absolute-tests.ts @@ -1,4 +1,3 @@ -/// import absolute from 'absolute'; diff --git a/absolute/absolute.d.ts b/absolute/absolute.d.ts deleted file mode 100644 index c0e8e9bd6e..0000000000 --- a/absolute/absolute.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Type definitions for absolute 0.0.1 -// Project: https://github.com/bahamas10/node-absolute -// Definitions by: Aya Morisawa -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "absolute" { - /** - * Test if a path is absolute - */ - function absolute(path: string): boolean; - - export default absolute; -} diff --git a/absolute/index.d.ts b/absolute/index.d.ts new file mode 100644 index 0000000000..acbcddfc4a --- /dev/null +++ b/absolute/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for absolute 0.0.1 +// Project: https://github.com/bahamas10/node-absolute +// Definitions by: Aya Morisawa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Test if a path is absolute + */ +declare function absolute(path: string): boolean; + +export default absolute; diff --git a/absolute/tsconfig.json b/absolute/tsconfig.json new file mode 100644 index 0000000000..b82b939f49 --- /dev/null +++ b/absolute/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "absolute-tests.ts" + ] +} \ No newline at end of file diff --git a/acc-wizard/acc-wizard-tests.ts b/acc-wizard/acc-wizard-tests.ts index 9cf089b44a..74f8df765a 100644 --- a/acc-wizard/acc-wizard-tests.ts +++ b/acc-wizard/acc-wizard-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + /** * @summary Test for "accwizard" without options. diff --git a/acc-wizard/acc-wizard.d.ts b/acc-wizard/index.d.ts similarity index 100% rename from acc-wizard/acc-wizard.d.ts rename to acc-wizard/index.d.ts diff --git a/acc-wizard/tsconfig.json b/acc-wizard/tsconfig.json new file mode 100644 index 0000000000..425a39e6b6 --- /dev/null +++ b/acc-wizard/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "acc-wizard-tests.ts" + ] +} \ No newline at end of file diff --git a/accounting/accounting-tests.ts b/accounting/accounting-tests.ts index bc9b74eaad..eff00e33b9 100644 --- a/accounting/accounting-tests.ts +++ b/accounting/accounting-tests.ts @@ -1,6 +1,4 @@ -/// - -// formatMoney +// formatMoney // Default usage: accounting.formatMoney(12345678); // $12,345,678.00 diff --git a/accounting/accounting.d.ts b/accounting/index.d.ts similarity index 100% rename from accounting/accounting.d.ts rename to accounting/index.d.ts diff --git a/accounting/tsconfig.json b/accounting/tsconfig.json new file mode 100644 index 0000000000..69ee4cf52f --- /dev/null +++ b/accounting/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "accounting-tests.ts" + ] +} \ No newline at end of file diff --git a/ace/all-tests.ts b/ace/all-tests.ts index 80717ac5da..7a7ef50a75 100644 --- a/ace/all-tests.ts +++ b/ace/all-tests.ts @@ -1,9 +1,9 @@ -/// + var exports: any; var assert: any; -var MockRenderer = null; -var JavaScriptMode = null; +var MockRenderer: any = null; +var JavaScriptMode: any = null; /// /// diff --git a/ace/all-tests.ts.tscparams b/ace/all-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/all-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/ace.d.ts b/ace/index.d.ts similarity index 100% rename from ace/ace.d.ts rename to ace/index.d.ts diff --git a/ace/tests/ace-anchor-tests.ts b/ace/tests/ace-anchor-tests.ts index 08ca8f43fc..2cec45ce1d 100644 --- a/ace/tests/ace-anchor-tests.ts +++ b/ace/tests/ace-anchor-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var exports = { diff --git a/ace/tests/ace-anchor-tests.ts.tscparams b/ace/tests/ace-anchor-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-anchor-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-background_tokenizer-tests.ts b/ace/tests/ace-background_tokenizer-tests.ts index 8f54bae51c..b77a9e0072 100644 --- a/ace/tests/ace-background_tokenizer-tests.ts +++ b/ace/tests/ace-background_tokenizer-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; diff --git a/ace/tests/ace-background_tokenizer-tests.ts.tscparams b/ace/tests/ace-background_tokenizer-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-background_tokenizer-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-default-tests.ts b/ace/tests/ace-default-tests.ts index f8a280c1a2..eed0e42c5b 100644 --- a/ace/tests/ace-default-tests.ts +++ b/ace/tests/ace-default-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var editor = ace.edit("editor"); diff --git a/ace/tests/ace-default-tests.ts.tscparams b/ace/tests/ace-default-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-default-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-document-tests.ts b/ace/tests/ace-document-tests.ts index 7fc342f746..8760717d61 100644 --- a/ace/tests/ace-document-tests.ts +++ b/ace/tests/ace-document-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var exports = { diff --git a/ace/tests/ace-document-tests.ts.tscparams b/ace/tests/ace-document-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-document-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-edit_session-tests.ts b/ace/tests/ace-edit_session-tests.ts index caa2f1729a..c057cb1297 100644 --- a/ace/tests/ace-edit_session-tests.ts +++ b/ace/tests/ace-edit_session-tests.ts @@ -1,4 +1,4 @@ -/// + var lang: any; var assert: any; diff --git a/ace/tests/ace-edit_session-tests.ts.tscparams b/ace/tests/ace-edit_session-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-edit_session-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-editor1-tests.ts b/ace/tests/ace-editor1-tests.ts index 78d3aff044..c14d344dae 100644 --- a/ace/tests/ace-editor1-tests.ts +++ b/ace/tests/ace-editor1-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var exports = { diff --git a/ace/tests/ace-editor1-tests.ts.tscparams b/ace/tests/ace-editor1-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-editor1-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-editor_highlight_selected_word-tests.ts b/ace/tests/ace-editor_highlight_selected_word-tests.ts index e02f32366a..da17d37c81 100644 --- a/ace/tests/ace-editor_highlight_selected_word-tests.ts +++ b/ace/tests/ace-editor_highlight_selected_word-tests.ts @@ -1,4 +1,4 @@ -/// + var lipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + "Mauris at arcu mi, eu lobortis mauris. Quisque ut libero eget " + diff --git a/ace/tests/ace-editor_highlight_selected_word-tests.ts.tscparams b/ace/tests/ace-editor_highlight_selected_word-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-editor_highlight_selected_word-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-editor_navigation-tests.ts b/ace/tests/ace-editor_navigation-tests.ts index b68ae9b9dc..407b1af5de 100644 --- a/ace/tests/ace-editor_navigation-tests.ts +++ b/ace/tests/ace-editor_navigation-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var renderer: AceAjax.VirtualRenderer; diff --git a/ace/tests/ace-editor_navigation-tests.ts.tscparams b/ace/tests/ace-editor_navigation-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-editor_navigation-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-editor_text_edit-tests.ts b/ace/tests/ace-editor_text_edit-tests.ts index 6231830163..b170fd051c 100644 --- a/ace/tests/ace-editor_text_edit-tests.ts +++ b/ace/tests/ace-editor_text_edit-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var renderer: AceAjax.VirtualRenderer; diff --git a/ace/tests/ace-multi_select-tests.ts b/ace/tests/ace-multi_select-tests.ts index 68c7d1af95..cc571cfee3 100644 --- a/ace/tests/ace-multi_select-tests.ts +++ b/ace/tests/ace-multi_select-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var editor: any; diff --git a/ace/tests/ace-multi_select-tests.ts.tscparams b/ace/tests/ace-multi_select-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-multi_select-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-placeholder-tests.ts b/ace/tests/ace-placeholder-tests.ts index b9693da372..ba0b27ca88 100644 --- a/ace/tests/ace-placeholder-tests.ts +++ b/ace/tests/ace-placeholder-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var renderer: AceAjax.VirtualRenderer; diff --git a/ace/tests/ace-placeholder-tests.ts.tscparams b/ace/tests/ace-placeholder-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-placeholder-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-range-tests.ts b/ace/tests/ace-range-tests.ts index 8e560e8d22..a32c74fbde 100644 --- a/ace/tests/ace-range-tests.ts +++ b/ace/tests/ace-range-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var exports = { diff --git a/ace/tests/ace-range_list-tests.ts b/ace/tests/ace-range_list-tests.ts index 3a531579eb..f1f06214f9 100644 --- a/ace/tests/ace-range_list-tests.ts +++ b/ace/tests/ace-range_list-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; function flatten(rangeList) { diff --git a/ace/tests/ace-range_list-tests.ts.tscparams b/ace/tests/ace-range_list-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-range_list-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-search-tests.ts b/ace/tests/ace-search-tests.ts index 14b53397bb..4857d5bfdc 100644 --- a/ace/tests/ace-search-tests.ts +++ b/ace/tests/ace-search-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var exports = { diff --git a/ace/tests/ace-selection-tests.ts b/ace/tests/ace-selection-tests.ts index 884631085e..ab151b88bc 100644 --- a/ace/tests/ace-selection-tests.ts +++ b/ace/tests/ace-selection-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var exports = { diff --git a/ace/tests/ace-selection-tests.ts.tscparams b/ace/tests/ace-selection-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-selection-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-token_iterator-tests.ts b/ace/tests/ace-token_iterator-tests.ts index 892d781b95..27856a7434 100644 --- a/ace/tests/ace-token_iterator-tests.ts +++ b/ace/tests/ace-token_iterator-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var mode: any; diff --git a/ace/tests/ace-token_iterator-tests.ts.tscparams b/ace/tests/ace-token_iterator-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-token_iterator-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-virtual_renderer-tests.ts b/ace/tests/ace-virtual_renderer-tests.ts index 51f349dad3..71b1d86bf1 100644 --- a/ace/tests/ace-virtual_renderer-tests.ts +++ b/ace/tests/ace-virtual_renderer-tests.ts @@ -1,4 +1,4 @@ -/// + var assert: any; var exports = { diff --git a/ace/tests/ace-virtual_renderer-tests.ts.tscparams b/ace/tests/ace-virtual_renderer-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/ace/tests/ace-virtual_renderer-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tsconfig.json b/ace/tsconfig.json new file mode 100644 index 0000000000..c76f465da5 --- /dev/null +++ b/ace/tsconfig.json @@ -0,0 +1,17 @@ +{ + "files": [ + "index.d.ts", + "all-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/acl/acl-mongodbBackend-tests.ts b/acl/acl-mongodbBackend-tests.ts index 01c9af9082..ae3b1d03c9 100644 --- a/acl/acl-mongodbBackend-tests.ts +++ b/acl/acl-mongodbBackend-tests.ts @@ -1,10 +1,8 @@ -/// - // https://github.com/OptimalBits/node_acl/blob/master/Readme.md import Acl = require('acl'); import mongodb = require('mongodb'); -var db: mongodb.Db; +declare var db: mongodb.Db; // Using the mongo db backend var acl = new Acl(new Acl.mongodbBackend(db, 'acl_', true)); diff --git a/acl/acl-redisBackend-tests.ts b/acl/acl-redisBackend-tests.ts index 273aeab3b7..ec1924cce6 100644 --- a/acl/acl-redisBackend-tests.ts +++ b/acl/acl-redisBackend-tests.ts @@ -1,10 +1,8 @@ -/// - // https://github.com/OptimalBits/node_acl/blob/master/Readme.md import Acl = require('acl'); import redis = require('redis'); -var client: redis.RedisClient; +declare var client: redis.RedisClient; // Using the redis backend var acl = new Acl(new Acl.redisBackend(client, 'acl_')); diff --git a/acl/acl-tests.ts b/acl/acl-tests.ts index 551ad9c1cd..07dc401891 100644 --- a/acl/acl-tests.ts +++ b/acl/acl-tests.ts @@ -1,5 +1,3 @@ -/// - // Sample code from // https://github.com/OptimalBits/node_acl/blob/master/Readme.md import Acl = require('acl'); diff --git a/acl/acl.d.ts b/acl/acl.d.ts deleted file mode 100644 index 06defa2449..0000000000 --- a/acl/acl.d.ts +++ /dev/null @@ -1,150 +0,0 @@ -// Type definitions for node_acl 0.4.7 -// Project: https://github.com/optimalbits/node_acl -// Definitions by: Qubo -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -/// -/// - -declare module "acl" { - import http = require('http'); - import Promise = require("bluebird"); - - type strings = string|string[]; - type Value = string|number; - type Values = Value|Value[]; - type Action = () => any; - type Callback = (err: Error) => any; - type AnyCallback = (err: Error, obj: any) => any; - type AllowedCallback = (err: Error, allowed: boolean) => any; - type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value; - - interface AclStatic { - new (backend: Backend, logger: Logger, options: Option): Acl; - new (backend: Backend, logger: Logger): Acl; - new (backend: Backend): Acl; - memoryBackend: MemoryBackendStatic; - } - - interface Logger { - debug: (msg: string)=>any; - } - - interface Acl { - addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; - removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; - userRoles: (userId: Value, cb?: (err: Error, roles: string[])=>any) => Promise; - roleUsers: (role: Value, cb?: (err: Error, users: Values)=>any) => Promise; - hasRole: (userId: Value, role: string, cb?: (err: Error, isInRole: boolean)=>any) => Promise; - addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise; - removeRole: (role: string, cb?: Callback) => Promise; - removeResource: (resource: string, cb?: Callback) => Promise; - allow: { - (roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise; - (aclSets: AclSet|AclSet[]): Promise; - } - removeAllow: (role: string, resources: strings, permissions: strings, cb?: Callback) => Promise; - removePermissions: (role: string, resources: strings, permissions: strings, cb?: Function) => Promise; - allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise; - isAllowed: (userId: Value, resources: strings, permissions: strings, cb?: AllowedCallback) => Promise; - areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise; - whatResources: (roles: strings, permissions: strings, cb?: AnyCallback) => Promise; - permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise; - middleware: (numPathComponents: number, userId: Value|GetUserId, actions: strings) => Promise; - } - - interface Option { - buckets?: BucketsOption; - } - - interface BucketsOption { - meta?: string; - parents?: string; - permissions?: string; - resources?: string; - roles?: string; - users?: string; - } - - interface AclSet { - roles: strings; - allows: AclAllow[]; - } - - interface AclAllow { - resources: strings; - permissions: strings; - } - - interface MemoryBackend extends Backend { } - interface MemoryBackendStatic { - new(): MemoryBackend; - } - - // - // For internal use - // - interface Backend { - begin: () => T; - end: (transaction: T, cb?: Action) => void; - clean: (cb?: Action) => void; - get: (bucket: string, key: Value, cb?: Action) => void; - union: (bucket: string, keys: Value[], cb?: Action) => void; - add: (transaction: T, bucket: string, key: Value, values: Values) => void; - del: (transaction: T, bucket: string, keys: Value[]) => void; - remove: (transaction: T, bucket: string, key: Value, values: Values) => void; - - endAsync: Function; //TODO: Give more specific function signature - getAsync: Function; - cleanAsync: Function; - unionAsync: Function; - } - - interface Contract { - (args: IArguments): Contract|NoOp; - debug: boolean; - fulfilled: boolean; - args: any[]; - checkedParams: string[]; - params: (...types: string[]) => Contract|NoOp; - end: () => void; - } - - interface NoOp { - params: (...types: string[]) => NoOp; - end: () => void; - } - - // for redis backend - import redis = require('redis'); - - interface AclStatic { - redisBackend: RedisBackendStatic; - } - - interface RedisBackend extends Backend { } - interface RedisBackendStatic { - new(redis: redis.RedisClient, prefix: string): RedisBackend; - new(redis: redis.RedisClient): RedisBackend; - } - - // for mongodb backend - import mongo = require('mongodb'); - - interface AclStatic { - mongodbBackend: MongodbBackendStatic; - } - - interface MongodbBackend extends Backend { } - interface MongodbBackendStatic { - new(db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend; - new(db: mongo.Db, prefix: string): MongodbBackend; - new(db: mongo.Db): MongodbBackend; - } - - var _: AclStatic; - export = _; -} diff --git a/acl/index.d.ts b/acl/index.d.ts new file mode 100644 index 0000000000..6939c9ce9f --- /dev/null +++ b/acl/index.d.ts @@ -0,0 +1,145 @@ +// Type definitions for node_acl 0.4.7 +// Project: https://github.com/optimalbits/node_acl +// Definitions by: Qubo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +import http = require('http'); +import Promise = require("bluebird"); + +type strings = string | string[]; +type Value = string | number; +type Values = Value | Value[]; +type Action = () => any; +type Callback = (err: Error) => any; +type AnyCallback = (err: Error, obj: any) => any; +type AllowedCallback = (err: Error, allowed: boolean) => any; +type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value; + +interface AclStatic { + new (backend: Backend, logger: Logger, options: Option): Acl; + new (backend: Backend, logger: Logger): Acl; + new (backend: Backend): Acl; + memoryBackend: MemoryBackendStatic; +} + +interface Logger { + debug: (msg: string) => any; +} + +interface Acl { + addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; + removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; + userRoles: (userId: Value, cb?: (err: Error, roles: string[]) => any) => Promise; + roleUsers: (role: Value, cb?: (err: Error, users: Values) => any) => Promise; + hasRole: (userId: Value, role: string, cb?: (err: Error, isInRole: boolean) => any) => Promise; + addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise; + removeRole: (role: string, cb?: Callback) => Promise; + removeResource: (resource: string, cb?: Callback) => Promise; + allow: { + (roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise; + (aclSets: AclSet | AclSet[]): Promise; + } + removeAllow: (role: string, resources: strings, permissions: strings, cb?: Callback) => Promise; + removePermissions: (role: string, resources: strings, permissions: strings, cb?: Function) => Promise; + allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise; + isAllowed: (userId: Value, resources: strings, permissions: strings, cb?: AllowedCallback) => Promise; + areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise; + whatResources: (roles: strings, permissions: strings, cb?: AnyCallback) => Promise; + permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise; + middleware: (numPathComponents: number, userId: Value | GetUserId, actions: strings) => Promise; +} + +interface Option { + buckets?: BucketsOption; +} + +interface BucketsOption { + meta?: string; + parents?: string; + permissions?: string; + resources?: string; + roles?: string; + users?: string; +} + +interface AclSet { + roles: strings; + allows: AclAllow[]; +} + +interface AclAllow { + resources: strings; + permissions: strings; +} + +interface MemoryBackend extends Backend { } +interface MemoryBackendStatic { + new (): MemoryBackend; +} + +// +// For internal use +// +interface Backend { + begin: () => T; + end: (transaction: T, cb?: Action) => void; + clean: (cb?: Action) => void; + get: (bucket: string, key: Value, cb?: Action) => void; + union: (bucket: string, keys: Value[], cb?: Action) => void; + add: (transaction: T, bucket: string, key: Value, values: Values) => void; + del: (transaction: T, bucket: string, keys: Value[]) => void; + remove: (transaction: T, bucket: string, key: Value, values: Values) => void; + + endAsync: Function; //TODO: Give more specific function signature + getAsync: Function; + cleanAsync: Function; + unionAsync: Function; +} + +interface Contract { + (args: IArguments): Contract | NoOp; + debug: boolean; + fulfilled: boolean; + args: any[]; + checkedParams: string[]; + params: (...types: string[]) => Contract | NoOp; + end: () => void; +} + +interface NoOp { + params: (...types: string[]) => NoOp; + end: () => void; +} + +// for redis backend +import redis = require('redis'); + +interface AclStatic { + redisBackend: RedisBackendStatic; +} + +interface RedisBackend extends Backend { } +interface RedisBackendStatic { + new (redis: redis.RedisClient, prefix: string): RedisBackend; + new (redis: redis.RedisClient): RedisBackend; +} + +// for mongodb backend +import mongo = require('mongodb'); + +interface AclStatic { + mongodbBackend: MongodbBackendStatic; +} + +interface MongodbBackend extends Backend { } +interface MongodbBackendStatic { + new (db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend; + new (db: mongo.Db, prefix: string): MongodbBackend; + new (db: mongo.Db): MongodbBackend; +} + +declare var _: AclStatic; +export = _; diff --git a/acl/tsconfig.json b/acl/tsconfig.json new file mode 100644 index 0000000000..3c28b25610 --- /dev/null +++ b/acl/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "acl-tests.ts" + ] +} \ No newline at end of file diff --git a/acorn/acorn-tests.ts b/acorn/acorn-tests.ts index 796ffc3eed..3b2a116897 100644 --- a/acorn/acorn-tests.ts +++ b/acorn/acorn-tests.ts @@ -1,13 +1,12 @@ -/// -/// +/// import acorn = require('acorn'); -var token: acorn.Token; -var tokens: acorn.Token[]; -var comment: acorn.Comment; -var comments: acorn.Comment[]; -var program: ESTree.Program; +declare var token: acorn.Token; +declare var tokens: acorn.Token[]; +declare var comment: acorn.Comment; +declare var comments: acorn.Comment[]; +declare var program: ESTree.Program; var any: any; var string: string; diff --git a/acorn/acorn.d.ts b/acorn/acorn.d.ts deleted file mode 100644 index 755aab2a54..0000000000 --- a/acorn/acorn.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -// Type definitions for Acorn v1.0.1 -// Project: https://github.com/marijnh/acorn -// Definitions by: RReverser -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace acorn { - var version: string; - function parse(input: string, options?: Options): ESTree.Program; - function parseExpressionAt(input: string, pos: number, options?: Options): ESTree.Expression; - function getLineInfo(input: string, offset: number): ESTree.Position; - var defaultOptions: Options; - - interface TokenType { - label: string; - keyword: string; - beforeExpr: boolean; - startsExpr: boolean; - isLoop: boolean; - isAssign: boolean; - prefix: boolean; - postfix: boolean; - binop: number; - updateContext: (prevType: TokenType) => any; - } - - interface AbstractToken { - start: number; - end: number; - loc: ESTree.SourceLocation; - range: [number, number]; - } - - interface Token extends AbstractToken { - type: TokenType; - value: any; - } - - interface Comment extends AbstractToken { - type: string; - value: string; - } - - interface Options { - ecmaVersion?: number; - sourceType?: string; - onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any; - onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any; - allowReserved?: boolean; - allowReturnOutsideFunction?: boolean; - allowImportExportEverywhere?: boolean; - allowHashBang?: boolean; - locations?: boolean; - onToken?: ((token: Token) => any) | Token[]; - onComment?: ((isBlock: boolean, text: string, start: number, end: number, startLoc?: ESTree.Position, endLoc?: ESTree.Position) => any) | Comment[]; - ranges?: boolean; - program?: ESTree.Program; - sourceFile?: string; - directSourceFile?: string; - preserveParens?: boolean; - plugins?: { [name: string]: Function; }; - } -} - -declare module "acorn" { - export = acorn -} diff --git a/acorn/index.d.ts b/acorn/index.d.ts new file mode 100644 index 0000000000..c7b76692c6 --- /dev/null +++ b/acorn/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for Acorn v1.0.1 +// Project: https://github.com/marijnh/acorn +// Definitions by: RReverser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export as namespace acorn; +export = acorn; + +declare namespace acorn { + var version: string; + function parse(input: string, options?: Options): ESTree.Program; + function parseExpressionAt(input: string, pos: number, options?: Options): ESTree.Expression; + function getLineInfo(input: string, offset: number): ESTree.Position; + var defaultOptions: Options; + + interface TokenType { + label: string; + keyword: string; + beforeExpr: boolean; + startsExpr: boolean; + isLoop: boolean; + isAssign: boolean; + prefix: boolean; + postfix: boolean; + binop: number; + updateContext: (prevType: TokenType) => any; + } + + interface AbstractToken { + start: number; + end: number; + loc: ESTree.SourceLocation; + range: [number, number]; + } + + interface Token extends AbstractToken { + type: TokenType; + value: any; + } + + interface Comment extends AbstractToken { + type: string; + value: string; + } + + interface Options { + ecmaVersion?: number; + sourceType?: string; + onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any; + onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any; + allowReserved?: boolean; + allowReturnOutsideFunction?: boolean; + allowImportExportEverywhere?: boolean; + allowHashBang?: boolean; + locations?: boolean; + onToken?: ((token: Token) => any) | Token[]; + onComment?: ((isBlock: boolean, text: string, start: number, end: number, startLoc?: ESTree.Position, endLoc?: ESTree.Position) => any) | Comment[]; + ranges?: boolean; + program?: ESTree.Program; + sourceFile?: string; + directSourceFile?: string; + preserveParens?: boolean; + plugins?: { [name: string]: Function; }; + } +} diff --git a/acorn/tsconfig.json b/acorn/tsconfig.json new file mode 100644 index 0000000000..7c27170693 --- /dev/null +++ b/acorn/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "acorn-tests.ts" + ] +} \ No newline at end of file diff --git a/adal-angular/adal-angular-tests.ts b/adal/adal-angular-tests.ts similarity index 97% rename from adal-angular/adal-angular-tests.ts rename to adal/adal-angular-tests.ts index 930d94388f..64ab64c898 100644 --- a/adal-angular/adal-angular-tests.ts +++ b/adal/adal-angular-tests.ts @@ -1,4 +1,4 @@ -/// + // Code samples from: // - https://github.com/AzureAD/azure-activedirectory-library-for-js diff --git a/adal-angular/adal-angular.d.ts b/adal/adal-angular.d.ts similarity index 92% rename from adal-angular/adal-angular.d.ts rename to adal/adal-angular.d.ts index 1d0b88d55a..7b8cbb849e 100644 --- a/adal-angular/adal-angular.d.ts +++ b/adal/adal-angular.d.ts @@ -3,8 +3,8 @@ // Definitions by: mmaitre314 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// + +/// declare namespace adal { diff --git a/adal-angular/adal-tests.ts b/adal/adal-tests.ts similarity index 92% rename from adal-angular/adal-tests.ts rename to adal/adal-tests.ts index 598134d0a0..4931a7befb 100644 --- a/adal-angular/adal-tests.ts +++ b/adal/adal-tests.ts @@ -1,4 +1,4 @@ -/// + var endpoints = { "https://yourhost/api": "b6a68585-5287-45b2-ba82-383ba1f60932", diff --git a/adal-angular/adal.d.ts b/adal/index.d.ts similarity index 100% rename from adal-angular/adal.d.ts rename to adal/index.d.ts diff --git a/adal/tsconfig.json b/adal/tsconfig.json new file mode 100644 index 0000000000..af9df9e110 --- /dev/null +++ b/adal/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "adal-tests.ts" + ] +} \ No newline at end of file diff --git a/add2home/add2home-tests.ts b/add2home/add2home-tests.ts index 371a8f752a..aeb14a1d18 100644 --- a/add2home/add2home-tests.ts +++ b/add2home/add2home-tests.ts @@ -1,4 +1,4 @@ -/// + addToHome.show(false); addToHome.close(); diff --git a/add2home/add2home.d.ts b/add2home/index.d.ts similarity index 100% rename from add2home/add2home.d.ts rename to add2home/index.d.ts diff --git a/add2home/tsconfig.json b/add2home/tsconfig.json new file mode 100644 index 0000000000..9403be7717 --- /dev/null +++ b/add2home/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "add2home-tests.ts" + ] +} \ No newline at end of file diff --git a/adm-zip/adm-zip-tests.ts b/adm-zip/adm-zip-tests.ts index 8637751bfa..2418597087 100644 --- a/adm-zip/adm-zip-tests.ts +++ b/adm-zip/adm-zip-tests.ts @@ -1,4 +1,4 @@ -/// + import AdmZip = require("adm-zip"); // reading archives diff --git a/adm-zip/adm-zip.d.ts b/adm-zip/adm-zip.d.ts deleted file mode 100644 index 19298149c3..0000000000 --- a/adm-zip/adm-zip.d.ts +++ /dev/null @@ -1,307 +0,0 @@ -// Type definitions for adm-zip v0.4.4 -// Project: https://github.com/cthackers/adm-zip -// Definitions by: John Vilk , Abner Oliveira -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "adm-zip" { - class AdmZip { - /** - * Create a new, empty archive. - */ - constructor(); - /** - * Read an existing archive. - */ - constructor(fileName: string); - /** - * Extracts the given entry from the archive and returns the content as a - * Buffer object. - * @param entry String with the full path of the entry - * @return Buffer or Null in case of error - */ - readFile(entry: string): Buffer; - /** - * Extracts the given entry from the archive and returns the content as a - * Buffer object. - * @param entry ZipEntry object - * @return Buffer or Null in case of error - */ - readFile(entry: AdmZip.IZipEntry): Buffer; - /** - * Asynchronous readFile - * @param entry String with the full path of the entry - * @param callback Called with a Buffer or Null in case of error - */ - readFileAsync(entry: string, callback: (data: Buffer, err: string) => any): void; - /** - * Asynchronous readFile - * @param entry ZipEntry object - * @param callback Called with a Buffer or Null in case of error - * @return Buffer or Null in case of error - */ - readFileAsync(entry: AdmZip.IZipEntry, callback: (data: Buffer, err: string) => any): void; - /** - * Extracts the given entry from the archive and returns the content as - * plain text in the given encoding - * @param entry String with the full path of the entry - * @param encoding Optional. If no encoding is specified utf8 is used - * @return String - */ - readAsText(fileName: string, encoding?: string): string; - /** - * Extracts the given entry from the archive and returns the content as - * plain text in the given encoding - * @param entry ZipEntry object - * @param encoding Optional. If no encoding is specified utf8 is used - * @return String - */ - readAsText(fileName: AdmZip.IZipEntry, encoding?: string): string; - /** - * Asynchronous readAsText - * @param entry String with the full path of the entry - * @param callback Called with the resulting string. - * @param encoding Optional. If no encoding is specified utf8 is used - */ - readAsTextAsync(fileName: string, callback: (data: string) => any, encoding?: string): void; - /** - * Asynchronous readAsText - * @param entry ZipEntry object - * @param callback Called with the resulting string. - * @param encoding Optional. If no encoding is specified utf8 is used - */ - readAsTextAsync(fileName: AdmZip.IZipEntry, callback: (data: string) => any, encoding?: string): void; - /** - * Remove the entry from the file or the entry and all its nested directories - * and files if the given entry is a directory - * @param entry String with the full path of the entry - */ - deleteFile(entry: string): void; - /** - * Remove the entry from the file or the entry and all its nested directories - * and files if the given entry is a directory - * @param entry A ZipEntry object. - */ - deleteFile(entry: AdmZip.IZipEntry): void; - /** - * Adds a comment to the zip. The zip must be rewritten after - * adding the comment. - * @param comment Content of the comment. - */ - addZipComment(comment: string): void; - /** - * Returns the zip comment - * @return The zip comment. - */ - getZipComment(): string; - /** - * Adds a comment to a specified zipEntry. The zip must be rewritten after - * adding the comment. - * The comment cannot exceed 65535 characters in length. - * @param entry String with the full path of the entry - * @param comment The comment to add to the entry. - */ - addZipEntryComment(entry: string, comment: string): void; - /** - * Adds a comment to a specified zipEntry. The zip must be rewritten after - * adding the comment. - * The comment cannot exceed 65535 characters in length. - * @param entry ZipEntry object. - * @param comment The comment to add to the entry. - */ - addZipEntryComment(entry: AdmZip.IZipEntry, comment: string): void; - /** - * Returns the comment of the specified entry. - * @param entry String with the full path of the entry. - * @return String The comment of the specified entry. - */ - getZipEntryComment(entry: string): string; - /** - * Returns the comment of the specified entry - * @param entry ZipEntry object. - * @return String The comment of the specified entry. - */ - getZipEntryComment(entry: AdmZip.IZipEntry): string; - /** - * Updates the content of an existing entry inside the archive. The zip - * must be rewritten after updating the content - * @param entry String with the full path of the entry. - * @param content The entry's new contents. - */ - updateFile(entry: string, content: Buffer): void; - /** - * Updates the content of an existing entry inside the archive. The zip - * must be rewritten after updating the content - * @param entry ZipEntry object. - * @param content The entry's new contents. - */ - updateFile(entry: AdmZip.IZipEntry, content: Buffer): void; - /** - * Adds a file from the disk to the archive. - * @param localPath Path to a file on disk. - * @param zipPath Path to a directory in the archive. Defaults to the empty - * string. - */ - addLocalFile(localPath: string, zipPath?: string): void; - /** - * Adds a local directory and all its nested files and directories to the - * archive. - * @param localPath Path to a folder on disk. - * @param zipPath Path to a folder in the archive. Defaults to an empty - * string. - */ - addLocalFolder(localPath: string, zipPath?: string): void; - /** - * Allows you to create a entry (file or directory) in the zip file. - * If you want to create a directory the entryName must end in / and a null - * buffer should be provided. - * @param entryName Entry path - * @param content Content to add to the entry; must be a 0-length buffer - * for a directory. - * @param comment Comment to add to the entry. - * @param attr Attribute to add to the entry. - */ - addFile(entryName: string, data: Buffer, comment?: string, attr?: number): void; - /** - * Returns an array of ZipEntry objects representing the files and folders - * inside the archive - */ - getEntries(): AdmZip.IZipEntry[]; - /** - * Returns a ZipEntry object representing the file or folder specified by - * ``name``. - * @param name Name of the file or folder to retrieve. - * @return ZipEntry The entry corresponding to the name. - */ - getEntry(name: string): AdmZip.IZipEntry; - /** - * Extracts the given entry to the given targetPath. - * If the entry is a directory inside the archive, the entire directory and - * its subdirectories will be extracted. - * @param entry String with the full path of the entry - * @param targetPath Target folder where to write the file - * @param maintainEntryPath If maintainEntryPath is true and the entry is - * inside a folder, the entry folder will be created in targetPath as - * well. Default is TRUE - * @param overwrite If the file already exists at the target path, the file - * will be overwriten if this is true. Default is FALSE - * - * @return Boolean - */ - extractEntryTo(entryPath: string, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean; - /** - * Extracts the given entry to the given targetPath. - * If the entry is a directory inside the archive, the entire directory and - * its subdirectories will be extracted. - * @param entry ZipEntry object - * @param targetPath Target folder where to write the file - * @param maintainEntryPath If maintainEntryPath is true and the entry is - * inside a folder, the entry folder will be created in targetPath as - * well. Default is TRUE - * @param overwrite If the file already exists at the target path, the file - * will be overwriten if this is true. Default is FALSE - * @return Boolean - */ - extractEntryTo(entryPath: AdmZip.IZipEntry, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean; - /** - * Extracts the entire archive to the given location - * @param targetPath Target location - * @param overwrite If the file already exists at the target path, the file - * will be overwriten if this is true. Default is FALSE - */ - extractAllTo(targetPath: string, overwrite?: boolean): void; - /** - * Extracts the entire archive to the given location - * @param targetPath Target location - * @param overwrite If the file already exists at the target path, the file - * will be overwriten if this is true. Default is FALSE - * @param callback The callback function will be called afeter extraction - */ - extractAllToAsync(targetPath: string, overwrite: boolean, callback: (error: Error) => void): void; - /** - * Writes the newly created zip file to disk at the specified location or - * if a zip was opened and no ``targetFileName`` is provided, it will - * overwrite the opened zip - * @param targetFileName - */ - writeZip(targetPath?: string): void; - /** - * Returns the content of the entire zip file as a Buffer object - * @return Buffer - */ - toBuffer(): Buffer; - } - - namespace AdmZip { - /** - * The ZipEntry is more than a structure representing the entry inside the - * zip file. Beside the normal attributes and headers a entry can have, the - * class contains a reference to the part of the file where the compressed - * data resides and decompresses it when requested. It also compresses the - * data and creates the headers required to write in the zip file. - */ - interface IZipEntry { - /** - * Represents the full name and path of the file - */ - entryName: string; - rawEntryName: Buffer; - /** - * Extra data associated with this entry. - */ - extra: Buffer; - /** - * Entry comment. - */ - comment: string; - name: string; - /** - * Read-Only property that indicates the type of the entry. - */ - isDirectory: boolean; - /** - * Get the header associated with this ZipEntry. - */ - header: Buffer; - /** - * Retrieve the compressed data for this entry. Note that this may trigger - * compression if any properties were modified. - */ - getCompressedData(): Buffer; - /** - * Asynchronously retrieve the compressed data for this entry. Note that - * this may trigger compression if any properties were modified. - */ - getCompressedDataAsync(callback: (data: Buffer) => void): void; - /** - * Set the (uncompressed) data to be associated with this entry. - */ - setData(value: string): void; - /** - * Set the (uncompressed) data to be associated with this entry. - */ - setData(value: Buffer): void; - /** - * Get the decompressed data associated with this entry. - */ - getData(): Buffer; - /** - * Asynchronously get the decompressed data associated with this entry. - */ - getDataAsync(callback: (data: Buffer) => void): void; - /** - * Returns the CEN Entry Header to be written to the output zip file, plus - * the extra data and the entry comment. - */ - packHeader(): Buffer; - /** - * Returns a nicely formatted string with the most important properties of - * the ZipEntry. - */ - toString(): string; - } - } - - export = AdmZip; -} diff --git a/adm-zip/index.d.ts b/adm-zip/index.d.ts new file mode 100644 index 0000000000..f22b929b76 --- /dev/null +++ b/adm-zip/index.d.ts @@ -0,0 +1,306 @@ +// Type definitions for adm-zip v0.4.4 +// Project: https://github.com/cthackers/adm-zip +// Definitions by: John Vilk , Abner Oliveira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +declare class AdmZip { + /** + * Create a new, empty archive. + */ + constructor(); + /** + * Read an existing archive. + */ + constructor(fileName: string); + /** + * Extracts the given entry from the archive and returns the content as a + * Buffer object. + * @param entry String with the full path of the entry + * @return Buffer or Null in case of error + */ + readFile(entry: string): Buffer; + /** + * Extracts the given entry from the archive and returns the content as a + * Buffer object. + * @param entry ZipEntry object + * @return Buffer or Null in case of error + */ + readFile(entry: AdmZip.IZipEntry): Buffer; + /** + * Asynchronous readFile + * @param entry String with the full path of the entry + * @param callback Called with a Buffer or Null in case of error + */ + readFileAsync(entry: string, callback: (data: Buffer, err: string) => any): void; + /** + * Asynchronous readFile + * @param entry ZipEntry object + * @param callback Called with a Buffer or Null in case of error + * @return Buffer or Null in case of error + */ + readFileAsync(entry: AdmZip.IZipEntry, callback: (data: Buffer, err: string) => any): void; + /** + * Extracts the given entry from the archive and returns the content as + * plain text in the given encoding + * @param entry String with the full path of the entry + * @param encoding Optional. If no encoding is specified utf8 is used + * @return String + */ + readAsText(fileName: string, encoding?: string): string; + /** + * Extracts the given entry from the archive and returns the content as + * plain text in the given encoding + * @param entry ZipEntry object + * @param encoding Optional. If no encoding is specified utf8 is used + * @return String + */ + readAsText(fileName: AdmZip.IZipEntry, encoding?: string): string; + /** + * Asynchronous readAsText + * @param entry String with the full path of the entry + * @param callback Called with the resulting string. + * @param encoding Optional. If no encoding is specified utf8 is used + */ + readAsTextAsync(fileName: string, callback: (data: string) => any, encoding?: string): void; + /** + * Asynchronous readAsText + * @param entry ZipEntry object + * @param callback Called with the resulting string. + * @param encoding Optional. If no encoding is specified utf8 is used + */ + readAsTextAsync(fileName: AdmZip.IZipEntry, callback: (data: string) => any, encoding?: string): void; + /** + * Remove the entry from the file or the entry and all its nested directories + * and files if the given entry is a directory + * @param entry String with the full path of the entry + */ + deleteFile(entry: string): void; + /** + * Remove the entry from the file or the entry and all its nested directories + * and files if the given entry is a directory + * @param entry A ZipEntry object. + */ + deleteFile(entry: AdmZip.IZipEntry): void; + /** + * Adds a comment to the zip. The zip must be rewritten after + * adding the comment. + * @param comment Content of the comment. + */ + addZipComment(comment: string): void; + /** + * Returns the zip comment + * @return The zip comment. + */ + getZipComment(): string; + /** + * Adds a comment to a specified zipEntry. The zip must be rewritten after + * adding the comment. + * The comment cannot exceed 65535 characters in length. + * @param entry String with the full path of the entry + * @param comment The comment to add to the entry. + */ + addZipEntryComment(entry: string, comment: string): void; + /** + * Adds a comment to a specified zipEntry. The zip must be rewritten after + * adding the comment. + * The comment cannot exceed 65535 characters in length. + * @param entry ZipEntry object. + * @param comment The comment to add to the entry. + */ + addZipEntryComment(entry: AdmZip.IZipEntry, comment: string): void; + /** + * Returns the comment of the specified entry. + * @param entry String with the full path of the entry. + * @return String The comment of the specified entry. + */ + getZipEntryComment(entry: string): string; + /** + * Returns the comment of the specified entry + * @param entry ZipEntry object. + * @return String The comment of the specified entry. + */ + getZipEntryComment(entry: AdmZip.IZipEntry): string; + /** + * Updates the content of an existing entry inside the archive. The zip + * must be rewritten after updating the content + * @param entry String with the full path of the entry. + * @param content The entry's new contents. + */ + updateFile(entry: string, content: Buffer): void; + /** + * Updates the content of an existing entry inside the archive. The zip + * must be rewritten after updating the content + * @param entry ZipEntry object. + * @param content The entry's new contents. + */ + updateFile(entry: AdmZip.IZipEntry, content: Buffer): void; + /** + * Adds a file from the disk to the archive. + * @param localPath Path to a file on disk. + * @param zipPath Path to a directory in the archive. Defaults to the empty + * string. + */ + addLocalFile(localPath: string, zipPath?: string): void; + /** + * Adds a local directory and all its nested files and directories to the + * archive. + * @param localPath Path to a folder on disk. + * @param zipPath Path to a folder in the archive. Defaults to an empty + * string. + */ + addLocalFolder(localPath: string, zipPath?: string): void; + /** + * Allows you to create a entry (file or directory) in the zip file. + * If you want to create a directory the entryName must end in / and a null + * buffer should be provided. + * @param entryName Entry path + * @param content Content to add to the entry; must be a 0-length buffer + * for a directory. + * @param comment Comment to add to the entry. + * @param attr Attribute to add to the entry. + */ + addFile(entryName: string, data: Buffer, comment?: string, attr?: number): void; + /** + * Returns an array of ZipEntry objects representing the files and folders + * inside the archive + */ + getEntries(): AdmZip.IZipEntry[]; + /** + * Returns a ZipEntry object representing the file or folder specified by + * ``name``. + * @param name Name of the file or folder to retrieve. + * @return ZipEntry The entry corresponding to the name. + */ + getEntry(name: string): AdmZip.IZipEntry; + /** + * Extracts the given entry to the given targetPath. + * If the entry is a directory inside the archive, the entire directory and + * its subdirectories will be extracted. + * @param entry String with the full path of the entry + * @param targetPath Target folder where to write the file + * @param maintainEntryPath If maintainEntryPath is true and the entry is + * inside a folder, the entry folder will be created in targetPath as + * well. Default is TRUE + * @param overwrite If the file already exists at the target path, the file + * will be overwriten if this is true. Default is FALSE + * + * @return Boolean + */ + extractEntryTo(entryPath: string, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean; + /** + * Extracts the given entry to the given targetPath. + * If the entry is a directory inside the archive, the entire directory and + * its subdirectories will be extracted. + * @param entry ZipEntry object + * @param targetPath Target folder where to write the file + * @param maintainEntryPath If maintainEntryPath is true and the entry is + * inside a folder, the entry folder will be created in targetPath as + * well. Default is TRUE + * @param overwrite If the file already exists at the target path, the file + * will be overwriten if this is true. Default is FALSE + * @return Boolean + */ + extractEntryTo(entryPath: AdmZip.IZipEntry, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean; + /** + * Extracts the entire archive to the given location + * @param targetPath Target location + * @param overwrite If the file already exists at the target path, the file + * will be overwriten if this is true. Default is FALSE + */ + extractAllTo(targetPath: string, overwrite?: boolean): void; + /** + * Extracts the entire archive to the given location + * @param targetPath Target location + * @param overwrite If the file already exists at the target path, the file + * will be overwriten if this is true. Default is FALSE + * @param callback The callback function will be called afeter extraction + */ + extractAllToAsync(targetPath: string, overwrite: boolean, callback: (error: Error) => void): void; + /** + * Writes the newly created zip file to disk at the specified location or + * if a zip was opened and no ``targetFileName`` is provided, it will + * overwrite the opened zip + * @param targetFileName + */ + writeZip(targetPath?: string): void; + /** + * Returns the content of the entire zip file as a Buffer object + * @return Buffer + */ + toBuffer(): Buffer; +} + +declare namespace AdmZip { + /** + * The ZipEntry is more than a structure representing the entry inside the + * zip file. Beside the normal attributes and headers a entry can have, the + * class contains a reference to the part of the file where the compressed + * data resides and decompresses it when requested. It also compresses the + * data and creates the headers required to write in the zip file. + */ + interface IZipEntry { + /** + * Represents the full name and path of the file + */ + entryName: string; + rawEntryName: Buffer; + /** + * Extra data associated with this entry. + */ + extra: Buffer; + /** + * Entry comment. + */ + comment: string; + name: string; + /** + * Read-Only property that indicates the type of the entry. + */ + isDirectory: boolean; + /** + * Get the header associated with this ZipEntry. + */ + header: Buffer; + /** + * Retrieve the compressed data for this entry. Note that this may trigger + * compression if any properties were modified. + */ + getCompressedData(): Buffer; + /** + * Asynchronously retrieve the compressed data for this entry. Note that + * this may trigger compression if any properties were modified. + */ + getCompressedDataAsync(callback: (data: Buffer) => void): void; + /** + * Set the (uncompressed) data to be associated with this entry. + */ + setData(value: string): void; + /** + * Set the (uncompressed) data to be associated with this entry. + */ + setData(value: Buffer): void; + /** + * Get the decompressed data associated with this entry. + */ + getData(): Buffer; + /** + * Asynchronously get the decompressed data associated with this entry. + */ + getDataAsync(callback: (data: Buffer) => void): void; + /** + * Returns the CEN Entry Header to be written to the output zip file, plus + * the extra data and the entry comment. + */ + packHeader(): Buffer; + /** + * Returns a nicely formatted string with the most important properties of + * the ZipEntry. + */ + toString(): string; + } +} + +export = AdmZip; diff --git a/adm-zip/tsconfig.json b/adm-zip/tsconfig.json new file mode 100644 index 0000000000..3f3e89e027 --- /dev/null +++ b/adm-zip/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "adm-zip-tests.ts" + ] +} \ No newline at end of file diff --git a/ag-grid/ag-grid-tests.ts b/ag-grid/ag-grid-tests.ts index 67b98f9f33..7c4ebb0c8c 100644 --- a/ag-grid/ag-grid-tests.ts +++ b/ag-grid/ag-grid-tests.ts @@ -1,4 +1,3 @@ -/// checkGridOptions({}); checkColDef({}); diff --git a/ag-grid/ag-grid.d.ts b/ag-grid/index.d.ts similarity index 100% rename from ag-grid/ag-grid.d.ts rename to ag-grid/index.d.ts diff --git a/ag-grid/tsconfig.json b/ag-grid/tsconfig.json new file mode 100644 index 0000000000..af7b7c89c6 --- /dev/null +++ b/ag-grid/tsconfig.json @@ -0,0 +1,17 @@ +{ + "files": [ + "index.d.ts", + "ag-grid-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/agenda/agenda-tests.ts b/agenda/agenda-tests.ts index 6be618e59d..8c5e3e19bb 100644 --- a/agenda/agenda-tests.ts +++ b/agenda/agenda-tests.ts @@ -1,8 +1,5 @@ -/// - import * as Agenda from "agenda"; - var mongoConnectionString = "mongodb://127.0.0.1/agenda"; var agenda = new Agenda({ db: { address: mongoConnectionString } }); diff --git a/agenda/agenda.d.ts b/agenda/agenda.d.ts deleted file mode 100644 index 011676bc86..0000000000 --- a/agenda/agenda.d.ts +++ /dev/null @@ -1,443 +0,0 @@ -// Type definitions for Agenda v0.8.9 -// Project: https://github.com/rschmukler/agenda -// Definitions by: Meir Gottlieb -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare module "agenda" { - - import {EventEmitter} from "events"; - import {Db, Collection, ObjectID} from "mongodb"; - - interface Callback { - (err?: Error): void; - } - - interface ResultCallback { - (err?: Error, result?: T): void; - } - - /** - * Agenda Configuration. - */ - interface AgendaConfiguration { - - /** - * Sets the interval with which the queue is checked. A number in milliseconds or a frequency string. - */ - processEvery?: string | number; - - /** - * Takes a number which specifies the default number of a specific job that can be running at any given moment. - * By default it is 5. - */ - defaultConcurrency?: number; - - /** - * Takes a number which specifies the max number of jobs that can be running at any given moment. By default it - * is 20. - */ - maxConcurrency?: number; - - /** - * Takes a number which specifies the default number of a specific job that can be locked at any given moment. - * By default it is 0 for no max. - */ - defaultLockLimit?: number; - - /** - * Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is - * 0 for no max. - */ - lockLimit?: number; - - /** - * Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This - * can be overridden by specifying the lockLifetime option to a defined job. - */ - defaultLockLifetime?: number; - - /** - * Specifies that Agenda should be initialized using and existing MongoDB connection. - */ - mongo?: { - /** - * The MongoDB database connection to use. - */ - db: Db; - - /** - * The name of the collection to use. - */ - collection?: string; - } - - /** - * Specifies that Agenda should connect to MongoDB. - */ - db?: { - /** - * The connection URL. - */ - address: string; - - /** - * The name of the collection to use. - */ - collection?: string; - - /** - * Connection options to pass to MongoDB. - */ - options?: any; - } - } - - /** - * The database record associated with a job. - */ - interface JobAttributes { - /** - * The record identity. - */ - _id: ObjectID; - - /** - * The name of the job. - */ - name: string; - - /** - * The type of the job (single|normal). - */ - type: string; - - /** - * The job details. - */ - data: { [name: string]: any }; - - /** - * The priority of the job. - */ - priority: number; - - /** - * How often the job is repeated using a human-readable or cron format. - */ - repeatInterval: string | number; - - /** - * The timezone that conforms to [moment-timezone](http://momentjs.com/timezone/). - */ - repeatTimezone: string; - - /** - * Date/time the job was las modified. - */ - lastModifiedBy: string; - - /** - * Date/time the job will run next. - */ - nextRunAt: Date; - - /** - * Date/time the job was locked. - */ - lockedAt: Date; - - /** - * Date/time the job was last run. - */ - lastRunAt: Date; - - /** - * Date/time the job last finished running. - */ - lastFinishedAt: Date; - - /** - * The reason the job failed. - */ - failReason: string; - - /** - * The number of times the job has failed. - */ - failCount: number; - - /** - * The date/time the job last failed. - */ - failedAt: Date; - } - - /** - * A scheduled job. - */ - interface Job { - - /** - * The database record associated with the job. - */ - attrs: JobAttributes; - - /** - * Specifies an interval on which the job should repeat. - * @param interval A human-readable format String, a cron format String, or a Number. - * @param options An optional argument that can include a timezone field. The timezone should be a string as - * accepted by moment-timezone and is considered when using an interval in the cron string format. - */ - repeatEvery(interval: string | number, options?: { timezone?: string }): Job - - /** - * Specifies a time when the job should repeat. [Possible values](https://github.com/matthewmueller/date#examples). - * @param time - */ - repeatAt(time: string): Job - - /** - * Disables the job. - */ - disable(): Job; - - /** - * Enables the job. - */ - enable(): Job; - - /** - * Ensure that only one instance of this job exists with the specified properties - * @param value The properties associated with the job that must be unqiue. - * @param opts - */ - unique(value: any, opts?: { insertOnly?: boolean }): Job; - - /** - * Specifies the next time at which the job should run. - * @param time The next time at which the job should run. - */ - schedule(time: string | Date): Job; - - /** - * Specifies the priority weighting of the job. - * @param value The priority of the job (lowest|low|normal|high|highest|number). - */ - priority(value: string | number): Job; - - /** - * Sets job.attrs.failedAt to now, and sets job.attrs.failReason to reason. - * @param reason A message or Error object that indicates why the job failed. - */ - fail(reason: string | Error): Job; - - /** - * Runs the given job and calls callback(err, job) upon completion. Normally you never need to call this manually - * @param cb Called when the job is completed. - */ - run(cb?: ResultCallback): Job; - - /** - * Returns true if the job is running; otherwise, returns false. - */ - isRunning(): boolean; - - /** - * Saves the job into the database. - * @param cb Called when the job is saved. - */ - save(cb?: ResultCallback): Job; - - /** - * Removes the job from the database and cancels the job. - * @param cb Called after the job has beeb removed from the database. - */ - remove(cb?: Callback): void; - - /** - * Resets the lock on the job. Useful to indicate that the job hasn't timed out when you have very long running - * jobs. - * @param cb Called after the job has been saved to the database. - */ - touch(cb?: Callback): void; - } - - interface JobOptions { - - /** - * Maximum number of that job that can be running at once (per instance of agenda) - */ - concurrency?: number; - - /** - * Maximum number of that job that can be locked at once (per instance of agenda) - */ - lockLimit?: number; - - /** - * Interval in ms of how long the job stays locked for (see multiple job processors for more info). A job will - * automatically unlock if done() is called. - */ - lockLifetime?: number; - - /** - * (lowest|low|normal|high|highest|number) specifies the priority of the job. Higher priority jobs will run - * first. - */ - priority?: string | number; - } - - class Agenda extends EventEmitter { - - /** - * Constructs a new Agenda object. - * @param config Optional configuration to initialize the Agenda. - * @param cb Optional callback called with the MongoDB colleciton. - */ - constructor(config?: AgendaConfiguration, cb?: ResultCallback); - - /** - * Connect to the specified MongoDB server and database. - */ - database(url: string, collection?: string, options?: any, cb?: ResultCallback): Agenda; - - /** - * Initialize agenda with an existing MongoDB connection. - */ - mongo(db: Db, collection?: string, cb?: ResultCallback): Agenda; - - /** - * Sets the agenda name. - */ - name(value: string): Agenda; - - /** - * Sets the interval with which the queue is checked. A number in milliseconds or a frequency string. - */ - processEvery(interval: string | number): Agenda; - - /** - * Takes a number which specifies the max number of jobs that can be running at any given moment. By default it - * is 20. - * @param value The value to set. - */ - maxConcurrency(value: number): Agenda; - - /** - * Takes a number which specifies the default number of a specific job that can be running at any given moment. - * By default it is 5. - * @param value The value to set. - */ - defaultConcurrency(value: number): Agenda; - - /** - * Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is - * 0 for no max. - * @param value The value to set. - */ - lockLimit(value: number): Agenda; - - /** - * Takes a number which specifies the default number of a specific job that can be locked at any given moment. - * By default it is 0 for no max. - * @param value The value to set. - */ - defaultLockLimit(value: number): Agenda; - - /** - * Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This - * can be overridden by specifying the lockLifetime option to a defined job. - * @param value The value to set. - */ - defaultLockLifetime(value: number): Agenda; - - /** - * Returns an instance of a jobName with data. This does NOT save the job in the database. See below to learn - * how to manually work with jobs. - * @param name The name of the job. - * @param data Data to associated with the job. - */ - create(name: string, data?: any): Job; - - /** - * Find all Jobs matching `query` and pass same back in cb(). - * @param query - * @param cb - */ - jobs(query: any, cb: ResultCallback): void; - - /** - * Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want - * to remove old jobs. - * @param cb Called with the number of jobs removed. - */ - purge(cb?: ResultCallback): void; - - /** - * Defines a job with the name of jobName. When a job of job name gets run, it will be passed to fn(job, done). - * To maintain asynchronous behavior, you must call done() when you are processing the job. If your function is - * synchronous, you may omit done from the signature. - * @param name The name of the jobs. - * @param options The options for the job. - * @param handler The handler to execute. - */ - define(name: string, handler: (job?: Job, done?: (err?: Error) => void) => void): void; - define(name: string, options: JobOptions, handler: (job?: Job, done?: (err?: Error) => void) => void): void; - - /** - * Runs job name at the given interval. Optionally, data and options can be passed in. - * @param interval Can be a human-readable format String, a cron format String, or a Number. - * @param names The name or names of the job(s) to run. - * @param data An optional argument that will be passed to the processing function under job.attrs.data. - * @param options An optional argument that will be passed to job.repeatEvery. - * @param cb An optional callback function which will be called when the job has been persisted in the database. - */ - every(interval: number | string, names: string, data?: any, options?: any, cb?: ResultCallback): Job; - every(interval: number | string, names: string[], data?: any, options?: any, cb?: ResultCallback): Job[]; - - /** - * Schedules a job to run name once at a given time. - * @param when A Date or a String such as tomorrow at 5pm. - * @param names The name or names of the job(s) to run. - * @param data An optional argument that will be passed to the processing function under job.attrs.data. - * @param cb An optional callback function which will be called when the job has been persisted in the database. - */ - schedule(when: Date | string, names: string, data?: any, cb?: ResultCallback): Job; - schedule(when: Date | string, names: string[], data?: any, cb?: ResultCallback): Job[]; - - /** - * Schedules a job to run name once immediately. - * @param name The name of the job to run. - * @param data An optional argument that will be passed to the processing function under job.attrs.data. - * @param cb An optional callback function which will be called when the job has been persisted in the database. - */ - now(name: string, data?: any, cb?: ResultCallback): Job; - - /** - * Cancels any jobs matching the passed mongodb-native query, and removes them from the database. - * @param query Mongodb native query. - * @param cb Called with the number of jobs removed. - */ - cancel(query: any, cb?: ResultCallback): void; - - /** - * Starts the job queue processing, checking processEvery time to see if there are new jobs. - */ - start(): void; - - /** - * Stops the job queue processing. Unlocks currently running jobs. - * @param cb Called after the job processing queue shuts down and unlocks all jobs. - */ - stop(cb: Callback): void; - } - - namespace Agenda { - - } - - export = Agenda; -} diff --git a/agenda/index.d.ts b/agenda/index.d.ts new file mode 100644 index 0000000000..dc252af65a --- /dev/null +++ b/agenda/index.d.ts @@ -0,0 +1,439 @@ +// Type definitions for Agenda v0.8.9 +// Project: https://github.com/rschmukler/agenda +// Definitions by: Meir Gottlieb +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import {EventEmitter} from "events"; +import {Db, Collection, ObjectID} from "mongodb"; + +interface Callback { + (err?: Error): void; +} + +interface ResultCallback { + (err?: Error, result?: T): void; +} + +/** + * Agenda Configuration. + */ +interface AgendaConfiguration { + + /** + * Sets the interval with which the queue is checked. A number in milliseconds or a frequency string. + */ + processEvery?: string | number; + + /** + * Takes a number which specifies the default number of a specific job that can be running at any given moment. + * By default it is 5. + */ + defaultConcurrency?: number; + + /** + * Takes a number which specifies the max number of jobs that can be running at any given moment. By default it + * is 20. + */ + maxConcurrency?: number; + + /** + * Takes a number which specifies the default number of a specific job that can be locked at any given moment. + * By default it is 0 for no max. + */ + defaultLockLimit?: number; + + /** + * Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is + * 0 for no max. + */ + lockLimit?: number; + + /** + * Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This + * can be overridden by specifying the lockLifetime option to a defined job. + */ + defaultLockLifetime?: number; + + /** + * Specifies that Agenda should be initialized using and existing MongoDB connection. + */ + mongo?: { + /** + * The MongoDB database connection to use. + */ + db: Db; + + /** + * The name of the collection to use. + */ + collection?: string; + } + + /** + * Specifies that Agenda should connect to MongoDB. + */ + db?: { + /** + * The connection URL. + */ + address: string; + + /** + * The name of the collection to use. + */ + collection?: string; + + /** + * Connection options to pass to MongoDB. + */ + options?: any; + } +} + +/** + * The database record associated with a job. + */ +interface JobAttributes { + /** + * The record identity. + */ + _id: ObjectID; + + /** + * The name of the job. + */ + name: string; + + /** + * The type of the job (single|normal). + */ + type: string; + + /** + * The job details. + */ + data: { [name: string]: any }; + + /** + * The priority of the job. + */ + priority: number; + + /** + * How often the job is repeated using a human-readable or cron format. + */ + repeatInterval: string | number; + + /** + * The timezone that conforms to [moment-timezone](http://momentjs.com/timezone/). + */ + repeatTimezone: string; + + /** + * Date/time the job was las modified. + */ + lastModifiedBy: string; + + /** + * Date/time the job will run next. + */ + nextRunAt: Date; + + /** + * Date/time the job was locked. + */ + lockedAt: Date; + + /** + * Date/time the job was last run. + */ + lastRunAt: Date; + + /** + * Date/time the job last finished running. + */ + lastFinishedAt: Date; + + /** + * The reason the job failed. + */ + failReason: string; + + /** + * The number of times the job has failed. + */ + failCount: number; + + /** + * The date/time the job last failed. + */ + failedAt: Date; +} + +/** + * A scheduled job. + */ +interface Job { + + /** + * The database record associated with the job. + */ + attrs: JobAttributes; + + /** + * Specifies an interval on which the job should repeat. + * @param interval A human-readable format String, a cron format String, or a Number. + * @param options An optional argument that can include a timezone field. The timezone should be a string as + * accepted by moment-timezone and is considered when using an interval in the cron string format. + */ + repeatEvery(interval: string | number, options?: { timezone?: string }): Job + + /** + * Specifies a time when the job should repeat. [Possible values](https://github.com/matthewmueller/date#examples). + * @param time + */ + repeatAt(time: string): Job + + /** + * Disables the job. + */ + disable(): Job; + + /** + * Enables the job. + */ + enable(): Job; + + /** + * Ensure that only one instance of this job exists with the specified properties + * @param value The properties associated with the job that must be unqiue. + * @param opts + */ + unique(value: any, opts?: { insertOnly?: boolean }): Job; + + /** + * Specifies the next time at which the job should run. + * @param time The next time at which the job should run. + */ + schedule(time: string | Date): Job; + + /** + * Specifies the priority weighting of the job. + * @param value The priority of the job (lowest|low|normal|high|highest|number). + */ + priority(value: string | number): Job; + + /** + * Sets job.attrs.failedAt to now, and sets job.attrs.failReason to reason. + * @param reason A message or Error object that indicates why the job failed. + */ + fail(reason: string | Error): Job; + + /** + * Runs the given job and calls callback(err, job) upon completion. Normally you never need to call this manually + * @param cb Called when the job is completed. + */ + run(cb?: ResultCallback): Job; + + /** + * Returns true if the job is running; otherwise, returns false. + */ + isRunning(): boolean; + + /** + * Saves the job into the database. + * @param cb Called when the job is saved. + */ + save(cb?: ResultCallback): Job; + + /** + * Removes the job from the database and cancels the job. + * @param cb Called after the job has beeb removed from the database. + */ + remove(cb?: Callback): void; + + /** + * Resets the lock on the job. Useful to indicate that the job hasn't timed out when you have very long running + * jobs. + * @param cb Called after the job has been saved to the database. + */ + touch(cb?: Callback): void; +} + +interface JobOptions { + + /** + * Maximum number of that job that can be running at once (per instance of agenda) + */ + concurrency?: number; + + /** + * Maximum number of that job that can be locked at once (per instance of agenda) + */ + lockLimit?: number; + + /** + * Interval in ms of how long the job stays locked for (see multiple job processors for more info). A job will + * automatically unlock if done() is called. + */ + lockLifetime?: number; + + /** + * (lowest|low|normal|high|highest|number) specifies the priority of the job. Higher priority jobs will run + * first. + */ + priority?: string | number; +} + +declare class Agenda extends EventEmitter { + + /** + * Constructs a new Agenda object. + * @param config Optional configuration to initialize the Agenda. + * @param cb Optional callback called with the MongoDB colleciton. + */ + constructor(config?: AgendaConfiguration, cb?: ResultCallback); + + /** + * Connect to the specified MongoDB server and database. + */ + database(url: string, collection?: string, options?: any, cb?: ResultCallback): Agenda; + + /** + * Initialize agenda with an existing MongoDB connection. + */ + mongo(db: Db, collection?: string, cb?: ResultCallback): Agenda; + + /** + * Sets the agenda name. + */ + name(value: string): Agenda; + + /** + * Sets the interval with which the queue is checked. A number in milliseconds or a frequency string. + */ + processEvery(interval: string | number): Agenda; + + /** + * Takes a number which specifies the max number of jobs that can be running at any given moment. By default it + * is 20. + * @param value The value to set. + */ + maxConcurrency(value: number): Agenda; + + /** + * Takes a number which specifies the default number of a specific job that can be running at any given moment. + * By default it is 5. + * @param value The value to set. + */ + defaultConcurrency(value: number): Agenda; + + /** + * Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is + * 0 for no max. + * @param value The value to set. + */ + lockLimit(value: number): Agenda; + + /** + * Takes a number which specifies the default number of a specific job that can be locked at any given moment. + * By default it is 0 for no max. + * @param value The value to set. + */ + defaultLockLimit(value: number): Agenda; + + /** + * Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This + * can be overridden by specifying the lockLifetime option to a defined job. + * @param value The value to set. + */ + defaultLockLifetime(value: number): Agenda; + + /** + * Returns an instance of a jobName with data. This does NOT save the job in the database. See below to learn + * how to manually work with jobs. + * @param name The name of the job. + * @param data Data to associated with the job. + */ + create(name: string, data?: any): Job; + + /** + * Find all Jobs matching `query` and pass same back in cb(). + * @param query + * @param cb + */ + jobs(query: any, cb: ResultCallback): void; + + /** + * Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want + * to remove old jobs. + * @param cb Called with the number of jobs removed. + */ + purge(cb?: ResultCallback): void; + + /** + * Defines a job with the name of jobName. When a job of job name gets run, it will be passed to fn(job, done). + * To maintain asynchronous behavior, you must call done() when you are processing the job. If your function is + * synchronous, you may omit done from the signature. + * @param name The name of the jobs. + * @param options The options for the job. + * @param handler The handler to execute. + */ + define(name: string, handler: (job?: Job, done?: (err?: Error) => void) => void): void; + define(name: string, options: JobOptions, handler: (job?: Job, done?: (err?: Error) => void) => void): void; + + /** + * Runs job name at the given interval. Optionally, data and options can be passed in. + * @param interval Can be a human-readable format String, a cron format String, or a Number. + * @param names The name or names of the job(s) to run. + * @param data An optional argument that will be passed to the processing function under job.attrs.data. + * @param options An optional argument that will be passed to job.repeatEvery. + * @param cb An optional callback function which will be called when the job has been persisted in the database. + */ + every(interval: number | string, names: string, data?: any, options?: any, cb?: ResultCallback): Job; + every(interval: number | string, names: string[], data?: any, options?: any, cb?: ResultCallback): Job[]; + + /** + * Schedules a job to run name once at a given time. + * @param when A Date or a String such as tomorrow at 5pm. + * @param names The name or names of the job(s) to run. + * @param data An optional argument that will be passed to the processing function under job.attrs.data. + * @param cb An optional callback function which will be called when the job has been persisted in the database. + */ + schedule(when: Date | string, names: string, data?: any, cb?: ResultCallback): Job; + schedule(when: Date | string, names: string[], data?: any, cb?: ResultCallback): Job[]; + + /** + * Schedules a job to run name once immediately. + * @param name The name of the job to run. + * @param data An optional argument that will be passed to the processing function under job.attrs.data. + * @param cb An optional callback function which will be called when the job has been persisted in the database. + */ + now(name: string, data?: any, cb?: ResultCallback): Job; + + /** + * Cancels any jobs matching the passed mongodb-native query, and removes them from the database. + * @param query Mongodb native query. + * @param cb Called with the number of jobs removed. + */ + cancel(query: any, cb?: ResultCallback): void; + + /** + * Starts the job queue processing, checking processEvery time to see if there are new jobs. + */ + start(): void; + + /** + * Stops the job queue processing. Unlocks currently running jobs. + * @param cb Called after the job processing queue shuts down and unlocks all jobs. + */ + stop(cb: Callback): void; +} + +declare namespace Agenda { + +} + +export = Agenda; diff --git a/agenda/tsconfig.json b/agenda/tsconfig.json new file mode 100644 index 0000000000..bfcc028e47 --- /dev/null +++ b/agenda/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "agenda-tests.ts" + ] +} \ No newline at end of file diff --git a/alertify/alertify-tests.ts b/alertify/alertify-tests.ts index 9f6c0cd860..61903e86ff 100644 --- a/alertify/alertify-tests.ts +++ b/alertify/alertify-tests.ts @@ -1,4 +1,4 @@ -/// + alertify.init(); diff --git a/alertify/alertify.d.ts b/alertify/index.d.ts similarity index 100% rename from alertify/alertify.d.ts rename to alertify/index.d.ts diff --git a/alertify/tsconfig.json b/alertify/tsconfig.json new file mode 100644 index 0000000000..c45376926c --- /dev/null +++ b/alertify/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "alertify-tests.ts" + ] +} \ No newline at end of file diff --git a/alt/alt-tests.ts b/alt/alt-tests.ts index fad079b020..8d1108ada3 100644 --- a/alt/alt-tests.ts +++ b/alt/alt-tests.ts @@ -1,8 +1,6 @@ /** * Created by shearerbeard on 6/28/15. */ -/// - import Alt = require("alt"); //New alt instance @@ -74,7 +72,7 @@ var testSource:AltJS.Source = { remote() { return new Promise((res:any, rej:any) => { setTimeout(() => { - if(true) { + if(!!true) { res("stuff"); } else { rej("Things have broken"); diff --git a/alt/alt.d.ts b/alt/alt.d.ts deleted file mode 100644 index 20da159f35..0000000000 --- a/alt/alt.d.ts +++ /dev/null @@ -1,166 +0,0 @@ -// Type definitions for Alt 0.16.10 -// Project: https://github.com/goatslacker/alt -// Definitions by: Michael Shearer -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace AltJS { - - interface StoreReduce { - action:any; - data: any; - } - - export interface StoreModel { - //Actions - bindAction?( action:Action, handler:ActionHandler):void; - bindActions?(actions:ActionsClass):void; - - //Methods/Listeners - exportPublicMethods?(exportConfig:any):void; - bindListeners?(config:{[methodName:string]:Action | Actions}):void; - exportAsync?(source:Source):void; - registerAsync?(datasource:Source):void; - - //state - setState?(state:S):void; - setState?(stateFn:(currentState:S, nextState:S) => S):void; - getState?():S; - waitFor?(store:AltStore):void; - - //events - onSerialize?(fn:(data:any) => any):void; - onDeserialize?(fn:(data:any) => any):void; - on?(event:AltJS.lifeCycleEvents, callback:() => any):void; - emitChange?():void; - waitFor?(storeOrStores:AltStore | Array>):void; - otherwise?(data:any, action:AltJS.Action):void; - observe?(alt:Alt):any; - reduce?(state:any, config:StoreReduce):Object; - preventDefault?():void; - afterEach?(payload:Object, state:Object):void; - beforeEach?(payload:Object, state:Object):void; - // TODO: Embed dispatcher interface in def - dispatcher?:any; - - //instance - getInstance?():AltJS.AltStore; - alt?:Alt; - displayName?:string; - } - - export type Source = {[name:string]: () => SourceModel}; - - export interface SourceModel { - local(state:any):any; - remote(state:any):Promise; - shouldFetch?(fetchFn:(...args:Array) => boolean):void; - loading?:(args:any) => void; - success?:(state:S) => void; - error?:(args:any) => void; - interceptResponse?(response:any, action:Action, ...args:Array):any; - } - - export interface AltStore { - getState():S; - listen(handler:(state:S) => any):() => void; - unlisten(handler:(state:S) => any):void; - emitChange():void; - } - - export enum lifeCycleEvents { - bootstrap, - snapshot, - init, - rollback, - error - } - - export type Actions = {[action:string]:Action}; - - export interface Action { - ( args:T):void; - defer(data:any):void; - } - - export interface ActionsClass { - generateActions?( ...action:Array):void; - dispatch( ...payload:Array):void; - actions?:Actions; - } - - type StateTransform = (store:StoreModel) => AltJS.AltStore; - - interface AltConfig { - dispatcher?:any; - serialize?:(serializeFn:(data:Object) => string) => void; - deserialize?:(deserializeFn:(serialData:string) => Object) => void; - storeTransforms?:Array; - batchingFunction?:(callback:( ...data:Array) => any) => void; - } - - class Alt { - constructor(config?:AltConfig); - actions:Actions; - bootstrap(jsonData:string):void; - takeSnapshot( ...storeNames:Array):string; - flush():Object; - recycle( ...stores:Array>):void; - rollback():void; - dispatch(action?:AltJS.Action, data?:Object, details?:any):void; - - //Actions methods - addActions(actionsName:string, ActionsClass: ActionsClassConstructor):void; - createActions(ActionsClass: ActionsClassConstructor, exportObj?: Object):T; - createActions(ActionsClass: ActionsClassConstructor, exportObj?: Object, ...constructorArgs:Array):T; - generateActions( ...actions:Array):T; - getActions(actionsName:string):AltJS.Actions; - - //Stores methods - addStore(name:string, store:StoreModel, saveStore?:boolean):void; - createStore(store:StoreModel, name?:string):AltJS.AltStore; - getStore(name:string):AltJS.AltStore; - } - - export interface AltFactory { - new(config?:AltConfig):Alt; - } - - type ActionsClassConstructor = new (alt:Alt) => AltJS.ActionsClass; - - type ActionHandler = ( ...data:Array) => any; - type ExportConfig = {[key:string]:(...args:Array) => any}; -} - -declare module "alt/utils/chromeDebug" { - function chromeDebug(alt:AltJS.Alt):void; - export = chromeDebug; -} - -declare module "alt/AltContainer" { - - import React = require("react"); - - interface ContainerProps { - store?:AltJS.AltStore; - stores?:Array>; - inject?:{[key:string]:any}; - actions?:{[key:string]:Object}; - render?:(...props:Array) => React.ReactElement; - flux?:AltJS.Alt; - transform?:(store:AltJS.AltStore, actions:any) => any; - shouldComponentUpdate?:(props:any) => boolean; - component?:React.Component; - } - - type AltContainer = React.ReactElement; - var AltContainer:React.ComponentClass; - - export = AltContainer; -} - -declare module "alt" { - var alt:AltJS.AltFactory; - export = alt; -} diff --git a/alt/index.d.ts b/alt/index.d.ts new file mode 100644 index 0000000000..1e084131a0 --- /dev/null +++ b/alt/index.d.ts @@ -0,0 +1,166 @@ +// Type definitions for Alt 0.16.10 +// Project: https://github.com/goatslacker/alt +// Definitions by: Michael Shearer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace AltJS { + + interface StoreReduce { + action:any; + data: any; + } + + export interface StoreModel { + //Actions + bindAction?( action:Action, handler:ActionHandler):void; + bindActions?(actions:ActionsClass):void; + + //Methods/Listeners + exportPublicMethods?(exportConfig:any):void; + bindListeners?(config:{[methodName:string]:Action | Actions}):void; + exportAsync?(source:Source):void; + registerAsync?(datasource:Source):void; + + //state + setState?(state:S):void; + setState?(stateFn:(currentState:S, nextState:S) => S):void; + getState?():S; + waitFor?(store:AltStore):void; + + //events + onSerialize?(fn:(data:any) => any):void; + onDeserialize?(fn:(data:any) => any):void; + on?(event:AltJS.lifeCycleEvents, callback:() => any):void; + emitChange?():void; + waitFor?(storeOrStores:AltStore | Array>):void; + otherwise?(data:any, action:AltJS.Action):void; + observe?(alt:Alt):any; + reduce?(state:any, config:StoreReduce):Object; + preventDefault?():void; + afterEach?(payload:Object, state:Object):void; + beforeEach?(payload:Object, state:Object):void; + // TODO: Embed dispatcher interface in def + dispatcher?:any; + + //instance + getInstance?():AltJS.AltStore; + alt?:Alt; + displayName?:string; + } + + export type Source = {[name:string]: () => SourceModel}; + + export interface SourceModel { + local(state:any):any; + remote(state:any):Promise; + shouldFetch?(fetchFn:(...args:Array) => boolean):void; + loading?:(args:any) => void; + success?:(state:S) => void; + error?:(args:any) => void; + interceptResponse?(response:any, action:Action, ...args:Array):any; + } + + export interface AltStore { + getState():S; + listen(handler:(state:S) => any):() => void; + unlisten(handler:(state:S) => any):void; + emitChange():void; + } + + export enum lifeCycleEvents { + bootstrap, + snapshot, + init, + rollback, + error + } + + export type Actions = {[action:string]:Action}; + + export interface Action { + ( args:T):void; + defer(data:any):void; + } + + export interface ActionsClass { + generateActions?( ...action:Array):void; + dispatch( ...payload:Array):void; + actions?:Actions; + } + + type StateTransform = (store:StoreModel) => AltJS.AltStore; + + interface AltConfig { + dispatcher?:any; + serialize?:(serializeFn:(data:Object) => string) => void; + deserialize?:(deserializeFn:(serialData:string) => Object) => void; + storeTransforms?:Array; + batchingFunction?:(callback:( ...data:Array) => any) => void; + } + + class Alt { + constructor(config?:AltConfig); + actions:Actions; + bootstrap(jsonData:string):void; + takeSnapshot( ...storeNames:Array):string; + flush():Object; + recycle( ...stores:Array>):void; + rollback():void; + dispatch(action?:AltJS.Action, data?:Object, details?:any):void; + + //Actions methods + addActions(actionsName:string, ActionsClass: ActionsClassConstructor):void; + createActions(ActionsClass: ActionsClassConstructor, exportObj?: Object):T; + createActions(ActionsClass: ActionsClassConstructor, exportObj?: Object, ...constructorArgs:Array):T; + generateActions( ...actions:Array):T; + getActions(actionsName:string):AltJS.Actions; + + //Stores methods + addStore(name:string, store:StoreModel, saveStore?:boolean):void; + createStore(store:StoreModel, name?:string):AltJS.AltStore; + getStore(name:string):AltJS.AltStore; + } + + export interface AltFactory { + new(config?:AltConfig):Alt; + } + + type ActionsClassConstructor = new (alt:Alt) => AltJS.ActionsClass; + + type ActionHandler = ( ...data:Array) => any; + type ExportConfig = {[key:string]:(...args:Array) => any}; +} + +declare module "alt/utils/chromeDebug" { + function chromeDebug(alt:AltJS.Alt):void; + export = chromeDebug; +} + +declare module "alt/AltContainer" { + + import React = require("react"); + + interface ContainerProps { + store?:AltJS.AltStore; + stores?:Array>; + inject?:{[key:string]:any}; + actions?:{[key:string]:Object}; + render?:(...props:Array) => React.ReactElement; + flux?:AltJS.Alt; + transform?:(store:AltJS.AltStore, actions:any) => any; + shouldComponentUpdate?:(props:any) => boolean; + component?:React.Component; + } + + type AltContainer = React.ReactElement; + var AltContainer:React.ComponentClass; + + export = AltContainer; +} + +declare module "alt" { + var alt:AltJS.AltFactory; + export = alt; +} diff --git a/alt/tsconfig.json b/alt/tsconfig.json new file mode 100644 index 0000000000..1587b6ba1a --- /dev/null +++ b/alt/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "alt-tests.ts" + ] +} \ No newline at end of file diff --git a/amazon-product-api/amazon-product-api-tests.ts b/amazon-product-api/amazon-product-api-tests.ts index b98e15710f..e173d76f36 100644 --- a/amazon-product-api/amazon-product-api-tests.ts +++ b/amazon-product-api/amazon-product-api-tests.ts @@ -1,5 +1,5 @@ -/// -/// + +/// import amazon = require('amazon-product-api'); diff --git a/amazon-product-api/amazon-product-api.d.ts b/amazon-product-api/amazon-product-api.d.ts deleted file mode 100644 index f7ccf905e5..0000000000 --- a/amazon-product-api/amazon-product-api.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Type definitions for amazon-product-api -// Project: https://github.com/t3chnoboy/amazon-product-api -// Definitions by: Matti Lehtinen -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "amazon-product-api" { - - interface ICredentials { - awsId: string, - awsSecret: string, - awsTag: string - } - - interface IAmazonProductQueryCallback { - (err: string, results: Object[]): void; - } - - interface IAmazonProductClient { - itemSearch(query: any, callback?: IAmazonProductQueryCallback) : Promise; - itemLookup(query: any, callback?: IAmazonProductQueryCallback) : Promise; - browseNodeLookup(query: any, callback?: IAmazonProductQueryCallback) : Promise; - } - - export function createClient(credentials:ICredentials) : IAmazonProductClient; -} diff --git a/amazon-product-api/index.d.ts b/amazon-product-api/index.d.ts new file mode 100644 index 0000000000..6cb7389c73 --- /dev/null +++ b/amazon-product-api/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for amazon-product-api +// Project: https://github.com/t3chnoboy/amazon-product-api +// Definitions by: Matti Lehtinen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + +interface ICredentials { + awsId: string, + awsSecret: string, + awsTag: string +} + +interface IAmazonProductQueryCallback { + (err: string, results: Object[]): void; +} + +interface IAmazonProductClient { + itemSearch(query: any, callback?: IAmazonProductQueryCallback): Promise; + itemLookup(query: any, callback?: IAmazonProductQueryCallback): Promise; + browseNodeLookup(query: any, callback?: IAmazonProductQueryCallback): Promise; +} + +export declare function createClient(credentials: ICredentials): IAmazonProductClient; diff --git a/amazon-product-api/tsconfig.json b/amazon-product-api/tsconfig.json new file mode 100644 index 0000000000..af7dd3eb8a --- /dev/null +++ b/amazon-product-api/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "amazon-product-api-tests.ts" + ] +} \ No newline at end of file diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts deleted file mode 100644 index 02d2c540a0..0000000000 --- a/amcharts/AmCharts.d.ts +++ /dev/null @@ -1,2558 +0,0 @@ -// Type definitions for amCharts -// Project: http://www.amcharts.com/ -// Definitions by: aleksey-bykov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// AmCharts object (it's not a class) is create automatically when amcharts.js or amstock.js file is included in a web page. -declare namespace AmCharts { - - /** Set it to true if you have base href set for your page. This will fix rendering problems in Firefox caused by base href. */ - var baseHref: boolean; - - /** Array of day names, used when formatting dates (if categoryAxis.parseDates is set to true) ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] */ - var dayNames: string[]; - - /** Array of month names, used when formatting dates (if categoryAxis.parseDates is set to true) ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] */ - var monthNames: string[]; - - /** Array of short versions of day names, used when formatting dates (if categoryAxis.parseDates is set to true) ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] */ - var shortDayNames: string[]; - - /** Array of short versions of month names, used when formatting dates (if categoryAxis.parseDates is set to true) ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] */ - var shortMonthNames: string[]; - - /** Set it to true if you want UTC time to be used instead of local time. */ - var useUTC: boolean; - - /** Clears all the charts on page, removes listeners and intervals. */ - function clear(); - - /** AmPieChart class creates pie/donut chart. In order to display pie chart you need to set at least three properties - dataProvider, titleField and valueField. - @example - var chartData = [{title:"Pie I have eaten",value:70},{title:"Pie I haven\'t eaten",value:30}]; - var chart = new AmCharts.AmPieChart(); - chart.valueField = "value"; - chart.titleField = "title"; - chart.dataProvider = chartData; - chart.write("chartdiv"); - */ - class AmPieChart { - /** Name of the field in chart's dataProvider which holds slice's alpha. */ - alphaField: string; - /** Pie lean angle (for 3D effect). Valid range is 0 - 90. */ - angle: number; - /** Balloon text. The following tags can be used: [[value]], [[title]], [[percents]], [[description]]. [[title]]: [[percents]]% ([[value]])\n[[description]] */ - balloonText: string; - /** Read-only. Array of Slice objects. */ - chartData: any[]; - /** Name of the field in chart's dataProvider which holds slice's color. */ - colorField: string; - /** Specifies the colors of the slices, if the slice color is not set. If there are more slices than colors in this array, the chart picks random color. ["#FF0F00", "#FF6600", "#FF9E01", "#FCD202", "#F8FF01", "#B0DE09", "#04D215", "#0D8ECF", "#0D52D1", "#2A0CD0", "#8A0CCF", "#CD0D74", "#754DEB", "#DDDDDD", "#999999", "#333333", "#000000", "#57032A", "#CA9726", "#990000", "#4B0C25"] */ - colors: any[]; - /** Depth of the pie (for 3D effect). */ - depth3D: number; - /** Name of the field in chart's dataProvider which holds a string with description. */ - descriptionField: string; - /** Example: [-0.2,0.2]. Will make slices to be filled with color gradients. */ - gradientRatio: number[]; - /** Opacity of the group slice. Value range is 0 - 1. - @default 1 - */ - groupedAlpha: number; - /** Color of the group slice. The default value is not set - this means the next available color from "colors" array will be used. */ - groupedColor: string; - /** Description of the group slice. */ - groupedDescription: string; - /** If this is set to true, the group slice will be pulled out when the chart loads. */ - groupedPulled: boolean; - /** Title of the group slice. Other */ - groupedTitle: string; - /** If there is more than one slice whose percentage of the pie is less than this number, those slices will be grouped together into one slice. This is the "other" slice. It will always be the last slice in a pie. */ - groupPercent: number; - /** Slices with percent less then hideLabelsPercent won't display labels This is useful to avoid cluttering up the chart, if you have a lot of small slices. 0 means all labels will be shown. */ - hideLabelsPercent: number; - /** Opacity of a hovered slice. Value range is 0 - 1. - @default 1 - */ - hoverAlpha: number; - /** Inner radius of the pie, in pixels or percents. */ - innerRadius: any; - /** The distance between the label and the slice, in pixels. You can use negative values to put the label on the slice. - @default 30 - */ - labelRadius: number; - /** Name of the field in dataProvider which specifies the length of a tick. Note, the chart will not try to arrange labels automatically if this property is set. */ - labelRadiusField: string; - /** Specifies whether data labels are visible. - @default true - */ - labelsEnabled: boolean; - /** Label text. The following tags can be used: [[value]], [[title]], [[percents]], [[description]]. [[title]]: [[percents]]% */ - labelText: string; - /** Label tick opacity. Value range is 0 - 1. 0.2 */ - labelTickAlpha: number; - /** Label tick color. #000000 */ - labelTickColor: string; - /** Bottom margin of the chart. - @default 5 - */ - marginBottom: number; - /** Left margin of the chart. */ - marginLeft: number; - /** Right margin of the chart. */ - marginRight: number; - /** Top margin of the chart. - @default 5 - */ - marginTop: number; - /** Minimum radius of the pie, in pixels. - @default 10 - */ - minRadius: number; - /** Pie outline opacity. Value range is 0 - 1. */ - outlineAlpha: number; - /** Pie outline color. #FFFFFF */ - outlineColor: string; - /** Pie outline thickness. - @default 1 - */ - outlineThickness: number; - /** Opacity of the slices. You can set the opacity of individual slice too. - @default 1 - */ - pieAlpha: number; - /** Color of the first slice. All the other will be colored with darker or brighter colors. */ - pieBaseColor: string; - /** Lightness increase of each subsequent slice. This is only useful if pieBaseColor is set. Use negative values for darker colors. Value range is from -255 to 255. - @default 30*/ - pieBrightnessStep: number; - /** You can set fixed position of a pie center, in pixels or in percents. */ - pieX: any; - /** You can set fixed position of a pie center, in pixels or in percents. */ - pieY: any; - /** Name of the field in chart's dataProvider which holds a boolean value telling the chart whether this slice must be pulled or not. */ - pulledField: string; - /** Pull out duration, in seconds. - @default 1 - */ - pullOutDuration: number; - /** Pull out effect. Possible values are ">", "<", elastic" and "bounce". bounce */ - pullOutEffect: string; - /** If this is set to true, only one slice can be pulled out at a time. If the viewer clicks on a slice, any other pulled-out slice will be pulled in. */ - pullOutOnlyOne: boolean; - /** Pull out radius, in pixels or percents 0.2 */ - pullOutRadius: any; - /** Radius of a pie, in pixels or percents. By default, radius is calculated automatically. */ - radius: any; - /** Specifies whether the animation should be sequenced or all slices should appear at once. */ - sequencedAnimation: boolean; - /** Initial opacity of all slices. If you set startDuration higher than 0, slices will fade in from startAlpha. - @default 1 - */ - startAlpha: number; - /** Angle of the first slice, in degrees. This will work properly only if "depth3D" is set to 0. If "depth3D" is greater than 0, then there can be two angles only: 90 and 270. Value range is 0-360. - @default 90 - */ - startAngle: number; - /** Duration of the animation, in seconds. - @default 1 - */ - startDuration: number; - /** Animation effect. Possible values are ">", "<", "elastic" and "bounce". bounce */ - startEffect: string; - /** Radius of the positions from which the slices will fly in. - default 5 - */ - startRadius: any; - /** Name of the field in chart's dataProvider which holds slice's title. */ - titleField: string; - /** Name of the field in chart's dataProvider which holds url which would be accessed if the user clicks on a slice. */ - urlField: string; - /** If url is specified for a slice, it will be opened when user clicks on it. urlTarget specifies target of this url. Use _blank if you want url to be opened in a new window. _self */ - urlTarget: string; - /** Name of the field in chart's dataProvider which holds slice's value. */ - valueField: string; - /** Name of the field in chart's dataProvider which holds boolean variable defining whether this data item should have an entry in the legend. */ - visibleInLegendField: string; - - /** You can trigger the animation of the pie chart. */ - animateAgain(); - /** You can trigger the click on a slice from outside. index - the number of a slice or Slice object. */ - clickSlice(index: number); - /** Hides slice. index - the number of a slice or Slice object. */ - hideSlice(index: number); - /** You can simulate roll-out of a slice from outside. index - the number of a slice or Slice object. */ - rollOutSlice(index: number); - /** You can simulate roll-over a slice from outside. index - the number of a slice or Slice object. */ - rollOverSlice(index: number); - /** Shows slice. index - the number of a slice or Slice object. */ - showSlice(index: number); - - /** Adds event listener of the type "clickSlice" or "pullInSlice" or "pullOutSlice" to the object. - @param type Always "clickSlice" or "pullInSlice" or "pullOutSlice". - @param handler - If the type is "clickSlice", dispatched when user clicks on a slice. - If the type is "pullInSlice", dispatched when user clicks on a slice and the slice is pulled-in. - If the type is "pullOutSlice", dispatched when user clicks on a slice and the slice is pulled-out. - If the type is "rollOutSlice", dispatched when user rolls-out of the slice. - If the type is "rollOverSlice", dispatched when user rolls-over the slice. - */ - addListener(type: string, handler: (e: {/** Always "rollOverSlice". */ - type: string; dataItem: Slice; - }) => void ); - } - - /** AmRadarChart is the class you have to use for radar and polar chart types. - @example - var chart; - var chartData = [ - {country:"Czech Republic",litres:156.90}, - {country:"Ireland",litres:131.10}, - {country:"Germany",litres:115.80}, - {country:"Australia",litres:109.90}, - {country:"Austria",litres:108.30}, - {country:"UK",litres:99.00} - ]; - - window.onload = function() { - chart = new AmCharts.AmRadarChart(); - chart.dataProvider = chartData; - chart.categoryField = "country"; - chart.startDuration = 2; - - var valueAxis = new AmCharts.ValueAxis(); - valueAxis.axisAlpha = 0.15; - valueAxis.minimum = 0; - valueAxis.dashLength = 3; - valueAxis.axisTitleOffset = 20; - valueAxis.gridCount = 5; - chart.addValueAxis(valueAxis); - - var graph = new AmCharts.AmGraph(); - graph.valueField = "litres"; - graph.bullet = "round"; - graph.balloonText = "[[value]] litres of beer per year" - chart.addGraph(graph); - - chart.write("chartdiv"); - } - */ - class AmRadarChart extends AmCoordinateChart { - /** Bottom margin of the chart. */ - marginBottom: number; - /** Left margin of the chart. */ - marginLeft: number; - /** Right margin of the chart. */ - marginRight: number; - /** Top margin of the chart. */ - marginTop: number; - /** Radius of a radar. 0.35 */ - radius: any; - } - - /** AmXYChart is the class you have to use for XY/Bubble/Scatter chart types. The chart supports simple and logarithmic scales, it can have multiple value axes. - @example - var chartData = [ - {x:10, y:14, value:59}, - {x:5, y:3, value:50}, - {x:-10, y:-3, value:19}, - {x:-6, y:5, value:65}, - {x:15, y:-4, value:92}, - {x:13, y:1, value:8}, - {x:1, y:6, value:35} - ]; - - var chart = new AmCharts.AmXYChart(); - chart.pathToImages = "../../amcharts/javascript/images/"; - chart.dataProvider = chartData; - chart.marginLeft = 35; - chart.startDuration = 1.5; - - var xAxis = new AmCharts.ValueAxis(); - xAxis.position = "left"; - xAxis.autoGridCount = true; - chart.addValueAxis(xAxis); - - var yAxis = new AmCharts.ValueAxis(); - yAxis.position = "bottom"; - yAxis.autoGridCount = true; - chart.addValueAxis(yAxis); - - var graph = new AmCharts.AmGraph(); - graph.valueField = "value"; - graph.xField = "x"; - graph.yField = "y"; - graph.lineAlpha = 0; - graph.bullet = "round"; - chart.addGraph(graph); - - var chartCursor = new AmCharts.ChartCursor(); - chart.addChartCursor(chartCursor); - - var chartScrollbar = new AmCharts.ChartScrollbar(); - chartScrollbar.hideResizeGrips = false; - chart.addChartScrollbar(chartScrollbar); - - chart.write("chartdiv); - */ - class AmXYChart extends AmRectangularChart { - /** Specifies if Scrollbar of X axis (horizontal) should be hidden. */ - hideXScrollbar: boolean; - /** Specifies if Scrollbar of Y axis (vertical) should be hidden. */ - hideYScrollbar: boolean; - /** Maximum zoom factor of the chart. - @default 20 - */ - maxZoomFactor: number; - /** Zooms out, charts shows all available data.*/ - zoomOut(); - } - /** Guides are straight vertical or horizontal lines or areas supported by AmSerialChart, AmXYChart and AmRadarChart. You can have guides both on value and category axes. To add/remove a guide to an axis, use axis.addGuide(guide)/axis.removeGuide(guide) methods. - -If you do not set properties such as dashLength, lineAlpha, lineColor, etc - values of the axis are used.*/ - class Guide { - /** If you set it to true, the guide will be displayed above the graphs. */ - above: boolean; - /** Radar chart only. Specifies angle at which guide should start. Affects only fills, not lines. */ - angle: number; - /** Baloon fill color. */ - balloonColor: string; - /** The text which will be displayed if the user rolls-over the guide. */ - balloonText: string; - /** Specifies if label should be bold or not. */ - boldLabel: boolean; - /** Category of the guide (in case the guide is for category axis). */ - category: string; - /** Dash length. */ - dashLength: number; - /** Date of the guide (in case the guide is for category axis and parseDates is set to true). */ - date: Date; - /** Works if a guide is added to CategoryAxis and this axis is non-date-based. If you set it to true, the guide will start (or be placed, if it's not a fill) on the beginning of the category cell and will end at the end of toCategory cell. */ - expand: boolean; - /** Fill opacity. Value range is 0 - 1. */ - fillAlpha: number; - /** Fill color. */ - fillColor: string; - /** Font size of guide label. */ - fontSize: string; - /** Unique id of a Guide. You don't need to set it, unless you want to. */ - id: string; - /** Specifies whether label should be placed inside or outside plot area. */ - inside: boolean; - /** The label which will be displayed near the guide. */ - label: string; - /** Rotation angle of a guide label. */ - labelRotation: number; - /** Line opacity. */ - lineAlpha: number; - /** Line color. */ - lineColor: string; - /** Line thickness. */ - lineThickness: number; - /** Position of guide label. Possible values are "left" or "right" for horizontal axis and "top" or "bottom" for vertical axis. */ - position: string; - /** Tick length. */ - tickLength: number; - /** Radar chart only. Specifies angle at which guide should end. Affects only fills, not lines. */ - toAngle: number; - /** To category of the guide (in case the guide is for category axis). */ - toCategory: string; - /** To date of the guide (in case the guide is for category axis and parseDates is set to true) If you have both date and toDate, the space between these two dates can be filled with color. */ - toDate: Date; - /** To value of the guide (in case the guide is for value axis). */ - toValue: number; - /** Value of the guide (in case the guide is for value axis). */ - value: number; - /** Value axis of a guide. As you can add guides directly to the chart, you might need to specify which which value axis should be used. */ - valueAxis: ValueAxis; - } - /** ImagesSettings is a class which holds common settings of all MapImage objects. */ - class ImagesSettings { - /** Opacity of the image. - @default 1 - */ - alpha: number; - /** Text which is displayed in a roll-over balloon. You can use the following tags: [[title]], [[description]], [[value]] and [[percent]]. [[title]] */ - balloonText: string; - /** Specifies if the image's center should be placed in the provided coordinates. If false, top-left corner will be at provided coordinates. - @default true - */ - centered: boolean; - /** Color of image. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. #000000 */ - color: string; - /** Height of a description window. */ - descriptionWindowHeight: number; - /** Width of a description window. - @default 250 - */ - descriptionWindowWidth: number; - /** X position of a description window. */ - descriptionWindowX: number; - /** Y position of a description window. */ - descriptionWindowY: number; - /** Label color. #000000 */ - labelColor: string; - /** Font size of a label. - @default 11 - */ - labelfontSize: string; - /** Position of the label. Allowed values are: left, right, top, bottom and middle. right */ - labelPosition: string; - /** Label roll-over color. #00CC00 */ - labelRollOverColor: string; - /** Opacity of image outline. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. */ - outlineAlpha: number; - /** Color of image outline. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. */ - outlineColor: string; - /** Thickness of image outline. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. - @default 1 - */ - outlineThickness: number; - /** Color of image when hovered. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. */ - rollOverColor: string; - /** Scale of the image when hovered. Use value like 1.5 - 2 to enlarge image when user rolls-over it. - @default 1 - */ - rollOverScale: number; - /** Scale of the image if it is selected. Use value like 1.5 - 2 to enlarge selected image. - @default 1 - */ - selectedScale: number; - } - - /** AreasSettings is a class which holds common settings of all MapArea objects. */ - class AreasSettings { - /** Opacity of areas. - @default 1 - */ - alpha: number; - /** Specifies if the areas should be zoomed-in when user clicks on them, event if zoom properties are not set. */ - autoZoom: boolean; - /** Text which is displayed in a roll-over balloon. You can use the following tags: [[title]], [[description]], [[value]] and [[percent]] [[title]] */ - balloonText: string; - /** Color of the areas. #FFCC00 */ - color: string; - /** Color of area with highest value. Colors for areas with values less then highest will be colored with intermediate colors between color and colorSolid. Use colorSteps property of AmMap to change the number of intermediate colors. #990000 */ - colorSolid: string; - /** Height of a description window. */ - descriptionWindowHeight: number; - /** Width of a description window. - @default 250 - */ - descriptionWindowWidth: number; - /** X position of a description window. */ - descriptionWindowX: number; - /** Y position of a description window. */ - descriptionWindowY: number; - /** Opacity of area's outline. - @default 1 - */ - outlineAlpha: number; - /** Color of area's outline. #FFFFFF */ - outlineColor: string; - /** Thickness of area's outline. 0.5 */ - outlineThickness: number; - /** Color of area when user rolls-over it. undefined */ - rollOverColor: string; - /** Color of area's outline when user rolls-over it. #CC0000 */ - rollOverOutlineColor: string; - /** Color of area which is currently selected. #CC0000 */ - selectedColor: string; - /** Opacity of all areas which are in the map svg file, but not listed as areas in DataSet. - @default 1 - */ - unlistedAreasAlpha: number; - /** Color of all areas which are in the map svg file, but not listed as areas in DataSet. #DDDDDD */ - unlistedAreasColor: string; - /** Opacity of all areas' outline which are in the map svg file, but not listed as areas in DataSet. - @default 1 - */ - unlistedAreasOutlineAlpha: number; - /** Color of all areas' outline which are in the map svg file, but not listed as areas in DataSet. #FFFFFF */ - unlistedAreasOutlineColor: string; - } - - /** Slice is an item of AmPieChart's chartData Array and holds all the information about the slice. When working with a pie chart, you do not create slices or change it's properties directly, instead you set array of data using dataProvider property. Consider properties of a Slice read-only - change values in chart's data provider if you need to. */ - class Slice { - /** Opacity of a slice. */ - alpha: number; - /** Color of a slice. */ - color: string; - /** Original object from data provider. */ - dataContext: Object; - /** Slice description. */ - description: string; - /** Specifies whether the slice is hidden */ - hidden: boolean; - /** Percent value of a slice. */ - percents: number; - /** Specifies whether the slice is pulled or not. */ - pulled: boolean; - /** Slice title */ - title: string; - /** Url of a slice */ - url: string; - /** Value of a slice */ - value: number; - /** specifies whether this slice has a legend entry */ - visibleInLegend: boolean; - } - - - /** AmStockChart is a main class Stock chart. */ - class AmStockChart { - /** Specifies if animation was already played. Animation is only played once, when chart is rendered for the first time. If you want the animation to be repeated, set this property to false. */ - animationPlayed: boolean; - /** Balloon object. */ - balloon: AmBalloon; - /** Settings for category axes. */ - categoryAxesSettings: CategoryAxesSettings; - /** Indicates if the chart is created. */ - chartCreated: boolean; - /** Chart cursor settings. */ - chartCursorSettings: ChartCursorSettings; - /** Chart scrollbar settings. */ - chartScrollbarSettings: ChartScrollbarSettings; - /** Array of colors used by data sets if no color was set explicitly on data set itself. #FF6600, "#FCD202", "#B0DE09", "#0D8ECF", "#2A0CD0", "#CD0D74", "#CC0000", "#00CC00", "#0000CC", "#DDDDDD", "#999999", "#333333", "#990000" */ - colors: any[]; - /** Array of data sets selected for comparing. */ - comparedDataSets: any[]; - /** Array of DataSets. */ - dataSets: any[]; - /** DataSetSelector object. You can add it if you have more than one data set and want users to be able to select/compare them. */ - dataSetSelector: DataSetSelector; - /** Current end date of the selected period, get only. To set start/end dates, use stockChart.zoom(startDate, endDate) method. */ - endDate: Date; - /** Defines on which day week starts. 0 - Sunday, 1 - Monday.. - @default 1 */ - firstDayOfWeek: number; - /** If set to true the scope of the data view will be set to the end after data update. */ - glueToTheEnd: boolean; - /** Legend settings. */ - legendSettings: LegendSettings; - /** Data set selected as main. */ - mainDataSet: DataSet; - /** Array of StockPanels (charts). */ - panels: any[]; - /** Settings for stock panels. */ - panelsSettings: PanelsSettings; - /** Period selector object. You can add it if you want user's to be able to enter date ranges or zoom chart with predefined period buttons. */ - periodSelector: PeriodSelector; - /** Scrollbar's chart object, get only. */ - scrollbarChart: AmSerialChart; - /** Current start date of the selected period, get only. To set start/end dates, use stockChart.zoom(startDate, endDate) method. */ - startDate: Date; - /** Settings for stock events. */ - stockEventsSettings: any; - /** Settings for value axes. */ - valueAxesSettings: ValueAxesSettings; - /** read-only. Indicates current version of a script. */ - version: string; - /** Specifies whether the chart should zoom-out when main data set is changed. */ - zoomOutOnDataSetChange: boolean; - - /** Adds panel to the stock chart. Requires stockChart.validateNow() method to be called after this action. */ - addPanel(panel: StockPanel); - /** Adds panel to the stock chart at a specified index. Requires stockChart.validateNow() method to be called after this action. */ - addPanelAt(panel: StockPanel, index: number); - /** Destroys chart, all timeouts and listeners. */ - clear(); - /** Hides event bullets. */ - hideStockEvents(); - /** Removes event listener from the object. */ - removeListener(obj: any, type: string, handler: any); - /** Removes panel from the stock chart. Requires stockChart.validateNow() method to be called after this action. */ - removePanel(panel: StockPanel); - /** Shows event bullets. */ - showStockEvents(); - /** Method which should be called after data was changed. */ - validateData(); - /** Method which forces the stock chart to rebuild. Should be called after properties are changed. */ - validateNow(); - /** Zooms chart to specified dates. startDate, endDate - Date objects. */ - zoom(startDate: Date, endDate: Date); - /** Zooms out the chart. */ - zoomOut(); - - /** Adds event listener of the type "dataUpdated" or "init" or "rendered" to the object. - @param type Always "dataUpdated" or "init" or "rendered". - @param handler - If the type is "dataUpdated", dispatched when the chart was updated with new data. - If the type is "init", dispatched when the chart is initialized for the first time. In case you want it to fire again after validateNow() method is called, set chart.chartCreated = false. - If the type is "rendered", dispatched each when chart is rendered. - */ - addListener(type: string, handler: (e: { - /** Either "dataUpdated" or "init". */ - type: string; - chart: AmStockChart; - }) => void ); - - /** Adds event listener of the type "rollOutStockEvent" or "rollOverStockEvent" or "clickStockEvent" to the object. - @param type // Either "rollOutStockEvent" or "rollOverStockEvent" or "clickStockEvent". - @param handler - If the type is "rollOutStockEvent", dispatched when the user rolls-out of the Stock event (bullet). - If the type is "rollOverStockEvent", dispatched when the user rolls-over of the Stock event (bullet). - If the type is "clickStockEvent", dispatched when the user clicks on the Stock event (bullet). - */ - - addListener(type: string, handler: (e: { - /** Always "rollOverStockEvent". */ - type: string; - eventObject: any; - graph: AmGraph; - date: Date; - chart: AmStockChart; - }) => void ); - - /** Adds event listener of the type "zoomed" to the object. - @param type Always "zoomed". - @param handler Dispatched when the chart is zoomed (even for the first time, when chart is initialized).*/ - addListener(type: string, handler: (e: { - /** Always "zoomed". */ - type: string; - startDate: Date; - endDate: Date; - period: string; - chart: AmStockChart; - }) => void ); - - /** Adds event listener of the type "panelRemoved" to the object. - @param type Always "panelRemoved". - @param handler Dispatched when the StockPanel is removed.*/ - addListener(type: string, handler: (e: { - /** Always "panelRemoved". */ - - type: string; - panel: StockPanel; - chart: AmStockChart; - }) => void ); - - /** Removes event listener from chart object. */ - removeListener(chart: AmChart, type: string, handler: any); - } - - /** ValueAxesSettings settings set 's settings for all ValueAxes. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of ValueAxis class will be used. */ - class ValueAxesSettings { - /** Specifies whether number for gridCount is specified automatically, according to the axis size. - @default true - */ - autoGridCount: boolean; - /** Axis opacity. */ - axisAlpha: number; - /** Axis color. */ - axisColor: string; - /** Thickness of the axis. */ - axisThickness: number; - /** Label color. */ - color: string; - /** Length of a dash. By default, the grid line is not dashed. */ - dashLength: number; - /** Fill opacity. Every second space between grid lines can be filled with color. */ - fillAlpha: number; - /** Fill color. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills. */ - fillColor: string; - /** Opacity of grid lines. */ - gridAlpha: number; - /** Color of grid lines. */ - gridColor: string; - /** Approximate number of grid lines. autoGridCount should be set to false, otherwise this property will be ignored. */ - gridCount: number; - /** Thickness of grid lines. */ - gridThickness: number; - /** Specifies whether guide values should be included when calculating min and max of the axis. */ - includeGuidesInMinMax: boolean; - /** If true, the axis will include hidden graphs when calculating min and max values. */ - includeHidden: boolean; - /** Specifies whether values should be placed inside or outside plot area. In case you set this to false, you'll have to adjust marginLeft or marginRight in [[PanelsSettings]] in order labels to be visible. - @default true - */ - inside: boolean; - /** Specifies whether values on axis can only be integers or both integers and doubles. */ - integersOnly: boolean; - /** Frequency at which labels should be placed. */ - labelFrequency: number; - /** Specifies whether value labels are displayed. */ - labelsEnabled: boolean; - /** Set to true if value axis is logarithmic, false otherwise. */ - logarithmic: boolean; - /** The distance of the axis to the plot area, in pixels. Useful if you have more then one axis on the same side. */ - offset: number; - /** Position of the value axis. Possible values are "left" and "right". */ - position: string; - /** Set to true if value axis is reversed (smaller values on top), false otherwise. */ - reversed: boolean; - /** Specifies if first label of value axis should be displayed. */ - showFirstLabel: boolean; - /** Specifies if last label of value axis should be displayed. */ - showLastLabel: boolean; - /** Stacking mode of the axis. Possible values are: "none", "regular", "100%", "3d". */ - stackType: string; - /** Tick length. */ - tickLength: number; - /** Unit which will be added to the value label. */ - unit: string; - /** Position of the unit. Possible values are "left" or "right". */ - unitPosition: string; - - } - - - /** AmLegend is the class that displays legend of the chart. Legend to the chart should be added using chart.addLegend(legend) method. - @example - var chart = new AmCharts.AmSerialChart(); - var legend = new AmCharts.AmLegend(); - chart.addLegend(legend); - */ - class AmLegend { - - /** Alignment of legend entries. Possible values are: "left", "center", "right". left */ - align: string; - /** Used if chart is Serial or XY. In case true, margins of the legend are adjusted and made equal to chart's margins. - @default true - */ - autoMargins: boolean; - /** Opacity of legend's background. Value range is 0 - 1 */ - backgroundAlpha: number; - /** Background color. You should set backgroundAlpha to >0 vallue in order background to be visible. #FFFFFF */ - backgroundColor: string; - /** Opacity of chart's border. Value range is 0 - 1. */ - borderAlpha: number; - /** Color of legend's border. You should set borderAlpha >0 in order border to be visible. #000000 */ - borderColor: string; - /** In case legend position is set to "absolute", you can set distance from bottom of the chart, in pixels. */ - bottom: number; - /** Text color. Will use chart's color if not set. */ - color: string; - /** This can be used by AmMap only. You can pass array of objects with title, color, markerType values, for example: [{title: "One", color: "#3366CC"},{title: "Two", color: "#FFCC33"}] */ - data: any[]; - /** Specifies if each of legend entry should be equal to the most wide entry. Won't look good if legend has more than one line. - @default true - */ - equalWidths: boolean; - /** Font size. Will use chart's font size if not set. */ - fontSize: string; - /** Horizontal space between legend item and left/right border. */ - horizontalGap: number; - /** The text which will be displayed in the legend. Tag [[title]] will be replaced with the title of the graph. [[title]] */ - labelText: string; - /** In case legend position is set to "absolute", you can set distance from left side of the chart, in pixels. */ - left: number; - /** Bottom margin. */ - marginBottom: number; - /** Left margin. This property will be ignored if chart is Serial or XY and autoMargins property of the legend is true (default). - @default 20 - */ - marginLeft: number; - /** Right margin. This property will be ignored if chart is Serial or XY and autoMargins property of the legend is true (default). - @default 20 - */ - marginRight: number; - /** Top margin. */ - marginTop: number; - /** Marker border opacity 1. */ - markerBorderAlpha: number; - /** Marker border color. If not set, will use the same color as marker. */ - markerBorderColor: string; - /** Thickness of the legend border. The default value (0) means the line will be a "hairline" (1 px). In case marker type is line, this style will be used for line thickness. - @default 1 - */ - markerBorderThickness: number; - /** The color of the disabled marker (when the graph is hidden). #AAB3B3 */ - markerDisabledColor: string; - /** Space between legend marker and legend text, in pixels. - @default 5 - */ - markerLabelGap: number; - /** Size of the legend marker (key). - @default 16 - */ - markerSize: number; - /** Shape of the legend marker (key). Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble", "none". square */ - markerType: string; - /** Maximum number of columns in the legend. If Legend's position is set to "right" or "left", maxColumns is automatically set to 1. */ - maxColumns: number; - /** Position of a legend. Possible values are: "bottom", "top", "left", "right" and "absolute". In case "absolute", you should set left and top properties too. (this setting is ignored in Stock charts). In case legend is used with AmMap, position is set to "absolute" automatically. bottom */ - position: string; - /** Specifies whether legend entries should be placed in reversed order. */ - reversedOrder: boolean; - /** In case legend position is set to "absolute", you can set distance from right side of the chart, in pixels. */ - right: number; - /** Legend item text color on roll-over. #CC0000 */ - rollOverColor: string; - /** When you roll-over the legend entry, all other graphs can reduce their opacity, so that the graph you rolled-over would be distinguished. This style specifies the opacity of the graphs. - @default 1 - */ - rollOverGraphAlpha: number; - /** You can use this property to turn all the legend entries off. - @default true - */ - showEntries: boolean; - /** Horizontal space between legend items, in pixels. - @default 10 - */ - spacing: number; - /** Whether showing/hiding of graphs by clicking on the legend marker is enabled or not. In case legend is used with AmMap, this is set to false automatically. - @default true - */ - switchable: boolean; - /** Legend switch color. #FFFFFF */ - switchColor: string; - /** Legend switch type (in case the legend is switchable). Possible values are "x" and "v". x */ - switchType: string; - /** If true, clicking on the text will show/hide balloon of the graph. Otherwise it will show/hide graph/slice, if switchable is set to true. */ - textClickEnabled: boolean; - /** In case legend position is set to "absolute", you can set distance from top of the chart, in pixels. */ - top: number; - /** Specifies if legend labels should be use same color as corresponding markers. */ - useMarkerColorForLabels: boolean; - /** Alignment of the value text. Possible values are "left" and "right". right */ - valueAlign: string; - /** The text which will be displayed in the value portion of the legend. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents]], [[description]]. [[value]] */ - valueText: string; - /** Width of the value text. - @default 80 - */ - valueWidth: number; - /** Vertical space between legend items also between legend border and first and last legend row. 10 */ - verticalGap: number; - /** Adds event listener of the type "clickLabel" or "clickMarker" or "hideItem" to the object. - @param type Either "clickLabel" or "clickMarker" or "hideItem". - @param handler - If the type is "clickLabel", dispatched when legend label is clicked. - If the type is "clickMarker", dispatched when legend marker is clicked. - If the type is "hideItem", dispatched when user clicks on a legend item marker and hides corresponding object. - If the type is "rollOutItem", dispatched when user rolls-out of the legend item label (or whole item, if switchable is set to false). - If the type if "rollOverItem", dispatched when user rolls-over the legend item label (or whole item, if switchable is set to false). - If the type is "rollOutMarker", dispatched when user clicks out of a legend item marker and shows corresponding object. - If the type if "rollOverMarker", dispatched when user clicks on a legend item marker and shows corresponding object. - */ - - /** Adds event listener of the type "showItem" to the object. - @param type Always "showItem". - @param handler - */ - addListener(type: string, handler: (e: {/** Always "showItem". */ - type: string; dataItem: Object; chart: AmChart; - }) => void ); - - /** Removes event listener from chart object. */ - removeListener(chart: AmChart, type: string, handler: any); - } - - /** StockLegend is a legend of StockPanel. */ - - class StockLegend extends AmLegend { - /** The text which will be displayed in the value portion of the legend when graph is comparable and at least one dataSet is selected for comparing. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents.value/open/close/low/high]], [[description]]. [[percents.value]]% */ - - valueTextComparing: string; - /** The text which will be displayed in the value portion of the legend. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents]], [[description]]. [[value]] */ - - valueTextRegular: string; - } - - /** StockPanel class creates stock panels (charts). AmStockChart can have multiple Stock panels. */ - - class StockPanel extends AmSerialChart { - /** Specifies whether x button will be displayed near the panel. This button allows turning panel off. */ - allowTurningOff: boolean; - /** If true, drawing icons will be displayed in top-right corner. */ - drawingIconsEnabled: boolean; - /** Specifies on which value axis user can draw trend lines. Set drawingIconsEnabled to true if you want drawing icons to be visible. First value axis will be used if not set here. */ - drawOnAxis: ValueAxis; - /** Specifies if all trend lines should be erased when erase button is clicked. If false, trend lines can be erased one by one. */ - eraseAll: boolean; - /** Size of trend line drawing icons. If you change this size, you should update icon images if you want them to look properly. - @default 18 - */ - iconSize: number; - /** Relative height of panel. Possible values 0 - 100. */ - percentHeight: number; - /** Specifies when values should be recalculated to percents. Possible values are: "never", "always", "whenComparing". whenComparing */ - recalculateToPercents: string; - /** Specifies whether this panel will show category axis. - @default true - */ - showCategoryAxis: boolean; - /** */ - stockGraphs: StockGraph[]; - /** Stock chart legend. */ - stockLegend: StockLegend; - /** Title of a panel. Note, StockLegend should be added in order title to be displayed. */ - title: string; - /** Trend line opacity. - @default 1 - */ - trendLineAlpha: number; - /** Trend line color. #00CC00 */ - trendLineColor: string; - /** Trend line dash length. */ - trendLineDashLength: number; - /** Trend line thickness. - @default 2 - */ - trendLineThickness: number; - /** Adds a graph to the panel. */ - addStockGraph(graph: StockGraph); - /** Removes graph from the panel. */ - removeStockGraph(graph: StockGraph); - } - - /** AmChart is a base class of all charts. It can not be instantiated explicitly. AmCoordinateChart, AmPieChart and AmMap extend AmChart class. */ - class AmChart { - /** used when constructing a chart with a theme */ - constructor(theme?: any); - /** Specifies, if class names should be added to chart elements. */ - addClassNames: boolean; - /** Array of Labels. Example of label object, with all possible properties: -{"x": 20, "y": 20, "text": "this is label", "align": "left", "size": 12, "color": "#CC0000", "alpha": 1, "rotation": 0, "bold": true, "url": "http://www.amcharts.com"} */ - allLabels: Label[]; - /** Set this to false if you don't want chart to resize itself whenever its parent container size changes. */ - autoResize: boolean; - /** Opacity of background. Set it to >0 value if you want backgroundColor to work. However we recommend changing div's background-color style for changing background color. */ - backgroundAlpha: number; - /** Background color. You should set backgroundAlpha to >0 value in order background to be visible. We recommend setting background color directly on a chart's DIV instead of using this property. #FFFFFF */ - backgroundColor: string; - /** The chart creates AmBalloon class itself. If you want to customize balloon, get balloon instance using this property, and then change balloon's properties. AmBalloon */ - balloon: AmBalloon; - /** Opacity of chart's border. Value range is 0 - 1. */ - borderAlpha: number; - /** Color of chart's border. You should set borderAlpha >0 in order border to be visible. We recommend setting border color directly on a chart's DIV instead of using this property. #000000 */ - borderColor: string; - /** This prefix is added to all class names which are added to all visual elements of a chart in case addClassNames is set to true. */ - classNamePrefix: string; - /** Text color. #000000 */ - color: string; - /** Non-commercial version only. Specifies position of link to amCharts site. Allowed values are: top-left, top-right, bottom-left and bottom-right. - @default 'top-left' - */ - creditsPosition: string; - /** Array of data objects, for example: [{country:"US", value:524},{country:"UK", value:624},{country:"Lithuania", value:824}]. You can have any number of fields and use any field names. In case of AmMap, data provider should be MapData object. */ - dataProvider: any[]; - /** Decimal separator. - @Default . */ - decimalSeparator: string; - /** Using this property you can add any additional information to SVG, like SVG filters or clip paths. The structure of this object should be identical to XML structure of a object you are adding, only in JSON format. */ - defs: any; - /** Export config. Specifies how export to image/data export/print/annotate menu will look and behave. You can find a lot of examples in amcharts/plugins/export folder. */ - export: ExportSettings; - /** Font family. Verdana */ - fontFamily: string; - /** Font size. - @default 11 - */ - fontSize: string; - /** If you set this to true, the lines of the chart will be distorted and will produce hand-drawn effect. Try to adjust chart.handDrawScatter and chart.handDrawThickness properties for a more scattered result. - @Default false - */ - handDrawn: boolean; - /** Defines by how many pixels hand-drawn line (when handDrawn is set to true) will fluctuate. - @Default 2 - */ - handDrawScatter: number; - /** Defines by how many pixels line thickness will fluctuate (when handDrawn is set to true). - @Default 1 - */ - handDrawThickness: number; - /** Time, in milliseconds after which balloon is hidden if the user rolls-out of the object. Might be useful for AmMap to avoid balloon flickering while moving mouse over the areas. Note, this is not duration of fade-out. Duration of fade-out is set in AmBalloon class. - @Default 150 - */ - hideBalloonTime: number; - /** Legend of a chart. */ - legend: AmLegend; - /** Reference to the div of the legend. */ - legendDiv: HTMLElement; - /** You can add listeners of events using this property. Example: listeners = [{"event":"dataUpdated", "method":handleEvent}]; */ - listerns: Object[]; - /** This setting affects touch-screen devices only. If a chart is on a page, and panEventsEnabled are set to true, the page won't move if the user touches the chart first. If a chart is big enough and occupies all the screen of your touch device, the user won’t be able to move the page at all. That's why the default value is "false". If you think that selecting/panning the chart or moving/pinching the map is a primary purpose of your users, you should set panEventsEnabled to true. */ - panEventsEnabled: boolean; - /** Specifies absolute or relative path to amCharts files, i.e. "amcharts/". (where all .js files are located) - If relative URLs are used, they will be relative to the current web page, displaying the chart. - You can also set path globally, using global JavaScript variable AmCharts_path. If this variable is set, and "path" is not set in chart config, the chart will assume the path from the global variable. This allows setting amCharts path globally. I.e.: - var AmCharts_path = "/libs/amcharts/"; - "path" parameter will be used by the charts to locate it's files, like images, plugins or patterns.*/ - path: string; - /** Specifies path to the folder where images like resize grips, lens and similar are. - IMPORTANT: Since V3.14.12, you should use "path" to point to amCharts directory instead. The "pathToImages" will be automatically set and does not need to be in the chart config, unless you keep your images separately from other amCharts files. */ - pathToImages: string; - /** Precision of percent values. -1 means percent values won't be rounded at all and show as they are. - @default 2 - */ - percentPrecision: number; - /** Precision of values. -1 means values won't be rounded at all and show as they are. - @Default 1*/ - precision: number; - /** Prefixes which are used to make big numbers shorter: 2M instead of 2000000, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e+3,prefix:"k"},{number:1e+6,prefix:"M"},{number:1e+9,prefix:"G"},{number:1e+12,prefix:"T"},{number:1e+15,prefix:"P"},{number:1e+18,prefix:"E"},{number:1e+21,prefix:"Z"},{number:1e+24,prefix:"Y"}] */ - prefixesOfBigNumbers: any[]; - /** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e-24, prefix:"y"},{number:1e-21, prefix:"z"},{number:1e-18, prefix:"a"},{number:1e-15, prefix:"f"},{number:1e-12, prefix:"p"},{number:1e-9, prefix:"n"},{number:1e-6, prefix:"μ"},{number:1e-3, prefix:"m"}] */ - prefixesOfSmallNumbers: any[]; - /** Theme of a chart. Config files of themes can be found in amcharts/themes/ folder. More info about using themes. */ - theme: string; - /** Thousands separator. - @default . - */ - thousandsSeparator: string; - /** Array of Title objects. */ - titles: Title[]; - /** Type of a chart. Required when creating chart using JSON. Possible types are: serial, pie, xy, radar, funnel, gauge, map, stock. */ - type: string; - /** If true, prefixes will be used for big and small numbers. You can set arrays of prefixes via prefixesOfSmallNumbers and prefixesOfBigNumbers properties. */ - usePrefixes: boolean; - /** Read-only. Indicates current version of a script. */ - version: string; - /** Adds a label on a chart. - You can use it for labeling axes, adding chart title, etc. x and y coordinates can be set in number, percent, or a number with ! in front of it - coordinate will be calculated from right or bottom instead of left or top. - x - horizontal coordinate - y - vertical coordinate - text - label's text - align - alignment (left/right/center) - size - text size - color - text color - rotation - angle of rotation - alpha - label alpha - bold - specifies if text is bold (true/false), - url - url - */ - addLabel(x: number, y: number, text: string, align: string, size: number, color: string, rotation: number, alpha: number, bold: boolean, url: string); - /** Adds a legend to the chart. - By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. - (NOTE: This method will not work on StockPanel.) - @param legend - @param legendDivId - Id of the legend div (optional). - */ - addLegend(legend: AmLegend, legendDivId?: string); - /** Adds a legend to the chart. - By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. - (NOTE: This method will not work on StockPanel.) - @param legend - @param legendDiv - Legend div (optional). - */ - addLegend(legend: AmLegend, legendDiv: HTMLElement); - - /** Adds title to the top of the chart. Pie, Radar positions are updated so that they won't overlap. Plot area of Serial/XY chart is also updated unless autoMargins property is set to false. You can add any number of titles - each of them will be placed in a new line. To remove titles, simply clear titles array: chart.titles = []; and call chart.validateNow() method. text - text of a title size - font size color - title color alpha - title opacity bold - boolean value indicating if title should be bold. */ - addTitle(text: string, size: number, color: string, alpha: number, bold: boolean); - /** Clears the chart area, intervals, etc. */ - clear(); - /** Removes all labels added to the chart. */ - clearLabels(); - /** Use this method to force the chart to resize to it's current container size. */ - invalidateSize(); - /** Removes chart's legend. */ - removeLegend(); - /** This method should be called after data in your data provider changed or a new array was set to dataProvider. After calling this method the chart will parse data and redraw. */ - validateData(); - /** This method should be called after you changed one or more properties of any class. The chart will redraw after this method is called. */ - validateNow(); - - /** Adds chart to the specified DIV. - @param container DIV object which will hold the chart. */ - write(container: HTMLElement): void; - /** Adds chart to the specified DIV. - @param container Id of a DIV which will hold the chart. */ - write(container: string): void; - - /** Adds event listener of the type "dataUpdated" or "init" to the object. - @param type "dataUpdated" or "init". - @param handler - If the type is "dataUpdated". - Dispatched when chart is build for the first time or after validateData() method was called. - If the type is "init". - Dispatched when chart is build for the first time. - */ - addListener(type: string, handler: (e: { - /** Either "dataUpdated" or "init". */ - type: string; - chart: AmChart; - }) => void ); - /** Removes event listener from chart object. */ - removeListener(chart: AmChart, type: string, handler: any); - } - - /** AmCoordinateChart is a base class of AmRectangularChart. It can not be instantiated explicitly. */ - - class AmCoordinateChart extends AmChart { - /** Read-only. Array, holding processed chart's data. */ - chartData: Object[]; - /** Specifies the colors of the graphs if the lineColor of a graph is not set. - It there are more graphs then colors in this array, the chart picks random color. - @default ['#FF6600', '#FCD202', '#B0DE09', '#0D8ECF', '#2A0CD0', '#CD0D74', '#CC0000', '#00CC00', '#0000CC', '#DDDDDD', '#999999', '#333333', '#990000'] */ - colors: string[]; - /** The array of graphs belonging to this chart. - To add/remove graph use addGraph/removeGraph methods instead of adding/removing graphs directly to array. - */ - graphs: AmGraph[]; - /** Specifies if grid should be drawn above the graphs or below. Will not work properly with 3D charts. - @default false - */ - gridAboveGraphs: boolean; - /** Instead of adding guides to the axes, you can push all of them to this array. In case guide has category or date defined, it will automatically will be assigned to the category axis. Otherwise to first value axis, unless you specify a different valueAxis for the guide. */ - guides: Guide[]; - /** Specifies whether the animation should be sequenced or all objects should appear at once. - @default true - */ - sequencedAnimation: boolean; - /** The initial opacity of the column/line. - If you set startDuration to a value higher than 0, the columns/lines will fade in from startAlpha. - Value range is 0 - 1. - @default 1 - */ - startAlpha: number; - /** Duration of the animation, in seconds. */ - startDuration: number; - /** Animation effect. - Possible values are ">", "<", elastic" and "bounce". - @default "elastic" - */ - startEffect: string; - /** Target of url. - @default this - */ - urlTarget: any; - /** The array of value axes. - To add/remove value axis use addValueAxis/removeValueAxis methods instead of adding/removing axes directly to array. - Chart creates one value axis automatically, so if you need only one value axis, you don't need to create it. - */ - valueAxes: any[]; - /** Adds a graph to the chart. - */ - addGraph(graph: AmGraph); - /** Adds a legend to the chart. By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. (NOTE: This method will not work on StockPanel.) */ - /** Adds value axis to the chart. - One value axis is created automatically, so if you don't want to change anything or add more value axes, you don't need to add it. - */ - addValueAxis(axis: ValueAxis); - /** You can trigger the animation of the chart. */ - animateAgain(); - - /** AmGraph Returns graph by id. */ - getGraphById(graphId: string): AmGraph; - - /** Returns value axis by id.*/ - getValueAxisById(axisId: string): ValueAxis; - - /** Hide the graph (if it is visible). Usually this method is called from the Legend, when you click on the legend marker. - */ - hideGraph(graph: AmGraph); - - /** Hide value balloon of a graph. Usually this method is called from the Legend, when you click on the legend text.*/ - hideGraphsBalloon(graph: AmGraph); - - /** Highlight the graph. Usually this method is called from the Legend, when you roll-over the legend entry.*/ - highlightGraph(graph: AmGraph); - - /** Removes graph from the chart.*/ - removeGraph(graph: AmGraph); - - /** Removes value axis from the chart. When you remove value axis, all graphs assigned to this axis are also removed. */ - removeValueAxis(axis: ValueAxis); - - /** Show the graph (if it is hidden). Usually this method is called from the Legend, when you click on the legend marker.*/ - showGraph(graph: AmGraph); - - /** Show value balloon of a graph. Usually this method is called from the Legend, when you click on the legend text.*/ - showGraphsBalloon(graph: AmGraph); - - /** UnhighlightGraph the graph. Usually this method is called from the Legend, when you roll-out the legend entry.*/ - unhighlightGraph(graph: AmGraph); - /** Adds event listener of the type "clickGraphItem" or "doubleClickGraphItem" or "rightClickGraphItem" or "rollOutGraphItem" or "rollOverGraphItem" to the object. - @param type Either "clickGraphItem" or "doubleClickGraphItem" or "rightClickGraphItem" or "rollOutGraphItem" or "rollOverGraphItem". - @param handler Dispatched when user clicks on the data item (column/bullet) - */ - addListener(type: string, handler: (e: { - /** Either "clickGraphItem" or "doubleClickGraphItem" or "rightClickGraphItem" or "rollOutGraphItem" or "rollOverGraphItem". */ - type: string; - graph: AmGraph; - item: GraphDataItem; - index: number; - chart: AmChart; - }) => void ); - } - - /** GraphDataItem holds all the information about the graph's data item. When working with a chart, you do not create GraphDataItem objects or change it's properties directly. GraphDataItem is passed to you by events when user interacts with data item on the chart. The list of properties below will help you to extract data item's value/coordinate/etc. */ - class GraphDataItem { - /** Opacity of the data item. */ - alpha: number; - /** Bullet type. */ - bullet: string; - /** Bullet size. */ - bulletSize: number; - /** Category value. */ - category: string; - /** Color of the data item. */ - color: string; - /** Custom bullet (path to file name). */ - customBullet: string; - /** Original object from data provider. */ - dataContext: Object; - /** Description. */ - description: string; - /** Array of colors of the data item, used by column and candlestick chart only. */ - fillColors: any[]; - /** Object which holds percents when recalculateToPercents is set to true. */ - percents: Object; - /** SerialDataItem of this graphDataItem */ - serialDataItem: SerialDataItem; - /** url */ - url: string; - /** Object which holds values of the data item (value, open, close, low, high). */ - values: Object; - /** x coordinate of the data item. */ - x: number; - /** y coordinate of the data item. */ - y: number; - } - - /** SerialDataItem holds all the information about each series. When working with a chart, you do not create SerialDataItem objects or change it's properties directly. Consider properties of a SerialDataItem read-only - change values in chart's data provider if you need to. When serial chart parses dataProvider, it generates "chartData" array. Objects of this array are SerialDataItem objects. */ - class SerialDataItem { - - /** You can access each GraphDataItem using this object. The data structure is: graphDataItem = serialDataItem.axes[axisId].graphs[graphId]. */ - axes: Object; - - /** category value. String if parseDates is false, Date if true. */ - category: any; - - /** Timestamp of a series date. Avalable only if parseDates property of CategoryAxis is set to true. */ - time: number; - - /** Coordinate (horizontal or vertical, depends on chart's rotate property) of the series. */ - x: number; - } - - class CategoryAxis extends AxisBase { - - /** When parse dates is on for the category axis, the chart will try to highlight the beginning of the periods, like month, in bold. Set this to false to disable the functionality. - @default true - */ - boldPeriodBeginning: boolean; - - /** Date formats of different periods. Possible period values: fff - milliseconds, ss - seconds, mm - minutes, hh - hours, DD - days, MM - months, WW - weeks, YYYY - years. Check this page for date formatting strings. [{period:'fff',format:'JJ:NN:SS'},{period:'ss',format:'JJ:NN:SS'},{period:'mm',format:'JJ:NN'},{period:'hh',format:'JJ:NN'},{period:'DD',format:'MMM DD'},{period:'WW',format:'MMM DD'},{period:'MM',format:'MMM'},{period:'YYYY',format:'YYYY'}] */ - dateFormats: any[]; - - /** In case your category axis values are Date objects and parseDates is set to true, the chart will parse dates and will place your data points at irregular intervals. However if you want dates to be parsed (displayed on the axis, baloons, etc), but data points to be placed at equal intervals (omiting dates with no data), set equalSpacing to true. */ - equalSpacing: boolean; - - /** Field in data provider which specifies if the category value should always be shown. For example: categoryAxis.forceShowField = "forceShow"; Field in data provider which specifies if the category value should always be shown. For example: categoryAxis.forceShowField = "forceShow"; - And in data: - {category:"one", forceShow:true, value:100} - Note, this works only when parseDates is set to false.*/ - forceShowField: string; - - /** Specifies if a grid line is placed on the center of a cell or on the beginning of a cell. Possible values are: "start" and "middle" This setting doesn't work if parseDates is set to true. middle */ - gridPosition: string; - - /** Specifies the shortest period of your data. This should be set only if parseDates is set to "true". Possible period values: fff - milliseconds, ss - seconds, mm - minutes, hh - hours, DD - days, MM - months, YYYY - years. DD */ - minPeriod: string; - - /** In case your category axis values are Date objects, set this to true. In this case the chart will parse dates and will place your data points at irregular intervals. If you want dates to be parsed, but data points to be placed at equal intervals, set both parseDates and equalSpacing to true. */ - parseDates: boolean; - - /** Specifies whether the graph should start on axis or not. In case you display columns, it is recommended to set this to false. If parseDates is set to true, startOnAxis will allways be false, unless equalSpacing is set to true. */ - startOnAxis: boolean; - - /** Number returns coordinate of a category. Works only if parseDates is false. If parseDates is true, use dateToCoordinate method. category - String */ - categoryToCoordinate(category: string); - - /** date - Date object Returns Date of the coordinate, in case parseDates is set to true and equalSpacing is set to false. coordinate - Number */ - coordinateToDate(coordinate: number); - - /** Number Returns coordinate of the date, in case parseDates is set to true. if parseDates is false, use categoryToCoordinate method. date - Date object */ - dateToCoordinate(date: Date); - - /** Number Returns index of the category which is most close to specified coordinate. x - coordinate */ - xToIndex(x: number); - } - - /** ChartScrollbar class displays chart scrollbar. Supported by AmSerialChart and AmXYChart. - @example - var chart = new AmCharts.AmSerialChart(); - var chartScrollbar = new AmCharts.ChartScrollbar(); - chart.addChartScrollbar(chartScrollbar); - */ - class ChartScrollbar { - /** Specifies whether number of gridCount is specified automatically, acoarding to the axis size. */ - autoGridCount: boolean; - /** Background opacity. - @default 1 - */ - backgroundAlpha: number; - /** Background color of the scrollbar. - @default #D4D4D4 - */ - backgroundColor: string; - /** Read-only. Category axis of the scrollbar. */ - categoryAxis: CategoryAxis; - /** Text color. Will use chart's color if not set. */ - color: string; - /** Specifies which graph will be displayed in the scrollbar. Only Serial chart's scrollbar can display a graph. */ - graph: AmGraph; - /** Graph fill opacity. Value range is 0 - 1. 0.1 */ - graphFillAlpha: number; - /** Graph fill color. #000000 */ - graphFillColor: string; - /** Graph line opacity. Value range is 0 - 1. */ - graphLineAlpha: number; - /** Graph line color. #000000 */ - graphLineColor: string; - /** by default the graph type is the same as the original graph's type, however in case of candlestick or ohlc you might want to show line graph in the scrollbar. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". */ - graphType: string; - /** Grid opacity. Value range is 0 - 1. 0.7 */ - gridAlpha: number; - /** Grid color. #FFFFFF */ - gridColor: string; - /** The number of grid lines. */ - gridCount: number; - /** Specifies whether resize grips are hidden when mouse is away from the scrollbar. */ - hideResizeGrips: boolean; - /** Specifies whether scrollbar has a resize feature. - @default true - */ - resizeEnabled: boolean; - /** Height (width, if chart is rotated) of a scrollbar. 20 */ - scrollbarHeight: number; - /** Duration of scrolling, when the user clicks on scrollbar's background, in seconds. - @default 2 - 3*/ - scrollDuration: number; - /** Selected backround opacity. - @default 1 - */ - selectedBackgroundAlpha: number; - /** Selected background color. #EFEFEF */ - selectedBackgroundColor: string; - /** Selected graph's fill opacity. Value range is 0 - 1. 0.5 */ - selectedGraphFillAlpha: number; - /** Selected graph's fill color. #000000 */ - selectedGraphFillColor: string; - /** Selected graph's line opacity. Value range is 0 - 1. */ - selectedGraphLineAlpha: number; - /** Selected graph's line color. #000000 */ - selectedGraphLineColor: string; - /** Specifies if the chart should be updated while dragging/resizing the scrollbar or only at the moment when user releases mouse button. */ - updateOnReleaseOnly: boolean; - } - - /** AmRectangularChart is a base class of AmSerialChart and AmXYChart. It can not be instantiated explicitly.*/ - class AmRectangularChart extends AmCoordinateChart { - /** The angle of the 3D part of plot area. This creates a 3D effect (if the "depth3D" is > 0). - @default 0 - */ - angle: number; - /** Space left from axis labels/title to the chart's outside border, if autoMargins set to true. - @default 10 - */ - autoMarginOffset: number; - /** Specifies if margins of a chart should be calculated automatically so that labels of axes would fit. The chart will adjust only margins with axes. Other margins will use values set with marginRight, marginTop, marginLeft and marginBottom properties. - @default true - */ - autoMargins: boolean; - /** Cursor of a chart. */ - chartCursor: ChartCursor; - /** Chart scrollbar. */ - chartScrollbar: ChartScrollbar; - /** The depth of the 3D part of plot area. This creates a 3D effect (if the "angle" is > 0). - @default 0*/ - depth3D: number; - /** Number of pixels between the container's bottom border and plot area. This space can be used for bottom axis' values. If autoMargin is true and bottom side has axis, this property is ignored. - @default 20 - */ - marginBottom: number; - /** Number of pixels between the container's left border and plot area. This space can be used for left axis' values. If autoMargin is true and left side has axis, this property is ignored. - @default 20 - */ - marginLeft: number; - /** Number of pixels between the container's right border and plot area. This space can be used for Right axis' values. If autoMargin is true and right side has axis, this property is ignored. - @default 20 - */ - marginRight: number; - /** Flag which should be set to false if you need margins to be recalculated on next chart.validateNow() call. - @default false - */ - marginsUpdated: boolean; - /** Number of pixels between the container's top border and plot area. This space can be used for top axis' values. If autoMargin is true and top side has axis, this property is ignored. - @default 20 - */ - marginTop: number; - /** The opacity of plot area's border. Value range is 0 - 1. - @default 0 - */ - plotAreaBorderAlpha: number; - /** The color of the plot area's border. Note, the it is invisible by default, as plotAreaBorderAlpha default value is 0. Set it to a value higher than 0 to make it visible. - @default '#000000'*/ - plotAreaBorderColor: string; - /** Opacity of plot area. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. - @default 0 - */ - plotAreaFillAlphas: number; - /** You can set both one color if you need a solid color or array of colors to generate gradients, for example: ["#000000", "#0000CC"] - @default '#FFFFFF' - */ - plotAreaFillColors: any; - /** If you are using gradients to fill the plot area, you can use this property to set gradient angle. The only allowed values are horizontal and vertical: 0, 90, 180, 270. - @default 0 - */ - plotAreaGradientAngle: number; - /** Array of trend lines added to a chart. You can add trend lines to a chart using this array or access already existing trend lines */ - trendLines: TrendLine[]; - /** Opacity of zoom-out button background. - @default 0 - */ - zoomOutButtonAlpha: number; - /** Zoom-out button background color. - @default '#e5e5e5' - */ - zoomOutButtonColor: string; - /** Name of zoom-out button image. In the images folder there is another lens image, called lensWhite.png. You might want to have white lens when background is dark. Or you can simply use your own image. - @default lens.png - */ - zoomOutButtonImage: string; - /** Size of zoom-out button image - @default: 17 - */ - zoomOutButtonImageSize: number; - /** Padding around the text and image. - @default: 8 - */ - zoomOutButtonPadding: number; - /** Opacity of zoom-out button background when mouse is over it. - @default: 1 - */ - zoomOutButtonRollOverAlpha: number; - /** Text in the zoom-out button. Show all */ - zoomOutText: string; - - /** Adds a ChartCursor object to a chart */ - addChartCursor(cursor: ChartCursor); - /** Adds a ChartScrollbar to a chart */ - addChartScrollbar(scrollbar: ChartScrollbar); - /** Adds a TrendLine to a chart. - You should call chart.validateNow() after this method is called in order the trend line to be visible. */ - addTrendLine(trendLine: TrendLine); - /** Removes cursor from the chart */ - removeChartCursor(); - /** Removes scrollbar from the chart */ - removeChartScrollbar(); - /** Removes a trend line from a chart. - You should call chart.validateNow() in order the changes to be visible. */ - removeTrendLine(trendLine: TrendLine); - } - - /* Trend lines are straight lines indicating trends, might also be used for some different purposes. Can be used by Serial and XY charts. To add/remove trend line, use chart.addTrendLine(trendLine)/chart.removeTrendLine(trendLine) methods or simply pass array of trend lines: chart.trendLines = [trendLine1, trendLine2]. - @example - var trendLine = new AmCharts.TrendLine(); - trendLine.initialDate = new Date(2012, 0, 2, 12); // 12 is hour - to start trend line in the middle of the day - trendLine.finalDate = new Date(2012, 0, 11, 12); - trendLine.initialValue = 10; - trendLine.finalValue = 19; - trendLine.lineColor = "#CC0000"; - chart.addTrendLine(trendLine); - */ - class TrendLine { - - } - - /** ChartCursor is a class which displays a cursor which follows the mouse. In case of Serial chart it also shows value and category balloons. - @example - var chart = new AmCharts.AmSerialChart(); - var chartCursor = new AmCharts.ChartCursor(); - chart.addChartCursor(chartCursor); - */ - class ChartCursor { - /** Specifies if bullet for each graph will follow the cursor. */ - bulletsEnabled: boolean; - /** Size of bullets, following the cursor. - @default 8 - */ - bulletSize: number; - /** Opacity of the category balloon. - @default 1 - */ - categoryBalloonAlpha: number; - /** Color of the category balloon. cursorColor is used if not set. */ - categoryBalloonColor: string; - /** Category balloon date format (used only if category axis parses dates). Check this page for instructions on how to format dates. MMM DD, YYYY */ - categoryBalloonDateFormat: string; - /** Specifies whether category balloon is enabled. - @default true - */ - categoryBalloonEnabled: boolean; - /** Text color. #FFFFFF */ - color: string; - /** Opacity of the cursor line. 1 */ - cursorAlpha: number; - /** Color of the cursor line. #CC0000 */ - cursorColor: string; - /** Specifies where the cursor line should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). If you want the cursor to follow mouse and not to glue to the nearest data point, set "mouse" here. Possible values are: "start", "middle", "mouse". */ - cursorPosition: string; - /** Specifies whether cursor is enabled. - @default true - */ - enabled: boolean; - /** If this is set to true, only one balloon at a time will be displayed. Note, this is quite CPU consuming. */ - oneBalloonOnly: boolean; - /** If this is set to true, the user will be able to pan the chart (Serial only) instead of zooming. */ - pan: boolean; - /** Opacity of the selection. */ - selectionAlpha: number; - /** Specifies if cursor should only mark selected area but not zoom-in after user releases mouse button. */ - selectWithoutZooming: boolean; - /** Specifies whether value balloons are enabled. In case they are not, the balloons might be displayed anyway, when the user rolls-over the column or bullet. - @default true - */ - valueBalloonsEnabled: boolean; - /** Specifies if the user can zoom-in the chart. If pan is set to true, zoomable is switched to false automatically. - @default true - */ - zoomable: boolean; - /** Indicates if currently user is selecting some chart area to zoom-in. */ - zooming: boolean; - - - /** Hides cursor. */ - hideCursor(); - /** You can force cursor to appear at specified cateogry or date. */ - showCursorAt(category: string); - /** Adds event listener of the type "changed" to the object. - @param type Always "changed". - @param handler Dispatched when cursor position is changed. "index" is a series index over which chart cursors currently is. "zooming" specifies if user is currently zooming (is selecting) the chart. mostCloseGraph property is set only when oneBalloonOnly is set to true.*/ - addListener(type: string, handler: (e: {/** Always "changed". */ - type: string; index: number; zooming: boolean; mostCloseGraph: AmGraph; chart: AmChart; - }) => void ); - /** Adds event listener of the type "onHideCursor" to the object. - @param type Always "onHideCursor". - @param handler Dispatched when cursor is hidden.*/ - addListener(type: string, handler: (e: {/** Always "onHideCursor". */ - type: string; chart: AmChart; - }) => void ); - /** Adds event listener of the type "selected" or "zoomed" to the object. - @param type "selected" or "zoomed". - @param handler - If the type is "selected". Dispatched if selectWithoutZooming is set to true and when user selects some period. start and end are indices or timestamp (when categoryAxis.parseDates is true) of selection start/end. - If the type is "zoomed". Dispatched when user zooms to some period. start and end are indices or timestamp (when categoryAxis.parseDates is true) of selection start/end. - */ - addListener(type: string, handler: (e: {/** Always "zoomed". */ - type: string; index: number; zooming: boolean; chart: AmChart; - }) => void ); - - /** Removes event listener from chart object. */ - removeListener(chart: AmChart, type: string, handler: any); - } - - /** AmSerialChart is the class you have to use for majority of chart types. The supported chart types are: line, area, column, bar, step line, smoothed line, candlestick and OHLC. The chart can be rotated by 90 degrees so the column chart becomes bar chart. The chart supports simple and logarithmic scales, it can have multiple value axes. The chart can place data points at equal intervals or can parse dates and place data points at irregular intervals. - @example - var chartData = [{title:"sample 1",value:130},{title:"sample 2",value:26}]; - - var chart = new AmCharts.AmSerialChart(); - chart.categoryField = "title"; - chart.dataProvider = chartData; - - var graph = new AmCharts.AmGraph(); - graph.valueField = "value"; - graph.type = "column"; - graph.fillAlphas = 1; - chart.addGraph(graph); - - chart.write("chartdiv"); - */ - class AmSerialChart extends AmRectangularChart { - /** Date format of the graph balloon (if chart parses dates and you don't use chartCursor). - @default 'MMM DD, YYYY' - */ - balloonDateFormat: string; - /** Read-only. Chart creates category axis itself. If you want to change some properties, you should get this axis from the chart and set properties to this object. */ - categoryAxis: CategoryAxis; - /** Category field name tells the chart the name of the field in your dataProvider object which will be used for category axis values. */ - categoryField: string; - /** The gap in pixels between two columns of the same category. - @default 5 - */ - columnSpacing: number; - /** Space between 3D stacked columns. - @default 0 - */ - columnSpacing3D: number; - /** Relative width of columns. Value range is 0 - 1. - @default 0.8 - */ - columnWidth: number; - /** Read-only. If category axis parses dates endDate indicates date to which the chart is currently displayed. */ - endDate: Date; - /** Read-only. Category index to which the chart is currently displayed. */ - endIndex: number; - /** Maximum number of series allowed to select. */ - maxSelectedSeries: number; - /** The longest time span allowed to select (in milliseconds) for example, 259200000 will limit selection to 3 days. */ - maxSelectedTime: number; - /** The shortest time span allowed to select (in milliseconds) for example, 1000 will limit selection to 1 second. - @default 0 - */ - minSelectedTime: number; - /** Specifies if scrolling of a chart with mouse wheel is enabled. If you press shift while rotating mouse wheel, the chart will zoom-in/out. */ - mouseWheelScrollEnabled: boolean; - /** Specifies if zooming of a chart with mouse wheel is enabled. If you press shift while rotating mouse wheel, the chart will scroll. */ - mouseWheelZoomEnabled: boolean; - /** If you set this to true, the chart will be rotated by 90 degrees (the columns will become bars). */ - rotate: boolean; - /** Read-only. If category axis parses dates startDate indicates date from which the chart is currently displayed. */ - startDate: Date; - /** Read-only. Category index from which the chart is currently displayed. */ - startIndex: number; - /** Specifies if chart should zoom-out when data is updated. - @default true - */ - zoomOutOnDataUpdate: boolean; - - /** Number Returns index of the specified category value. value - series (category value) which index you want to find. */ - getCategoryIndexByValue(value: number); - /** Zooms out, charts shows all available data. */ - zoomOut(); - /** Zooms the chart by the value of the category axis. start - category value, String \\ end - category value, String */ - zoomToCategoryValues(start: Date, end: Date); - /** Zooms the chart from one date to another. start - start date, Date object \\ end - end date, Date object */ - zoomToDates(start: Date, end: Date); - /** Zooms the chart by the index of the category. start - start index, Number \\ end - end index, Number */ - zoomToIndexes(start: Date, end: Date); - } - - class PeriodSelector { - /** Date format of date input fields. Check [[http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/formatters/DateFormatter.html DD-MM-YYYY */ - dateFormat: string; - /** Text displayed next to "from" date input field. From: */ - fromText: string; - /** Specifies if period buttons with date range bigger than available data should be hidden. - @default true - */ - hideOutOfScopePeriods: boolean; - /** Specifies whether period selector displays "from" and "to" date input fields. - @default true - */ - inputFieldsEnabled: boolean; - /** Width of date input fields, in pixels. Works only if period selector is horizontal. - @default 100 - */ - inputFieldWidth: number; - /** Array of predefined period objects. Period object has 4 properties - period, count, label and selected. Possible period values are: "ss" - seconds, "mm" - minutes, "hh" - hours, "DD" - days, "MM" - months and "YYYY" - years. property "count" specifies how many periods this button will select. "label" will be displayed on a button and "selected" is a boolean which specifies if this button is selected when chart is initialized or not. Example: {period:"DD", count:10, label:"10 days", selected:false}. */ - periods: any[]; - /** Text displayed next to predefined period buttons. Zoom: */ - periodsText: string; - /** Possible values: "right", "left", "top", "bottom". bottom */ - position: string; - /** Specifies whether predefined period buttons should select a period from the beginning or the end of the data. */ - selectFromStart: boolean; - /** Text displayed next to "to" date input field. To: */ - toText: string; - /** Width of a period selector, when position is "left" or "right". - @default 180 - */ - width: number; - - /** Adds event listener to the object. - . -@param handler - Dispatched when dates in period selector input fields are changed or user clicks on one of the predefined period buttons. */ - - addListener(type: string, handler: (e: { - /** Always: "changed" */ - - type: string; - startDate: Date; - endDate: Date; - predefinedPeriod: string; - count: number; - }) => void ); - - /** Removes event listener from chart object. */ - removeListener(chart: AmChart, type: string, handler: any); - } - - /** PanelsSettings settings set's settings for all StockPanels. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of StockPanel class will be used. */ - - class PanelsSettings { - /** The angle of the 3D part of plot area. This creates a 3D effect (if the "depth3D" is > 0). */ - angle: number; - /** Opacity of panel background. Possible values are 1 and 0. Values like 0.5 will not make it half-transparent. */ - backgroundAlpha: number; - /** Background color of panels. Set backgroundAlpha to > 0 value in order to make background visible. #FFFFFF */ - backgroundColor: string; - /** The gap in pixels between two columns of the same category. */ - columnSpacing: number; - /** Relative width of columns. Valid values 0 - 1. */ - columnWidth: number; - /** The depth of the 3D part of plot area. This creates a 3D effect (if the "angle" is > 0). */ - depth3D: number; - /** Font family. */ - fontFamily: string; - /** Font size. */ - fontSize: string; - /** Number of pixels between the container's bottom border and plot area. - @default 1 - */ - marginBottom: number; - /** Number of pixels between the container's left border and plot area. If your left valueAxis values ar not placed inside the plot area, you should set marginLeft to 80 or some close value. */ - marginLeft: number; - /** Number of pixels between the container's left border and plot area. If your right valueAxis values ar not placed inside the plot area, you should set marginRight to 80 or some close value. */ - marginRight: number; - /** Number of pixels between the container's top border and plot area. */ - marginTop: number; - /** Gap between panels. - @default 8 - */ - panelSpacing: number; - /** This setting affects touch-screen devices only. If a chart is on a page, and panEventsEnabled are set to true, the page won't move if the user touches the chart first. If a chart is big enough and occupies all the screen of your touch device, the user won’t be able to move the page at all. That's why the default value is "false". If you think that selecting or or panning the chart is a primary purpose of your chart users, you should set panEventsEnabled to true. */ - panEventsEnabled: boolean; - /** The opacity of plot area's border. */ - plotAreaBorderAlpha: number; - /** The color of the plot area's border. */ - plotAreaBorderColor: string; - /** Opacity of plot area fill. */ - plotAreaFillAlphas: number; - /** Specifies the colors used to tint the background gradient fill of the plot area. String or Array of Strings */ - plotAreaFillColors: any; - /** Prefixes which are used to make big numbers shorter: 2M instead of 2000000, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e+3,prefix:"k"},{number:1e+6,prefix:"M"},{number:1e+9,prefix:"G"},{number:1e+12,prefix:"T"},{number:1e+15,prefix:"P"},{number:1e+18,prefix:"E"},{number:1e+21,prefix:"Z"},{number:1e+24,prefix:"Y"}] */ - prefixesOfBigNumbers: any[]; - /** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e-24, prefix:"y"},{number:1e-21, prefix:"z"},{number:1e-18, prefix:"a"},{number:1e-15, prefix:"f"},{number:1e-12, prefix:"p"},{number:1e-9, prefix:"n"},{number:1e-6, prefix:"μ"},{number:1e-3, prefix:"m"}] */ - prefixesOfSmallNumbers: any[]; - /** Specifies whether the animation should be sequenced or all objects should appear at once. */ - sequencedAnimation: boolean; - /** The initial opacity of the column/line. If you set startDuration to a value higher than 0, the columns/lines will fade in from startAlpha. */ - startAlpha: number; - /** Duration of the animation, in seconds. */ - startDuration: number; - /** Possible values are: "linear", "<", ">" "<>", "elastic", "bounce". */ - startEffect: string; - /** If true, prefixes will be used for big and small numbers. */ - usePrefixes: boolean; - } - - /** DataSet is objects which holds all information about data. */ - - class DataSet { - /** Category field name in your dataProvider. */ - categoryField: string; - /** Color of the data set. One of colors from AmStockChart.colors array will be used if not set. */ - color: string; - /** Whether this data set is selected for comparing. If you change this property, you should call stockChart.validateData() method in order the changes to be applied. */ - compared: boolean; - /** Data provider of the data set. */ - dataProvider: any[]; - /** Array of field mappings. Field mapping is an object with fromField and toField properties. fromField is a name of your value field in dataProvider. toField might be chosen freely, it will be used to set value/open/close/high/low fields for the StockGraph. Example: {fromField:"val1", toField:"value"}. */ - fieldMappings: any[]; - /** Specifies whether this data set should be visible in "compare to" list. - @default true - */ - showInCompare: boolean; - /** Specifies whether this data set should be visible in "select" dropdown. - @default true - */ - showInSelect: boolean; - /** Array of StockEvent objects. */ - stockEvents: StockEvent[]; - /** DataSet title. */ - title: string; - } - - class StockGraph extends AmGraph { - /** Specifies whether this graph will be compared if some data set is selected for comparing. */ - comparable: boolean; - /** Specifies a field to be used to generate comparing graph. Note, this field is not the one used in your dataProvider, but toField from FieldMapping object. */ - compareField: string; - /** Balloon color of comparing graph. */ - compareGraphBalloonColor: string; - /** Balloon text of comparing graph. */ - compareGraphBalloonText: string; - /** Bullet of comparing graph. Possible values are: "square", "round", "line", "triangleUp", "triangleDown", "dashedLine", "bubble". */ - compareGraphBullet: string; - /** Bullet size of comparing graph. */ - compareGraphBulletSize: number; - /** Corner radius of comparing graph (if type is "column"). */ - compareGraphCornerRadiusTop: number; - /** Dash length of compare graph. */ - compareGraphDashLength: number; - /** Fill alpha of comparing graph. */ - compareGraphFillAlphas: number; - /** Fill color of comparing graph. */ - compareGraphFillColors: string; - /** Opacity of comparing graph line. */ - compareGraphLineAlpha: number; - /** Thickness of compare graph. */ - compareGraphLineThickness: number; - /** Type of comparing graph. Possible values are: "line", "column", "step", "smoothedLine." line */ - compareGraphType: string; - /** Specifies if compare graph is visible in legend. - @default true - */ - compareGraphVisibleInLegend: boolean; - /** When data is grouped to periods, the graph must know which period value should be used. Possible values are: "Open", "Low", "High", "Close", "Average" and "Sum". Close */ - periodValue: string; - /** Specifies whether data set color should be used as this graph's lineColor. - @default true - */ - useDataSetColors: boolean; - } - - /** StockEvent is object which holds information about event(bullet).Values from StockEventsSettings will be used if not set.Stock event bullet's size depends on it's graphs fontSize.When user rolls - over, clicks or rolls - out of the event bullet, AmStockChart dispatches events.*/ - class StockEvent { - /** Opacity of bullet background. - @default 1 - */ - backgroundAlpha: number; - /** Color of bullet background. #DADADA */ - backgroundColor: string; - /** Opacity of bullet border. - @default 1 - */ - borderAlpha: number; - /** Bullet border color. #888888 */ - borderColor: string; - /** The color of the event text. #000000 */ - color: string; - /** Date of an event. Must be Date object, not a string. */ - date: Date; - /** graph on which event will be displayed. */ - graph: StockGraph; - /** Roll-over background color. #CC0000 */ - rollOverColor: string; - /** Specifies if the event should be displayed on category axis */ - showOnAxis: boolean; - /** Letter which will be displayed on the event. Not all types can display letters. "text" type can display longer texts. */ - text: string; - /** Type of bullet. Possible values are: "flag", "sign", "pin", "triangleUp", "triangleDown", "triangleLeft", "triangleRight", "text", "arrowUp", "arrowDown". sign */ - type: string; - /** A URL to go to when user clicks the event. */ - url: string; - /** target of url, "_blank" for example. */ - urlTarget: string; - } - - /** Creates a label on the chart which can be placed anywhere, multiple can be assigned. */ - class Label { - /** @Default 'left' */ - align: string; - /** @Default 1 */ - alpha: number; - /** Specifies if label is bold or not. */ - bold: boolean; - /** Color of a label */ - color: string; - /** Unique id of a Label. You don't need to set it, unless you want to. */ - id: string; - /** Rotation angle. */ - rotation: number; - /** Text size */ - size: number; - /** Text of a label */ - text: string; - /** URL which will be access if user clicks on a label. */ - url: string; - /** X position of a label. */ - x: number|string; - /** y position of a label. */ - y: number|string; - } - /** Common settings of legends. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of StockLegend class will be used. */ - class LegendSettings { - /** Alignment of legend entries. Possible values are: "left", "right" and "center". */ - align: string; - /** Specifies if each legend entry should take the same space as the longest legend entry. */ - equalWidths: boolean; - /** Horizontal space between legend item and left/right border. */ - horizontalGap: number; - /** The text which will be displayed in the legend. Tag [[title]] will be replaced with the title of the graph. */ - labelText: string; - /** Space below the last row of the legend, in pixels. */ - marginBottom: number; - /** Space above the first row of the legend, in pixels. */ - marginTop: number; - /** Opacity of marker border. */ - markerBorderAlpha: number; - /** Marker border color. */ - markerBorderColor: string; - /** Thickness of the legend border. */ - markerBorderThickness: number; - /** The color of the disabled marker (when the graph is hidden). */ - markerDisabledColor: string; - /** Space between legend marker and legend text, in pixels. */ - markerLabelGap: number; - /** Size of the legend marker (key). */ - markerSize: number; - /** Shape of the legend marker (key). Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble", "none". */ - markerType: string; - /** Specifies whether legend entries should be placed in reversed order. */ - reversedOrder: boolean; - /** Legend item text color on roll-over. */ - rollOverColor: string; - /** When you roll-over the legend entry, all other graphs can reduce their opacity, so that the graph you rolled-over would be distinguished. This property specifies the opacity of the graphs. */ - rollOverGraphAlpha: number; - /** Whether showing/hiding of graphs by clicking on the legend marker is enabled or not. */ - switchable: boolean; - /** Legend switch color. */ - switchColor: string; - /** Legend switch type (in case the legend is switchable). Possible values are: "x" and "v". */ - switchType: string; - /** Specifies whether the legend text is clickable or not. Clicking on legend text can show/hide value balloons if they are enabled. */ - textClickEnabled: boolean; - /** Specifies if legend labels should be use same color as corresponding markers. */ - useMarkerColorForLabels: boolean; - /** The text which will be displayed in the value portion of the legend when graph is comparable and at least one dataSet is selected for comparing. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents]], [[description]]. */ - valueTextComparing: string; - /** The text which will be displayed in the value portion of the legend. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents]], [[description]]. */ - valueTextRegular: string; - /** Width of the value text. Increase this value if your values do not fit in the allocated space. */ - valueWidth: number; - /** Vertical space between legend items, in pixels. */ - verticalGap: number; - - } - - /** DataSetSelector is a tool for selecting data set's as main and for comparing with main data set. */ - class DataSetSelector { - /** Text displayed in the "compare to" combobox (when position is "top" or "bottom"). Select... */ - comboBoxSelectText: string; - /** Text displayed near "compare to" list. Compare to: */ - compareText: string; - /** The maximum height of the Compare to field in pixels. - @default 150 - */ - listHeight: number; - /** Possible values: "right", "left", "top", "bottom". "top" and "bottom" positions has a limitation - only one data set can be selected for comparing. left */ - position: string; - /** Text displayed near "Select" dropDown. Select: */ - selectText: string; - /** Width of a Data set selector, when position is "left" or "right". - @default 180 - */ - width: number; - } - - /** AmBalloon is the class which generates balloons (datatips). Balloon follows the mouse when you roll-over the pie slice/line bullet/column/etc, chart indicator of serial charts displays value balloons and category balloon. Balloon instance is created by the chart automatically and can be accessed via "balloon" property of AmChart. Chart shows/hides and sets position for every balloon automatically, so all you need to do is to change balloon appearance, if you want to. - @example - var chart = new AmCharts.AmSerialChart(); - // get balloon intance - var balloon = chart.balloon; - // set properties - balloon.adjustBorderColor = true; - balloon.color = "#000000"; - balloon.cornerRadius = 5; - balloon.fillColor = "#FFFFFF"; - */ - class AmBalloon { - /** If this is set to true, border color instead of background color will be changed when user rolls-over the slice, graph, etc. */ - adjustBorderColor: boolean; - /** Balloon border opacity. Value range is 0 - 1. - @default 1 - */ - borderAlpha: number; - /** Balloon border color. #FFFFFF */ - borderColor: string; - /** Balloon border thickness. - @default 2 - */ - borderThickness: number; - /** Color of text in the balloon. #FFFFFF */ - color: string; - /** Balloon corner radius. - @default 6 - */ - cornerRadius: number; - /** Balloon background opacity. - @default 1 - */ - fillAlpha: number; - /** Balloon background color. Usually balloon background color is set by the chart. Only if "adjustBorderColor" is "true" this color will be used. #CC0000 */ - fillColor: string; - /** Size of text in the balloon. Chart's fontSize is used by default. */ - fontSize: string; - /** Horizontal padding of the balloon. - @default 8 - 3*/ - horizontalPadding: number; - /** The width of the pointer (arrow) "root". Only used if cornerRadius is 0. - @default 10 - */ - pointerWidth: number; - /** If cornerRadius of a balloon is >0, showBullet is set to true for value balloons when ChartCursor is used. If you don't want the bullet near the balloon, set it to false: chart.balloon.showBullet = false */ - showBullet: boolean; - /** Text alignment, possible values "left", "middle" and "right" middle */ - textAlign: string; - /** Color of the text shadow. #000000 */ - textShadowColor: string; - /** Vertical padding of the balloon. - @default 5 - */ - verticalPadding: number; - /** Hides balloon. */ - hide(); - /** Defines a square within which the balloon should appear. Bounds are set by chart class, you don't need to call this method yourself. */ - setBounds(left: number, top: number, right: number, bottom: number); - /** Sets coordinates the balloon should point to. */ - setPosition(x: number, y: number); - /** Specifies the text which should be displayed. */ - show(value: string); - } - - /** CategoryAxesSettings settings set's settings common for all CategoryAxes of StockPanels. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of CategoryAxis class will be used. */ - class CategoryAxesSettings { - /** Specifies whether number of gridCount is specified automatically, according to the axis size. - @default true - */ - autoGridCount: boolean; - /** Axis opacity. */ - axisAlpha: number; - /** Axis color. */ - axisColor: string; - /** Height of category axes. Set it to 0 if you set inside property to true. - @default 28 - */ - axisHeight: number; - /** Thickness of the axis. */ - axisThickness: number; - /** Text color. */ - color: string; - /** Length of a dash. */ - dashLength: number; - /** Date formats of different periods. Possible period values: fff - milliseconds, ss - seconds, mm - minutes, hh - hours, DD - days, MM - months, WW - weeks, YYYY - years. Check this page for date formatting strings. */ - dateFormats: any[]; - /** If you want data points to be placed at equal intervals (omiting dates with no data), set equalSpacing to true. */ - equalSpacing: boolean; - /** Fill opacity. Every second space between grid lines can be filled with fillColor. */ - fillAlpha: number; - /** Fill color. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills. */ - fillColor: string; - /** Text size. */ - fontSize: string; - /** Opacity of grid lines. */ - gridAlpha: number; - /** Color of grid lines. */ - gridColor: string; - /** Approximate number of grid lines. You should set autoGridCount to false in order this property not to be ignored. - @default 10 - */ - gridCount: number; - /** Thickness of grid lines. */ - gridThickness: number; - /** Periods to which data will be gruoped in case there are more data items in the selected period than specified in maxSeries property. ["ss", "10ss", "30ss", "mm", "10mm", "30mm", "hh", "DD", "WW", "MM", "YYYY"] */ - groupToPeriods: any[]; - /** Specifies whether values should be placed inside or outside of plot area. */ - inside: boolean; - /** Rotation angle of a label. */ - labelRotation: number; - /** Maximum series shown at a time. In case there are more data points in the selection than maxSeries, the chart will group data to longer periods, for example - you have 250 days in the selection, and maxSeries is 150 - the chart will group data to weeks. - @default 150 - */ - maxSeries: number; - /** Specifies the shortest period of your data. fff - millisecond, ss - second, mm - minute, hh - hour, DD - day, MM - month, YYYY - year. DD */ - minPeriod: string; - /** top or "bottom". */ - position: string; - /** Specifies whether the graph should start on axis or not. In case you display columns, it is recommended to set this to false. startOnAxis can be set to true only if equalSpacing is set to true. */ - startOnAxis: boolean; - /** Tick length. */ - tickLength: number; - } - - /** ChartCursorSettings settings set's settings for chart cursor. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of ChartCursor class will be used. */ - class ChartCursorSettings { - /** Specifies if bullet for each graph will follow the cursor. */ - bulletsEnabled: boolean; - /** Size of bullets, following the cursor. */ - bulletSize: number; - /** Opacity of the category balloon. */ - categoryBalloonAlpha: number; - /** Color of the category balloon. */ - categoryBalloonColor: string; - /** Array of date format objects. Date format object must have "period" and "format" items. Available periods are: fff - millisecond, ss - second, mm - minute, hh - hour, DD - date, WW - week, MM - month, YYYY - year. [{period:"YYYY", format:"YYYY"}, {period:"MM", format:"MMM, YYYY"}, {period:"WW", format:"MMM DD, YYYY"}, {period:"DD", format:"MMM DD, YYYY"}, {period:"hh", format:"JJ:NN"}, {period:"mm", format:"JJ:NN"}, {period:"ss", format:"JJ:NN:SS"}, {period:"fff", format:"JJ:NN:SS"}] */ - categoryBalloonDateFormats: any[]; - /** Specifies whether category balloon is enabled. */ - categoryBalloonEnabled: boolean; - /** Opacity of the cursor line. */ - cursorAlpha: number; - /** Color of the cursor line. */ - cursorColor: string; - /** Possible values: "start", "middle" and "mouse". */ - cursorPosition: string; - /** Set this to "false" if you don't want chart cursor to appear in your charts. - @default true - */ - enabled: boolean; - /** If this is set to true, the user will be able to pan the chart instead of zooming. */ - pan: boolean; - /** Specifies whether value balloons are enabled. In case they are not, the balloons might be displayed anyway, when the user rolls-over the column or bullet. */ - valueBalloonsEnabled: boolean; - /** Specifies if the user can zoom-in the chart. If pan is set to true, zoomable is switched to false automatically. */ - zoomable: boolean; - } - - /* ChartScrollbarSettings settings set's settings for chart scrollbar. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of ChartScrollbar class will be used.*/ - class ChartScrollbarSettings { - /** Specifies whether number of gridCount is specified automatically, according to the axis size. - @default true - */ - autoGridCount: boolean; - /** Background opacity. */ - backgroundAlpha: number; - /** Background color of the scrollbar. */ - backgroundColor: string; - /** Text color. */ - color: string; - /** Set false if you don't need scrollbar. - @default true - */ - enabled: boolean; - /** Font size. */ - fontSize: string; - /** Specifies which graph will be displayed in the scrollbar. */ - graph: AmGraph; - /** Graph fill opacity. */ - graphFillAlpha: number; - /** Graph fill color. */ - graphFillColor: string; - /** Graph line opacity. */ - graphLineAlpha: number; - /** Graph line color. */ - graphLineColor: string; - /** Type of chart scrollbar's graph. By default the graph type is the same as the original graph's type, however in case of candlestick or ohlc you might want to show line graph in the scrollbar. Possible values are: line, column, step, smoothedLine, candlestick, ohlc. */ - graphType: string; - /** Grid opacity. */ - gridAlpha: number; - /** Grid color. */ - gridColor: string; - /** Grid count. You should set autoGridCount to false in order this property to work. */ - gridCount: number; - /** Height of scrollbar, in pixels. - @default 40 - */ - height: number; - /** Specifies whether resize grips are hidden when mouse is away from the scrollbar. */ - hideResizeGrips: boolean; - /** Duration of scrolling, when the user clicks on scrollbar's background, in seconds. */ - scrollDuration: number; - /** Selected background opacity. */ - selectedBackgroundAlpha: number; - /** Selected background color. */ - selectedBackgroundColor: string; - /** Selected graph'sfill opacity. */ - selectedGraphFillAlpha: number; - /** Selected graph'sfill color. */ - selectedGraphFillColor: string; - /** Selected graph'sline opacity. */ - selectedGraphLineAlpha: number; - /** Selected graph's line color. */ - selectedGraphLineColor: string; - /** Specifies if the chart should be updated while dragging/resizing the scrollbar or only at the moment when user releases mouse button. Usefull when working with large data sets. - @default true - */ - updateOnReleaseOnly: boolean; - } - - /** AmGraph class displays all types of graphs - line, column, step line, smoothed line, ohlc and candlestick. - @example - var chart = new AmCharts.AmSerialChart(); - var graph = new AmCharts.AmGraph(); - graph.valueField = 'value'; - graph.type = 'column'; - graph.fillAlphas = 1; - chart.addGraph(graph); - */ - class AmGraph { - /** Name of the alpha field in your dataProvider. */ - alphaField: string; - /** Value balloon color. Will use graph or data item color if not set. */ - balloonColor: string; - /** If you set some function, the graph will call it and pass GraphDataItem and AmGraph object to it. This function should return a string which will be displayed in a balloon. */ - balloonFunction(graphDataItem: GraphDataItem, amGraph: AmGraph): string; - /** Balloon text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] [[value]] */ - balloonText: string; - /** Specifies if the line graph should be placed behind column graphs */ - behindColumns: boolean; - /** Type of the bullets. Possible values are: "none", "round", "square", "triangleUp", "triangleDown", "bubble", "custom". none */ - bullet: string; - /** Opacity of bullets. Value range is 0 - 1. - @default 1 - */ - bulletAlpha: number; - /** Bullet border opacity. - @default 1 - */ - bulletBorderAlpha: number; - /** Bullet border color. Will use lineColor if not set. */ - bulletBorderColor: string; - /** Bullet border thickness. - @default 2 - */ - bulletBorderThickness: number; - /** Bullet color. Will use lineColor if not set. */ - bulletColor: string; - /** Name of the bullet field in your dataProvider. */ - bulletField: string; - /** Bullet offset. Distance from the actual data point to the bullet. Can be used to place custom bullets above the columns. */ - bulletOffset: number; - /** Bullet size. - @default 8 - */ - bulletSize: number; - /** Name of the bullet size field in your dataProvider. */ - bulletSizeField: string; - /** Name of the close field (used by candlesticks and ohlc) in your dataProvider. */ - closeField: string; - /** Color of value labels. Will use chart's color if not set. */ - color: string; - /** Name of the color field in your dataProvider. */ - colorField: string; - /** Specifies whether to connect data points if data is missing. The default value is true. - @default true - */ - connect: boolean; - /** Corner radius of column. It can be set both in pixels or in percents. The chart's depth and angle styles must be set to 0. The default value is 0. Note, cornerRadiusTop will be applied for all corners of the column, JavaScript charts do not have a possibility to set separate corner radius for top and bottom. As we want all the property names to be the same both on JS and Flex, we didn't change this too. */ - cornerRadiusTop: number; - /** If bulletsEnabled of ChartCurosor is true, a bullet on each graph follows the cursor. You can set opacity of each graphs bullet. In case you want to disable these bullets for a certain graph, set opacity to 0. - @default 1 - */ - cursorBulletAlpha: number; - /** Path to the image of custom bullet. */ - customBullet: string; - /** Name of the custom bullet field in your dataProvider. */ - customBulletField: string; - /** Dash length. If you set it to a value greater than 0, the graph line will be dashed. */ - dashLength: number; - /** Name of the description field in your dataProvider. */ - descriptionField: string; - /** Opacity of fill. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. */ - fillAlphas: number; - /** Fill color. Will use lineColor if not set. */ - fillColors: any; - /** Name of the fill colors field in your dataProvider. */ - fillColorsField: string; - /** You can set another graph here and if fillAlpha is >0, the area from this graph to fillToGraph will be filled (instead of filling the area to the X axis). */ - fillToGraph: AmGraph; - /** Size of value labels text. Will use chart's fontSize if not set. */ - fontSize: string; - /** Orientation of the gradient fills (only for "column" graph type). Possible values are "vertical" and "horizontal". vertical */ - gradientOrientation: string; - /** Specifies whether the graph is hidden. Do not use this to show/hide the graph, use hideGraph(graph) and showGraph(graph) methods instead. */ - hidden: boolean; - /** If there are more data points than hideBulletsCount, the bullets will not be shown. 0 means the bullets will always be visible. */ - hideBulletsCount: number; - /** Name of the high field (used by candlesticks and ohlc) in your dataProvider. */ - highField: string; - /** Whether to include this graph when calculating min and max value of the axis. - @default true - */ - includeInMinMax: boolean; - /** Name of label color field in data provider. */ - labelColorField: string; - /** Position of value label. Possible values are: "bottom", "top", "right", "left", "inside", "middle". Sometimes position is changed by the chart, depending on a graph type, rotation, etc. top */ - labelPosition: string; - /** Value label text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]]. */ - labelText: string; - /** Legend marker opacity. Will use lineAlpha if not set. Value range is 0 - 1. */ - legendAlpha: number; - /** Legend marker color. Will use lineColor if not set. */ - legendColor: string; - /** Legend value text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] You can also use custom fields from your dataProvider. If not set, uses Legend's valueText. */ - legendValueText: string; - /** Opacity of the line (or column border). Value range is 0 - 1. - @default 1 - */ - lineAlpha: number; - /** Color of the line (or column border). If you do not set any, the color from [[AmCoordinateChart */ - lineColor: string; - /** Name of the line color field (used by columns and candlesticks only) in your dataProvider. */ - lineColorField: string; - /** Specifies thickness of the graph line (or column border). - @default 1 - */ - lineThickness: number; - /** Name of the low field (used by candlesticks and ohlc) in your dataProvider. */ - lowField: string; - /** Legend marker type. You can set legend marker (key) type for individual graphs. Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble". */ - markerType: string; - /** Specifies size of the bullet which value is the biggest (XY chart). - @default 50 - */ - maxBulletSize: number; - /** Specifies minimum size of the bullet (XY chart). */ - minBulletSize: number; - /** If you use different colors for your negative values, a graph below zero line is filled with negativeColor. With this property you can define a different base value at which colors should be changed to negative colors. */ - negativeBase: number; - /** Fill opacity of negative part of the graph. Will use fillAlphas if not set. */ - negativeFillAlphas: number; - /** Fill color of negative part of the graph. Will use fillColors if not set. */ - negativeFillColors: any; //String /Array; - /** Color of the line (or column) when the values are negative. In case the graph type is candlestick or ohlc, negativeLineColor is used when close value is less then open value. */ - negativeLineColor: string; - /** Example: {precision:-1, decimalSeparator:'.', thousandsSeparator:','}. The graph uses this object's values to format the numbers. Uses chart's numberFormatter if not defined. */ - numberFormatter: Object; - /** Name of the open field (used by floating columns, candlesticks and ohlc) in your dataProvider. */ - openField: string; - /** Specifies where data points should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). This setting affects Serial chart only. Possible values are "start" and "middle". middle */ - pointPosition: string; - /** If graph's type is column and labelText is set, graph hides labels which do not fit into the column's space. If you don't want these labels to be hidden, set this to true. */ - showAllValueLabels: boolean; - /** Specifies whether the value balloon of this graph is shown when mouse is over data item or chart's indicator is over some series. - @default true - */ - showBalloon: boolean; - /** Specifies graphs value at which cursor is showed. This is only important for candlestick and ohlc charts, also if column chart has "open" value. Possible values are: "open", "close", "high", "low". close */ - showBalloonAt: string; - /** If the value axis of this graph has stack types like "regular" or "100%" You can exclude this graph from stacking. - @default true - */ - stackable: boolean; - /** Graph title. */ - title: string; - /** Type of the graph. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". XY and Radar charts can only display "line" type graphs. line */ - type: string; - /** Name of the url field in your dataProvider. */ - urlField: string; - /** Target to open URLs in, i.e. _blank, _top, etc. */ - urlTarget: string; - /** Specifies which value axis the graph will use. Will use the first value axis if not set. */ - valueAxis: ValueAxis; - /** Name of the value field in your dataProvider. */ - valueField: string; - /** Specifies whether this graph should be shown in the Legend. - @default true - */ - visibleInLegend: boolean; - /** XY chart only. A horizontal value axis object to attach graph to. */ - xAxis: ValueAxis; - /** XY chart only. Name of the x field in your dataProvider. */ - xField: string; - /** XY chart only. A vertical value axis object to attach graph to. */ - yAxis: ValueAxis; - /** XY chart only. Name of the y field in your dataProvider. */ - yField: string; - } - - /** AxisBase is the base class for ValueAxis and CategoryAxis. It can not be instantiated explicitly. */ - class AxisBase { - /** Specifies whether number of gridCount is specified automatically, acoarding to the axis size. - @default true - */ - autoGridCount: boolean; - /** Axis opacity. Value range is 0 - 1. - @default 1 - */ - axisAlpha: number; - /** Axis color. #000000 */ - axisColor: string; - /** Thickness of the axis. - @default 1 - */ - axisThickness: number; - /** Color of axis value labels. Will use chart's color if not set. */ - color: string; - /** Length of a dash. 0 means line is not dashed. */ - dashLength: number; - /** Fill opacity. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills. */ - fillAlpha: number; - /** Fill color. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills. #FFFFFF */ - fillColor: string; - /** Size of value labels text. Will use chart's fontSize if not set. */ - fontSize: string; - /** Opacity of grid lines. 0.2 */ - gridAlpha: number; - /** Color of grid lines. #000000 */ - gridColor: string; - /** Number of grid lines. In case this is value axis, or your categoryAxis parses dates, the number is approximate. The default value is 5. If you set autoGridCount to true, this property is ignored. - @default 5 - */ - gridCount: number; - /** Thickness of grid lines. - @default 1 - */ - gridThickness: number; - /** The array of guides belonging to this axis. */ - guides: any[]; - /** If autoMargins of a chart is set to true, but you want this axis not to be measured when calculating margin, set ignoreAxisWidth to true. */ - ignoreAxisWidth: boolean; - /** Specifies whether values should be placed inside or outside plot area. */ - inside: boolean; - /** Frequency at which labels should be placed. Doesn't work for CategoryAxis if parseDates is set to true. - @default 1 - */ - labelFrequency: number; - /** Rotation angle of a label. Only horizontal axis' values can be rotated. If you set this for vertical axis, the setting will be ignored. */ - labelRotation: number; - /** Specifies whether axis displays category axis' labels and value axis' values. - @default true - */ - labelsEnabled: boolean; - /** The distance of the axis to the plot area, in pixels. Negative values can also be used. */ - offset: number; - /** Possible values are: "top", "bottom", "left", "right". If axis is vertical, default position is "left". If axis is horizontal, default position is "bottom". */ - position: string; - /** Whether to show first axis label or not. - @default true - */ - showFirstLabel: boolean; - /** Whether to show last axis label or not. - @default true - */ - showLastLabel: boolean; - /** Length of the tick marks. - @default 5 - */ - tickLength: number; - /** Title of the axis. */ - title: string; - /** Specifies if title should be bold or not. - @default true - */ - titleBold: boolean; - /** Color of axis title. Will use text color of chart if not set any. */ - titleColor: string; - /** Font size of axis title. Will use font size of chart plus two pixels if not set any. */ - titlefontSize: string; - - /** Adds guide to the axis. */ - addGuide(guide:Guide); - /** Removes guide from the axis. */ - removeGuide(guide:Guide); - } - - /** ValueAxis is the class which displays value axis for the chart. The chart can have any number of value axes. For Serial chart one value axis is created automatically. For XY Chart two value axes (horizontal and vertical) are created automatically. */ - class ValueAxis extends AxisBase { - /** Radar chart only. Specifies distance from axis to the axis title (category) 10 */ - axisTitleOffset: number; - /** Read-only. Coordinate of the base value. */ - baseCoord: number; - /** Specifies base value of the axis. */ - baseValue: number; - /** If your values represents time units, and you want value axis labels to be formatted as duration, you have to set the duration unit. Possible values are: "ss", "mm", "hh" and "DD". */ - duration: string; - /** If duration property is set, you can specify what string should be displayed next to day, hour, minute and second. {DD:"d. ", hh:":", mm:":",ss:""} */ - durationUnits: Object; - /** Radar chart only. Possible values are: "polygons" and "circles". Set "circles" for polar charts. polygons */ - gridType: string; - /** Unique id of value axis. It is not required to set it, unless you need to tell the graph which exact value axis it should use. */ - id: string; - /** Specifies whether guide values should be included when calculating min and max of the axis. */ - includeGuidesInMinMax: boolean; - /** If true, the axis will include hidden graphs when calculating min and max values. */ - includeHidden: boolean; - /** Specifies whether values on axis can only be integers or both integers and doubles. */ - integersOnly: boolean; - /** You can use this function to format Value axis labels. This function is called and these parameters are passed: labelFunction(value, valueText, valueAxis); -Where value is numeric value, valueText is formatted string and valueAxis is a reference to valueAxis object. - -If axis type is "date", labelFunction will pass different arguments: -labelFunction(valueText, date, valueAxis) - -Your function should return string.*/ - labelFunction(value: number, valueText: string, valueAxis: ValueAxis): string; - labelFunction(valueText: string, data: Date, valueAxis: ValueAxis): string; - /** Specifies if this value axis' scale should be logarithmic. */ - logarithmic: boolean; - /** Read-only. Maximum value of the axis. */ - max: number; - /** If you don't want max value to be calculated by the chart, set it using this property. This value might still be adjusted so that it would be possible to draw grid at rounded intervals. */ - maximum: number; - /** If your value axis is date-based, you can specify maximum date of the axis. Can be set as date object, timestamp number or string if dataDateFormat is set. */ - maximumData: Date; - /** Read-only. Minimum value of the axis. */ - min: number; - /** If you don't want min value to be calculated by the chart, set it using this property. This value might still be adjusted so that it would be possible to draw grid at rounded intervals. */ - minimum: number; - /** If your value axis is date-based, you can specify minimum date of the axis. Can be set as date object, timestamp number or string if dataDateFormat is set. */ - minimumDate: Date; - /** If set value axis scale (min and max numbers) will be multiplied by it. I.e. if set to 1.2 the scope of values will increase by 20%. */ - minMaxMultiplier: number; - /** Works with radar charts only. If you set it to “middle”, labels and data points will be placed in the middle between axes. */ - pointPosition: string; - /** Possible values are: "top", "bottom", "left", "right". If axis is vertical, default position is "left". If axis is horizontal, default position is "bottom". */ - position: string; - /** Precision (number of decimals) of values. */ - precision: number; - /** Radar chart only. Specifies if categories (axes' titles) should be displayed near axes) - @default true - */ - radarCategoriesEnabled: boolean; - /** pecifies if graphs's values should be recalculated to percents. */ - recalculateToPercents: boolean; - /** Specifies if value axis should be reversed (smaller values on top). */ - reversed: boolean; - /** Stacking mode of the axis. Possible values are: "none", "regular", "100%", "3d". none Note, only graphs of one type will be stacked. */ - stackType: string; - /** Read-only. Value difference between two grid lines. */ - step: number; - /** If you set minimum and maximum for your axis, chart adjusts them so that grid would start and end on the beginning and end of plot area and grid would be at equal intervals. If you set strictMinMax to true, the chart will not adjust minimum and maximum of value axis. */ - strictMinMax: boolean; - /** In case you synchronize one value axis with another, you need to set the synchronization multiplier. Use synchronizeWithAxis method to set with which axis it should be synced. */ - synchronizationMultiplier: number; - /** One value axis can be synchronized with another value axis. You can use both reference to your axis or id of the axis here. You should set synchronizationMultiplyer in order for this to work. */ - synchronizeWith: ValueAxis; - /** If this value axis is stacked and has columns, setting valueAxis.totalText = "[[total]]" will make it to display total value above the most-top column. */ - totalText: string; - /** Color of total text. */ - totalTextColor: string; - /** Distance from data point to total text. */ - totalTextOffset: number; - /** This allows you to have logarithmic value axis and have zero values in the data. You must set it to >0 value in order to work. */ - treatZeroAs: number; - /** Type of value axis. If your values in data provider are dates and you want this axis to show dates instead of numbers, set it to "date". */ - type: string; - /** Unit which will be added to the value label. */ - unit: string; - /** Position of the unit. Possible values are "left" and "right". right */ - unitPosition: string; - /** If true, prefixes will be used for big and small numbers. You can set arrays of prefixes directly to the chart object via prefixesOfSmallNumbers and prefixesOfBigNumbers. */ - usePrefixes: boolean; - /** If true, values will always be formatted using scientific notation (5e+8, 5e-8...) Otherwise only values bigger then 1e+21 and smaller then 1e-7 will be displayed in scientific notation. */ - useScientificNotation: boolean; - - /** Adds guide to the axis. */ - addGuide(guide: Guide); - /** Adds event listener to the object. type - string like 'axisChanged' (should be listed in 'events' section of this class or classes which extend this class). handler - function which is called when event happens */ - addListener(type: string, handler: any); - /** Number, - value of coordinate. Returns value of the coordinate. coordinate - y or x coordinate, in pixels. */ - coordinateToValue(coordinate: number); - /** Number - coordinate Returns coordinate of the value in pixels. value - Number */ - getCoordinate(value: number); - /** Removes guide from the axis.*/ - removeGuide(guide: Guide); - /** Removes event listener from the object. */ - removeListener(obj: any, type: string, handler: any); - - /** One value axis can be synchronized with another value axis. You should set synchronizationMultiplyer in order for this to work. */ - synchronizeWithAxis(axis:ValueAxis); - /** XY Chart only. Zooms-in the axis to the provided values. */ - zoomToValues(startValue: number, endValue: number); - - /** Adds event listener of the type "axisZoomed" to the object. - @param type Always "axisZoomed". - @param handler XY chart only. Dispatched when axis is zoomed.*/ - addListener(type: string, handler: (e: { - /** Always "axisZoomed". */ - type: string; startValue: Date; endValue: Date; chart: AmChart; - }) => void ); - /** Adds event listener of the type "logarithmicAxisFailed" to the object. - @param type Always "logarithmicAxisFailed". - @param handler Dispatched when valueAxis is logarithmic and values equal or less then zero were found in data.*/ - addListener(type: string, handler: (e: { - /** Always "logarithmicAxisFailed". */ - type: string; chart: AmChart; - }) => void ); - - /** Removes event listener from chart object. */ - removeListener(chart: AmChart, type: string, handler: any); - } - - class Title { - /** @default 1 */ - alpha: number; - /** Specifies if the tile is bold or not. - @default false*/ - bold: boolean; - /** Text color of a title. */ - color: string; - /** Unique id of a Title. You don't need to set it, unless you want to. */ - id: string; - /** Text size */ - size: number; - /** Text of a label */ - text: string; - } - class ExportSettings { - enabled: boolean; - libs: Object; - menu: Object; - } -} diff --git a/amcharts/AmCharts.d.ts.tscparams b/amcharts/AmCharts.d.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/amcharts/AmCharts.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/amcharts/index.d.ts b/amcharts/index.d.ts new file mode 100644 index 0000000000..a54ed5d515 --- /dev/null +++ b/amcharts/index.d.ts @@ -0,0 +1,2579 @@ +// Type definitions for amCharts +// Project: http://www.amcharts.com/ +// Definitions by: aleksey-bykov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// AmCharts object (it's not a class) is create automatically when amcharts.js or amstock.js file is included in a web page. +declare namespace AmCharts { + + /** Set it to true if you have base href set for your page. This will fix rendering problems in Firefox caused by base href. */ + var baseHref: boolean; + + /** Array of day names, used when formatting dates (if categoryAxis.parseDates is set to true) ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] */ + var dayNames: string[]; + + /** Array of month names, used when formatting dates (if categoryAxis.parseDates is set to true) ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] */ + var monthNames: string[]; + + /** Array of short versions of day names, used when formatting dates (if categoryAxis.parseDates is set to true) ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] */ + var shortDayNames: string[]; + + /** Array of short versions of month names, used when formatting dates (if categoryAxis.parseDates is set to true) ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] */ + var shortMonthNames: string[]; + + /** Set it to true if you want UTC time to be used instead of local time. */ + var useUTC: boolean; + + /** Clears all the charts on page, removes listeners and intervals. */ + function clear(); + + /** AmPieChart class creates pie/donut chart. In order to display pie chart you need to set at least three properties - dataProvider, titleField and valueField. + @example + var chartData = [{title:"Pie I have eaten",value:70},{title:"Pie I haven\'t eaten",value:30}]; + var chart = new AmCharts.AmPieChart(); + chart.valueField = "value"; + chart.titleField = "title"; + chart.dataProvider = chartData; + chart.write("chartdiv"); + */ + class AmPieChart { + /** Name of the field in chart's dataProvider which holds slice's alpha. */ + alphaField: string; + /** Pie lean angle (for 3D effect). Valid range is 0 - 90. */ + angle: number; + /** Balloon text. The following tags can be used: [[value]], [[title]], [[percents]], [[description]]. [[title]]: [[percents]]% ([[value]])\n[[description]] */ + balloonText: string; + /** Read-only. Array of Slice objects. */ + chartData: any[]; + /** Name of the field in chart's dataProvider which holds slice's color. */ + colorField: string; + /** Specifies the colors of the slices, if the slice color is not set. If there are more slices than colors in this array, the chart picks random color. ["#FF0F00", "#FF6600", "#FF9E01", "#FCD202", "#F8FF01", "#B0DE09", "#04D215", "#0D8ECF", "#0D52D1", "#2A0CD0", "#8A0CCF", "#CD0D74", "#754DEB", "#DDDDDD", "#999999", "#333333", "#000000", "#57032A", "#CA9726", "#990000", "#4B0C25"] */ + colors: any[]; + /** Depth of the pie (for 3D effect). */ + depth3D: number; + /** Name of the field in chart's dataProvider which holds a string with description. */ + descriptionField: string; + /** Example: [-0.2,0.2]. Will make slices to be filled with color gradients. */ + gradientRatio: number[]; + /** Opacity of the group slice. Value range is 0 - 1. + @default 1 + */ + groupedAlpha: number; + /** Color of the group slice. The default value is not set - this means the next available color from "colors" array will be used. */ + groupedColor: string; + /** Description of the group slice. */ + groupedDescription: string; + /** If this is set to true, the group slice will be pulled out when the chart loads. */ + groupedPulled: boolean; + /** Title of the group slice. Other */ + groupedTitle: string; + /** If there is more than one slice whose percentage of the pie is less than this number, those slices will be grouped together into one slice. This is the "other" slice. It will always be the last slice in a pie. */ + groupPercent: number; + /** Slices with percent less then hideLabelsPercent won't display labels This is useful to avoid cluttering up the chart, if you have a lot of small slices. 0 means all labels will be shown. */ + hideLabelsPercent: number; + /** Opacity of a hovered slice. Value range is 0 - 1. + @default 1 + */ + hoverAlpha: number; + /** Inner radius of the pie, in pixels or percents. */ + innerRadius: any; + /** The distance between the label and the slice, in pixels. You can use negative values to put the label on the slice. + @default 30 + */ + labelRadius: number; + /** Name of the field in dataProvider which specifies the length of a tick. Note, the chart will not try to arrange labels automatically if this property is set. */ + labelRadiusField: string; + /** Specifies whether data labels are visible. + @default true + */ + labelsEnabled: boolean; + /** Label text. The following tags can be used: [[value]], [[title]], [[percents]], [[description]]. [[title]]: [[percents]]% */ + labelText: string; + /** Label tick opacity. Value range is 0 - 1. 0.2 */ + labelTickAlpha: number; + /** Label tick color. #000000 */ + labelTickColor: string; + /** Bottom margin of the chart. + @default 5 + */ + marginBottom: number; + /** Left margin of the chart. */ + marginLeft: number; + /** Right margin of the chart. */ + marginRight: number; + /** Top margin of the chart. + @default 5 + */ + marginTop: number; + /** Minimum radius of the pie, in pixels. + @default 10 + */ + minRadius: number; + /** Pie outline opacity. Value range is 0 - 1. */ + outlineAlpha: number; + /** Pie outline color. #FFFFFF */ + outlineColor: string; + /** Pie outline thickness. + @default 1 + */ + outlineThickness: number; + /** Opacity of the slices. You can set the opacity of individual slice too. + @default 1 + */ + pieAlpha: number; + /** Color of the first slice. All the other will be colored with darker or brighter colors. */ + pieBaseColor: string; + /** Lightness increase of each subsequent slice. This is only useful if pieBaseColor is set. Use negative values for darker colors. Value range is from -255 to 255. + @default 30*/ + pieBrightnessStep: number; + /** You can set fixed position of a pie center, in pixels or in percents. */ + pieX: any; + /** You can set fixed position of a pie center, in pixels or in percents. */ + pieY: any; + /** Name of the field in chart's dataProvider which holds a boolean value telling the chart whether this slice must be pulled or not. */ + pulledField: string; + /** Pull out duration, in seconds. + @default 1 + */ + pullOutDuration: number; + /** Pull out effect. Possible values are ">", "<", elastic" and "bounce". bounce */ + pullOutEffect: string; + /** If this is set to true, only one slice can be pulled out at a time. If the viewer clicks on a slice, any other pulled-out slice will be pulled in. */ + pullOutOnlyOne: boolean; + /** Pull out radius, in pixels or percents 0.2 */ + pullOutRadius: any; + /** Radius of a pie, in pixels or percents. By default, radius is calculated automatically. */ + radius: any; + /** Specifies whether the animation should be sequenced or all slices should appear at once. */ + sequencedAnimation: boolean; + /** Initial opacity of all slices. If you set startDuration higher than 0, slices will fade in from startAlpha. + @default 1 + */ + startAlpha: number; + /** Angle of the first slice, in degrees. This will work properly only if "depth3D" is set to 0. If "depth3D" is greater than 0, then there can be two angles only: 90 and 270. Value range is 0-360. + @default 90 + */ + startAngle: number; + /** Duration of the animation, in seconds. + @default 1 + */ + startDuration: number; + /** Animation effect. Possible values are ">", "<", "elastic" and "bounce". bounce */ + startEffect: string; + /** Radius of the positions from which the slices will fly in. + default 5 + */ + startRadius: any; + /** Name of the field in chart's dataProvider which holds slice's title. */ + titleField: string; + /** Name of the field in chart's dataProvider which holds url which would be accessed if the user clicks on a slice. */ + urlField: string; + /** If url is specified for a slice, it will be opened when user clicks on it. urlTarget specifies target of this url. Use _blank if you want url to be opened in a new window. _self */ + urlTarget: string; + /** Name of the field in chart's dataProvider which holds slice's value. */ + valueField: string; + /** Name of the field in chart's dataProvider which holds boolean variable defining whether this data item should have an entry in the legend. */ + visibleInLegendField: string; + + /** You can trigger the animation of the pie chart. */ + animateAgain(); + /** You can trigger the click on a slice from outside. index - the number of a slice or Slice object. */ + clickSlice(index: number); + /** Hides slice. index - the number of a slice or Slice object. */ + hideSlice(index: number); + /** You can simulate roll-out of a slice from outside. index - the number of a slice or Slice object. */ + rollOutSlice(index: number); + /** You can simulate roll-over a slice from outside. index - the number of a slice or Slice object. */ + rollOverSlice(index: number); + /** Shows slice. index - the number of a slice or Slice object. */ + showSlice(index: number); + + /** Adds event listener of the type "clickSlice" or "pullInSlice" or "pullOutSlice" to the object. + @param type Always "clickSlice" or "pullInSlice" or "pullOutSlice". + @param handler + If the type is "clickSlice", dispatched when user clicks on a slice. + If the type is "pullInSlice", dispatched when user clicks on a slice and the slice is pulled-in. + If the type is "pullOutSlice", dispatched when user clicks on a slice and the slice is pulled-out. + If the type is "rollOutSlice", dispatched when user rolls-out of the slice. + If the type is "rollOverSlice", dispatched when user rolls-over the slice. + */ + addListener(type: string, handler: (e: {/** Always "rollOverSlice". */ + type: string; dataItem: Slice; + }) => void ); + } + + /** AmRadarChart is the class you have to use for radar and polar chart types. + @example + var chart; + var chartData = [ + {country:"Czech Republic",litres:156.90}, + {country:"Ireland",litres:131.10}, + {country:"Germany",litres:115.80}, + {country:"Australia",litres:109.90}, + {country:"Austria",litres:108.30}, + {country:"UK",litres:99.00} + ]; + + window.onload = function() { + chart = new AmCharts.AmRadarChart(); + chart.dataProvider = chartData; + chart.categoryField = "country"; + chart.startDuration = 2; + + var valueAxis = new AmCharts.ValueAxis(); + valueAxis.axisAlpha = 0.15; + valueAxis.minimum = 0; + valueAxis.dashLength = 3; + valueAxis.axisTitleOffset = 20; + valueAxis.gridCount = 5; + chart.addValueAxis(valueAxis); + + var graph = new AmCharts.AmGraph(); + graph.valueField = "litres"; + graph.bullet = "round"; + graph.balloonText = "[[value]] litres of beer per year" + chart.addGraph(graph); + + chart.write("chartdiv"); + } + */ + class AmRadarChart extends AmCoordinateChart { + /** Bottom margin of the chart. */ + marginBottom: number; + /** Left margin of the chart. */ + marginLeft: number; + /** Right margin of the chart. */ + marginRight: number; + /** Top margin of the chart. */ + marginTop: number; + /** Radius of a radar. 0.35 */ + radius: any; + } + + /** AmXYChart is the class you have to use for XY/Bubble/Scatter chart types. The chart supports simple and logarithmic scales, it can have multiple value axes. + @example + var chartData = [ + {x:10, y:14, value:59}, + {x:5, y:3, value:50}, + {x:-10, y:-3, value:19}, + {x:-6, y:5, value:65}, + {x:15, y:-4, value:92}, + {x:13, y:1, value:8}, + {x:1, y:6, value:35} + ]; + + var chart = new AmCharts.AmXYChart(); + chart.pathToImages = "../../amcharts/javascript/images/"; + chart.dataProvider = chartData; + chart.marginLeft = 35; + chart.startDuration = 1.5; + + var xAxis = new AmCharts.ValueAxis(); + xAxis.position = "left"; + xAxis.autoGridCount = true; + chart.addValueAxis(xAxis); + + var yAxis = new AmCharts.ValueAxis(); + yAxis.position = "bottom"; + yAxis.autoGridCount = true; + chart.addValueAxis(yAxis); + + var graph = new AmCharts.AmGraph(); + graph.valueField = "value"; + graph.xField = "x"; + graph.yField = "y"; + graph.lineAlpha = 0; + graph.bullet = "round"; + chart.addGraph(graph); + + var chartCursor = new AmCharts.ChartCursor(); + chart.addChartCursor(chartCursor); + + var chartScrollbar = new AmCharts.ChartScrollbar(); + chartScrollbar.hideResizeGrips = false; + chart.addChartScrollbar(chartScrollbar); + + chart.write("chartdiv); + */ + class AmXYChart extends AmRectangularChart { + /** Specifies if Scrollbar of X axis (horizontal) should be hidden. */ + hideXScrollbar: boolean; + /** Specifies if Scrollbar of Y axis (vertical) should be hidden. */ + hideYScrollbar: boolean; + /** Maximum zoom factor of the chart. + @default 20 + */ + maxZoomFactor: number; + /** Zooms out, charts shows all available data.*/ + zoomOut(); + } + /** Guides are straight vertical or horizontal lines or areas supported by AmSerialChart, AmXYChart and AmRadarChart. You can have guides both on value and category axes. To add/remove a guide to an axis, use axis.addGuide(guide)/axis.removeGuide(guide) methods. + +If you do not set properties such as dashLength, lineAlpha, lineColor, etc - values of the axis are used.*/ + class Guide { + /** If you set it to true, the guide will be displayed above the graphs. */ + above: boolean; + /** Radar chart only. Specifies angle at which guide should start. Affects only fills, not lines. */ + angle: number; + /** Baloon fill color. */ + balloonColor: string; + /** The text which will be displayed if the user rolls-over the guide. */ + balloonText: string; + /** Specifies if label should be bold or not. */ + boldLabel: boolean; + /** Category of the guide (in case the guide is for category axis). */ + category: string; + /** Dash length. */ + dashLength: number; + /** Date of the guide (in case the guide is for category axis and parseDates is set to true). */ + date: Date; + /** Works if a guide is added to CategoryAxis and this axis is non-date-based. If you set it to true, the guide will start (or be placed, if it's not a fill) on the beginning of the category cell and will end at the end of toCategory cell. */ + expand: boolean; + /** Fill opacity. Value range is 0 - 1. */ + fillAlpha: number; + /** Fill color. */ + fillColor: string; + /** Font size of guide label. */ + fontSize: string; + /** Unique id of a Guide. You don't need to set it, unless you want to. */ + id: string; + /** Specifies whether label should be placed inside or outside plot area. */ + inside: boolean; + /** The label which will be displayed near the guide. */ + label: string; + /** Rotation angle of a guide label. */ + labelRotation: number; + /** Line opacity. */ + lineAlpha: number; + /** Line color. */ + lineColor: string; + /** Line thickness. */ + lineThickness: number; + /** Position of guide label. Possible values are "left" or "right" for horizontal axis and "top" or "bottom" for vertical axis. */ + position: string; + /** Tick length. */ + tickLength: number; + /** Radar chart only. Specifies angle at which guide should end. Affects only fills, not lines. */ + toAngle: number; + /** To category of the guide (in case the guide is for category axis). */ + toCategory: string; + /** To date of the guide (in case the guide is for category axis and parseDates is set to true) If you have both date and toDate, the space between these two dates can be filled with color. */ + toDate: Date; + /** To value of the guide (in case the guide is for value axis). */ + toValue: number; + /** Value of the guide (in case the guide is for value axis). */ + value: number; + /** Value axis of a guide. As you can add guides directly to the chart, you might need to specify which which value axis should be used. */ + valueAxis: ValueAxis; + } + /** ImagesSettings is a class which holds common settings of all MapImage objects. */ + class ImagesSettings { + /** Opacity of the image. + @default 1 + */ + alpha: number; + /** Text which is displayed in a roll-over balloon. You can use the following tags: [[title]], [[description]], [[value]] and [[percent]]. [[title]] */ + balloonText: string; + /** Specifies if the image's center should be placed in the provided coordinates. If false, top-left corner will be at provided coordinates. + @default true + */ + centered: boolean; + /** Color of image. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. #000000 */ + color: string; + /** Height of a description window. */ + descriptionWindowHeight: number; + /** Width of a description window. + @default 250 + */ + descriptionWindowWidth: number; + /** X position of a description window. */ + descriptionWindowX: number; + /** Y position of a description window. */ + descriptionWindowY: number; + /** Label color. #000000 */ + labelColor: string; + /** Font size of a label. + @default 11 + */ + labelfontSize: string; + /** Position of the label. Allowed values are: left, right, top, bottom and middle. right */ + labelPosition: string; + /** Label roll-over color. #00CC00 */ + labelRollOverColor: string; + /** Opacity of image outline. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. */ + outlineAlpha: number; + /** Color of image outline. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. */ + outlineColor: string; + /** Thickness of image outline. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. + @default 1 + */ + outlineThickness: number; + /** Color of image when hovered. This will affect only predefined images (with "type" property set) and images with svgPath set. This property won't affect bitmap images and loaded SVG images. */ + rollOverColor: string; + /** Scale of the image when hovered. Use value like 1.5 - 2 to enlarge image when user rolls-over it. + @default 1 + */ + rollOverScale: number; + /** Scale of the image if it is selected. Use value like 1.5 - 2 to enlarge selected image. + @default 1 + */ + selectedScale: number; + } + + /** AreasSettings is a class which holds common settings of all MapArea objects. */ + class AreasSettings { + /** Opacity of areas. + @default 1 + */ + alpha: number; + /** Specifies if the areas should be zoomed-in when user clicks on them, event if zoom properties are not set. */ + autoZoom: boolean; + /** Text which is displayed in a roll-over balloon. You can use the following tags: [[title]], [[description]], [[value]] and [[percent]] [[title]] */ + balloonText: string; + /** Color of the areas. #FFCC00 */ + color: string; + /** Color of area with highest value. Colors for areas with values less then highest will be colored with intermediate colors between color and colorSolid. Use colorSteps property of AmMap to change the number of intermediate colors. #990000 */ + colorSolid: string; + /** Height of a description window. */ + descriptionWindowHeight: number; + /** Width of a description window. + @default 250 + */ + descriptionWindowWidth: number; + /** X position of a description window. */ + descriptionWindowX: number; + /** Y position of a description window. */ + descriptionWindowY: number; + /** Opacity of area's outline. + @default 1 + */ + outlineAlpha: number; + /** Color of area's outline. #FFFFFF */ + outlineColor: string; + /** Thickness of area's outline. 0.5 */ + outlineThickness: number; + /** Color of area when user rolls-over it. undefined */ + rollOverColor: string; + /** Color of area's outline when user rolls-over it. #CC0000 */ + rollOverOutlineColor: string; + /** Color of area which is currently selected. #CC0000 */ + selectedColor: string; + /** Opacity of all areas which are in the map svg file, but not listed as areas in DataSet. + @default 1 + */ + unlistedAreasAlpha: number; + /** Color of all areas which are in the map svg file, but not listed as areas in DataSet. #DDDDDD */ + unlistedAreasColor: string; + /** Opacity of all areas' outline which are in the map svg file, but not listed as areas in DataSet. + @default 1 + */ + unlistedAreasOutlineAlpha: number; + /** Color of all areas' outline which are in the map svg file, but not listed as areas in DataSet. #FFFFFF */ + unlistedAreasOutlineColor: string; + } + + /** Slice is an item of AmPieChart's chartData Array and holds all the information about the slice. When working with a pie chart, you do not create slices or change it's properties directly, instead you set array of data using dataProvider property. Consider properties of a Slice read-only - change values in chart's data provider if you need to. */ + class Slice { + /** Opacity of a slice. */ + alpha: number; + /** Color of a slice. */ + color: string; + /** Original object from data provider. */ + dataContext: Object; + /** Slice description. */ + description: string; + /** Specifies whether the slice is hidden */ + hidden: boolean; + /** Percent value of a slice. */ + percents: number; + /** Specifies whether the slice is pulled or not. */ + pulled: boolean; + /** Slice title */ + title: string; + /** Url of a slice */ + url: string; + /** Value of a slice */ + value: number; + /** specifies whether this slice has a legend entry */ + visibleInLegend: boolean; + } + + + /** AmStockChart is a main class Stock chart. */ + class AmStockChart { + /** Specifies if animation was already played. Animation is only played once, when chart is rendered for the first time. If you want the animation to be repeated, set this property to false. */ + animationPlayed: boolean; + /** Balloon object. */ + balloon: AmBalloon; + /** Settings for category axes. */ + categoryAxesSettings: CategoryAxesSettings; + /** Indicates if the chart is created. */ + chartCreated: boolean; + /** Chart cursor settings. */ + chartCursorSettings: ChartCursorSettings; + /** Chart scrollbar settings. */ + chartScrollbarSettings: ChartScrollbarSettings; + /** Array of colors used by data sets if no color was set explicitly on data set itself. #FF6600, "#FCD202", "#B0DE09", "#0D8ECF", "#2A0CD0", "#CD0D74", "#CC0000", "#00CC00", "#0000CC", "#DDDDDD", "#999999", "#333333", "#990000" */ + colors: any[]; + /** Array of data sets selected for comparing. */ + comparedDataSets: any[]; + /** Array of DataSets. */ + dataSets: any[]; + /** DataSetSelector object. You can add it if you have more than one data set and want users to be able to select/compare them. */ + dataSetSelector: DataSetSelector; + /** Current end date of the selected period, get only. To set start/end dates, use stockChart.zoom(startDate, endDate) method. */ + endDate: Date; + /** Defines on which day week starts. 0 - Sunday, 1 - Monday.. + @default 1 */ + firstDayOfWeek: number; + /** If set to true the scope of the data view will be set to the end after data update. */ + glueToTheEnd: boolean; + /** Legend settings. */ + legendSettings: LegendSettings; + /** Data set selected as main. */ + mainDataSet: DataSet; + /** Array of StockPanels (charts). */ + panels: any[]; + /** Settings for stock panels. */ + panelsSettings: PanelsSettings; + /** Period selector object. You can add it if you want user's to be able to enter date ranges or zoom chart with predefined period buttons. */ + periodSelector: PeriodSelector; + /** Scrollbar's chart object, get only. */ + scrollbarChart: AmSerialChart; + /** Current start date of the selected period, get only. To set start/end dates, use stockChart.zoom(startDate, endDate) method. */ + startDate: Date; + /** Settings for stock events. */ + stockEventsSettings: any; + /** Settings for value axes. */ + valueAxesSettings: ValueAxesSettings; + /** read-only. Indicates current version of a script. */ + version: string; + /** Specifies whether the chart should zoom-out when main data set is changed. */ + zoomOutOnDataSetChange: boolean; + + /** Adds panel to the stock chart. Requires stockChart.validateNow() method to be called after this action. */ + addPanel(panel: StockPanel); + /** Adds panel to the stock chart at a specified index. Requires stockChart.validateNow() method to be called after this action. */ + addPanelAt(panel: StockPanel, index: number); + /** Destroys chart, all timeouts and listeners. */ + clear(); + /** Hides event bullets. */ + hideStockEvents(); + /** Removes event listener from the object. */ + removeListener(obj: any, type: string, handler: any); + /** Removes panel from the stock chart. Requires stockChart.validateNow() method to be called after this action. */ + removePanel(panel: StockPanel); + /** Shows event bullets. */ + showStockEvents(); + /** Method which should be called after data was changed. */ + validateData(); + /** Method which forces the stock chart to rebuild. Should be called after properties are changed. */ + validateNow(); + /** Zooms chart to specified dates. startDate, endDate - Date objects. */ + zoom(startDate: Date, endDate: Date); + /** Zooms out the chart. */ + zoomOut(); + + /** Adds event listener of the type "dataUpdated" or "init" or "rendered" to the object. + @param type Always "dataUpdated" or "init" or "rendered". + @param handler + If the type is "dataUpdated", dispatched when the chart was updated with new data. + If the type is "init", dispatched when the chart is initialized for the first time. In case you want it to fire again after validateNow() method is called, set chart.chartCreated = false. + If the type is "rendered", dispatched each when chart is rendered. + */ + addListener(type: string, handler: (e: { + /** Either "dataUpdated" or "init". */ + type: string; + chart: AmStockChart; + }) => void ); + + /** Adds event listener of the type "rollOutStockEvent" or "rollOverStockEvent" or "clickStockEvent" to the object. + @param type // Either "rollOutStockEvent" or "rollOverStockEvent" or "clickStockEvent". + @param handler + If the type is "rollOutStockEvent", dispatched when the user rolls-out of the Stock event (bullet). + If the type is "rollOverStockEvent", dispatched when the user rolls-over of the Stock event (bullet). + If the type is "clickStockEvent", dispatched when the user clicks on the Stock event (bullet). + */ + + addListener(type: string, handler: (e: { + /** Always "rollOverStockEvent". */ + type: string; + eventObject: any; + graph: AmGraph; + date: Date; + chart: AmStockChart; + }) => void ); + + /** Adds event listener of the type "zoomed" to the object. + @param type Always "zoomed". + @param handler Dispatched when the chart is zoomed (even for the first time, when chart is initialized).*/ + addListener(type: string, handler: (e: { + /** Always "zoomed". */ + type: string; + startDate: Date; + endDate: Date; + period: string; + chart: AmStockChart; + }) => void ); + + /** Adds event listener of the type "panelRemoved" to the object. + @param type Always "panelRemoved". + @param handler Dispatched when the StockPanel is removed.*/ + addListener(type: string, handler: (e: { + /** Always "panelRemoved". */ + + type: string; + panel: StockPanel; + chart: AmStockChart; + }) => void ); + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + } + + /** ValueAxesSettings settings set 's settings for all ValueAxes. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of ValueAxis class will be used. */ + class ValueAxesSettings { + /** Specifies whether number for gridCount is specified automatically, according to the axis size. + @default true + */ + autoGridCount: boolean; + /** Axis opacity. */ + axisAlpha: number; + /** Axis color. */ + axisColor: string; + /** Thickness of the axis. */ + axisThickness: number; + /** Label color. */ + color: string; + /** Length of a dash. By default, the grid line is not dashed. */ + dashLength: number; + /** Fill opacity. Every second space between grid lines can be filled with color. */ + fillAlpha: number; + /** Fill color. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills. */ + fillColor: string; + /** Opacity of grid lines. */ + gridAlpha: number; + /** Color of grid lines. */ + gridColor: string; + /** Approximate number of grid lines. autoGridCount should be set to false, otherwise this property will be ignored. */ + gridCount: number; + /** Thickness of grid lines. */ + gridThickness: number; + /** Specifies whether guide values should be included when calculating min and max of the axis. */ + includeGuidesInMinMax: boolean; + /** If true, the axis will include hidden graphs when calculating min and max values. */ + includeHidden: boolean; + /** Specifies whether values should be placed inside or outside plot area. In case you set this to false, you'll have to adjust marginLeft or marginRight in [[PanelsSettings]] in order labels to be visible. + @default true + */ + inside: boolean; + /** Specifies whether values on axis can only be integers or both integers and doubles. */ + integersOnly: boolean; + /** Frequency at which labels should be placed. */ + labelFrequency: number; + /** Specifies whether value labels are displayed. */ + labelsEnabled: boolean; + /** Set to true if value axis is logarithmic, false otherwise. */ + logarithmic: boolean; + /** The distance of the axis to the plot area, in pixels. Useful if you have more then one axis on the same side. */ + offset: number; + /** Position of the value axis. Possible values are "left" and "right". */ + position: string; + /** Set to true if value axis is reversed (smaller values on top), false otherwise. */ + reversed: boolean; + /** Specifies if first label of value axis should be displayed. */ + showFirstLabel: boolean; + /** Specifies if last label of value axis should be displayed. */ + showLastLabel: boolean; + /** Stacking mode of the axis. Possible values are: "none", "regular", "100%", "3d". */ + stackType: string; + /** Tick length. */ + tickLength: number; + /** Unit which will be added to the value label. */ + unit: string; + /** Position of the unit. Possible values are "left" or "right". */ + unitPosition: string; + + } + + + /** AmLegend is the class that displays legend of the chart. Legend to the chart should be added using chart.addLegend(legend) method. + @example + var chart = new AmCharts.AmSerialChart(); + var legend = new AmCharts.AmLegend(); + chart.addLegend(legend); + */ + class AmLegend { + + /** Alignment of legend entries. Possible values are: "left", "center", "right". left */ + align: string; + /** Used if chart is Serial or XY. In case true, margins of the legend are adjusted and made equal to chart's margins. + @default true + */ + autoMargins: boolean; + /** Opacity of legend's background. Value range is 0 - 1 */ + backgroundAlpha: number; + /** Background color. You should set backgroundAlpha to >0 vallue in order background to be visible. #FFFFFF */ + backgroundColor: string; + /** Opacity of chart's border. Value range is 0 - 1. */ + borderAlpha: number; + /** Color of legend's border. You should set borderAlpha >0 in order border to be visible. #000000 */ + borderColor: string; + /** In case legend position is set to "absolute", you can set distance from bottom of the chart, in pixels. */ + bottom: number; + /** Text color. Will use chart's color if not set. */ + color: string; + /** This can be used by AmMap only. You can pass array of objects with title, color, markerType values, for example: [{title: "One", color: "#3366CC"},{title: "Two", color: "#FFCC33"}] */ + data: any[]; + /** Specifies if each of legend entry should be equal to the most wide entry. Won't look good if legend has more than one line. + @default true + */ + equalWidths: boolean; + /** Font size. Will use chart's font size if not set. */ + fontSize: string; + /** Horizontal space between legend item and left/right border. */ + horizontalGap: number; + /** The text which will be displayed in the legend. Tag [[title]] will be replaced with the title of the graph. [[title]] */ + labelText: string; + /** In case legend position is set to "absolute", you can set distance from left side of the chart, in pixels. */ + left: number; + /** Bottom margin. */ + marginBottom: number; + /** Left margin. This property will be ignored if chart is Serial or XY and autoMargins property of the legend is true (default). + @default 20 + */ + marginLeft: number; + /** Right margin. This property will be ignored if chart is Serial or XY and autoMargins property of the legend is true (default). + @default 20 + */ + marginRight: number; + /** Top margin. */ + marginTop: number; + /** Marker border opacity 1. */ + markerBorderAlpha: number; + /** Marker border color. If not set, will use the same color as marker. */ + markerBorderColor: string; + /** Thickness of the legend border. The default value (0) means the line will be a "hairline" (1 px). In case marker type is line, this style will be used for line thickness. + @default 1 + */ + markerBorderThickness: number; + /** The color of the disabled marker (when the graph is hidden). #AAB3B3 */ + markerDisabledColor: string; + /** Space between legend marker and legend text, in pixels. + @default 5 + */ + markerLabelGap: number; + /** Size of the legend marker (key). + @default 16 + */ + markerSize: number; + /** Shape of the legend marker (key). Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble", "none". square */ + markerType: string; + /** Maximum number of columns in the legend. If Legend's position is set to "right" or "left", maxColumns is automatically set to 1. */ + maxColumns: number; + /** Position of a legend. Possible values are: "bottom", "top", "left", "right" and "absolute". In case "absolute", you should set left and top properties too. (this setting is ignored in Stock charts). In case legend is used with AmMap, position is set to "absolute" automatically. bottom */ + position: string; + /** Specifies whether legend entries should be placed in reversed order. */ + reversedOrder: boolean; + /** In case legend position is set to "absolute", you can set distance from right side of the chart, in pixels. */ + right: number; + /** Legend item text color on roll-over. #CC0000 */ + rollOverColor: string; + /** When you roll-over the legend entry, all other graphs can reduce their opacity, so that the graph you rolled-over would be distinguished. This style specifies the opacity of the graphs. + @default 1 + */ + rollOverGraphAlpha: number; + /** You can use this property to turn all the legend entries off. + @default true + */ + showEntries: boolean; + /** Horizontal space between legend items, in pixels. + @default 10 + */ + spacing: number; + /** Whether showing/hiding of graphs by clicking on the legend marker is enabled or not. In case legend is used with AmMap, this is set to false automatically. + @default true + */ + switchable: boolean; + /** Legend switch color. #FFFFFF */ + switchColor: string; + /** Legend switch type (in case the legend is switchable). Possible values are "x" and "v". x */ + switchType: string; + /** If true, clicking on the text will show/hide balloon of the graph. Otherwise it will show/hide graph/slice, if switchable is set to true. */ + textClickEnabled: boolean; + /** In case legend position is set to "absolute", you can set distance from top of the chart, in pixels. */ + top: number; + /** Legend markers can mirror graph’s settings, displaying a line and a real bullet as in the graph itself. + Set this property to true if you want to enable this feature. Note, if you set graph colors in dataProvider, they will not be reflected in the marker. + @default false*/ + useGraphSettings: boolean; + /** Specifies if legend labels should be use same color as corresponding markers. */ + useMarkerColorForLabels: boolean; + /** Alignment of the value text. Possible values are "left" and "right". right */ + valueAlign: string; + /** The text which will be displayed in the value portion of the legend. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents]], [[description]]. [[value]] */ + valueText: string; + /** Width of the value text. + @default 80 + */ + valueWidth: number; + /** Vertical space between legend items also between legend border and first and last legend row. 10 */ + verticalGap: number; + /** Adds event listener of the type "clickLabel" or "clickMarker" or "hideItem" to the object. + @param type Either "clickLabel" or "clickMarker" or "hideItem". + @param handler + If the type is "clickLabel", dispatched when legend label is clicked. + If the type is "clickMarker", dispatched when legend marker is clicked. + If the type is "hideItem", dispatched when user clicks on a legend item marker and hides corresponding object. + If the type is "rollOutItem", dispatched when user rolls-out of the legend item label (or whole item, if switchable is set to false). + If the type if "rollOverItem", dispatched when user rolls-over the legend item label (or whole item, if switchable is set to false). + If the type is "rollOutMarker", dispatched when user clicks out of a legend item marker and shows corresponding object. + If the type if "rollOverMarker", dispatched when user clicks on a legend item marker and shows corresponding object. + */ + + /** Adds event listener of the type "showItem" to the object. + @param type Always "showItem". + @param handler + */ + addListener(type: string, handler: (e: {/** Always "showItem". */ + type: string; dataItem: Object; chart: AmChart; + }) => void ); + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + } + + /** StockLegend is a legend of StockPanel. */ + + class StockLegend extends AmLegend { + /** The text which will be displayed in the value portion of the legend when graph is comparable and at least one dataSet is selected for comparing. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents.value/open/close/low/high]], [[description]]. [[percents.value]]% */ + + valueTextComparing: string; + /** The text which will be displayed in the value portion of the legend. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents]], [[description]]. [[value]] */ + + valueTextRegular: string; + } + + /** StockPanel class creates stock panels (charts). AmStockChart can have multiple Stock panels. */ + + class StockPanel extends AmSerialChart { + /** Specifies whether x button will be displayed near the panel. This button allows turning panel off. */ + allowTurningOff: boolean; + /** If true, drawing icons will be displayed in top-right corner. */ + drawingIconsEnabled: boolean; + /** Specifies on which value axis user can draw trend lines. Set drawingIconsEnabled to true if you want drawing icons to be visible. First value axis will be used if not set here. */ + drawOnAxis: ValueAxis; + /** Specifies if all trend lines should be erased when erase button is clicked. If false, trend lines can be erased one by one. */ + eraseAll: boolean; + /** Size of trend line drawing icons. If you change this size, you should update icon images if you want them to look properly. + @default 18 + */ + iconSize: number; + /** Relative height of panel. Possible values 0 - 100. */ + percentHeight: number; + /** Specifies when values should be recalculated to percents. Possible values are: "never", "always", "whenComparing". whenComparing */ + recalculateToPercents: string; + /** Specifies whether this panel will show category axis. + @default true + */ + showCategoryAxis: boolean; + /** */ + stockGraphs: StockGraph[]; + /** Stock chart legend. */ + stockLegend: StockLegend; + /** Title of a panel. Note, StockLegend should be added in order title to be displayed. */ + title: string; + /** Trend line opacity. + @default 1 + */ + trendLineAlpha: number; + /** Trend line color. #00CC00 */ + trendLineColor: string; + /** Trend line dash length. */ + trendLineDashLength: number; + /** Trend line thickness. + @default 2 + */ + trendLineThickness: number; + /** Adds a graph to the panel. */ + addStockGraph(graph: StockGraph); + /** Removes graph from the panel. */ + removeStockGraph(graph: StockGraph); + } + + /** AmChart is a base class of all charts. It can not be instantiated explicitly. AmCoordinateChart, AmPieChart and AmMap extend AmChart class. */ + class AmChart { + /** used when constructing a chart with a theme */ + constructor(theme?: any); + /** Specifies, if class names should be added to chart elements. */ + addClassNames: boolean; + /** Array of Labels. Example of label object, with all possible properties: +{"x": 20, "y": 20, "text": "this is label", "align": "left", "size": 12, "color": "#CC0000", "alpha": 1, "rotation": 0, "bold": true, "url": "http://www.amcharts.com"} */ + allLabels: Label[]; + /** Set this to false if you don't want chart to resize itself whenever its parent container size changes. */ + autoResize: boolean; + /** Opacity of background. Set it to >0 value if you want backgroundColor to work. However we recommend changing div's background-color style for changing background color. */ + backgroundAlpha: number; + /** Background color. You should set backgroundAlpha to >0 value in order background to be visible. We recommend setting background color directly on a chart's DIV instead of using this property. #FFFFFF */ + backgroundColor: string; + /** The chart creates AmBalloon class itself. If you want to customize balloon, get balloon instance using this property, and then change balloon's properties. AmBalloon */ + balloon: AmBalloon; + /** Opacity of chart's border. Value range is 0 - 1. */ + borderAlpha: number; + /** Color of chart's border. You should set borderAlpha >0 in order border to be visible. We recommend setting border color directly on a chart's DIV instead of using this property. #000000 */ + borderColor: string; + /** This prefix is added to all class names which are added to all visual elements of a chart in case addClassNames is set to true. */ + classNamePrefix: string; + /** Text color. #000000 */ + color: string; + /** Non-commercial version only. Specifies position of link to amCharts site. Allowed values are: top-left, top-right, bottom-left and bottom-right. + @default 'top-left' + */ + creditsPosition: string; + /** Array of data objects, for example: [{country:"US", value:524},{country:"UK", value:624},{country:"Lithuania", value:824}]. You can have any number of fields and use any field names. In case of AmMap, data provider should be MapData object. */ + dataProvider: any[]; + /** Decimal separator. + @Default . */ + decimalSeparator: string; + /** Using this property you can add any additional information to SVG, like SVG filters or clip paths. The structure of this object should be identical to XML structure of a object you are adding, only in JSON format. */ + defs: any; + /** Export config. Specifies how export to image/data export/print/annotate menu will look and behave. You can find a lot of examples in amcharts/plugins/export folder. */ + export: ExportSettings; + /** Font family. Verdana */ + fontFamily: string; + /** Font size. + @default 11 + */ + fontSize: string; + /** If you set this to true, the lines of the chart will be distorted and will produce hand-drawn effect. Try to adjust chart.handDrawScatter and chart.handDrawThickness properties for a more scattered result. + @Default false + */ + handDrawn: boolean; + /** Defines by how many pixels hand-drawn line (when handDrawn is set to true) will fluctuate. + @Default 2 + */ + handDrawScatter: number; + /** Defines by how many pixels line thickness will fluctuate (when handDrawn is set to true). + @Default 1 + */ + handDrawThickness: number; + /** Time, in milliseconds after which balloon is hidden if the user rolls-out of the object. Might be useful for AmMap to avoid balloon flickering while moving mouse over the areas. Note, this is not duration of fade-out. Duration of fade-out is set in AmBalloon class. + @Default 150 + */ + hideBalloonTime: number; + /** Legend of a chart. */ + legend: AmLegend; + /** Reference to the div of the legend. */ + legendDiv: HTMLElement; + /** You can add listeners of events using this property. Example: listeners = [{"event":"dataUpdated", "method":handleEvent}]; */ + listerns: Object[]; + /** This setting affects touch-screen devices only. If a chart is on a page, and panEventsEnabled are set to true, the page won't move if the user touches the chart first. If a chart is big enough and occupies all the screen of your touch device, the user won’t be able to move the page at all. That's why the default value is "false". If you think that selecting/panning the chart or moving/pinching the map is a primary purpose of your users, you should set panEventsEnabled to true. */ + panEventsEnabled: boolean; + /** Specifies absolute or relative path to amCharts files, i.e. "amcharts/". (where all .js files are located) + If relative URLs are used, they will be relative to the current web page, displaying the chart. + You can also set path globally, using global JavaScript variable AmCharts_path. If this variable is set, and "path" is not set in chart config, the chart will assume the path from the global variable. This allows setting amCharts path globally. I.e.: + var AmCharts_path = "/libs/amcharts/"; + "path" parameter will be used by the charts to locate it's files, like images, plugins or patterns.*/ + path: string; + /** Specifies path to the folder where images like resize grips, lens and similar are. + IMPORTANT: Since V3.14.12, you should use "path" to point to amCharts directory instead. The "pathToImages" will be automatically set and does not need to be in the chart config, unless you keep your images separately from other amCharts files. */ + pathToImages: string; + /** Precision of percent values. -1 means percent values won't be rounded at all and show as they are. + @default 2 + */ + percentPrecision: number; + /** Precision of values. -1 means values won't be rounded at all and show as they are. + @Default 1*/ + precision: number; + /** Prefixes which are used to make big numbers shorter: 2M instead of 2000000, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e+3,prefix:"k"},{number:1e+6,prefix:"M"},{number:1e+9,prefix:"G"},{number:1e+12,prefix:"T"},{number:1e+15,prefix:"P"},{number:1e+18,prefix:"E"},{number:1e+21,prefix:"Z"},{number:1e+24,prefix:"Y"}] */ + prefixesOfBigNumbers: any[]; + /** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e-24, prefix:"y"},{number:1e-21, prefix:"z"},{number:1e-18, prefix:"a"},{number:1e-15, prefix:"f"},{number:1e-12, prefix:"p"},{number:1e-9, prefix:"n"},{number:1e-6, prefix:"μ"},{number:1e-3, prefix:"m"}] */ + prefixesOfSmallNumbers: any[]; + /** Theme of a chart. Config files of themes can be found in amcharts/themes/ folder. More info about using themes. */ + theme: string; + /** Thousands separator. + @default . + */ + thousandsSeparator: string; + /** Array of Title objects. */ + titles: Title[]; + /** Type of a chart. Required when creating chart using JSON. Possible types are: serial, pie, xy, radar, funnel, gauge, map, stock. */ + type: string; + /** If true, prefixes will be used for big and small numbers. You can set arrays of prefixes via prefixesOfSmallNumbers and prefixesOfBigNumbers properties. */ + usePrefixes: boolean; + /** Read-only. Indicates current version of a script. */ + version: string; + /** Adds a label on a chart. + You can use it for labeling axes, adding chart title, etc. x and y coordinates can be set in number, percent, or a number with ! in front of it - coordinate will be calculated from right or bottom instead of left or top. + x - horizontal coordinate + y - vertical coordinate + text - label's text + align - alignment (left/right/center) + size - text size + color - text color + rotation - angle of rotation + alpha - label alpha + bold - specifies if text is bold (true/false), + url - url + */ + addLabel(x: number, y: number, text: string, align: string, size: number, color: string, rotation: number, alpha: number, bold: boolean, url: string); + /** Adds a legend to the chart. + By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. + (NOTE: This method will not work on StockPanel.) + @param legend + @param legendDivId - Id of the legend div (optional). + */ + addLegend(legend: AmLegend, legendDivId?: string); + /** Adds a legend to the chart. + By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. + (NOTE: This method will not work on StockPanel.) + @param legend + @param legendDiv - Legend div (optional). + */ + addLegend(legend: AmLegend, legendDiv: HTMLElement); + + /** Adds title to the top of the chart. Pie, Radar positions are updated so that they won't overlap. Plot area of Serial/XY chart is also updated unless autoMargins property is set to false. You can add any number of titles - each of them will be placed in a new line. To remove titles, simply clear titles array: chart.titles = []; and call chart.validateNow() method. text - text of a title size - font size color - title color alpha - title opacity bold - boolean value indicating if title should be bold. */ + addTitle(text: string, size: number, color: string, alpha: number, bold: boolean); + /** Clears the chart area, intervals, etc. */ + clear(); + /** Removes all labels added to the chart. */ + clearLabels(); + /** Use this method to force the chart to resize to it's current container size. */ + invalidateSize(); + /** Removes chart's legend. */ + removeLegend(); + /** This method should be called after data in your data provider changed or a new array was set to dataProvider. After calling this method the chart will parse data and redraw. */ + validateData(); + /** This method should be called after you changed one or more properties of any class. The chart will redraw after this method is called. */ + validateNow(); + + /** Adds chart to the specified DIV. + @param container DIV object which will hold the chart. */ + write(container: HTMLElement): void; + /** Adds chart to the specified DIV. + @param container Id of a DIV which will hold the chart. */ + write(container: string): void; + + /** Adds event listener of the type "dataUpdated" or "init" to the object. + @param type "dataUpdated" or "init". + @param handler + If the type is "dataUpdated". + Dispatched when chart is build for the first time or after validateData() method was called. + If the type is "init". + Dispatched when chart is build for the first time. + */ + addListener(type: string, handler: (e: { + /** Either "dataUpdated" or "init". */ + type: string; + chart: AmChart; + }) => void ); + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + } + + /** AmCoordinateChart is a base class of AmRectangularChart. It can not be instantiated explicitly. */ + + class AmCoordinateChart extends AmChart { + /** Read-only. Array, holding processed chart's data. */ + chartData: Object[]; + /** Specifies the colors of the graphs if the lineColor of a graph is not set. + It there are more graphs then colors in this array, the chart picks random color. + @default ['#FF6600', '#FCD202', '#B0DE09', '#0D8ECF', '#2A0CD0', '#CD0D74', '#CC0000', '#00CC00', '#0000CC', '#DDDDDD', '#999999', '#333333', '#990000'] */ + colors: string[]; + /** The array of graphs belonging to this chart. + To add/remove graph use addGraph/removeGraph methods instead of adding/removing graphs directly to array. + */ + graphs: AmGraph[]; + /** Specifies if grid should be drawn above the graphs or below. Will not work properly with 3D charts. + @default false + */ + gridAboveGraphs: boolean; + /** Instead of adding guides to the axes, you can push all of them to this array. In case guide has category or date defined, it will automatically will be assigned to the category axis. Otherwise to first value axis, unless you specify a different valueAxis for the guide. */ + guides: Guide[]; + /** Specifies whether the animation should be sequenced or all objects should appear at once. + @default true + */ + sequencedAnimation: boolean; + /** The initial opacity of the column/line. + If you set startDuration to a value higher than 0, the columns/lines will fade in from startAlpha. + Value range is 0 - 1. + @default 1 + */ + startAlpha: number; + /** Duration of the animation, in seconds. */ + startDuration: number; + /** Animation effect. + Possible values are ">", "<", elastic" and "bounce". + @default "elastic" + */ + startEffect: string; + /** Target of url. + @default this + */ + urlTarget: any; + /** The array of value axes. + To add/remove value axis use addValueAxis/removeValueAxis methods instead of adding/removing axes directly to array. + Chart creates one value axis automatically, so if you need only one value axis, you don't need to create it. + */ + valueAxes: any[]; + /** Adds a graph to the chart. + */ + addGraph(graph: AmGraph); + /** Adds a legend to the chart. By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter. (NOTE: This method will not work on StockPanel.) */ + /** Adds value axis to the chart. + One value axis is created automatically, so if you don't want to change anything or add more value axes, you don't need to add it. + */ + addValueAxis(axis: ValueAxis); + /** You can trigger the animation of the chart. */ + animateAgain(); + + /** AmGraph Returns graph by id. */ + getGraphById(graphId: string): AmGraph; + + /** Returns value axis by id.*/ + getValueAxisById(axisId: string): ValueAxis; + + /** Hide the graph (if it is visible). Usually this method is called from the Legend, when you click on the legend marker. + */ + hideGraph(graph: AmGraph); + + /** Hide value balloon of a graph. Usually this method is called from the Legend, when you click on the legend text.*/ + hideGraphsBalloon(graph: AmGraph); + + /** Highlight the graph. Usually this method is called from the Legend, when you roll-over the legend entry.*/ + highlightGraph(graph: AmGraph); + + /** Removes graph from the chart.*/ + removeGraph(graph: AmGraph); + + /** Removes value axis from the chart. When you remove value axis, all graphs assigned to this axis are also removed. */ + removeValueAxis(axis: ValueAxis); + + /** Show the graph (if it is hidden). Usually this method is called from the Legend, when you click on the legend marker.*/ + showGraph(graph: AmGraph); + + /** Show value balloon of a graph. Usually this method is called from the Legend, when you click on the legend text.*/ + showGraphsBalloon(graph: AmGraph); + + /** UnhighlightGraph the graph. Usually this method is called from the Legend, when you roll-out the legend entry.*/ + unhighlightGraph(graph: AmGraph); + /** Adds event listener of the type "clickGraphItem" or "doubleClickGraphItem" or "rightClickGraphItem" or "rollOutGraphItem" or "rollOverGraphItem" to the object. + @param type Either "clickGraphItem" or "doubleClickGraphItem" or "rightClickGraphItem" or "rollOutGraphItem" or "rollOverGraphItem". + @param handler Dispatched when user clicks on the data item (column/bullet) + */ + addListener(type: string, handler: (e: { + /** Either "clickGraphItem" or "doubleClickGraphItem" or "rightClickGraphItem" or "rollOutGraphItem" or "rollOverGraphItem". */ + type: string; + graph: AmGraph; + item: GraphDataItem; + index: number; + chart: AmChart; + }) => void ); + } + + /** GraphDataItem holds all the information about the graph's data item. When working with a chart, you do not create GraphDataItem objects or change it's properties directly. GraphDataItem is passed to you by events when user interacts with data item on the chart. The list of properties below will help you to extract data item's value/coordinate/etc. */ + class GraphDataItem { + /** Opacity of the data item. */ + alpha: number; + /** Bullet type. */ + bullet: string; + /** Bullet size. */ + bulletSize: number; + /** Category value. */ + category: string; + /** Color of the data item. */ + color: string; + /** Custom bullet (path to file name). */ + customBullet: string; + /** Original object from data provider. */ + dataContext: Object; + /** Description. */ + description: string; + /** Array of colors of the data item, used by column and candlestick chart only. */ + fillColors: any[]; + /** Object which holds percents when recalculateToPercents is set to true. */ + percents: Object; + /** SerialDataItem of this graphDataItem */ + serialDataItem: SerialDataItem; + /** url */ + url: string; + /** Object which holds values of the data item (value, open, close, low, high). */ + values: Object; + /** x coordinate of the data item. */ + x: number; + /** y coordinate of the data item. */ + y: number; + } + + /** SerialDataItem holds all the information about each series. When working with a chart, you do not create SerialDataItem objects or change it's properties directly. Consider properties of a SerialDataItem read-only - change values in chart's data provider if you need to. When serial chart parses dataProvider, it generates "chartData" array. Objects of this array are SerialDataItem objects. */ + class SerialDataItem { + + /** You can access each GraphDataItem using this object. The data structure is: graphDataItem = serialDataItem.axes[axisId].graphs[graphId]. */ + axes: Object; + + /** category value. String if parseDates is false, Date if true. */ + category: any; + + /** Timestamp of a series date. Avalable only if parseDates property of CategoryAxis is set to true. */ + time: number; + + /** Coordinate (horizontal or vertical, depends on chart's rotate property) of the series. */ + x: number; + } + + class CategoryAxis extends AxisBase { + + /** When parse dates is on for the category axis, the chart will try to highlight the beginning of the periods, like month, in bold. Set this to false to disable the functionality. + @default true + */ + boldPeriodBeginning: boolean; + + /** Date formats of different periods. Possible period values: fff - milliseconds, ss - seconds, mm - minutes, hh - hours, DD - days, MM - months, WW - weeks, YYYY - years. Check this page for date formatting strings. [{period:'fff',format:'JJ:NN:SS'},{period:'ss',format:'JJ:NN:SS'},{period:'mm',format:'JJ:NN'},{period:'hh',format:'JJ:NN'},{period:'DD',format:'MMM DD'},{period:'WW',format:'MMM DD'},{period:'MM',format:'MMM'},{period:'YYYY',format:'YYYY'}] */ + dateFormats: any[]; + + /** In case your category axis values are Date objects and parseDates is set to true, the chart will parse dates and will place your data points at irregular intervals. However if you want dates to be parsed (displayed on the axis, baloons, etc), but data points to be placed at equal intervals (omiting dates with no data), set equalSpacing to true. */ + equalSpacing: boolean; + + /** Field in data provider which specifies if the category value should always be shown. For example: categoryAxis.forceShowField = "forceShow"; Field in data provider which specifies if the category value should always be shown. For example: categoryAxis.forceShowField = "forceShow"; + And in data: + {category:"one", forceShow:true, value:100} + Note, this works only when parseDates is set to false.*/ + forceShowField: string; + + /** Specifies if a grid line is placed on the center of a cell or on the beginning of a cell. Possible values are: "start" and "middle" This setting doesn't work if parseDates is set to true. middle */ + gridPosition: string; + + /** Specifies if minor grid should be displayed. + NOTE: If equalSpacing is set to true, this setting will be ignored. + @default false*/ + minorGridEnabled: boolean; + + /** Specifies the shortest period of your data. This should be set only if parseDates is set to "true". Possible period values: fff - milliseconds, ss - seconds, mm - minutes, hh - hours, DD - days, MM - months, YYYY - years. DD */ + minPeriod: string; + + /** In case your category axis values are Date objects, set this to true. In this case the chart will parse dates and will place your data points at irregular intervals. If you want dates to be parsed, but data points to be placed at equal intervals, set both parseDates and equalSpacing to true. */ + parseDates: boolean; + + /** Specifies whether the graph should start on axis or not. In case you display columns, it is recommended to set this to false. If parseDates is set to true, startOnAxis will allways be false, unless equalSpacing is set to true. */ + startOnAxis: boolean; + + /** Works only when parseDates is set to true and equalSpacing is false. If you set it to true, at the position where bigger period changes, + category axis will display date strings of bot small and big period, in two rows. + @default false*/ + twoLineMode: boolean; + + /** Use line color for bullet + @default false*/ + useLineColorForBulletBorder: boolean; + /** Number returns coordinate of a category. Works only if parseDates is false. If parseDates is true, use dateToCoordinate method. category - String */ + categoryToCoordinate(category: string); + + /** date - Date object Returns Date of the coordinate, in case parseDates is set to true and equalSpacing is set to false. coordinate - Number */ + coordinateToDate(coordinate: number); + + /** Number Returns coordinate of the date, in case parseDates is set to true. if parseDates is false, use categoryToCoordinate method. date - Date object */ + dateToCoordinate(date: Date); + + /** Number Returns index of the category which is most close to specified coordinate. x - coordinate */ + xToIndex(x: number); + } + + /** ChartScrollbar class displays chart scrollbar. Supported by AmSerialChart and AmXYChart. + @example + var chart = new AmCharts.AmSerialChart(); + var chartScrollbar = new AmCharts.ChartScrollbar(); + chart.addChartScrollbar(chartScrollbar); + */ + class ChartScrollbar { + /** Specifies whether number of gridCount is specified automatically, acoarding to the axis size. */ + autoGridCount: boolean; + /** Background opacity. + @default 1 + */ + backgroundAlpha: number; + /** Background color of the scrollbar. + @default #D4D4D4 + */ + backgroundColor: string; + /** Read-only. Category axis of the scrollbar. */ + categoryAxis: CategoryAxis; + /** Text color. Will use chart's color if not set. */ + color: string; + /** Specifies which graph will be displayed in the scrollbar. Only Serial chart's scrollbar can display a graph. */ + graph: AmGraph; + /** Graph fill opacity. Value range is 0 - 1. 0.1 */ + graphFillAlpha: number; + /** Graph fill color. #000000 */ + graphFillColor: string; + /** Graph line opacity. Value range is 0 - 1. */ + graphLineAlpha: number; + /** Graph line color. #000000 */ + graphLineColor: string; + /** by default the graph type is the same as the original graph's type, however in case of candlestick or ohlc you might want to show line graph in the scrollbar. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". */ + graphType: string; + /** Grid opacity. Value range is 0 - 1. 0.7 */ + gridAlpha: number; + /** Grid color. #FFFFFF */ + gridColor: string; + /** The number of grid lines. */ + gridCount: number; + /** Specifies whether resize grips are hidden when mouse is away from the scrollbar. */ + hideResizeGrips: boolean; + /** Specifies whether scrollbar has a resize feature. + @default true + */ + resizeEnabled: boolean; + /** Height (width, if chart is rotated) of a scrollbar. 20 */ + scrollbarHeight: number; + /** Duration of scrolling, when the user clicks on scrollbar's background, in seconds. + @default 2 + 3*/ + scrollDuration: number; + /** Selected backround opacity. + @default 1 + */ + selectedBackgroundAlpha: number; + /** Selected background color. #EFEFEF */ + selectedBackgroundColor: string; + /** Selected graph's fill opacity. Value range is 0 - 1. 0.5 */ + selectedGraphFillAlpha: number; + /** Selected graph's fill color. #000000 */ + selectedGraphFillColor: string; + /** Selected graph's line opacity. Value range is 0 - 1. */ + selectedGraphLineAlpha: number; + /** Selected graph's line color. #000000 */ + selectedGraphLineColor: string; + /** Specifies if the chart should be updated while dragging/resizing the scrollbar or only at the moment when user releases mouse button. */ + updateOnReleaseOnly: boolean; + } + + /** AmRectangularChart is a base class of AmSerialChart and AmXYChart. It can not be instantiated explicitly.*/ + class AmRectangularChart extends AmCoordinateChart { + /** The angle of the 3D part of plot area. This creates a 3D effect (if the "depth3D" is > 0). + @default 0 + */ + angle: number; + /** Space left from axis labels/title to the chart's outside border, if autoMargins set to true. + @default 10 + */ + autoMarginOffset: number; + /** Specifies if margins of a chart should be calculated automatically so that labels of axes would fit. The chart will adjust only margins with axes. Other margins will use values set with marginRight, marginTop, marginLeft and marginBottom properties. + @default true + */ + autoMargins: boolean; + /** Cursor of a chart. */ + chartCursor: ChartCursor; + /** Chart scrollbar. */ + chartScrollbar: ChartScrollbar; + /** The depth of the 3D part of plot area. This creates a 3D effect (if the "angle" is > 0). + @default 0*/ + depth3D: number; + /** Number of pixels between the container's bottom border and plot area. This space can be used for bottom axis' values. If autoMargin is true and bottom side has axis, this property is ignored. + @default 20 + */ + marginBottom: number; + /** Number of pixels between the container's left border and plot area. This space can be used for left axis' values. If autoMargin is true and left side has axis, this property is ignored. + @default 20 + */ + marginLeft: number; + /** Number of pixels between the container's right border and plot area. This space can be used for Right axis' values. If autoMargin is true and right side has axis, this property is ignored. + @default 20 + */ + marginRight: number; + /** Flag which should be set to false if you need margins to be recalculated on next chart.validateNow() call. + @default false + */ + marginsUpdated: boolean; + /** Number of pixels between the container's top border and plot area. This space can be used for top axis' values. If autoMargin is true and top side has axis, this property is ignored. + @default 20 + */ + marginTop: number; + /** The opacity of plot area's border. Value range is 0 - 1. + @default 0 + */ + plotAreaBorderAlpha: number; + /** The color of the plot area's border. Note, the it is invisible by default, as plotAreaBorderAlpha default value is 0. Set it to a value higher than 0 to make it visible. + @default '#000000'*/ + plotAreaBorderColor: string; + /** Opacity of plot area. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. + @default 0 + */ + plotAreaFillAlphas: number; + /** You can set both one color if you need a solid color or array of colors to generate gradients, for example: ["#000000", "#0000CC"] + @default '#FFFFFF' + */ + plotAreaFillColors: any; + /** If you are using gradients to fill the plot area, you can use this property to set gradient angle. The only allowed values are horizontal and vertical: 0, 90, 180, 270. + @default 0 + */ + plotAreaGradientAngle: number; + /** Array of trend lines added to a chart. You can add trend lines to a chart using this array or access already existing trend lines */ + trendLines: TrendLine[]; + /** Opacity of zoom-out button background. + @default 0 + */ + zoomOutButtonAlpha: number; + /** Zoom-out button background color. + @default '#e5e5e5' + */ + zoomOutButtonColor: string; + /** Name of zoom-out button image. In the images folder there is another lens image, called lensWhite.png. You might want to have white lens when background is dark. Or you can simply use your own image. + @default lens.png + */ + zoomOutButtonImage: string; + /** Size of zoom-out button image + @default: 17 + */ + zoomOutButtonImageSize: number; + /** Padding around the text and image. + @default: 8 + */ + zoomOutButtonPadding: number; + /** Opacity of zoom-out button background when mouse is over it. + @default: 1 + */ + zoomOutButtonRollOverAlpha: number; + /** Text in the zoom-out button. Show all */ + zoomOutText: string; + + /** Adds a ChartCursor object to a chart */ + addChartCursor(cursor: ChartCursor); + /** Adds a ChartScrollbar to a chart */ + addChartScrollbar(scrollbar: ChartScrollbar); + /** Adds a TrendLine to a chart. + You should call chart.validateNow() after this method is called in order the trend line to be visible. */ + addTrendLine(trendLine: TrendLine); + /** Removes cursor from the chart */ + removeChartCursor(); + /** Removes scrollbar from the chart */ + removeChartScrollbar(); + /** Removes a trend line from a chart. + You should call chart.validateNow() in order the changes to be visible. */ + removeTrendLine(trendLine: TrendLine); + } + + /* Trend lines are straight lines indicating trends, might also be used for some different purposes. Can be used by Serial and XY charts. To add/remove trend line, use chart.addTrendLine(trendLine)/chart.removeTrendLine(trendLine) methods or simply pass array of trend lines: chart.trendLines = [trendLine1, trendLine2]. + @example + var trendLine = new AmCharts.TrendLine(); + trendLine.initialDate = new Date(2012, 0, 2, 12); // 12 is hour - to start trend line in the middle of the day + trendLine.finalDate = new Date(2012, 0, 11, 12); + trendLine.initialValue = 10; + trendLine.finalValue = 19; + trendLine.lineColor = "#CC0000"; + chart.addTrendLine(trendLine); + */ + class TrendLine { + + } + + /** ChartCursor is a class which displays a cursor which follows the mouse. In case of Serial chart it also shows value and category balloons. + @example + var chart = new AmCharts.AmSerialChart(); + var chartCursor = new AmCharts.ChartCursor(); + chart.addChartCursor(chartCursor); + */ + class ChartCursor { + /** Specifies if bullet for each graph will follow the cursor. */ + bulletsEnabled: boolean; + /** Size of bullets, following the cursor. + @default 8 + */ + bulletSize: number; + /** Opacity of the category balloon. + @default 1 + */ + categoryBalloonAlpha: number; + /** Color of the category balloon. cursorColor is used if not set. */ + categoryBalloonColor: string; + /** Category balloon date format (used only if category axis parses dates). Check this page for instructions on how to format dates. MMM DD, YYYY */ + categoryBalloonDateFormat: string; + /** Specifies whether category balloon is enabled. + @default true + */ + categoryBalloonEnabled: boolean; + /** Text color. #FFFFFF */ + color: string; + /** Opacity of the cursor line. 1 */ + cursorAlpha: number; + /** Color of the cursor line. #CC0000 */ + cursorColor: string; + /** Specifies where the cursor line should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). If you want the cursor to follow mouse and not to glue to the nearest data point, set "mouse" here. Possible values are: "start", "middle", "mouse". */ + cursorPosition: string; + /** Specifies whether cursor is enabled. + @default true + */ + enabled: boolean; + /** If set to true, instead of a cursor line user will see a fill which width will always be equal to the width of one data item. + Recommend setting cursorAlpha to 0.1 or some other small number if using this feature. + @default false*/ + fullWidth: boolean; + /** If this is set to true, only one balloon at a time will be displayed. Note, this is quite CPU consuming. */ + oneBalloonOnly: boolean; + /** If this is set to true, the user will be able to pan the chart (Serial only) instead of zooming. */ + pan: boolean; + /** Opacity of the selection. */ + selectionAlpha: number; + /** Specifies if cursor should only mark selected area but not zoom-in after user releases mouse button. */ + selectWithoutZooming: boolean; + /** Specifies whether value balloons are enabled. In case they are not, the balloons might be displayed anyway, when the user rolls-over the column or bullet. + @default true + */ + valueBalloonsEnabled: boolean; + /** Specifies if the user can zoom-in the chart. If pan is set to true, zoomable is switched to false automatically. + @default true + */ + zoomable: boolean; + /** Indicates if currently user is selecting some chart area to zoom-in. */ + zooming: boolean; + + + /** Hides cursor. */ + hideCursor(); + /** You can force cursor to appear at specified cateogry or date. */ + showCursorAt(category: string); + /** Adds event listener of the type "changed" to the object. + @param type Always "changed". + @param handler Dispatched when cursor position is changed. "index" is a series index over which chart cursors currently is. "zooming" specifies if user is currently zooming (is selecting) the chart. mostCloseGraph property is set only when oneBalloonOnly is set to true.*/ + addListener(type: string, handler: (e: {/** Always "changed". */ + type: string; index: number; zooming: boolean; mostCloseGraph: AmGraph; chart: AmChart; + }) => void ); + /** Adds event listener of the type "onHideCursor" to the object. + @param type Always "onHideCursor". + @param handler Dispatched when cursor is hidden.*/ + addListener(type: string, handler: (e: {/** Always "onHideCursor". */ + type: string; chart: AmChart; + }) => void ); + /** Adds event listener of the type "selected" or "zoomed" to the object. + @param type "selected" or "zoomed". + @param handler + If the type is "selected". Dispatched if selectWithoutZooming is set to true and when user selects some period. start and end are indices or timestamp (when categoryAxis.parseDates is true) of selection start/end. + If the type is "zoomed". Dispatched when user zooms to some period. start and end are indices or timestamp (when categoryAxis.parseDates is true) of selection start/end. + */ + addListener(type: string, handler: (e: {/** Always "zoomed". */ + type: string; index: number; zooming: boolean; chart: AmChart; + }) => void ); + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + } + + /** AmSerialChart is the class you have to use for majority of chart types. The supported chart types are: line, area, column, bar, step line, smoothed line, candlestick and OHLC. The chart can be rotated by 90 degrees so the column chart becomes bar chart. The chart supports simple and logarithmic scales, it can have multiple value axes. The chart can place data points at equal intervals or can parse dates and place data points at irregular intervals. + @example + var chartData = [{title:"sample 1",value:130},{title:"sample 2",value:26}]; + + var chart = new AmCharts.AmSerialChart(); + chart.categoryField = "title"; + chart.dataProvider = chartData; + + var graph = new AmCharts.AmGraph(); + graph.valueField = "value"; + graph.type = "column"; + graph.fillAlphas = 1; + chart.addGraph(graph); + + chart.write("chartdiv"); + */ + class AmSerialChart extends AmRectangularChart { + /** Date format of the graph balloon (if chart parses dates and you don't use chartCursor). + @default 'MMM DD, YYYY' + */ + balloonDateFormat: string; + /** Read-only. Chart creates category axis itself. If you want to change some properties, you should get this axis from the chart and set properties to this object. */ + categoryAxis: CategoryAxis; + /** Category field name tells the chart the name of the field in your dataProvider object which will be used for category axis values. */ + categoryField: string; + /** The gap in pixels between two columns of the same category. + @default 5 + */ + columnSpacing: number; + /** Space between 3D stacked columns. + @default 0 + */ + columnSpacing3D: number; + /** Relative width of columns. Value range is 0 - 1. + @default 0.8 + */ + columnWidth: number; + /** Read-only. If category axis parses dates endDate indicates date to which the chart is currently displayed. */ + endDate: Date; + /** Read-only. Category index to which the chart is currently displayed. */ + endIndex: number; + /** Maximum number of series allowed to select. */ + maxSelectedSeries: number; + /** The longest time span allowed to select (in milliseconds) for example, 259200000 will limit selection to 3 days. */ + maxSelectedTime: number; + /** The shortest time span allowed to select (in milliseconds) for example, 1000 will limit selection to 1 second. + @default 0 + */ + minSelectedTime: number; + /** Specifies if scrolling of a chart with mouse wheel is enabled. If you press shift while rotating mouse wheel, the chart will zoom-in/out. */ + mouseWheelScrollEnabled: boolean; + /** Specifies if zooming of a chart with mouse wheel is enabled. If you press shift while rotating mouse wheel, the chart will scroll. */ + mouseWheelZoomEnabled: boolean; + /** If you set this to true, the chart will be rotated by 90 degrees (the columns will become bars). */ + rotate: boolean; + /** Read-only. If category axis parses dates startDate indicates date from which the chart is currently displayed. */ + startDate: Date; + /** Read-only. Category index from which the chart is currently displayed. */ + startIndex: number; + /** Specifies if chart should zoom-out when data is updated. + @default true + */ + zoomOutOnDataUpdate: boolean; + + /** Number Returns index of the specified category value. value - series (category value) which index you want to find. */ + getCategoryIndexByValue(value: number); + /** Zooms out, charts shows all available data. */ + zoomOut(); + /** Zooms the chart by the value of the category axis. start - category value, String \\ end - category value, String */ + zoomToCategoryValues(start: Date, end: Date); + /** Zooms the chart from one date to another. start - start date, Date object \\ end - end date, Date object */ + zoomToDates(start: Date, end: Date); + /** Zooms the chart by the index of the category. start - start index, Number \\ end - end index, Number */ + zoomToIndexes(start: Date, end: Date); + } + + class PeriodSelector { + /** Date format of date input fields. Check [[http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/formatters/DateFormatter.html DD-MM-YYYY */ + dateFormat: string; + /** Text displayed next to "from" date input field. From: */ + fromText: string; + /** Specifies if period buttons with date range bigger than available data should be hidden. + @default true + */ + hideOutOfScopePeriods: boolean; + /** Specifies whether period selector displays "from" and "to" date input fields. + @default true + */ + inputFieldsEnabled: boolean; + /** Width of date input fields, in pixels. Works only if period selector is horizontal. + @default 100 + */ + inputFieldWidth: number; + /** Array of predefined period objects. Period object has 4 properties - period, count, label and selected. Possible period values are: "ss" - seconds, "mm" - minutes, "hh" - hours, "DD" - days, "MM" - months and "YYYY" - years. property "count" specifies how many periods this button will select. "label" will be displayed on a button and "selected" is a boolean which specifies if this button is selected when chart is initialized or not. Example: {period:"DD", count:10, label:"10 days", selected:false}. */ + periods: any[]; + /** Text displayed next to predefined period buttons. Zoom: */ + periodsText: string; + /** Possible values: "right", "left", "top", "bottom". bottom */ + position: string; + /** Specifies whether predefined period buttons should select a period from the beginning or the end of the data. */ + selectFromStart: boolean; + /** Text displayed next to "to" date input field. To: */ + toText: string; + /** Width of a period selector, when position is "left" or "right". + @default 180 + */ + width: number; + + /** Adds event listener to the object. + . +@param handler - Dispatched when dates in period selector input fields are changed or user clicks on one of the predefined period buttons. */ + + addListener(type: string, handler: (e: { + /** Always: "changed" */ + + type: string; + startDate: Date; + endDate: Date; + predefinedPeriod: string; + count: number; + }) => void ); + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + } + + /** PanelsSettings settings set's settings for all StockPanels. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of StockPanel class will be used. */ + + class PanelsSettings { + /** The angle of the 3D part of plot area. This creates a 3D effect (if the "depth3D" is > 0). */ + angle: number; + /** Opacity of panel background. Possible values are 1 and 0. Values like 0.5 will not make it half-transparent. */ + backgroundAlpha: number; + /** Background color of panels. Set backgroundAlpha to > 0 value in order to make background visible. #FFFFFF */ + backgroundColor: string; + /** The gap in pixels between two columns of the same category. */ + columnSpacing: number; + /** Relative width of columns. Valid values 0 - 1. */ + columnWidth: number; + /** The depth of the 3D part of plot area. This creates a 3D effect (if the "angle" is > 0). */ + depth3D: number; + /** Font family. */ + fontFamily: string; + /** Font size. */ + fontSize: string; + /** Number of pixels between the container's bottom border and plot area. + @default 1 + */ + marginBottom: number; + /** Number of pixels between the container's left border and plot area. If your left valueAxis values ar not placed inside the plot area, you should set marginLeft to 80 or some close value. */ + marginLeft: number; + /** Number of pixels between the container's left border and plot area. If your right valueAxis values ar not placed inside the plot area, you should set marginRight to 80 or some close value. */ + marginRight: number; + /** Number of pixels between the container's top border and plot area. */ + marginTop: number; + /** Gap between panels. + @default 8 + */ + panelSpacing: number; + /** This setting affects touch-screen devices only. If a chart is on a page, and panEventsEnabled are set to true, the page won't move if the user touches the chart first. If a chart is big enough and occupies all the screen of your touch device, the user won’t be able to move the page at all. That's why the default value is "false". If you think that selecting or or panning the chart is a primary purpose of your chart users, you should set panEventsEnabled to true. */ + panEventsEnabled: boolean; + /** The opacity of plot area's border. */ + plotAreaBorderAlpha: number; + /** The color of the plot area's border. */ + plotAreaBorderColor: string; + /** Opacity of plot area fill. */ + plotAreaFillAlphas: number; + /** Specifies the colors used to tint the background gradient fill of the plot area. String or Array of Strings */ + plotAreaFillColors: any; + /** Prefixes which are used to make big numbers shorter: 2M instead of 2000000, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e+3,prefix:"k"},{number:1e+6,prefix:"M"},{number:1e+9,prefix:"G"},{number:1e+12,prefix:"T"},{number:1e+15,prefix:"P"},{number:1e+18,prefix:"E"},{number:1e+21,prefix:"Z"},{number:1e+24,prefix:"Y"}] */ + prefixesOfBigNumbers: any[]; + /** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e-24, prefix:"y"},{number:1e-21, prefix:"z"},{number:1e-18, prefix:"a"},{number:1e-15, prefix:"f"},{number:1e-12, prefix:"p"},{number:1e-9, prefix:"n"},{number:1e-6, prefix:"μ"},{number:1e-3, prefix:"m"}] */ + prefixesOfSmallNumbers: any[]; + /** Specifies whether the animation should be sequenced or all objects should appear at once. */ + sequencedAnimation: boolean; + /** The initial opacity of the column/line. If you set startDuration to a value higher than 0, the columns/lines will fade in from startAlpha. */ + startAlpha: number; + /** Duration of the animation, in seconds. */ + startDuration: number; + /** Possible values are: "linear", "<", ">" "<>", "elastic", "bounce". */ + startEffect: string; + /** If true, prefixes will be used for big and small numbers. */ + usePrefixes: boolean; + } + + /** DataSet is objects which holds all information about data. */ + + class DataSet { + /** Category field name in your dataProvider. */ + categoryField: string; + /** Color of the data set. One of colors from AmStockChart.colors array will be used if not set. */ + color: string; + /** Whether this data set is selected for comparing. If you change this property, you should call stockChart.validateData() method in order the changes to be applied. */ + compared: boolean; + /** Data provider of the data set. */ + dataProvider: any[]; + /** Array of field mappings. Field mapping is an object with fromField and toField properties. fromField is a name of your value field in dataProvider. toField might be chosen freely, it will be used to set value/open/close/high/low fields for the StockGraph. Example: {fromField:"val1", toField:"value"}. */ + fieldMappings: any[]; + /** Specifies whether this data set should be visible in "compare to" list. + @default true + */ + showInCompare: boolean; + /** Specifies whether this data set should be visible in "select" dropdown. + @default true + */ + showInSelect: boolean; + /** Array of StockEvent objects. */ + stockEvents: StockEvent[]; + /** DataSet title. */ + title: string; + } + + class StockGraph extends AmGraph { + /** Specifies whether this graph will be compared if some data set is selected for comparing. */ + comparable: boolean; + /** Specifies a field to be used to generate comparing graph. Note, this field is not the one used in your dataProvider, but toField from FieldMapping object. */ + compareField: string; + /** Balloon color of comparing graph. */ + compareGraphBalloonColor: string; + /** Balloon text of comparing graph. */ + compareGraphBalloonText: string; + /** Bullet of comparing graph. Possible values are: "square", "round", "line", "triangleUp", "triangleDown", "dashedLine", "bubble". */ + compareGraphBullet: string; + /** Bullet size of comparing graph. */ + compareGraphBulletSize: number; + /** Corner radius of comparing graph (if type is "column"). */ + compareGraphCornerRadiusTop: number; + /** Dash length of compare graph. */ + compareGraphDashLength: number; + /** Fill alpha of comparing graph. */ + compareGraphFillAlphas: number; + /** Fill color of comparing graph. */ + compareGraphFillColors: string; + /** Opacity of comparing graph line. */ + compareGraphLineAlpha: number; + /** Thickness of compare graph. */ + compareGraphLineThickness: number; + /** Type of comparing graph. Possible values are: "line", "column", "step", "smoothedLine." line */ + compareGraphType: string; + /** Specifies if compare graph is visible in legend. + @default true + */ + compareGraphVisibleInLegend: boolean; + /** When data is grouped to periods, the graph must know which period value should be used. Possible values are: "Open", "Low", "High", "Close", "Average" and "Sum". Close */ + periodValue: string; + /** Specifies whether data set color should be used as this graph's lineColor. + @default true + */ + useDataSetColors: boolean; + } + + /** StockEvent is object which holds information about event(bullet).Values from StockEventsSettings will be used if not set.Stock event bullet's size depends on it's graphs fontSize.When user rolls - over, clicks or rolls - out of the event bullet, AmStockChart dispatches events.*/ + class StockEvent { + /** Opacity of bullet background. + @default 1 + */ + backgroundAlpha: number; + /** Color of bullet background. #DADADA */ + backgroundColor: string; + /** Opacity of bullet border. + @default 1 + */ + borderAlpha: number; + /** Bullet border color. #888888 */ + borderColor: string; + /** The color of the event text. #000000 */ + color: string; + /** Date of an event. Must be Date object, not a string. */ + date: Date; + /** graph on which event will be displayed. */ + graph: StockGraph; + /** Roll-over background color. #CC0000 */ + rollOverColor: string; + /** Specifies if the event should be displayed on category axis */ + showOnAxis: boolean; + /** Letter which will be displayed on the event. Not all types can display letters. "text" type can display longer texts. */ + text: string; + /** Type of bullet. Possible values are: "flag", "sign", "pin", "triangleUp", "triangleDown", "triangleLeft", "triangleRight", "text", "arrowUp", "arrowDown". sign */ + type: string; + /** A URL to go to when user clicks the event. */ + url: string; + /** target of url, "_blank" for example. */ + urlTarget: string; + } + + /** Creates a label on the chart which can be placed anywhere, multiple can be assigned. */ + class Label { + /** @Default 'left' */ + align: string; + /** @Default 1 */ + alpha: number; + /** Specifies if label is bold or not. */ + bold: boolean; + /** Color of a label */ + color: string; + /** Unique id of a Label. You don't need to set it, unless you want to. */ + id: string; + /** Rotation angle. */ + rotation: number; + /** Text size */ + size: number; + /** Text of a label */ + text: string; + /** URL which will be access if user clicks on a label. */ + url: string; + /** X position of a label. */ + x: number|string; + /** y position of a label. */ + y: number|string; + } + /** Common settings of legends. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of StockLegend class will be used. */ + class LegendSettings { + /** Alignment of legend entries. Possible values are: "left", "right" and "center". */ + align: string; + /** Specifies if each legend entry should take the same space as the longest legend entry. */ + equalWidths: boolean; + /** Horizontal space between legend item and left/right border. */ + horizontalGap: number; + /** The text which will be displayed in the legend. Tag [[title]] will be replaced with the title of the graph. */ + labelText: string; + /** Space below the last row of the legend, in pixels. */ + marginBottom: number; + /** Space above the first row of the legend, in pixels. */ + marginTop: number; + /** Opacity of marker border. */ + markerBorderAlpha: number; + /** Marker border color. */ + markerBorderColor: string; + /** Thickness of the legend border. */ + markerBorderThickness: number; + /** The color of the disabled marker (when the graph is hidden). */ + markerDisabledColor: string; + /** Space between legend marker and legend text, in pixels. */ + markerLabelGap: number; + /** Size of the legend marker (key). */ + markerSize: number; + /** Shape of the legend marker (key). Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble", "none". */ + markerType: string; + /** Specifies whether legend entries should be placed in reversed order. */ + reversedOrder: boolean; + /** Legend item text color on roll-over. */ + rollOverColor: string; + /** When you roll-over the legend entry, all other graphs can reduce their opacity, so that the graph you rolled-over would be distinguished. This property specifies the opacity of the graphs. */ + rollOverGraphAlpha: number; + /** Whether showing/hiding of graphs by clicking on the legend marker is enabled or not. */ + switchable: boolean; + /** Legend switch color. */ + switchColor: string; + /** Legend switch type (in case the legend is switchable). Possible values are: "x" and "v". */ + switchType: string; + /** Specifies whether the legend text is clickable or not. Clicking on legend text can show/hide value balloons if they are enabled. */ + textClickEnabled: boolean; + /** Specifies if legend labels should be use same color as corresponding markers. */ + useMarkerColorForLabels: boolean; + /** The text which will be displayed in the value portion of the legend when graph is comparable and at least one dataSet is selected for comparing. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents]], [[description]]. */ + valueTextComparing: string; + /** The text which will be displayed in the value portion of the legend. You can use tags like [[value]], [[open]], [[high]], [[low]], [[close]], [[percents]], [[description]]. */ + valueTextRegular: string; + /** Width of the value text. Increase this value if your values do not fit in the allocated space. */ + valueWidth: number; + /** Vertical space between legend items, in pixels. */ + verticalGap: number; + + } + + /** DataSetSelector is a tool for selecting data set's as main and for comparing with main data set. */ + class DataSetSelector { + /** Text displayed in the "compare to" combobox (when position is "top" or "bottom"). Select... */ + comboBoxSelectText: string; + /** Text displayed near "compare to" list. Compare to: */ + compareText: string; + /** The maximum height of the Compare to field in pixels. + @default 150 + */ + listHeight: number; + /** Possible values: "right", "left", "top", "bottom". "top" and "bottom" positions has a limitation - only one data set can be selected for comparing. left */ + position: string; + /** Text displayed near "Select" dropDown. Select: */ + selectText: string; + /** Width of a Data set selector, when position is "left" or "right". + @default 180 + */ + width: number; + } + + /** AmBalloon is the class which generates balloons (datatips). Balloon follows the mouse when you roll-over the pie slice/line bullet/column/etc, chart indicator of serial charts displays value balloons and category balloon. Balloon instance is created by the chart automatically and can be accessed via "balloon" property of AmChart. Chart shows/hides and sets position for every balloon automatically, so all you need to do is to change balloon appearance, if you want to. + @example + var chart = new AmCharts.AmSerialChart(); + // get balloon intance + var balloon = chart.balloon; + // set properties + balloon.adjustBorderColor = true; + balloon.color = "#000000"; + balloon.cornerRadius = 5; + balloon.fillColor = "#FFFFFF"; + */ + class AmBalloon { + /** If this is set to true, border color instead of background color will be changed when user rolls-over the slice, graph, etc. */ + adjustBorderColor: boolean; + /** Balloon border opacity. Value range is 0 - 1. + @default 1 + */ + borderAlpha: number; + /** Balloon border color. #FFFFFF */ + borderColor: string; + /** Balloon border thickness. + @default 2 + */ + borderThickness: number; + /** Color of text in the balloon. #FFFFFF */ + color: string; + /** Balloon corner radius. + @default 6 + */ + cornerRadius: number; + /** Balloon background opacity. + @default 1 + */ + fillAlpha: number; + /** Balloon background color. Usually balloon background color is set by the chart. Only if "adjustBorderColor" is "true" this color will be used. #CC0000 */ + fillColor: string; + /** Size of text in the balloon. Chart's fontSize is used by default. */ + fontSize: string; + /** Horizontal padding of the balloon. + @default 8 + 3*/ + horizontalPadding: number; + /** The width of the pointer (arrow) "root". Only used if cornerRadius is 0. + @default 10 + */ + pointerWidth: number; + /** If cornerRadius of a balloon is >0, showBullet is set to true for value balloons when ChartCursor is used. If you don't want the bullet near the balloon, set it to false: chart.balloon.showBullet = false */ + showBullet: boolean; + /** Text alignment, possible values "left", "middle" and "right" middle */ + textAlign: string; + /** Color of the text shadow. #000000 */ + textShadowColor: string; + /** Vertical padding of the balloon. + @default 5 + */ + verticalPadding: number; + /** Hides balloon. */ + hide(); + /** Defines a square within which the balloon should appear. Bounds are set by chart class, you don't need to call this method yourself. */ + setBounds(left: number, top: number, right: number, bottom: number); + /** Sets coordinates the balloon should point to. */ + setPosition(x: number, y: number); + /** Specifies the text which should be displayed. */ + show(value: string); + } + + /** CategoryAxesSettings settings set's settings common for all CategoryAxes of StockPanels. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of CategoryAxis class will be used. */ + class CategoryAxesSettings { + /** Specifies whether number of gridCount is specified automatically, according to the axis size. + @default true + */ + autoGridCount: boolean; + /** Axis opacity. */ + axisAlpha: number; + /** Axis color. */ + axisColor: string; + /** Height of category axes. Set it to 0 if you set inside property to true. + @default 28 + */ + axisHeight: number; + /** Thickness of the axis. */ + axisThickness: number; + /** Text color. */ + color: string; + /** Length of a dash. */ + dashLength: number; + /** Date formats of different periods. Possible period values: fff - milliseconds, ss - seconds, mm - minutes, hh - hours, DD - days, MM - months, WW - weeks, YYYY - years. Check this page for date formatting strings. */ + dateFormats: any[]; + /** If you want data points to be placed at equal intervals (omiting dates with no data), set equalSpacing to true. */ + equalSpacing: boolean; + /** Fill opacity. Every second space between grid lines can be filled with fillColor. */ + fillAlpha: number; + /** Fill color. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills. */ + fillColor: string; + /** Text size. */ + fontSize: string; + /** Opacity of grid lines. */ + gridAlpha: number; + /** Color of grid lines. */ + gridColor: string; + /** Approximate number of grid lines. You should set autoGridCount to false in order this property not to be ignored. + @default 10 + */ + gridCount: number; + /** Thickness of grid lines. */ + gridThickness: number; + /** Periods to which data will be gruoped in case there are more data items in the selected period than specified in maxSeries property. ["ss", "10ss", "30ss", "mm", "10mm", "30mm", "hh", "DD", "WW", "MM", "YYYY"] */ + groupToPeriods: any[]; + /** Specifies whether values should be placed inside or outside of plot area. */ + inside: boolean; + /** Rotation angle of a label. */ + labelRotation: number; + /** Maximum series shown at a time. In case there are more data points in the selection than maxSeries, the chart will group data to longer periods, for example - you have 250 days in the selection, and maxSeries is 150 - the chart will group data to weeks. + @default 150 + */ + maxSeries: number; + /** Specifies the shortest period of your data. fff - millisecond, ss - second, mm - minute, hh - hour, DD - day, MM - month, YYYY - year. DD */ + minPeriod: string; + /** top or "bottom". */ + position: string; + /** Specifies whether the graph should start on axis or not. In case you display columns, it is recommended to set this to false. startOnAxis can be set to true only if equalSpacing is set to true. */ + startOnAxis: boolean; + /** Tick length. */ + tickLength: number; + } + + /** ChartCursorSettings settings set's settings for chart cursor. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of ChartCursor class will be used. */ + class ChartCursorSettings { + /** Specifies if bullet for each graph will follow the cursor. */ + bulletsEnabled: boolean; + /** Size of bullets, following the cursor. */ + bulletSize: number; + /** Opacity of the category balloon. */ + categoryBalloonAlpha: number; + /** Color of the category balloon. */ + categoryBalloonColor: string; + /** Array of date format objects. Date format object must have "period" and "format" items. Available periods are: fff - millisecond, ss - second, mm - minute, hh - hour, DD - date, WW - week, MM - month, YYYY - year. [{period:"YYYY", format:"YYYY"}, {period:"MM", format:"MMM, YYYY"}, {period:"WW", format:"MMM DD, YYYY"}, {period:"DD", format:"MMM DD, YYYY"}, {period:"hh", format:"JJ:NN"}, {period:"mm", format:"JJ:NN"}, {period:"ss", format:"JJ:NN:SS"}, {period:"fff", format:"JJ:NN:SS"}] */ + categoryBalloonDateFormats: any[]; + /** Specifies whether category balloon is enabled. */ + categoryBalloonEnabled: boolean; + /** Opacity of the cursor line. */ + cursorAlpha: number; + /** Color of the cursor line. */ + cursorColor: string; + /** Possible values: "start", "middle" and "mouse". */ + cursorPosition: string; + /** Set this to "false" if you don't want chart cursor to appear in your charts. + @default true + */ + enabled: boolean; + /** If this is set to true, the user will be able to pan the chart instead of zooming. */ + pan: boolean; + /** Specifies whether value balloons are enabled. In case they are not, the balloons might be displayed anyway, when the user rolls-over the column or bullet. */ + valueBalloonsEnabled: boolean; + /** Specifies if the user can zoom-in the chart. If pan is set to true, zoomable is switched to false automatically. */ + zoomable: boolean; + } + + /* ChartScrollbarSettings settings set's settings for chart scrollbar. If you change a property after the chart is initialized, you should call stockChart.validateNow() method in order for it to work. If there is no default value specified, default value of ChartScrollbar class will be used.*/ + class ChartScrollbarSettings { + /** Specifies whether number of gridCount is specified automatically, according to the axis size. + @default true + */ + autoGridCount: boolean; + /** Background opacity. */ + backgroundAlpha: number; + /** Background color of the scrollbar. */ + backgroundColor: string; + /** Text color. */ + color: string; + /** Set false if you don't need scrollbar. + @default true + */ + enabled: boolean; + /** Font size. */ + fontSize: string; + /** Specifies which graph will be displayed in the scrollbar. */ + graph: AmGraph; + /** Graph fill opacity. */ + graphFillAlpha: number; + /** Graph fill color. */ + graphFillColor: string; + /** Graph line opacity. */ + graphLineAlpha: number; + /** Graph line color. */ + graphLineColor: string; + /** Type of chart scrollbar's graph. By default the graph type is the same as the original graph's type, however in case of candlestick or ohlc you might want to show line graph in the scrollbar. Possible values are: line, column, step, smoothedLine, candlestick, ohlc. */ + graphType: string; + /** Grid opacity. */ + gridAlpha: number; + /** Grid color. */ + gridColor: string; + /** Grid count. You should set autoGridCount to false in order this property to work. */ + gridCount: number; + /** Height of scrollbar, in pixels. + @default 40 + */ + height: number; + /** Specifies whether resize grips are hidden when mouse is away from the scrollbar. */ + hideResizeGrips: boolean; + /** Duration of scrolling, when the user clicks on scrollbar's background, in seconds. */ + scrollDuration: number; + /** Selected background opacity. */ + selectedBackgroundAlpha: number; + /** Selected background color. */ + selectedBackgroundColor: string; + /** Selected graph'sfill opacity. */ + selectedGraphFillAlpha: number; + /** Selected graph'sfill color. */ + selectedGraphFillColor: string; + /** Selected graph'sline opacity. */ + selectedGraphLineAlpha: number; + /** Selected graph's line color. */ + selectedGraphLineColor: string; + /** Specifies if the chart should be updated while dragging/resizing the scrollbar or only at the moment when user releases mouse button. Usefull when working with large data sets. + @default true + */ + updateOnReleaseOnly: boolean; + } + + /** AmGraph class displays all types of graphs - line, column, step line, smoothed line, ohlc and candlestick. + @example + var chart = new AmCharts.AmSerialChart(); + var graph = new AmCharts.AmGraph(); + graph.valueField = 'value'; + graph.type = 'column'; + graph.fillAlphas = 1; + chart.addGraph(graph); + */ + class AmGraph { + /** Name of the alpha field in your dataProvider. */ + alphaField: string; + /** Value balloon color. Will use graph or data item color if not set. */ + balloonColor: string; + /** If you set some function, the graph will call it and pass GraphDataItem and AmGraph object to it. This function should return a string which will be displayed in a balloon. */ + balloonFunction(graphDataItem: GraphDataItem, amGraph: AmGraph): string; + /** Balloon text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] [[value]] */ + balloonText: string; + /** Specifies if the line graph should be placed behind column graphs */ + behindColumns: boolean; + /** Type of the bullets. Possible values are: "none", "round", "square", "triangleUp", "triangleDown", "bubble", "custom". none */ + bullet: string; + /** Opacity of bullets. Value range is 0 - 1. + @default 1 + */ + bulletAlpha: number; + /** Bullet border opacity. + @default 1 + */ + bulletBorderAlpha: number; + /** Bullet border color. Will use lineColor if not set. */ + bulletBorderColor: string; + /** Bullet border thickness. + @default 2 + */ + bulletBorderThickness: number; + /** Bullet color. Will use lineColor if not set. */ + bulletColor: string; + /** Name of the bullet field in your dataProvider. */ + bulletField: string; + /** Bullet offset. Distance from the actual data point to the bullet. Can be used to place custom bullets above the columns. */ + bulletOffset: number; + /** Bullet size. + @default 8 + */ + bulletSize: number; + /** Name of the bullet size field in your dataProvider. */ + bulletSizeField: string; + /** Name of the close field (used by candlesticks and ohlc) in your dataProvider. */ + closeField: string; + /** Color of value labels. Will use chart's color if not set. */ + color: string; + /** Name of the color field in your dataProvider. */ + colorField: string; + /** Specifies whether to connect data points if data is missing. The default value is true. + @default true + */ + connect: boolean; + /** Corner radius of column. It can be set both in pixels or in percents. The chart's depth and angle styles must be set to 0. The default value is 0. Note, cornerRadiusTop will be applied for all corners of the column, JavaScript charts do not have a possibility to set separate corner radius for top and bottom. As we want all the property names to be the same both on JS and Flex, we didn't change this too. */ + cornerRadiusTop: number; + /** If bulletsEnabled of ChartCurosor is true, a bullet on each graph follows the cursor. You can set opacity of each graphs bullet. In case you want to disable these bullets for a certain graph, set opacity to 0. + @default 1 + */ + cursorBulletAlpha: number; + /** Path to the image of custom bullet. */ + customBullet: string; + /** Name of the custom bullet field in your dataProvider. */ + customBulletField: string; + /** Dash length. If you set it to a value greater than 0, the graph line will be dashed. */ + dashLength: number; + /** Name of the description field in your dataProvider. */ + descriptionField: string; + /** Opacity of fill. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. */ + fillAlphas: number; + /** Fill color. Will use lineColor if not set. */ + fillColors: any; + /** Name of the fill colors field in your dataProvider. */ + fillColorsField: string; + /** You can set another graph here and if fillAlpha is >0, the area from this graph to fillToGraph will be filled (instead of filling the area to the X axis). */ + fillToGraph: AmGraph; + /** Size of value labels text. Will use chart's fontSize if not set. */ + fontSize: string; + /** Orientation of the gradient fills (only for "column" graph type). Possible values are "vertical" and "horizontal". vertical */ + gradientOrientation: string; + /** Specifies whether the graph is hidden. Do not use this to show/hide the graph, use hideGraph(graph) and showGraph(graph) methods instead. */ + hidden: boolean; + /** If there are more data points than hideBulletsCount, the bullets will not be shown. 0 means the bullets will always be visible. */ + hideBulletsCount: number; + /** Name of the high field (used by candlesticks and ohlc) in your dataProvider. */ + highField: string; + /** Whether to include this graph when calculating min and max value of the axis. + @default true + */ + includeInMinMax: boolean; + /** Name of label color field in data provider. */ + labelColorField: string; + /** Position of value label. Possible values are: "bottom", "top", "right", "left", "inside", "middle". Sometimes position is changed by the chart, depending on a graph type, rotation, etc. top */ + labelPosition: string; + /** Value label text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]]. */ + labelText: string; + /** Legend marker opacity. Will use lineAlpha if not set. Value range is 0 - 1. */ + legendAlpha: number; + /** Legend marker color. Will use lineColor if not set. */ + legendColor: string; + /** Legend value text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] You can also use custom fields from your dataProvider. If not set, uses Legend's valueText. */ + legendValueText: string; + /** Opacity of the line (or column border). Value range is 0 - 1. + @default 1 + */ + lineAlpha: number; + /** Color of the line (or column border). If you do not set any, the color from [[AmCoordinateChart */ + lineColor: string; + /** Name of the line color field (used by columns and candlesticks only) in your dataProvider. */ + lineColorField: string; + /** Specifies thickness of the graph line (or column border). + @default 1 + */ + lineThickness: number; + /** Name of the low field (used by candlesticks and ohlc) in your dataProvider. */ + lowField: string; + /** Legend marker type. You can set legend marker (key) type for individual graphs. Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble". */ + markerType: string; + /** Specifies size of the bullet which value is the biggest (XY chart). + @default 50 + */ + maxBulletSize: number; + /** Specifies minimum size of the bullet (XY chart). */ + minBulletSize: number; + /** If you use different colors for your negative values, a graph below zero line is filled with negativeColor. With this property you can define a different base value at which colors should be changed to negative colors. */ + negativeBase: number; + /** Fill opacity of negative part of the graph. Will use fillAlphas if not set. */ + negativeFillAlphas: number; + /** Fill color of negative part of the graph. Will use fillColors if not set. */ + negativeFillColors: any; //String /Array; + /** Color of the line (or column) when the values are negative. In case the graph type is candlestick or ohlc, negativeLineColor is used when close value is less then open value. */ + negativeLineColor: string; + /** Example: {precision:-1, decimalSeparator:'.', thousandsSeparator:','}. The graph uses this object's values to format the numbers. Uses chart's numberFormatter if not defined. */ + numberFormatter: Object; + /** Name of the open field (used by floating columns, candlesticks and ohlc) in your dataProvider. */ + openField: string; + /** Specifies where data points should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). This setting affects Serial chart only. Possible values are "start" and "middle". middle */ + pointPosition: string; + /** If graph's type is column and labelText is set, graph hides labels which do not fit into the column's space. If you don't want these labels to be hidden, set this to true. */ + showAllValueLabels: boolean; + /** Specifies whether the value balloon of this graph is shown when mouse is over data item or chart's indicator is over some series. + @default true + */ + showBalloon: boolean; + /** Specifies graphs value at which cursor is showed. This is only important for candlestick and ohlc charts, also if column chart has "open" value. Possible values are: "open", "close", "high", "low". close */ + showBalloonAt: string; + /** If the value axis of this graph has stack types like "regular" or "100%" You can exclude this graph from stacking. + @default true + */ + stackable: boolean; + /** Graph title. */ + title: string; + /** Type of the graph. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". XY and Radar charts can only display "line" type graphs. line */ + type: string; + /** Name of the url field in your dataProvider. */ + urlField: string; + /** Target to open URLs in, i.e. _blank, _top, etc. */ + urlTarget: string; + /** Specifies which value axis the graph will use. Will use the first value axis if not set. */ + valueAxis: ValueAxis; + /** Name of the value field in your dataProvider. */ + valueField: string; + /** Specifies whether this graph should be shown in the Legend. + @default true + */ + visibleInLegend: boolean; + /** XY chart only. A horizontal value axis object to attach graph to. */ + xAxis: ValueAxis; + /** XY chart only. Name of the x field in your dataProvider. */ + xField: string; + /** XY chart only. A vertical value axis object to attach graph to. */ + yAxis: ValueAxis; + /** XY chart only. Name of the y field in your dataProvider. */ + yField: string; + } + + /** AxisBase is the base class for ValueAxis and CategoryAxis. It can not be instantiated explicitly. */ + class AxisBase { + /** Specifies whether number of gridCount is specified automatically, acoarding to the axis size. + @default true + */ + autoGridCount: boolean; + /** Axis opacity. Value range is 0 - 1. + @default 1 + */ + axisAlpha: number; + /** Axis color. #000000 */ + axisColor: string; + /** Thickness of the axis. + @default 1 + */ + axisThickness: number; + /** Color of axis value labels. Will use chart's color if not set. */ + color: string; + /** Length of a dash. 0 means line is not dashed. */ + dashLength: number; + /** Fill opacity. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills. */ + fillAlpha: number; + /** Fill color. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills. #FFFFFF */ + fillColor: string; + /** Size of value labels text. Will use chart's fontSize if not set. */ + fontSize: string; + /** Opacity of grid lines. 0.2 */ + gridAlpha: number; + /** Color of grid lines. #000000 */ + gridColor: string; + /** Number of grid lines. In case this is value axis, or your categoryAxis parses dates, the number is approximate. The default value is 5. If you set autoGridCount to true, this property is ignored. + @default 5 + */ + gridCount: number; + /** Thickness of grid lines. + @default 1 + */ + gridThickness: number; + /** The array of guides belonging to this axis. */ + guides: any[]; + /** If autoMargins of a chart is set to true, but you want this axis not to be measured when calculating margin, set ignoreAxisWidth to true. */ + ignoreAxisWidth: boolean; + /** Specifies whether values should be placed inside or outside plot area. */ + inside: boolean; + /** Frequency at which labels should be placed. Doesn't work for CategoryAxis if parseDates is set to true. + @default 1 + */ + labelFrequency: number; + /** Rotation angle of a label. Only horizontal axis' values can be rotated. If you set this for vertical axis, the setting will be ignored. */ + labelRotation: number; + /** Specifies whether axis displays category axis' labels and value axis' values. + @default true + */ + labelsEnabled: boolean; + /** The distance of the axis to the plot area, in pixels. Negative values can also be used. */ + offset: number; + /** Possible values are: "top", "bottom", "left", "right". If axis is vertical, default position is "left". If axis is horizontal, default position is "bottom". */ + position: string; + /** Whether to show first axis label or not. + @default true + */ + showFirstLabel: boolean; + /** Whether to show last axis label or not. + @default true + */ + showLastLabel: boolean; + /** Length of the tick marks. + @default 5 + */ + tickLength: number; + /** Title of the axis. */ + title: string; + /** Specifies if title should be bold or not. + @default true + */ + titleBold: boolean; + /** Color of axis title. Will use text color of chart if not set any. */ + titleColor: string; + /** Font size of axis title. Will use font size of chart plus two pixels if not set any. */ + titlefontSize: string; + + /** Adds guide to the axis. */ + addGuide(guide:Guide); + /** Removes guide from the axis. */ + removeGuide(guide:Guide); + } + + /** ValueAxis is the class which displays value axis for the chart. The chart can have any number of value axes. For Serial chart one value axis is created automatically. For XY Chart two value axes (horizontal and vertical) are created automatically. */ + class ValueAxis extends AxisBase { + /** Radar chart only. Specifies distance from axis to the axis title (category) 10 */ + axisTitleOffset: number; + /** Read-only. Coordinate of the base value. */ + baseCoord: number; + /** Specifies base value of the axis. */ + baseValue: number; + /** If your values represents time units, and you want value axis labels to be formatted as duration, you have to set the duration unit. Possible values are: "ss", "mm", "hh" and "DD". */ + duration: string; + /** If duration property is set, you can specify what string should be displayed next to day, hour, minute and second. {DD:"d. ", hh:":", mm:":",ss:""} */ + durationUnits: Object; + /** Radar chart only. Possible values are: "polygons" and "circles". Set "circles" for polar charts. polygons */ + gridType: string; + /** Unique id of value axis. It is not required to set it, unless you need to tell the graph which exact value axis it should use. */ + id: string; + /** Specifies whether guide values should be included when calculating min and max of the axis. */ + includeGuidesInMinMax: boolean; + /** If true, the axis will include hidden graphs when calculating min and max values. */ + includeHidden: boolean; + /** Specifies whether values on axis can only be integers or both integers and doubles. */ + integersOnly: boolean; + /** You can use this function to format Value axis labels. This function is called and these parameters are passed: labelFunction(value, valueText, valueAxis); +Where value is numeric value, valueText is formatted string and valueAxis is a reference to valueAxis object. + +If axis type is "date", labelFunction will pass different arguments: +labelFunction(valueText, date, valueAxis) + +Your function should return string.*/ + labelFunction(value: number, valueText: string, valueAxis: ValueAxis): string; + labelFunction(valueText: string, data: Date, valueAxis: ValueAxis): string; + /** Specifies if this value axis' scale should be logarithmic. */ + logarithmic: boolean; + /** Read-only. Maximum value of the axis. */ + max: number; + /** If you don't want max value to be calculated by the chart, set it using this property. This value might still be adjusted so that it would be possible to draw grid at rounded intervals. */ + maximum: number; + /** If your value axis is date-based, you can specify maximum date of the axis. Can be set as date object, timestamp number or string if dataDateFormat is set. */ + maximumData: Date; + /** Read-only. Minimum value of the axis. */ + min: number; + /** If you don't want min value to be calculated by the chart, set it using this property. This value might still be adjusted so that it would be possible to draw grid at rounded intervals. */ + minimum: number; + /** If your value axis is date-based, you can specify minimum date of the axis. Can be set as date object, timestamp number or string if dataDateFormat is set. */ + minimumDate: Date; + /** If set value axis scale (min and max numbers) will be multiplied by it. I.e. if set to 1.2 the scope of values will increase by 20%. */ + minMaxMultiplier: number; + /** Works with radar charts only. If you set it to “middle”, labels and data points will be placed in the middle between axes. */ + pointPosition: string; + /** Possible values are: "top", "bottom", "left", "right". If axis is vertical, default position is "left". If axis is horizontal, default position is "bottom". */ + position: string; + /** Precision (number of decimals) of values. */ + precision: number; + /** Radar chart only. Specifies if categories (axes' titles) should be displayed near axes) + @default true + */ + radarCategoriesEnabled: boolean; + /** pecifies if graphs's values should be recalculated to percents. */ + recalculateToPercents: boolean; + /** Specifies if value axis should be reversed (smaller values on top). */ + reversed: boolean; + /** Stacking mode of the axis. Possible values are: "none", "regular", "100%", "3d". none Note, only graphs of one type will be stacked. */ + stackType: string; + /** Read-only. Value difference between two grid lines. */ + step: number; + /** If you set minimum and maximum for your axis, chart adjusts them so that grid would start and end on the beginning and end of plot area and grid would be at equal intervals. If you set strictMinMax to true, the chart will not adjust minimum and maximum of value axis. */ + strictMinMax: boolean; + /** In case you synchronize one value axis with another, you need to set the synchronization multiplier. Use synchronizeWithAxis method to set with which axis it should be synced. */ + synchronizationMultiplier: number; + /** One value axis can be synchronized with another value axis. You can use both reference to your axis or id of the axis here. You should set synchronizationMultiplyer in order for this to work. */ + synchronizeWith: ValueAxis; + /** If this value axis is stacked and has columns, setting valueAxis.totalText = "[[total]]" will make it to display total value above the most-top column. */ + totalText: string; + /** Color of total text. */ + totalTextColor: string; + /** Distance from data point to total text. */ + totalTextOffset: number; + /** This allows you to have logarithmic value axis and have zero values in the data. You must set it to >0 value in order to work. */ + treatZeroAs: number; + /** Type of value axis. If your values in data provider are dates and you want this axis to show dates instead of numbers, set it to "date". */ + type: string; + /** Unit which will be added to the value label. */ + unit: string; + /** Position of the unit. Possible values are "left" and "right". right */ + unitPosition: string; + /** If true, prefixes will be used for big and small numbers. You can set arrays of prefixes directly to the chart object via prefixesOfSmallNumbers and prefixesOfBigNumbers. */ + usePrefixes: boolean; + /** If true, values will always be formatted using scientific notation (5e+8, 5e-8...) Otherwise only values bigger then 1e+21 and smaller then 1e-7 will be displayed in scientific notation. */ + useScientificNotation: boolean; + + /** Adds guide to the axis. */ + addGuide(guide: Guide); + /** Adds event listener to the object. type - string like 'axisChanged' (should be listed in 'events' section of this class or classes which extend this class). handler - function which is called when event happens */ + addListener(type: string, handler: any); + /** Number, - value of coordinate. Returns value of the coordinate. coordinate - y or x coordinate, in pixels. */ + coordinateToValue(coordinate: number); + /** Number - coordinate Returns coordinate of the value in pixels. value - Number */ + getCoordinate(value: number); + /** Removes guide from the axis.*/ + removeGuide(guide: Guide); + /** Removes event listener from the object. */ + removeListener(obj: any, type: string, handler: any); + + /** One value axis can be synchronized with another value axis. You should set synchronizationMultiplyer in order for this to work. */ + synchronizeWithAxis(axis:ValueAxis); + /** XY Chart only. Zooms-in the axis to the provided values. */ + zoomToValues(startValue: number, endValue: number); + + /** Adds event listener of the type "axisZoomed" to the object. + @param type Always "axisZoomed". + @param handler XY chart only. Dispatched when axis is zoomed.*/ + addListener(type: string, handler: (e: { + /** Always "axisZoomed". */ + type: string; startValue: Date; endValue: Date; chart: AmChart; + }) => void ); + /** Adds event listener of the type "logarithmicAxisFailed" to the object. + @param type Always "logarithmicAxisFailed". + @param handler Dispatched when valueAxis is logarithmic and values equal or less then zero were found in data.*/ + addListener(type: string, handler: (e: { + /** Always "logarithmicAxisFailed". */ + type: string; chart: AmChart; + }) => void ); + + /** Removes event listener from chart object. */ + removeListener(chart: AmChart, type: string, handler: any); + } + + class Title { + /** @default 1 */ + alpha: number; + /** Specifies if the tile is bold or not. + @default false*/ + bold: boolean; + /** Text color of a title. */ + color: string; + /** Unique id of a Title. You don't need to set it, unless you want to. */ + id: string; + /** Text size */ + size: number; + /** Text of a label */ + text: string; + } + class ExportSettings { + enabled: boolean; + libs: Object; + menu: Object; + } +} diff --git a/amcharts/tsconfig.json b/amcharts/tsconfig.json new file mode 100644 index 0000000000..af6755830c --- /dev/null +++ b/amcharts/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/amplify-deferred/amplify-deferred-tests.ts b/amplify-deferred/amplify-deferred-tests.ts index 957941cd29..9482a8ef02 100644 --- a/amplify-deferred/amplify-deferred-tests.ts +++ b/amplify-deferred/amplify-deferred-tests.ts @@ -1,5 +1,5 @@ -/// -/// + +/// // Copied examples directly from AmplifyJs site diff --git a/amplify-deferred/amplify-deferred-tests.ts.tscparams b/amplify-deferred/amplify-deferred-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/amplify-deferred/amplify-deferred-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/amplify-deferred/amplify-deferred.d.ts b/amplify-deferred/amplify-deferred.d.ts deleted file mode 100644 index b8c1142899..0000000000 --- a/amplify-deferred/amplify-deferred.d.ts +++ /dev/null @@ -1,182 +0,0 @@ -// Type definitions for AmplifyJs 1.1.0 using JQuery Deferred -// Project: http://amplifyjs.com/ -// Definitions by: Jonas Eriksson , Laurentiu Stamate -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface amplifyRequestSettings { - resourceId: string; - data?: any; - success?: (...args: any[]) => void; - error?: (...args: any[]) => void; -} - -interface amplifyDecoder { - ( - data?: any, - status?: string, - xhr?: JQueryXHR, - success?: (...args: any[]) => void, - error?: (...args: any[]) => void - ): void -} - -interface amplifyDecoders { - [decoderName: string]: amplifyDecoder; - jsSend: amplifyDecoder; -} - -interface amplifyAjaxSettings extends JQueryAjaxSettings { - cache?: any; - dataMap?: {} | ((data: any) => {}); - decoder?: any /* string or amplifyDecoder */; -} - -interface amplifyRequest { - - /*** - * Request a resource. - * resourceId: Identifier string for the resource. - * data: A set of key/value pairs of data to be sent to the resource. - * callback: A function to invoke if the resource is retrieved successfully. - */ - (resourceId: string, hash?: any, callback?: Function): JQueryPromise; - - /*** - * Request a resource. - * settings: A set of key/value pairs of settings for the request. - * resourceId: Identifier string for the resource. - * data (optional): Data associated with the request. - * success (optional): Function to invoke on success. - * error (optional): Function to invoke on error. - */ - (settings: amplifyRequestSettings): JQueryPromise; - - /*** - * Define a resource. - * resourceId: Identifier string for the resource. - * requestType: The type of data retrieval method from the server. See the request types sections for more information. - * settings: A set of key/value pairs that relate to the server communication technology. The following settings are available: - * Any settings found in jQuery.ajax(). - * cache: See the cache section for more details. - * decoder: See the decoder section for more details. - */ - define(resourceId: string, requestType: string, settings?: amplifyAjaxSettings): void; - - /*** - * Define a custom request. - * resourceId: Identifier string for the resource. - * resource: Function to handle requests. Receives a hash with the following properties: - * resourceId: Identifier string for the resource. - * data: Data provided by the user. - * success: Callback to invoke on success. - * error: Callback to invoke on error. - */ - define(resourceId: string, resource: (settings: amplifyRequestSettings) => void): void; - - decoders: amplifyDecoders; - cache: any; -} - -interface amplifySubscribe { - /*** - * Subscribe to a message. - * topic: Name of the message to subscribe to. - * callback: Function to invoke when the message is published. - */ - (topic: string, callback: Function): void; - /*** - * Subscribe to a message. - * topic: Name of the message to subscribe to. - * context: What this will be when the callback is invoked. - * callback: Function to invoke when the message is published. - * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. - */ - (topic: string, context: any, callback: Function, priority?: number): void; - /*** - * Subscribe to a message. - * topic: Name of the message to subscribe to. - * callback: Function to invoke when the message is published. - * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. - */ - (topic: string, callback: Function, priority?: number): void; -} -interface amplifyStorageTypeStore { - /*** - * Stores a value for a given key using the default storage type. - * - * key: Identifier for the value being stored. - * value: The value to store. The value can be anything that can be serialized as JSON. - * [options]: A set of key/value pairs that relate to settings for storing the value. - */ - (key: string, value: any, options?: any): void; - - /*** - * Gets a stored value based on the key. - */ - (key: string): any; - - /*** - * Gets a hash of all stored values. - */ - (): any; -} - -interface amplifyStore extends amplifyStorageTypeStore { - - /*** - * IE 8+, Firefox 3.5+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ - */ - localStorage: amplifyStorageTypeStore; - - /*** - * IE 8+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ - */ - sessionStorage: amplifyStorageTypeStore; - - /*** - * Firefox 2+ - */ - globalStorage: amplifyStorageTypeStore; - - /*** - * IE 5 - 7 - */ - userData: amplifyStorageTypeStore; - - /*** - * An in-memory store is provided as a fallback if none of the other storage types are available. - */ - memory: amplifyStorageTypeStore; - - -} - -interface amplifyStatic { - - subscribe: amplifySubscribe; - - /*** - * Remove a subscription. - * topic: The topic being unsubscribed from. - * callback: The callback that was originally subscribed. - */ - unsubscribe(topic: string, callback: Function): void; - - /*** - * Publish a message. - * topic: The name of the message to publish. - * Any additional parameters will be passed to the subscriptions. - * amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked. - */ - publish(topic: string, ...args: any[]): boolean; - - store: amplifyStore; - - request: amplifyRequest; - -} - -declare var amplify: amplifyStatic; - diff --git a/amplify-deferred/index.d.ts b/amplify-deferred/index.d.ts new file mode 100644 index 0000000000..3736a6644b --- /dev/null +++ b/amplify-deferred/index.d.ts @@ -0,0 +1,182 @@ +// Type definitions for AmplifyJs 1.1.0 using JQuery Deferred +// Project: http://amplifyjs.com/ +// Definitions by: Jonas Eriksson , Laurentiu Stamate +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface amplifyRequestSettings { + resourceId: string; + data?: any; + success?: (...args: any[]) => void; + error?: (...args: any[]) => void; +} + +interface amplifyDecoder { + ( + data?: any, + status?: string, + xhr?: JQueryXHR, + success?: (...args: any[]) => void, + error?: (...args: any[]) => void + ): void +} + +interface amplifyDecoders { + [decoderName: string]: amplifyDecoder; + jsSend: amplifyDecoder; +} + +interface amplifyAjaxSettings extends JQueryAjaxSettings { + cache?: any; + dataMap?: {} | ((data: any) => {}); + decoder?: any /* string or amplifyDecoder */; +} + +interface amplifyRequest { + + /*** + * Request a resource. + * resourceId: Identifier string for the resource. + * data: A set of key/value pairs of data to be sent to the resource. + * callback: A function to invoke if the resource is retrieved successfully. + */ + (resourceId: string, hash?: any, callback?: Function): JQueryPromise; + + /*** + * Request a resource. + * settings: A set of key/value pairs of settings for the request. + * resourceId: Identifier string for the resource. + * data (optional): Data associated with the request. + * success (optional): Function to invoke on success. + * error (optional): Function to invoke on error. + */ + (settings: amplifyRequestSettings): JQueryPromise; + + /*** + * Define a resource. + * resourceId: Identifier string for the resource. + * requestType: The type of data retrieval method from the server. See the request types sections for more information. + * settings: A set of key/value pairs that relate to the server communication technology. The following settings are available: + * Any settings found in jQuery.ajax(). + * cache: See the cache section for more details. + * decoder: See the decoder section for more details. + */ + define(resourceId: string, requestType: string, settings?: amplifyAjaxSettings): void; + + /*** + * Define a custom request. + * resourceId: Identifier string for the resource. + * resource: Function to handle requests. Receives a hash with the following properties: + * resourceId: Identifier string for the resource. + * data: Data provided by the user. + * success: Callback to invoke on success. + * error: Callback to invoke on error. + */ + define(resourceId: string, resource: (settings: amplifyRequestSettings) => void): void; + + decoders: amplifyDecoders; + cache: any; +} + +interface amplifySubscribe { + /*** + * Subscribe to a message. + * topic: Name of the message to subscribe to. + * callback: Function to invoke when the message is published. + */ + (topic: string, callback: Function): void; + /*** + * Subscribe to a message. + * topic: Name of the message to subscribe to. + * context: What this will be when the callback is invoked. + * callback: Function to invoke when the message is published. + * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. + */ + (topic: string, context: any, callback: Function, priority?: number): void; + /*** + * Subscribe to a message. + * topic: Name of the message to subscribe to. + * callback: Function to invoke when the message is published. + * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. + */ + (topic: string, callback: Function, priority?: number): void; +} +interface amplifyStorageTypeStore { + /*** + * Stores a value for a given key using the default storage type. + * + * key: Identifier for the value being stored. + * value: The value to store. The value can be anything that can be serialized as JSON. + * [options]: A set of key/value pairs that relate to settings for storing the value. + */ + (key: string, value: any, options?: any): void; + + /*** + * Gets a stored value based on the key. + */ + (key: string): any; + + /*** + * Gets a hash of all stored values. + */ + (): any; +} + +interface amplifyStore extends amplifyStorageTypeStore { + + /*** + * IE 8+, Firefox 3.5+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ + */ + localStorage: amplifyStorageTypeStore; + + /*** + * IE 8+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ + */ + sessionStorage: amplifyStorageTypeStore; + + /*** + * Firefox 2+ + */ + globalStorage: amplifyStorageTypeStore; + + /*** + * IE 5 - 7 + */ + userData: amplifyStorageTypeStore; + + /*** + * An in-memory store is provided as a fallback if none of the other storage types are available. + */ + memory: amplifyStorageTypeStore; + + +} + +interface amplifyStatic { + + subscribe: amplifySubscribe; + + /*** + * Remove a subscription. + * topic: The topic being unsubscribed from. + * callback: The callback that was originally subscribed. + */ + unsubscribe(topic: string, callback: Function): void; + + /*** + * Publish a message. + * topic: The name of the message to publish. + * Any additional parameters will be passed to the subscriptions. + * amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked. + */ + publish(topic: string, ...args: any[]): boolean; + + store: amplifyStore; + + request: amplifyRequest; + +} + +declare var amplify: amplifyStatic; + diff --git a/amplify-deferred/tsconfig.json b/amplify-deferred/tsconfig.json new file mode 100644 index 0000000000..3d0d08164f --- /dev/null +++ b/amplify-deferred/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "amplify-deferred-tests.ts" + ] +} \ No newline at end of file diff --git a/amplifyjs/amplifyjs-tests.ts b/amplify/amplifyjs-tests.ts similarity index 98% rename from amplifyjs/amplifyjs-tests.ts rename to amplify/amplifyjs-tests.ts index a104d4a7cc..ec3807435d 100644 --- a/amplifyjs/amplifyjs-tests.ts +++ b/amplify/amplifyjs-tests.ts @@ -1,5 +1,5 @@ -/// -/// + +/// // Copied examples directly from AmplifyJs site diff --git a/amplify/index.d.ts b/amplify/index.d.ts new file mode 100644 index 0000000000..8955fdc7de --- /dev/null +++ b/amplify/index.d.ts @@ -0,0 +1,182 @@ +// Type definitions for AmplifyJs 1.1.0 +// Project: http://amplifyjs.com/ +// Definitions by: Jonas Eriksson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface amplifyRequestSettings { + resourceId: string; + data?: any; + success?: (...args: any[]) => void; + error?: (...args: any[]) => void; +} + +interface amplifyDecoder { + ( + data?: any, + status?: string, + xhr?: JQueryXHR, + success?: (...args: any[]) => void, + error?: (...args: any[]) => void + ): void +} + +interface amplifyDecoders { + [decoderName: string]: amplifyDecoder; + jsSend: amplifyDecoder; +} + +interface amplifyAjaxSettings extends JQueryAjaxSettings { + cache?: any; + dataMap?: {} | ((data: any) => {}); + decoder?: any /* string or amplifyDecoder */; +} + +interface amplifyRequest { + + /*** + * Request a resource. + * resourceId: Identifier string for the resource. + * data: A set of key/value pairs of data to be sent to the resource. + * callback: A function to invoke if the resource is retrieved successfully. + */ + (resourceId: string, hash?: any, callback?: Function): void; + + /*** + * Request a resource. + * settings: A set of key/value pairs of settings for the request. + * resourceId: Identifier string for the resource. + * data (optional): Data associated with the request. + * success (optional): Function to invoke on success. + * error (optional): Function to invoke on error. + */ + (settings: amplifyRequestSettings): any; + + /*** + * Define a resource. + * resourceId: Identifier string for the resource. + * requestType: The type of data retrieval method from the server. See the request types sections for more information. + * settings: A set of key/value pairs that relate to the server communication technology. The following settings are available: + * Any settings found in jQuery.ajax(). + * cache: See the cache section for more details. + * decoder: See the decoder section for more details. + */ + define(resourceId: string, requestType: string, settings?: amplifyAjaxSettings): void; + + /*** + * Define a custom request. + * resourceId: Identifier string for the resource. + * resource: Function to handle requests. Receives a hash with the following properties: + * resourceId: Identifier string for the resource. + * data: Data provided by the user. + * success: Callback to invoke on success. + * error: Callback to invoke on error. + */ + define(resourceId: string, resource: (settings: amplifyRequestSettings) => void): void; + + decoders: amplifyDecoders; + cache: any; +} + +interface amplifySubscribe { + /*** + * Subscribe to a message. + * topic: Name of the message to subscribe to. + * callback: Function to invoke when the message is published. + */ + (topic: string, callback: Function): void; + /*** + * Subscribe to a message. + * topic: Name of the message to subscribe to. + * context: What this will be when the callback is invoked. + * callback: Function to invoke when the message is published. + * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. + */ + (topic: string, context: any, callback: Function, priority?: number): void; + /*** + * Subscribe to a message. + * topic: Name of the message to subscribe to. + * callback: Function to invoke when the message is published. + * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. + */ + (topic: string, callback: Function, priority?: number): void; +} +interface amplifyStorageTypeStore { + /*** + * Stores a value for a given key using the default storage type. + * + * key: Identifier for the value being stored. + * value: The value to store. The value can be anything that can be serialized as JSON. + * [options]: A set of key/value pairs that relate to settings for storing the value. + */ + (key: string, value: any, options?: any): void; + + /*** + * Gets a stored value based on the key. + */ + (key: string): any; + + /*** + * Gets a hash of all stored values. + */ + (): any; +} + +interface amplifyStore extends amplifyStorageTypeStore{ + + /*** + * IE 8+, Firefox 3.5+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ + */ + localStorage: amplifyStorageTypeStore; + + /*** + * IE 8+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ + */ + sessionStorage: amplifyStorageTypeStore; + + /*** + * Firefox 2+ + */ + globalStorage: amplifyStorageTypeStore; + + /*** + * IE 5 - 7 + */ + userData: amplifyStorageTypeStore; + + /*** + * An in-memory store is provided as a fallback if none of the other storage types are available. + */ + memory: amplifyStorageTypeStore; + + +} + +interface amplifyStatic { + + subscribe: amplifySubscribe; + + /*** + * Remove a subscription. + * topic: The topic being unsubscribed from. + * callback: The callback that was originally subscribed. + */ + unsubscribe(topic: string, callback: Function): void; + + /*** + * Publish a message. + * topic: The name of the message to publish. + * Any additional parameters will be passed to the subscriptions. + * amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked. + */ + publish(topic: string, ...args: any[]): boolean; + + store: amplifyStore; + + request: amplifyRequest; + +} + +declare var amplify: amplifyStatic; +declare module "amplify" { export =amplify; } diff --git a/amplify/tsconfig.json b/amplify/tsconfig.json new file mode 100644 index 0000000000..3fb579d728 --- /dev/null +++ b/amplify/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "amplifyjs-tests.ts" + ] +} \ No newline at end of file diff --git a/amplifyjs/amplifyjs-tests.ts.tscparams b/amplifyjs/amplifyjs-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/amplifyjs/amplifyjs-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/amplifyjs/amplifyjs.d.ts b/amplifyjs/amplifyjs.d.ts deleted file mode 100644 index 555c9a378e..0000000000 --- a/amplifyjs/amplifyjs.d.ts +++ /dev/null @@ -1,182 +0,0 @@ -// Type definitions for AmplifyJs 1.1.0 -// Project: http://amplifyjs.com/ -// Definitions by: Jonas Eriksson -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface amplifyRequestSettings { - resourceId: string; - data?: any; - success?: (...args: any[]) => void; - error?: (...args: any[]) => void; -} - -interface amplifyDecoder { - ( - data?: any, - status?: string, - xhr?: JQueryXHR, - success?: (...args: any[]) => void, - error?: (...args: any[]) => void - ): void -} - -interface amplifyDecoders { - [decoderName: string]: amplifyDecoder; - jsSend: amplifyDecoder; -} - -interface amplifyAjaxSettings extends JQueryAjaxSettings { - cache?: any; - dataMap?: {} | ((data: any) => {}); - decoder?: any /* string or amplifyDecoder */; -} - -interface amplifyRequest { - - /*** - * Request a resource. - * resourceId: Identifier string for the resource. - * data: A set of key/value pairs of data to be sent to the resource. - * callback: A function to invoke if the resource is retrieved successfully. - */ - (resourceId: string, hash?: any, callback?: Function): void; - - /*** - * Request a resource. - * settings: A set of key/value pairs of settings for the request. - * resourceId: Identifier string for the resource. - * data (optional): Data associated with the request. - * success (optional): Function to invoke on success. - * error (optional): Function to invoke on error. - */ - (settings: amplifyRequestSettings): any; - - /*** - * Define a resource. - * resourceId: Identifier string for the resource. - * requestType: The type of data retrieval method from the server. See the request types sections for more information. - * settings: A set of key/value pairs that relate to the server communication technology. The following settings are available: - * Any settings found in jQuery.ajax(). - * cache: See the cache section for more details. - * decoder: See the decoder section for more details. - */ - define(resourceId: string, requestType: string, settings?: amplifyAjaxSettings): void; - - /*** - * Define a custom request. - * resourceId: Identifier string for the resource. - * resource: Function to handle requests. Receives a hash with the following properties: - * resourceId: Identifier string for the resource. - * data: Data provided by the user. - * success: Callback to invoke on success. - * error: Callback to invoke on error. - */ - define(resourceId: string, resource: (settings: amplifyRequestSettings) => void): void; - - decoders: amplifyDecoders; - cache: any; -} - -interface amplifySubscribe { - /*** - * Subscribe to a message. - * topic: Name of the message to subscribe to. - * callback: Function to invoke when the message is published. - */ - (topic: string, callback: Function): void; - /*** - * Subscribe to a message. - * topic: Name of the message to subscribe to. - * context: What this will be when the callback is invoked. - * callback: Function to invoke when the message is published. - * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. - */ - (topic: string, context: any, callback: Function, priority?: number): void; - /*** - * Subscribe to a message. - * topic: Name of the message to subscribe to. - * callback: Function to invoke when the message is published. - * [priority]: Priority relative to other subscriptions for the same message. Lower values have higher priority. Default is 10. - */ - (topic: string, callback: Function, priority?: number): void; -} -interface amplifyStorageTypeStore { - /*** - * Stores a value for a given key using the default storage type. - * - * key: Identifier for the value being stored. - * value: The value to store. The value can be anything that can be serialized as JSON. - * [options]: A set of key/value pairs that relate to settings for storing the value. - */ - (key: string, value: any, options?: any): void; - - /*** - * Gets a stored value based on the key. - */ - (key: string): any; - - /*** - * Gets a hash of all stored values. - */ - (): any; -} - -interface amplifyStore extends amplifyStorageTypeStore{ - - /*** - * IE 8+, Firefox 3.5+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ - */ - localStorage: amplifyStorageTypeStore; - - /*** - * IE 8+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ - */ - sessionStorage: amplifyStorageTypeStore; - - /*** - * Firefox 2+ - */ - globalStorage: amplifyStorageTypeStore; - - /*** - * IE 5 - 7 - */ - userData: amplifyStorageTypeStore; - - /*** - * An in-memory store is provided as a fallback if none of the other storage types are available. - */ - memory: amplifyStorageTypeStore; - - -} - -interface amplifyStatic { - - subscribe: amplifySubscribe; - - /*** - * Remove a subscription. - * topic: The topic being unsubscribed from. - * callback: The callback that was originally subscribed. - */ - unsubscribe(topic: string, callback: Function): void; - - /*** - * Publish a message. - * topic: The name of the message to publish. - * Any additional parameters will be passed to the subscriptions. - * amplify.publish returns a boolean indicating whether any subscriptions returned false. The return value is true if none of the subscriptions returned false, and false otherwise. Note that only one subscription can return false because doing so will prevent additional subscriptions from being invoked. - */ - publish(topic: string, ...args: any[]): boolean; - - store: amplifyStore; - - request: amplifyRequest; - -} - -declare var amplify: amplifyStatic; -declare module "amplify" { export =amplify; } diff --git a/amqp-rpc/amqp-rpc-tests.ts b/amqp-rpc/amqp-rpc-tests.ts index 71df096a8d..eb101188ab 100644 --- a/amqp-rpc/amqp-rpc-tests.ts +++ b/amqp-rpc/amqp-rpc-tests.ts @@ -1,4 +1,4 @@ -/// + import amqp_rpc = require('amqp-rpc'); var rpc = amqp_rpc.factory(); diff --git a/amqp-rpc/amqp-rpc.d.ts b/amqp-rpc/amqp-rpc.d.ts deleted file mode 100644 index b2eee1d2ca..0000000000 --- a/amqp-rpc/amqp-rpc.d.ts +++ /dev/null @@ -1,72 +0,0 @@ -// Type definitions for amqp-rpc v0.0.8 -// Project: https://github.com/demchenkoe/node-amqp-rpc/ -// Definitions by: Wonshik Kim -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "amqp-rpc" { - - export interface Options { - connection?: any; - url?: string; - exchangeInstance?: any; - exchange?: string; - exchange_options?: { - exclusive?: boolean; - autoDelete?: boolean; - }; - ipml_options?: { - defaultExchangeName?: string; - } - conn_options?: any; - } - - export interface CallOptions { - correlationId?: string; - autoDeleteCallback?: any; - } - - export interface HandlerOptions { - queueName?: string; - durable?: boolean; - exclusive?: boolean; - autoDelete?: boolean; - } - - export interface BroadcastOptions { - ttl?: number; - onResponse?: any; - context?: any; - onComplete?: any; - } - - export interface CommandInfo { - cmd?: string; - exchange?: string; - contentType?: string; - size?: number; - } - - export interface Callback { - (...args: any[]): void; - } - - export interface CallbackWithError { - (err: any, ...args: any[]): void; - } - - export function factory(opt?: Options): amqpRPC; - - export class amqpRPC { - constructor(opt?: Options); - generateQueueName(type: string): string; - disconnect(): void; - call(cmd: string, params: T, cb?: Callback, context?: any, options?: CallOptions): string; - on(cmd: string, cb: (param?: T, cb?: Callback, info?: CommandInfo) => void, context?: any, options?: HandlerOptions): boolean; - off(cmd: string): boolean; - callBroadcast(cmd: string, params: T, options?: BroadcastOptions): void; - onBroadcast(cmd: string, cb?: (params?: T, cb?: CallbackWithError) => void, context?: any, options?: any): boolean; - offBroadcast(cmd: string): boolean; - } -} diff --git a/amqp-rpc/index.d.ts b/amqp-rpc/index.d.ts new file mode 100644 index 0000000000..337f8d8a16 --- /dev/null +++ b/amqp-rpc/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for amqp-rpc v0.0.8 +// Project: https://github.com/demchenkoe/node-amqp-rpc/ +// Definitions by: Wonshik Kim +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + + +export interface Options { + connection?: any; + url?: string; + exchangeInstance?: any; + exchange?: string; + exchange_options?: { + exclusive?: boolean; + autoDelete?: boolean; + }; + ipml_options?: { + defaultExchangeName?: string; + } + conn_options?: any; +} + +export interface CallOptions { + correlationId?: string; + autoDeleteCallback?: any; +} + +export interface HandlerOptions { + queueName?: string; + durable?: boolean; + exclusive?: boolean; + autoDelete?: boolean; +} + +export interface BroadcastOptions { + ttl?: number; + onResponse?: any; + context?: any; + onComplete?: any; +} + +export interface CommandInfo { + cmd?: string; + exchange?: string; + contentType?: string; + size?: number; +} + +export interface Callback { + (...args: any[]): void; +} + +export interface CallbackWithError { + (err: any, ...args: any[]): void; +} + +export declare function factory(opt?: Options): amqpRPC; + +export declare class amqpRPC { + constructor(opt?: Options); + generateQueueName(type: string): string; + disconnect(): void; + call(cmd: string, params: T, cb?: Callback, context?: any, options?: CallOptions): string; + on(cmd: string, cb: (param?: T, cb?: Callback, info?: CommandInfo) => void, context?: any, options?: HandlerOptions): boolean; + off(cmd: string): boolean; + callBroadcast(cmd: string, params: T, options?: BroadcastOptions): void; + onBroadcast(cmd: string, cb?: (params?: T, cb?: CallbackWithError) => void, context?: any, options?: any): boolean; + offBroadcast(cmd: string): boolean; +} diff --git a/amqp-rpc/tsconfig.json b/amqp-rpc/tsconfig.json new file mode 100644 index 0000000000..cd51029de4 --- /dev/null +++ b/amqp-rpc/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "amqp-rpc-tests.ts" + ] +} \ No newline at end of file diff --git a/amqplib/amqplib-tests.ts b/amqplib/amqplib-tests.ts index 85763c9ee1..07b9ec5402 100644 --- a/amqplib/amqplib-tests.ts +++ b/amqplib/amqplib-tests.ts @@ -1,4 +1,4 @@ -/// + // promise api tests import amqp = require("amqplib"); diff --git a/amqplib/amqplib.d.ts b/amqplib/amqplib.d.ts deleted file mode 100644 index 6c393014f9..0000000000 --- a/amqplib/amqplib.d.ts +++ /dev/null @@ -1,219 +0,0 @@ -// Type definitions for amqplib 0.3.x -// Project: https://github.com/squaremo/amqp.node -// Definitions by: Michael Nahkies , Ab Reitsma -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare module "amqplib/properties" { - namespace Replies { - interface Empty { - } - interface AssertQueue { - queue: string; - messageCount: number; - consumerCount: number; - } - interface PurgeQueue { - messageCount: number; - } - interface DeleteQueue { - messageCount: number; - } - interface AssertExchange { - exchange: string; - } - interface Consume { - consumerTag: string; - } - } - - namespace Options { - interface AssertQueue { - exclusive?: boolean; - durable?: boolean; - autoDelete?: boolean; - arguments?: any; - messageTtl?: number; - expires?: number; - deadLetterExchange?: string; - deadLetterRoutingKey?: string; - maxLength?: number; - } - interface DeleteQueue { - ifUnused?: boolean; - ifEmpty?: boolean; - } - interface AssertExchange { - durable?: boolean; - internal?: boolean; - autoDelete?: boolean; - alternateExchange?: string; - arguments?: any; - } - interface DeleteExchange { - ifUnused?: boolean; - } - interface Publish { - expiration?: string; - userId?: string; - CC?: string | string[]; - - mandatory?: boolean; - persistent?: boolean; - deliveryMode?: boolean | number; - BCC?: string | string[]; - - contentType?: string; - contentEncoding?: string; - headers?: any; - priority?: number; - correlationId?: string; - replyTo?: string; - messageId?: string; - timestamp?: number; - type?: string; - appId?: string; - } - interface Consume { - consumerTag?: string; - noLocal?: boolean; - noAck?: boolean; - exclusive?: boolean; - priority?: number; - arguments?: any; - } - interface Get { - noAck?: boolean; - } - } - - interface Message { - content: Buffer; - fields: any; - properties: any; - } -} - -declare module "amqplib" { - - import events = require("events"); - import when = require("when"); - import shared = require("amqplib/properties") - export import Replies = shared.Replies; - export import Options = shared.Options; - export import Message = shared.Message; - - interface Connection extends events.EventEmitter { - close(): when.Promise; - createChannel(): when.Promise; - createConfirmChannel(): when.Promise; - } - - interface Channel extends events.EventEmitter { - close(): when.Promise; - - assertQueue(queue: string, options?: Options.AssertQueue): when.Promise; - checkQueue(queue: string): when.Promise; - - deleteQueue(queue: string, options?: Options.DeleteQueue): when.Promise; - purgeQueue(queue: string): when.Promise; - - bindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise; - unbindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise; - - assertExchange(exchange: string, type: string, options?: Options.AssertExchange): when.Promise; - checkExchange(exchange: string): when.Promise; - - deleteExchange(exchange: string, options?: Options.DeleteExchange): when.Promise; - - bindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise; - unbindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise; - - publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; - sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; - - consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): when.Promise; - - cancel(consumerTag: string): when.Promise; - get(queue: string, options?: Options.Get): when.Promise; - - ack(message: Message, allUpTo?: boolean): void; - ackAll(): void; - - nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; - nackAll(requeue?: boolean): void; - reject(message: Message, requeue?: boolean): void; - - prefetch(count: number, global?: boolean): when.Promise; - recover(): when.Promise; - } - - function connect(url: string, socketOptions?: any): when.Promise; -} - -declare module "amqplib/callback_api" { - - import events = require("events"); - import shared = require("amqplib/properties") - export import Replies = shared.Replies; - export import Options = shared.Options; - export import Message = shared.Message; - - interface Connection extends events.EventEmitter { - close(callback?: (err: any) => void): void; - createChannel(callback: (err: any, channel: Channel) => void): void; - createConfirmChannel(callback: (err: any, confirmChannel: ConfirmChannel) => void): void; - } - - interface Channel extends events.EventEmitter { - close(callback: (err: any) => void): void; - - assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err:any, ok: Replies.AssertQueue) => void): void; - checkQueue(queue: string, callback?: (err: any, ok: Replies.AssertQueue) => void): void; - - deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err:any, ok: Replies.DeleteQueue) => void): void; - purgeQueue(queue: string, callback?: (err:any, ok: Replies.PurgeQueue) => void): void; - - bindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; - unbindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; - - assertExchange(exchange: string, type: string, options?: Options.AssertExchange, callback?: (err: any, ok: Replies.AssertExchange) => void): void; - checkExchange(exchange: string, callback?: (err: any, ok: Replies.Empty) => void): void; - - deleteExchange(exchange: string, options?: Options.DeleteExchange, callback?: (err: any, ok: Replies.Empty) => void): void; - - bindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; - unbindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; - - publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; - sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; - - consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume, callback?: (err: any, ok: Replies.Consume) => void): void; - - cancel(consumerTag: string, callback?: (err: any, ok: Replies.Empty) => void): void; - get(queue: string, options?: Options.Get, callback?: (err: any, ok: Message | boolean) => void): void; - - ack(message: Message, allUpTo?: boolean): void; - ackAll(): void; - - nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; - nackAll(requeue?: boolean): void; - reject(message: Message, requeue?: boolean): void; - - prefetch(count: number, global?: boolean): void; - recover(callback?: (err: any, ok: Replies.Empty) => void): void; - } - - interface ConfirmChannel extends Channel { - publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; - sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; - - waitForConfirms(callback?: (err: any) => void): void; - } - - function connect(callback: (err: any, connection: Connection) => void): void; - function connect(url: string, callback: (err: any, connection: Connection) => void): void; - function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void; -} diff --git a/amqplib/index.d.ts b/amqplib/index.d.ts new file mode 100644 index 0000000000..3138f7494e --- /dev/null +++ b/amqplib/index.d.ts @@ -0,0 +1,219 @@ +// Type definitions for amqplib 0.3.x +// Project: https://github.com/squaremo/amqp.node +// Definitions by: Michael Nahkies , Ab Reitsma +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module "amqplib/properties" { + namespace Replies { + interface Empty { + } + interface AssertQueue { + queue: string; + messageCount: number; + consumerCount: number; + } + interface PurgeQueue { + messageCount: number; + } + interface DeleteQueue { + messageCount: number; + } + interface AssertExchange { + exchange: string; + } + interface Consume { + consumerTag: string; + } + } + + namespace Options { + interface AssertQueue { + exclusive?: boolean; + durable?: boolean; + autoDelete?: boolean; + arguments?: any; + messageTtl?: number; + expires?: number; + deadLetterExchange?: string; + deadLetterRoutingKey?: string; + maxLength?: number; + } + interface DeleteQueue { + ifUnused?: boolean; + ifEmpty?: boolean; + } + interface AssertExchange { + durable?: boolean; + internal?: boolean; + autoDelete?: boolean; + alternateExchange?: string; + arguments?: any; + } + interface DeleteExchange { + ifUnused?: boolean; + } + interface Publish { + expiration?: string; + userId?: string; + CC?: string | string[]; + + mandatory?: boolean; + persistent?: boolean; + deliveryMode?: boolean | number; + BCC?: string | string[]; + + contentType?: string; + contentEncoding?: string; + headers?: any; + priority?: number; + correlationId?: string; + replyTo?: string; + messageId?: string; + timestamp?: number; + type?: string; + appId?: string; + } + interface Consume { + consumerTag?: string; + noLocal?: boolean; + noAck?: boolean; + exclusive?: boolean; + priority?: number; + arguments?: any; + } + interface Get { + noAck?: boolean; + } + } + + interface Message { + content: Buffer; + fields: any; + properties: any; + } +} + +declare module "amqplib" { + + import events = require("events"); + import when = require("when"); + import shared = require("amqplib/properties") + export import Replies = shared.Replies; + export import Options = shared.Options; + export import Message = shared.Message; + + interface Connection extends events.EventEmitter { + close(): when.Promise; + createChannel(): when.Promise; + createConfirmChannel(): when.Promise; + } + + interface Channel extends events.EventEmitter { + close(): when.Promise; + + assertQueue(queue: string, options?: Options.AssertQueue): when.Promise; + checkQueue(queue: string): when.Promise; + + deleteQueue(queue: string, options?: Options.DeleteQueue): when.Promise; + purgeQueue(queue: string): when.Promise; + + bindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise; + unbindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise; + + assertExchange(exchange: string, type: string, options?: Options.AssertExchange): when.Promise; + checkExchange(exchange: string): when.Promise; + + deleteExchange(exchange: string, options?: Options.DeleteExchange): when.Promise; + + bindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise; + unbindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise; + + publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; + sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; + + consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): when.Promise; + + cancel(consumerTag: string): when.Promise; + get(queue: string, options?: Options.Get): when.Promise; + + ack(message: Message, allUpTo?: boolean): void; + ackAll(): void; + + nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; + nackAll(requeue?: boolean): void; + reject(message: Message, requeue?: boolean): void; + + prefetch(count: number, global?: boolean): when.Promise; + recover(): when.Promise; + } + + function connect(url: string, socketOptions?: any): when.Promise; +} + +declare module "amqplib/callback_api" { + + import events = require("events"); + import shared = require("amqplib/properties") + export import Replies = shared.Replies; + export import Options = shared.Options; + export import Message = shared.Message; + + interface Connection extends events.EventEmitter { + close(callback?: (err: any) => void): void; + createChannel(callback: (err: any, channel: Channel) => void): void; + createConfirmChannel(callback: (err: any, confirmChannel: ConfirmChannel) => void): void; + } + + interface Channel extends events.EventEmitter { + close(callback: (err: any) => void): void; + + assertQueue(queue?: string, options?: Options.AssertQueue, callback?: (err:any, ok: Replies.AssertQueue) => void): void; + checkQueue(queue: string, callback?: (err: any, ok: Replies.AssertQueue) => void): void; + + deleteQueue(queue: string, options?: Options.DeleteQueue, callback?: (err:any, ok: Replies.DeleteQueue) => void): void; + purgeQueue(queue: string, callback?: (err:any, ok: Replies.PurgeQueue) => void): void; + + bindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; + unbindQueue(queue: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; + + assertExchange(exchange: string, type: string, options?: Options.AssertExchange, callback?: (err: any, ok: Replies.AssertExchange) => void): void; + checkExchange(exchange: string, callback?: (err: any, ok: Replies.Empty) => void): void; + + deleteExchange(exchange: string, options?: Options.DeleteExchange, callback?: (err: any, ok: Replies.Empty) => void): void; + + bindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; + unbindExchange(destination: string, source: string, pattern: string, args?: any, callback?: (err: any, ok: Replies.Empty) => void): void; + + publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; + sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; + + consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume, callback?: (err: any, ok: Replies.Consume) => void): void; + + cancel(consumerTag: string, callback?: (err: any, ok: Replies.Empty) => void): void; + get(queue: string, options?: Options.Get, callback?: (err: any, ok: Message | boolean) => void): void; + + ack(message: Message, allUpTo?: boolean): void; + ackAll(): void; + + nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; + nackAll(requeue?: boolean): void; + reject(message: Message, requeue?: boolean): void; + + prefetch(count: number, global?: boolean): void; + recover(callback?: (err: any, ok: Replies.Empty) => void): void; + } + + interface ConfirmChannel extends Channel { + publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; + sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): boolean; + + waitForConfirms(callback?: (err: any) => void): void; + } + + function connect(callback: (err: any, connection: Connection) => void): void; + function connect(url: string, callback: (err: any, connection: Connection) => void): void; + function connect(url: string, socketOptions: any, callback: (err: any, connection: Connection) => void): void; +} diff --git a/amqplib/tsconfig.json b/amqplib/tsconfig.json new file mode 100644 index 0000000000..0757eb2ef7 --- /dev/null +++ b/amqplib/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "amqplib-tests.ts" + ] +} \ No newline at end of file diff --git a/analytics-node/analytics-node-tests.ts b/analytics-node/analytics-node-tests.ts index 57c48252ff..594c15fae6 100644 --- a/analytics-node/analytics-node-tests.ts +++ b/analytics-node/analytics-node-tests.ts @@ -1,10 +1,8 @@ -/// - +import AnalyticsNode = require("analytics-node"); var analytics: AnalyticsNode.Analytics; -import Analytics = require("analytics-node"); function testConfig(): void { - analytics = new Analytics('YOUR_WRITE_KEY', { + analytics = new AnalyticsNode.Analytics('YOUR_WRITE_KEY', { flushAt: 20, flushAfter: 10000 }); diff --git a/analytics-node/analytics-node.d.ts b/analytics-node/analytics-node.d.ts deleted file mode 100644 index aed257c9cc..0000000000 --- a/analytics-node/analytics-node.d.ts +++ /dev/null @@ -1,83 +0,0 @@ -// Type definitions for Segment's analytics.js for Node.js -// Project: https://segment.com/docs/libraries/node/ -// Definitions by: Andrew Fong -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace AnalyticsNode { - - interface Integrations { - [index: string]: boolean; - } - - export class Analytics { - constructor(writeKey: string, opts?: { - flushAt?: number, - flushAfter?: number - }); - - /* The identify method lets you tie a user to their actions and record - traits about them. */ - identify(message: { - userId: string | number; - traits?: Object; - timestamp?: Date; - context?: Object; - integrations?: Integrations; - }): Analytics; - - /* The track method lets you record the actions your users perform. */ - track(message: { - userId: string | number; - event: string; - properties?: Object; - timestamp?: Date; - context?: Object; - integrations?: Integrations; - }): Analytics; - - /* The page method lets you record page views on your website, along with - optional extra information about the page being viewed. */ - page(message: { - userId: string | number; - category?: string; - name?: string; - properties?: Object; - timestamp?: Date; - context?: Object; - integrations?: Integrations; - }): Analytics; - - /* alias is how you associate one identity with another. */ - alias(message: { - previousId: string | number; - userId: string | number; - integrations?: Integrations; - }): Analytics; - - /* Group calls can be used to associate individual users with shared - accounts or companies. */ - group(message: { - userId: string | number; - groupId: string | number; - traits?: Object; - context?: Object; - timestamp?: Date; - anonymous_id?: string | number; - integrations?: Integrations; - }): Analytics; - - /* Flush batched calls to make sure nothing is left in the queue */ - flush(fn?: (err: Error, batch: { - batch: Array<{ - type: string; - }>; - messageId: string; - sentAt: Date; - timestamp: Date; - }) => void): Analytics; - } -} - -declare module "analytics-node" { - export = AnalyticsNode.Analytics; -} diff --git a/analytics-node/index.d.ts b/analytics-node/index.d.ts new file mode 100644 index 0000000000..455b13c92b --- /dev/null +++ b/analytics-node/index.d.ts @@ -0,0 +1,81 @@ +// Type definitions for Segment's analytics.js for Node.js +// Project: https://segment.com/docs/libraries/node/ +// Definitions by: Andrew Fong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = AnalyticsNode; + +declare namespace AnalyticsNode { + + interface Integrations { + [index: string]: boolean; + } + + export class Analytics { + constructor(writeKey: string, opts?: { + flushAt?: number, + flushAfter?: number + }); + + /* The identify method lets you tie a user to their actions and record + traits about them. */ + identify(message: { + userId: string | number; + traits?: Object; + timestamp?: Date; + context?: Object; + integrations?: Integrations; + }): Analytics; + + /* The track method lets you record the actions your users perform. */ + track(message: { + userId: string | number; + event: string; + properties?: Object; + timestamp?: Date; + context?: Object; + integrations?: Integrations; + }): Analytics; + + /* The page method lets you record page views on your website, along with + optional extra information about the page being viewed. */ + page(message: { + userId: string | number; + category?: string; + name?: string; + properties?: Object; + timestamp?: Date; + context?: Object; + integrations?: Integrations; + }): Analytics; + + /* alias is how you associate one identity with another. */ + alias(message: { + previousId: string | number; + userId: string | number; + integrations?: Integrations; + }): Analytics; + + /* Group calls can be used to associate individual users with shared + accounts or companies. */ + group(message: { + userId: string | number; + groupId: string | number; + traits?: Object; + context?: Object; + timestamp?: Date; + anonymous_id?: string | number; + integrations?: Integrations; + }): Analytics; + + /* Flush batched calls to make sure nothing is left in the queue */ + flush(fn?: (err: Error, batch: { + batch: Array<{ + type: string; + }>; + messageId: string; + sentAt: Date; + timestamp: Date; + }) => void): Analytics; + } +} diff --git a/analytics-node/tsconfig.json b/analytics-node/tsconfig.json new file mode 100644 index 0000000000..ec22377baf --- /dev/null +++ b/analytics-node/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "analytics-node-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-agility/angular-agility-tests.ts b/angular-agility/angular-agility-tests.ts index 1e8eea478b..985eb368a0 100644 --- a/angular-agility/angular-agility-tests.ts +++ b/angular-agility/angular-agility-tests.ts @@ -1,5 +1,4 @@ -/// -/// + var validIconStrategy:aa.IValidIconStrategy = {}; validIconStrategy.validIcon = ""; diff --git a/angular-agility/angular-agility.d.ts b/angular-agility/angular-agility.d.ts deleted file mode 100644 index 33a8c3b8a4..0000000000 --- a/angular-agility/angular-agility.d.ts +++ /dev/null @@ -1,106 +0,0 @@ -// Type definitions for AngularAgility -// Project: https://github.com/AngularAgility/AngularAgility -// Definitions by: Roland Zwaga -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace aa { - - export interface ILabelStrategies { - [strategyName: string]: (element:ng.IAugmentedJQueryStatic, labelText:string, isRequired:boolean)=>void; - } - - export interface IFieldGroupStrategies { - [strategyName: string]: (element:ng.IAugmentedJQueryStatic)=>void; - } - - export interface IValMsgPlacementStrategies { - [strategyName: string]: (formFieldElement:ng.IAugmentedJQueryStatic, formName:string, formFieldName:string)=>void; - } - - export interface IValidIconStrategy { - validIcon:string; - invalidIcon:string; - getContainer(element:ng.IAugmentedJQueryStatic):void; - } - - export interface ISpinnerClickStrategies { - [strategyName: string]: (element:ng.IAugmentedJQueryStatic)=>void; - } - - export interface IOnNavigateAwayStrategies { - [strategyName: string]: (rootFormScope:ng.IScope, rootForm:ng.IAugmentedJQueryStatic, $injector:ng.auto.IInjectorService)=>void; - } - - export interface IValidationMessages { - [validationKey: string]: string; - } - - export interface IGlobalSettings { - [settingName: string]: any; - } - - export interface IFormExtensionsProvider extends ng.IServiceProvider { - defaultLabelStrategy:string; - defaultFieldGroupStrategy:string; - defaultValMsgPlacementStrategy:string; - validIconStrategy:IValidIconStrategy; - defaultSpinnerClickStrategy:string; - defaultNotifyTarget:string; - defaultOnNavigateAwayStrategy:string; - validationMessages:IValidationMessages; - valMsgForTemplate:string; - confirmResetStrategy:()=>boolean; - globalSettings:IGlobalSettings; - - labelStrategies:ILabelStrategies; - fieldGroupStrategies:IFieldGroupStrategies; - valMsgPlacementStrategies:IValMsgPlacementStrategies; - spinnerClickStrategies:ISpinnerClickStrategies; - onNavigateAwayStrategies:IOnNavigateAwayStrategies; - } - - export interface INotifyPredicate { - (message:string, options:any, notifier:any):any; - } - - export interface INotifyDefaults { - success: INotifyPredicate; - info: INotifyPredicate; - warning: INotifyPredicate; - danger: INotifyPredicate; - error: INotifyPredicate; - } - - export interface INotifyConfig { - name:string; - template?:string; - templateName?:string; - options:INotifyOptions; - namedDefaults:INotifyDefaults; - } - - export interface INotifyOptions { - cssClasses?:string; - messageType:string; - allowHtml:boolean; - message:string; - } - - export interface INotifyConfigProvider extends ng.IServiceProvider { - notifyConfigs:any; - defaultTargetContainerName:string; - defaultNotifyConfig:string; - addOrUpdateNotifyConfig(name:string, opts:INotifyConfig):void; - optionsTransformer(options:INotifyOptions, $sce:ng.ISCEService):void; - } - - export interface IExternalFormValidationConfig { - validations:any; - ignore?:any; - globals?:any; - resolve?:any; - resolveFn?:(modelValue:string)=>string; - } -} diff --git a/angular-agility/index.d.ts b/angular-agility/index.d.ts new file mode 100644 index 0000000000..c27792498f --- /dev/null +++ b/angular-agility/index.d.ts @@ -0,0 +1,106 @@ +// Type definitions for AngularAgility +// Project: https://github.com/AngularAgility/AngularAgility +// Definitions by: Roland Zwaga +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace aa { + + export interface ILabelStrategies { + [strategyName: string]: (element:ng.IAugmentedJQueryStatic, labelText:string, isRequired:boolean)=>void; + } + + export interface IFieldGroupStrategies { + [strategyName: string]: (element:ng.IAugmentedJQueryStatic)=>void; + } + + export interface IValMsgPlacementStrategies { + [strategyName: string]: (formFieldElement:ng.IAugmentedJQueryStatic, formName:string, formFieldName:string)=>void; + } + + export interface IValidIconStrategy { + validIcon:string; + invalidIcon:string; + getContainer(element:ng.IAugmentedJQueryStatic):void; + } + + export interface ISpinnerClickStrategies { + [strategyName: string]: (element:ng.IAugmentedJQueryStatic)=>void; + } + + export interface IOnNavigateAwayStrategies { + [strategyName: string]: (rootFormScope:ng.IScope, rootForm:ng.IAugmentedJQueryStatic, $injector:ng.auto.IInjectorService)=>void; + } + + export interface IValidationMessages { + [validationKey: string]: string; + } + + export interface IGlobalSettings { + [settingName: string]: any; + } + + export interface IFormExtensionsProvider extends ng.IServiceProvider { + defaultLabelStrategy:string; + defaultFieldGroupStrategy:string; + defaultValMsgPlacementStrategy:string; + validIconStrategy:IValidIconStrategy; + defaultSpinnerClickStrategy:string; + defaultNotifyTarget:string; + defaultOnNavigateAwayStrategy:string; + validationMessages:IValidationMessages; + valMsgForTemplate:string; + confirmResetStrategy:()=>boolean; + globalSettings:IGlobalSettings; + + labelStrategies:ILabelStrategies; + fieldGroupStrategies:IFieldGroupStrategies; + valMsgPlacementStrategies:IValMsgPlacementStrategies; + spinnerClickStrategies:ISpinnerClickStrategies; + onNavigateAwayStrategies:IOnNavigateAwayStrategies; + } + + export interface INotifyPredicate { + (message:string, options:any, notifier:any):any; + } + + export interface INotifyDefaults { + success: INotifyPredicate; + info: INotifyPredicate; + warning: INotifyPredicate; + danger: INotifyPredicate; + error: INotifyPredicate; + } + + export interface INotifyConfig { + name:string; + template?:string; + templateName?:string; + options:INotifyOptions; + namedDefaults:INotifyDefaults; + } + + export interface INotifyOptions { + cssClasses?:string; + messageType:string; + allowHtml:boolean; + message:string; + } + + export interface INotifyConfigProvider extends ng.IServiceProvider { + notifyConfigs:any; + defaultTargetContainerName:string; + defaultNotifyConfig:string; + addOrUpdateNotifyConfig(name:string, opts:INotifyConfig):void; + optionsTransformer(options:INotifyOptions, $sce:ng.ISCEService):void; + } + + export interface IExternalFormValidationConfig { + validations:any; + ignore?:any; + globals?:any; + resolve?:any; + resolveFn?:(modelValue:string)=>string; + } +} diff --git a/angular-agility/tsconfig.json b/angular-agility/tsconfig.json new file mode 100644 index 0000000000..464333d396 --- /dev/null +++ b/angular-agility/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-agility-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-bootstrap-calendar/angular-bootstrap-calendar-tests.ts b/angular-bootstrap-calendar/angular-bootstrap-calendar-tests.ts index a704ced3b2..53d74f0800 100644 --- a/angular-bootstrap-calendar/angular-bootstrap-calendar-tests.ts +++ b/angular-bootstrap-calendar/angular-bootstrap-calendar-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// +/// var myApp = angular.module('testModule'); diff --git a/angular-bootstrap-calendar/angular-bootstrap-calendar.d.ts b/angular-bootstrap-calendar/angular-bootstrap-calendar.d.ts deleted file mode 100644 index e32dcfca68..0000000000 --- a/angular-bootstrap-calendar/angular-bootstrap-calendar.d.ts +++ /dev/null @@ -1,138 +0,0 @@ -// Type definitions for angular-bootstrap-calendar -// Project: https://github.com/mattlewis92/angular-bootstrap-calendar -// Definitions by: Egor Komarov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.bootstrap.calendar { - interface IEvent { - /** - * The title of the event - */ - title: string; - /** - * The type of the event (determines its color). Can be important, warning, info, inverse, success or special - */ - type: string; - /** - * A javascript date object for when the event starts - */ - startsAt: Date; - /** - * Optional - a javascript date object for when the event ends - */ - endsAt?: Date; - /** - * If edit-event-html is set and this field is explicitly set to false then dont make it editable. - */ - editable?: boolean; - /** - * If delete-event-html is set and this field is explicitly set to false then dont make it deleteable - */ - deletable?: boolean; - /** - * Allow an event to be dragged and dropped - */ - draggable?: boolean; - /** - * Allow an event to be resizable - */ - resizable?: boolean; - /** - * If set to false then will not count towards the badge total amount on the month and year view - */ - incrementsBadgeTotal?: boolean; - /** - * If set the event will recur on the given period. Valid values are year or month - */ - recursOn?: string; - /** - * A CSS class (or more, just separate with spaces) that will be added to the event when it is displayed on each view. Useful for marking an event as selected / active etc - */ - cssClass?: string; - } - - interface ICalendarConfig { - allDateFormats: { - angular: IFormats; - moment: IFormats; - }; - dateFormats: IDateFormats; - titleFormats: ITitleFormats; - dateFormatter: string; - displayEventEndTimes: boolean; - showTimesOnWeekView: boolean; - displayAllMonthEvents: boolean; - i18nStrings: { weekNumber: string; }; - templates: { - calendarDayView: string; - calendarHourList: string; - calendarMonthCell: string; - calendarMonthCellEvents: string; - calendarMonthView: string; - calendarSlideBox: string; - calendarWeekView: string; - calendarYearView: string; - }; - } - - interface IFormats { - date: IDateFormats; - title: ITitleFormats; - } - - interface IDateFormats { - hour: string; - day: string; - month: string; - weekDay: string; - time: string; - datetime: string; - } - - interface ITitleFormats { - day: string; - week: string; - month: string; - year: string; - } - - interface ICalendarCell { - label: number; - date: moment.Moment; - inMonth: boolean; - isPast: boolean; - isToday: boolean; - isFuture: boolean; - isWeekend: boolean; - events: IEvent[]; - badgeTotal: number; - } - - namespace events { - interface IOnEventClick { - (calendarEvent: IEvent): void; - } - - interface IOnEventTimesChanged { - (calendarEvent: IEvent, calendarNewEventStart: Date, calendarNewEventEnd: Date): void; - } - - interface IOnEditEventClick { - (calendarEvent: IEvent): void; - } - - interface IOnDeleteEventClick { - (calendarEvent: IEvent): void; - } - - interface IOnTimespanClick { - (calendarDate: Date, calendarCell: ICalendarCell): void; - } - - interface IOnViewChangeClick { - (calendarDate: Date, calendarNextView: string): void; - } - } -} diff --git a/angular-bootstrap-calendar/index.d.ts b/angular-bootstrap-calendar/index.d.ts new file mode 100644 index 0000000000..bb529e706b --- /dev/null +++ b/angular-bootstrap-calendar/index.d.ts @@ -0,0 +1,140 @@ +// Type definitions for angular-bootstrap-calendar +// Project: https://github.com/mattlewis92/angular-bootstrap-calendar +// Definitions by: Egor Komarov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as moment from '../moment'; + +declare global { + namespace angular.bootstrap.calendar { + interface IEvent { + /** + * The title of the event + */ + title: string; + /** + * The type of the event (determines its color). Can be important, warning, info, inverse, success or special + */ + type: string; + /** + * A javascript date object for when the event starts + */ + startsAt: Date; + /** + * Optional - a javascript date object for when the event ends + */ + endsAt?: Date; + /** + * If edit-event-html is set and this field is explicitly set to false then dont make it editable. + */ + editable?: boolean; + /** + * If delete-event-html is set and this field is explicitly set to false then dont make it deleteable + */ + deletable?: boolean; + /** + * Allow an event to be dragged and dropped + */ + draggable?: boolean; + /** + * Allow an event to be resizable + */ + resizable?: boolean; + /** + * If set to false then will not count towards the badge total amount on the month and year view + */ + incrementsBadgeTotal?: boolean; + /** + * If set the event will recur on the given period. Valid values are year or month + */ + recursOn?: string; + /** + * A CSS class (or more, just separate with spaces) that will be added to the event when it is displayed on each view. Useful for marking an event as selected / active etc + */ + cssClass?: string; + } + + interface ICalendarConfig { + allDateFormats: { + angular: IFormats; + moment: IFormats; + }; + dateFormats: IDateFormats; + titleFormats: ITitleFormats; + dateFormatter: string; + displayEventEndTimes: boolean; + showTimesOnWeekView: boolean; + displayAllMonthEvents: boolean; + i18nStrings: { weekNumber: string; }; + templates: { + calendarDayView: string; + calendarHourList: string; + calendarMonthCell: string; + calendarMonthCellEvents: string; + calendarMonthView: string; + calendarSlideBox: string; + calendarWeekView: string; + calendarYearView: string; + }; + } + + interface IFormats { + date: IDateFormats; + title: ITitleFormats; + } + + interface IDateFormats { + hour: string; + day: string; + month: string; + weekDay: string; + time: string; + datetime: string; + } + + interface ITitleFormats { + day: string; + week: string; + month: string; + year: string; + } + + interface ICalendarCell { + label: number; + date: moment.Moment; + inMonth: boolean; + isPast: boolean; + isToday: boolean; + isFuture: boolean; + isWeekend: boolean; + events: IEvent[]; + badgeTotal: number; + } + + namespace events { + interface IOnEventClick { + (calendarEvent: IEvent): void; + } + + interface IOnEventTimesChanged { + (calendarEvent: IEvent, calendarNewEventStart: Date, calendarNewEventEnd: Date): void; + } + + interface IOnEditEventClick { + (calendarEvent: IEvent): void; + } + + interface IOnDeleteEventClick { + (calendarEvent: IEvent): void; + } + + interface IOnTimespanClick { + (calendarDate: Date, calendarCell: ICalendarCell): void; + } + + interface IOnViewChangeClick { + (calendarDate: Date, calendarNextView: string): void; + } + } + } +} diff --git a/angular-bootstrap-calendar/tsconfig.json b/angular-bootstrap-calendar/tsconfig.json new file mode 100644 index 0000000000..d16259ef3f --- /dev/null +++ b/angular-bootstrap-calendar/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-bootstrap-calendar-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts b/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts index 21e9b2ce98..a2373785ce 100644 --- a/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts +++ b/angular-bootstrap-lightbox/angular-bootstrap-lightbox-tests.ts @@ -1,5 +1,3 @@ -/// - var imageList:angular.bootstrap.lightbox.ILightboxImageInfo[] = []; imageList.push({ url: 'url1', diff --git a/angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts b/angular-bootstrap-lightbox/index.d.ts similarity index 100% rename from angular-bootstrap-lightbox/angular-bootstrap-lightbox.d.ts rename to angular-bootstrap-lightbox/index.d.ts diff --git a/angular-bootstrap-lightbox/tsconfig.json b/angular-bootstrap-lightbox/tsconfig.json new file mode 100644 index 0000000000..f9004cb8c8 --- /dev/null +++ b/angular-bootstrap-lightbox/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-bootstrap-lightbox-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-breadcrumb/angular-breadcrumb.d.ts b/angular-breadcrumb/angular-breadcrumb.d.ts deleted file mode 100644 index 7df33ddef5..0000000000 --- a/angular-breadcrumb/angular-breadcrumb.d.ts +++ /dev/null @@ -1,79 +0,0 @@ -// Type definitions for angular-breadcrumb 0.4.1 -// Project: https://github.com/ncuillery/angular-breadcrumb -// Definitions by: Marc Talary -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -declare namespace angular.ui { - export interface IState { - ncyBreadcrumb?: { - /** - * Contains the label for the step in the breadcrumb. The state name is used if not defined. - **/ - label?: string; - /** - * Override the parent state (only for the breadcrumb) - **/ - parent?: string; - /** - * When defined to true, the state is never included in the chain of states and never appears in the breadcrumb - **/ - skip?: boolean; - }, - ncyBreadcrumbLabel?: string; - ncyBreadcrumbLink?: string; - } -} - -declare namespace ncy { - - /** - * Provider that returns an instance of $breadcrumb service. It contains the global configuration of the module. - **/ - export interface $breadcrumbProvider { - /** - * Setter for options defined in a module.config block - **/ - setOptions(options: breadcrumbProviderOptions): void; - } - - /** - * Global configuration options for angular-breadcrumb - **/ - export interface breadcrumbProviderOptions { - /** - * An existing state's name to be the state is the first step of the breadcrumb - **/ - prefixStateName?: string; - - /** - * Contains a predefined template's name; 'bootstrap3' (default), 'bootstrap2' or HTML for a custom template. This property is ignored if templateUrl is defined. - **/ - template?: string; - - /** - * Contains the path to a template file. This property takes precedence over the template property. - **/ - templateUrl?: string; - - /** - * If true, abstract states are included in the breadcrumb. This option has a lower priority than the state-specific option skip - **/ - includeAbstract?: boolean; - } - - /** - * Service responsible for access to $state and for directive configuration. - **/ - export interface $breadcrumbService { - /** - * Returns the state chain to the current state (i.e. all the steps of the breadcrumb). It's an array of state object enriched with the module-specific property ncyBreadcrumbLink (the href for the breadcrumb step). - **/ - getStatesChain(): angular.ui.IState[]; - - /** - * Return the last step of the breadcrumb, generally the one relative to the current state, expect if it is configured as skipped (the method returns its parent). As getStatesChain, the state object is enriched with ncyBreadcrumbLink. - **/ - getLastStep(): angular.ui.IState; - } -} \ No newline at end of file diff --git a/angular-breadcrumb/index.d.ts b/angular-breadcrumb/index.d.ts new file mode 100644 index 0000000000..cc3da7fff4 --- /dev/null +++ b/angular-breadcrumb/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for angular-breadcrumb 0.4.1 +// Project: https://github.com/ncuillery/angular-breadcrumb +// Definitions by: Marc Talary +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +declare namespace angular.ui { + export interface IState { + ncyBreadcrumb?: { + /** + * Contains the label for the step in the breadcrumb. The state name is used if not defined. + **/ + label?: string; + /** + * Override the parent state (only for the breadcrumb) + **/ + parent?: string; + /** + * When defined to true, the state is never included in the chain of states and never appears in the breadcrumb + **/ + skip?: boolean; + }, + ncyBreadcrumbLabel?: string; + ncyBreadcrumbLink?: string; + } +} + +declare namespace ncy { + + /** + * Provider that returns an instance of $breadcrumb service. It contains the global configuration of the module. + **/ + export interface $breadcrumbProvider { + /** + * Setter for options defined in a module.config block + **/ + setOptions(options: breadcrumbProviderOptions): void; + } + + /** + * Global configuration options for angular-breadcrumb + **/ + export interface breadcrumbProviderOptions { + /** + * An existing state's name to be the state is the first step of the breadcrumb + **/ + prefixStateName?: string; + + /** + * Contains a predefined template's name; 'bootstrap3' (default), 'bootstrap2' or HTML for a custom template. This property is ignored if templateUrl is defined. + **/ + template?: string; + + /** + * Contains the path to a template file. This property takes precedence over the template property. + **/ + templateUrl?: string; + + /** + * If true, abstract states are included in the breadcrumb. This option has a lower priority than the state-specific option skip + **/ + includeAbstract?: boolean; + } + + /** + * Service responsible for access to $state and for directive configuration. + **/ + export interface $breadcrumbService { + /** + * Returns the state chain to the current state (i.e. all the steps of the breadcrumb). It's an array of state object enriched with the module-specific property ncyBreadcrumbLink (the href for the breadcrumb step). + **/ + getStatesChain(): angular.ui.IState[]; + + /** + * Return the last step of the breadcrumb, generally the one relative to the current state, expect if it is configured as skipped (the method returns its parent). As getStatesChain, the state object is enriched with ncyBreadcrumbLink. + **/ + getLastStep(): angular.ui.IState; + } +} \ No newline at end of file diff --git a/angular-breadcrumb/tsconfig.json b/angular-breadcrumb/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/angular-breadcrumb/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/angular-cookie/angular-cookie-tests.ts b/angular-cookie/angular-cookie-tests.ts index e6280fbeba..7600762086 100644 --- a/angular-cookie/angular-cookie-tests.ts +++ b/angular-cookie/angular-cookie-tests.ts @@ -1,6 +1,3 @@ -/// -/// - angular.module('myApp', ['ipCookie']) .controller('cookieController', ['ipCookie', function(ipCookie: angular.cookie.CookieService) { ipCookie('key', 'value'); diff --git a/angular-cookie/angular-cookie.d.ts b/angular-cookie/angular-cookie.d.ts deleted file mode 100644 index 02700ea1bd..0000000000 --- a/angular-cookie/angular-cookie.d.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Type definitions for angular-cookie v4.1.0 -// Project: https://github.com/ivpusic/angular-cookie -// Definitions by: Borislav Zhivkov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace angular.cookie { - interface CookieService { - /** - * Get all cookies - */ - (): any; - - /** - * Get a cookie with a specific key - */ - (key: string): any; - - /** - * Create a cookie - */ - (key: string, value: any, options?: CookieOptions): any; - - /** - * Remove a cookie - */ - remove(key: string, options?: CookieOptions): void; - } - - interface CookieOptions { - /** - * The domain tells the browser to which domain the cookie should be sent. If you don't specify it, it becomes the domain of the page that sets the cookie. - */ - domain?: string; - - /** - * The path gives you the chance to specify a directory where the cookie is active. - */ - path?: string; - - /** - * Each cookie has an expiry date after which it is trashed. If you don't specify the expiry date the cookie is trashed when you close the browser. - */ - expires?: number; - - /** - * Allows you to set the expiration time in hours, minutes, seconds, or `milliseconds. If this is not specified, any expiration time specified will default to days. - */ - expirationUnit?: string; - - /** - * The Secure attribute is meant to keep cookie communication limited to encrypted transmission, directing browsers to use cookies only via secure/encrypted connections. - */ - secure?: boolean; - - /** - * The method that will be used to encode the cookie value (should be passed when using Set). - */ - encode?: (value: any) => any; - - /** - * The method that will be used to decode extracted cookie values (should be passed when using Get). - */ - decode?: (value: any) => any; - } -} diff --git a/angular-cookie/index.d.ts b/angular-cookie/index.d.ts new file mode 100644 index 0000000000..0296a91b60 --- /dev/null +++ b/angular-cookie/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for angular-cookie v4.1.0 +// Project: https://github.com/ivpusic/angular-cookie +// Definitions by: Borislav Zhivkov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.cookie { + interface CookieService { + /** + * Get all cookies + */ + (): any; + + /** + * Get a cookie with a specific key + */ + (key: string): any; + + /** + * Create a cookie + */ + (key: string, value: any, options?: CookieOptions): any; + + /** + * Remove a cookie + */ + remove(key: string, options?: CookieOptions): void; + } + + interface CookieOptions { + /** + * The domain tells the browser to which domain the cookie should be sent. If you don't specify it, it becomes the domain of the page that sets the cookie. + */ + domain?: string; + + /** + * The path gives you the chance to specify a directory where the cookie is active. + */ + path?: string; + + /** + * Each cookie has an expiry date after which it is trashed. If you don't specify the expiry date the cookie is trashed when you close the browser. + */ + expires?: number; + + /** + * Allows you to set the expiration time in hours, minutes, seconds, or `milliseconds. If this is not specified, any expiration time specified will default to days. + */ + expirationUnit?: string; + + /** + * The Secure attribute is meant to keep cookie communication limited to encrypted transmission, directing browsers to use cookies only via secure/encrypted connections. + */ + secure?: boolean; + + /** + * The method that will be used to encode the cookie value (should be passed when using Set). + */ + encode?: (value: any) => any; + + /** + * The method that will be used to decode extracted cookie values (should be passed when using Get). + */ + decode?: (value: any) => any; + } +} diff --git a/angular-cookie/tsconfig.json b/angular-cookie/tsconfig.json new file mode 100644 index 0000000000..daef4f499a --- /dev/null +++ b/angular-cookie/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-cookie-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-dialog-service/angular-dialog-service-tests.ts b/angular-dialog-service/angular-dialog-service-tests.ts index 8142a3a713..bdacb26da2 100644 --- a/angular-dialog-service/angular-dialog-service-tests.ts +++ b/angular-dialog-service/angular-dialog-service-tests.ts @@ -1,4 +1,4 @@ -/// + var options : angular.dialogservice.IDialogOptions = {}; diff --git a/angular-dialog-service/angular-dialog-service.d.ts b/angular-dialog-service/angular-dialog-service.d.ts deleted file mode 100644 index 3d75e32222..0000000000 --- a/angular-dialog-service/angular-dialog-service.d.ts +++ /dev/null @@ -1,82 +0,0 @@ -// Type definitions for Angular Dialog Service 5.2.8 -// Project: https://github.com/m-e-conroy/angular-dialog-service -// Definitions by: William Comartin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare namespace angular.dialogservice { - - interface IDialogOptions { - /** - * Set to false to disable animations on new modal/backdrop. Does not toggle animations for modals/backdrops that are already displayed. - * - * @default false - */ - animation?: boolean; - - /** - * controls the presence of a backdrop - * Allowed values: - * - true (default) - * - false (no backdrop) - * - 'static' backdrop is present but modal window is not closed when clicking outside of the modal window - * - * @default true - */ - backdrop?: boolean | string; - - /** - * indicates whether the dialog should be closable by hitting the ESC key - * - * @default true - */ - keyboard?: boolean; - - /** - * additional CSS class(es) to be added to a modal backdrop template - * - * @default 'dialogs-backdrop-default' - */ - backdropClass?: string; - - /** - * additional CSS class(es) to be added to a modal window template - * - * @default 'dialogs-default' - */ - windowClass?: string; - - /** - * Optional suffix of modal window class. The value used is appended to the `modal-` class, i.e. a value of `sm` gives `modal-sm`. - * - * @default 'lg' - */ - size?: string; - } - - interface IDialogService { - /** - * Opens a new error modal instance. - */ - error(header: string, msg: string, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance - /** - * Opens a new wait modal instance. - */ - wait(header: string, msg: string, progress: number, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance - /** - * Opens a new notify modal instance. - */ - notify(header: string, msg: string, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance - /** - * Opens a new confirm modal instance. - */ - confirm(header: string, msg: string, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance - /** - * Opens a new custom modal instance. - */ - create(url: string, ctrlr: string, data: any, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance - } - -} diff --git a/angular-dialog-service/index.d.ts b/angular-dialog-service/index.d.ts new file mode 100644 index 0000000000..1b5bd031c4 --- /dev/null +++ b/angular-dialog-service/index.d.ts @@ -0,0 +1,82 @@ +// Type definitions for Angular Dialog Service 5.2.8 +// Project: https://github.com/m-e-conroy/angular-dialog-service +// Definitions by: William Comartin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace angular.dialogservice { + + interface IDialogOptions { + /** + * Set to false to disable animations on new modal/backdrop. Does not toggle animations for modals/backdrops that are already displayed. + * + * @default false + */ + animation?: boolean; + + /** + * controls the presence of a backdrop + * Allowed values: + * - true (default) + * - false (no backdrop) + * - 'static' backdrop is present but modal window is not closed when clicking outside of the modal window + * + * @default true + */ + backdrop?: boolean | string; + + /** + * indicates whether the dialog should be closable by hitting the ESC key + * + * @default true + */ + keyboard?: boolean; + + /** + * additional CSS class(es) to be added to a modal backdrop template + * + * @default 'dialogs-backdrop-default' + */ + backdropClass?: string; + + /** + * additional CSS class(es) to be added to a modal window template + * + * @default 'dialogs-default' + */ + windowClass?: string; + + /** + * Optional suffix of modal window class. The value used is appended to the `modal-` class, i.e. a value of `sm` gives `modal-sm`. + * + * @default 'lg' + */ + size?: string; + } + + interface IDialogService { + /** + * Opens a new error modal instance. + */ + error(header: string, msg: string, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance + /** + * Opens a new wait modal instance. + */ + wait(header: string, msg: string, progress: number, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance + /** + * Opens a new notify modal instance. + */ + notify(header: string, msg: string, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance + /** + * Opens a new confirm modal instance. + */ + confirm(header: string, msg: string, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance + /** + * Opens a new custom modal instance. + */ + create(url: string, ctrlr: string, data: any, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance + } + +} diff --git a/angular-dialog-service/tsconfig.json b/angular-dialog-service/tsconfig.json new file mode 100644 index 0000000000..d3a707034f --- /dev/null +++ b/angular-dialog-service/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-dialog-service-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-dynamic-locale/angular-dynamic-locale-tests.ts b/angular-dynamic-locale/angular-dynamic-locale-tests.ts index a42d0c4460..968d4995e8 100644 --- a/angular-dynamic-locale/angular-dynamic-locale-tests.ts +++ b/angular-dynamic-locale/angular-dynamic-locale-tests.ts @@ -1,6 +1,4 @@ -/// -/// - +import * as angular from 'angularjs'; var app = angular.module('testModule', ['tmh.dynamicLocale']); app.config((localStorageServiceProvider: angular.dynamicLocale.tmhDynamicLocaleProvider) => { localStorageServiceProvider diff --git a/angular-dynamic-locale/angular-dynamic-locale.d.ts b/angular-dynamic-locale/angular-dynamic-locale.d.ts deleted file mode 100644 index 4b7a1f9656..0000000000 --- a/angular-dynamic-locale/angular-dynamic-locale.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Type definitions for angular-dynamic-locale v0.1.27 -// Project: https://github.com/lgalfaso/angular-dynamic-locale -// Definitions by: Stephen Lautier -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "angular-dynamic-locale" { - import ng = angular.dynamicLocale; - export = ng; -} - -declare namespace angular.dynamicLocale { - - interface tmhDynamicLocaleService { - set(locale: string): void; - get(): string; - } - - interface tmhDynamicLocaleProvider extends angular.IServiceProvider { - localeLocationPattern(location: string): tmhDynamicLocaleProvider; - localeLocationPattern(): string; - useStorage(storageName: string): void; - useCookieStorage(): void; - } -} diff --git a/angular-dynamic-locale/index.d.ts b/angular-dynamic-locale/index.d.ts new file mode 100644 index 0000000000..13bf9d795f --- /dev/null +++ b/angular-dynamic-locale/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for angular-dynamic-locale v0.1.27 +// Project: https://github.com/lgalfaso/angular-dynamic-locale +// Definitions by: Stephen Lautier +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as angular from 'angularjs'; + +declare module 'angularjs' { + export namespace dynamicLocale { + + interface tmhDynamicLocaleService { + set(locale: string): void; + get(): string; + } + + interface tmhDynamicLocaleProvider extends angular.IServiceProvider { + localeLocationPattern(location: string): tmhDynamicLocaleProvider; + localeLocationPattern(): string; + useStorage(storageName: string): void; + useCookieStorage(): void; + } + } +} + + diff --git a/angular-dynamic-locale/tsconfig.json b/angular-dynamic-locale/tsconfig.json new file mode 100644 index 0000000000..d67e7e4e4d --- /dev/null +++ b/angular-dynamic-locale/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-dynamic-locale-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-environment/angular-environment-tests.ts b/angular-environment/angular-environment-tests.ts index e7c077fafe..3b63095202 100644 --- a/angular-environment/angular-environment-tests.ts +++ b/angular-environment/angular-environment-tests.ts @@ -1,4 +1,4 @@ -/// + var envServiceProvider: angular.environment.ServiceProvider; var envService: angular.environment.Service; diff --git a/angular-environment/angular-environment.d.ts b/angular-environment/index.d.ts similarity index 100% rename from angular-environment/angular-environment.d.ts rename to angular-environment/index.d.ts diff --git a/angular-environment/tsconfig.json b/angular-environment/tsconfig.json new file mode 100644 index 0000000000..2cef36a142 --- /dev/null +++ b/angular-environment/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-environment-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-file-upload/angular-file-upload.d.ts b/angular-file-upload/angular-file-upload.d.ts deleted file mode 100644 index c79f6b5528..0000000000 --- a/angular-file-upload/angular-file-upload.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for Angular File Upload 4.2.1 -// Project: https://github.com/danialfarid/ng-file-upload -// Definitions by: John Reilly -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -// THIS FILE WILL REMOVE IF angular-file-upload.d.ts incoming. diff --git a/angular-file-upload/index.d.ts b/angular-file-upload/index.d.ts new file mode 100644 index 0000000000..6a5d821a91 --- /dev/null +++ b/angular-file-upload/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for Angular File Upload 4.2.1 +// Project: https://github.com/danialfarid/ng-file-upload +// Definitions by: John Reilly +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +// THIS FILE WILL REMOVE IF angular-file-upload.d.ts incoming. diff --git a/angular-file-upload/tsconfig.json b/angular-file-upload/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/angular-file-upload/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/angular-formly/angular-formly-tests.ts b/angular-formly/angular-formly-tests.ts index 01449aa4b7..83f13af2d4 100644 --- a/angular-formly/angular-formly-tests.ts +++ b/angular-formly/angular-formly-tests.ts @@ -1,4 +1,4 @@ -/// + var app = angular.module('app', ['formly']); diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts deleted file mode 100644 index 206d3294f9..0000000000 --- a/angular-formly/angular-formly.d.ts +++ /dev/null @@ -1,637 +0,0 @@ -// Type definitions for angular-formly 7.2.3 -// Project: https://github.com/formly-js/angular-formly -// Definitions by: Scott Hatcher -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'AngularFormly' { - export = AngularFormly; -} - -declare module 'angular-formly' { - var angularFormlyDefaultExport: string; - export = angularFormlyDefaultExport; -} - -declare namespace AngularFormly { - - interface IFieldArray extends Array { - - } - - interface IFieldGroup { - data?: { - [key: string]: any; - }; - className?: string; - elementAttributes?: string; - fieldGroup?: IFieldArray; - form?: Object; - hide?: boolean; - hideExpression?: string | IExpressionFunction; - key?: string | number; - model?: string | { - [key: string]: any; - }; - options?: IFormOptionsAPI; - templateOptions?: ITemplateOptions; - wrapper?: string | string[]; - } - - - interface IFormOptionsAPI { - data?: { - [key: string]: any; - }; - fieldTransform?: Function; - formState?: Object; - removeChromeAutoComplete?: boolean; - resetModel?: Function; - templateManipulators?: ITemplateManipulators; - updateInitialValue?: Function; - wrapper?: string | string[]; - } - - - /** - * see http://docs.angular-formly.com/docs/formly-expressions#expressionproperties-validators--messages - */ - interface IExpressionFunction { - ($viewValue: any, $modelValue: any, scope: ITemplateScope): any; - } - - - interface IModelOptions { - updateOn?: string; - debounce?: number; - allowInvalid?: boolean; - getterSetter?: string; - timezone?: string; - } - - - interface ITemplateManipulator { - (template: string | HTMLElement, options: Object, scope: ITemplateScope): string | HTMLElement; - } - - - interface ITemplateManipulators { - preWrapper?: ITemplateManipulator[]; - postWrapper?: ITemplateManipulator[]; - } - - interface ISelectOption { - name: string; - value?: string; - group?: string; - } - - /** - * see http://docs.angular-formly.com/docs/ngmodelattrstemplatemanipulator - */ - interface ITemplateOptions { - - // both attribute or regular attribute - disabled?: boolean; - maxlength?: number; - minlength?: number; - pattern?: string; - required?: boolean; - - //attribute only - max?: number; - min?: number; - placeholder?: number | string; - tabindex?: number; - type?: string; - - //expression types - onBlur?: string | IExpressionFunction; - onChange?: string | IExpressionFunction; - onClick?: string | IExpressionFunction; - onFocus?: string | IExpressionFunction; - onKeydown?: string | IExpressionFunction; - onKeypress?: string | IExpressionFunction; - onKeyup?: string | IExpressionFunction; - - //Bootstrap types - label?: string; - description?: string; - [key: string]: any; - - // types for select/radio fields - options?: Array; - groupProp?: string; // default: group - valueProp?: string; // default: value - labelProp?: string; // default: name - - } - - - /** - * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object - */ - interface IValidator { - expression: string | IExpressionFunction; - message?: string | IExpressionFunction; - } - - - /** - * An object which has at least two properties called expression and listener. The watch.expression - * is added to the formly-form directive's scope (to allow it to run even when hide is true). You - * can specify a type ($watchCollection or $watchGroup) via the watcher.type property (defaults to - * $watch) and whether you want it to be a deep watch via the watcher.deep property (defaults to false). - * - * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches - */ - interface IWatcher { - deep?: boolean; //Defaults to false - expression?: string | { (field: string, scope: ITemplateScope): boolean }; - listener: (field: string, newValue: any, oldValue: any, scope: ITemplateScope, stopWatching: Function) => void; - type?: string; //Defaults to $watch but can be set to $watchCollection or $watchGroup - } - - - // see http://docs.angular-formly.com/docs/field-configuration-object - interface IFieldConfigurationObject { - - - /** - * Added in 6.18.0 - * - * Demo - * see http://angular-formly.com/#/example/other/unique-value-async-validation - */ - asyncValidators?: { - [key: string]: string | IExpressionFunction | IValidator; - }; - - /** - * This is a great way to add custom behavior to a specific field. It is injectable with the $scope of the - * field, and anything else you have in your injector. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#controller-controller-name-as-string--controller-f - */ - controller?: string | Function; - - - /** - * This is reserved for the developer. You have our guarantee to be able to use this and not worry about - * future versions of formly overriding your usage and preventing you from upgrading :-) - * - * see http://docs.angular-formly.com/docs/field-configuration-object#data-object - */ - data?: { - [key: string]: any; - }; - - - /** - * Use defaultValue to initialize it the model. If this is provided and the value of the - * model at compile-time is undefined, then the value of the model will be assigned to defaultValue. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#defaultvalue-any - */ - defaultValue?: any; - - - /** - * You can specify your own class that will be applied to the formly-field directive (or ng-form of - * a fieldGroup). - * - * see http://docs.angular-formly.com/docs/field-configuration-object#classname-string - */ - className?: string; - - - elementAttributes?: { - [key: string]: string; - }; - - - /** - * An object where the key is a property to be set on the main field config and the value is an - * expression used to assign that property. The value is a formly expressions. The returned value is - * wrapped in $q.when so you can return a promise from your function :-) - * - * see http://docs.angular-formly.com/docs/field-configuration-object#expressionproperties-object - */ - expressionProperties?: { - [key: string]: string | IExpressionFunction | IValidator; - }; - - - /** - * Uses ng-if. Whether to hide the field. Defaults to false. If you wish this to be conditional, use - * hideExpression. See below. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#hide-boolean - */ - hide?: boolean; - - - /** - * This is similar to expressionProperties with a slight difference. You should (hopefully) never - * notice the difference with the most common use case. This is available due to limitations with - * expressionProperties and ng-if not working together very nicely. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#hideexpression-string--function - */ - hideExpression?: string | IExpressionFunction; - - - /** - * This allows you to specify the id of your field (which will be used for its name as well unless - * a name is provided). Note, you can also override the id generation code using the formlyConfig - * extra called getFieldId. - * - * AVOID THIS - * If you don't have to do this, don't. Specifying IDs makes it harder to re-use things and it's - * just extra work. Part of the beauty that angular-formly provides is the fact that you don't need - * to concern yourself with making sure that this is unique. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#id-string - */ - id?: string; - - - initialValue?: any; - - - /** - * Can be set instead of type or template to use a custom html template form field. Works - * just like a directive templateUrl and uses the $templateCache - * - * see http://docs.angular-formly.com/docs/field-configuration-object#key-string - */ - key?: string | number; - - - /** - * This allows you to specify a link function. It is invoked after your template has finished compiling. - * You are passed the normal arguments for a normal link function. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#link-link-function - */ - link?: ng.IDirectiveLinkFn; - - - /** - * By default, the model passed to the formly-field directive is the same as the model passed to the - * formly-form. However, if the field has a model specified, then it is used for that field (and that - * field only). In addition, a deep watch is added to the formly-field directive's scope to run the - * expressionProperties when the specified model changes. - * - * Note, the formly-form directive will allow you to specify a string which is an (almost) formly - * expression which allows you to define the model as relative to the scope of the form. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#model-object--string - */ - model?: string | { - [key: string]: any; - }; - - - /** - * Allows you to take advantage of ng-model-options directive. Formly's built-in templateManipulator (see - * below) will add this attribute to your ng-model element automatically if this property exists. Note, - * if you use the getter/setter option, formly's templateManipulator will change the value of ng-model - * to options.value which is a getterSetter that formly adds to field options. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#modeloptions - */ - modelOptions?: IModelOptions; - - - /** - * If you wish to, you can specify a specific name for your ng-model. This is useful if you're posting - * the form to a server using techniques of yester-year. - * - * AVOID THIS - * If you don't have to do this, don't. It's just extra work. Part of the beauty that angular-formly - * provides is the fact that you don't need to concern yourself with stuff like this. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#name-string - */ - name?: string; - - - /** - * This is used by ngModelAttrsTemplateManipulator to automatically add attributes to the ng-model element - * of field templates. You will likely not use this often. This object is a little complex, but extremely - * powerful. It's best to explain this api via an example. For more information, see the guide on ngModelAttrs. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#ngmodelattrs-object - */ - ngModelAttrs?: { - attribute?: any; - bound?: any; - expression?: any; - value?: any; - [key: string]: any; - }; - - - /** - * This allows you to place attributes with string values on the ng-model element. - * Easy to use alternative to ngModelAttrs option. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#ngmodelelattrs-object - */ - ngModelElAttrs?: { - [key: string]: string; - }; - - - /** - * Used to tell angular-formly to not attempt to add the formControl property to your object. This is useful - * for things like validation, but not necessary if your "field" doesn't use ng-model (if it's just a horizontal - * line for example). Defaults to undefined. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#noformcontrol-boolean - */ - noFormControl?: boolean; - - - /** - * Allows you to specify extra types to get options from. Duplicate options are overridden in later priority - * (index 1 will override index 0 properties). Also, these are applied after the type's defaultOptions and - * hence will override any duplicates of those properties as well. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#optionstypes-string--array-of-strings - */ - optionsTypes?: string | string[]; - - - /** - * Can be set instead of type or templateUrl to use a custom html - * template form field. Recommended to be used with one-liners mostly - * (like a directive), or if you're using webpack with the ability to require templates :-) - * - * If a function is passed, it is invoked with the field configuration object and can return - * either a string for the template or a promise that resolves to a string. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#template-string--function - */ - template?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; - - - /** - * Allows you to specify custom template manipulators for this specific field. (use defaultOptions in a - * type configuration if you want it to apply to all fields of a certain type). - * - * see http://docs.angular-formly.com/docs/field-configuration-object#templatemanipulator-object-of-arrays-of-functions - */ - templateManipulators?: ITemplateManipulators; - - - /** - * This is reserved for the templates. Any template-specific options go in here. Look at your specific - * template implementation to know the options required for this. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#templateoptions-object - */ - templateOptions?: ITemplateOptions; - - - /** - * Can be set instead of type or template to use a custom html template form field. Works - * just like a directive templateUrl and uses the $templateCache - * - * see http://docs.angular-formly.com/docs/field-configuration-object#templateurl-string--function - */ - templateUrl?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; - - - /** - * The type of field to be rendered. This is the recommended method - * for defining fields. Types must be pre-defined using formlyConfig. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#type-string - */ - type?: string; - - - /** - * An object with a few useful properties mostly handy when used in combination with ng-messages - */ - validation?: { - - /** - * This is set by angular-formly. This is a boolean indicating whether an error message should be shown. Because - * you generally only want to show error messages when the user has interacted with a specific field, this value - * is set to true based on this rule: field invalid && (field touched || validation.show) (with slight difference - * for pre-angular 1.3 because it doesn't have touched support). - */ - errorExistsAndShouldBeVisible?: boolean; - - - /** - * A map of Formly Expressions mapped to message names. This is really useful when you're using ng-messages - * like in this example. - */ - messages?: { - [key: string]: IExpressionFunction | string; - } - - - /** - * A boolean you as the developer can set to specify to force options.validation.errorExistsAndShouldBeVisible - * to be set to true when there are $errors. This is useful when you're trying to call the user's attention to - * some fields for some reason. - */ - show?: boolean; - - }; - - - /** - * An object where the keys are the name of the validator and the values are Formly Expressions; - * - * Async Validation - * All function validators can return true/false/Promise. A validator passes if it returns true or a promise - * that is resolved. A validator fails if it returns false or a promise that is rejected. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object - */ - validators?: { - [key: string]: string | IExpressionFunction | IValidator; - }; - - - /** - * This is a getter/setter function for the value that your field is representing. Useful when using getterSetter: true - * in the modelOptions (in fact, if you don't disable the ngModelAttrsTemplateManipulator that comes built-in with formly, - * it will automagically change your field's ng-model attribute to use options.value. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#value-gettersetter-function - */ - value?(): any; //Getter - value?(val: any): void; //Setter - - - /** - * An object which has at least two properties called expression and listener. The watch.expression is added - * to the formly-form directive's scope (to allow it to run even when hide is true). You can specify a type - * ($watchCollection or $watchGroup) via the watcher.type property (defaults to $watch) and whether you want - * it to be a deep watch via the watcher.deep property (defaults to false). - * - * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches - */ - watcher?: IWatcher | IWatcher[]; - - - /** - * This makes reference to setWrapper in formlyConfig. It is expected to be the name of the wrapper. If - * given an array, the formly field template will be wrapped by the first wrapper, then the second, then - * the third, etc. You can also specify these as part of a type (which is the recommended approach). - * Specifying this property will override the wrappers for the type for this field. - * - * http://docs.angular-formly.com/docs/field-configuration-object#wrapper-string--array-of-strings - */ - wrapper?: string | string[]; - - - //ALL PROPERTIES BELOW ARE ADDED (So you should not be setting them yourself.) - - - /** - * This is the NgModelController for the field. It provides you with awesome stuff like $errors :-) - * - * see http://docs.angular-formly.com/docs/field-configuration-object#formcontrol-ngmodelcontroller - */ - formControl?: ng.IFormController | ng.IFormController[]; - - - /** - * Will reset the field's model and the field control to the last initialValue. This is used by the - * formly-form's options.resetModel function. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#resetmodel-function - */ - resetModel?: () => void; - - - /** - * It is not likely that you'll ever want to invoke this function. It simply runs the expressionProperties expressions. - * It is used internally and you shouldn't have to use it, but you can if you want to, and any breaking changes to the - * way it works will result in a major version change, so you can rely on its api. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#runexpressions-function - */ - runExpressions?: () => void; - - - /** - * Will reset the field's initialValue to the current state of the model. Useful if you load the model asynchronously. - * Invoke this when the model gets set. This is used by the formly-form's options.updateInitialValue function. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#updateinitialvalue-function - */ - updateInitialValue?: () => void; - - } - - /** - * - * - * see http://docs.angular-formly.com/docs/custom-templates#section-formlyconfig-settype-options - */ - interface ITypeOptions { - apiCheck?: { [key: string]: Function }; - apiCheckFunction?: string; //'throw' or 'warn - apiCheckInstance?: any; - apiCheckOptions?: Object; - defaultOptions?: IFieldConfigurationObject | Function; - controller?: Function | string | any[]; - data?: { - [key: string]: any; - }; - extends?: string; - link?: ng.IDirectiveLinkFn; - overwriteOk?: boolean; - name: string; - template?: Function | string; - templateUrl?: Function | string; - validateOptions?: Function; - wrapper?: string | string[]; - } - - interface IWrapperOptions { - apiCheck?: { [key: string]: Function }; - apiCheckFunction?: string; //'throw' or 'warn - apiCheckInstance?: any; - apiCheckOptions?: Object; - overwriteOk?: boolean; - name?: string; - template?: string; - templateUrl?: string; - types?: string[]; - validateOptions?: Function; - } - - interface IFormlyConfigExtras { - disableNgModelAttrsManipulator: boolean; - apiCheckInstance: any; - ngModelAttrsManipulatorPreferUnbound: boolean; - removeChromeAutoComplete: boolean; - defaultHideDirective: string; - errorExistsAndShouldBeVisibleExpression: any; - getFieldId: Function; - fieldTransform: Function; - explicitAsync: boolean; - } - - interface IFormlyConfig { - disableWarnings: boolean; - extras: IFormlyConfigExtras; - setType(typeOptions: ITypeOptions): void; - setWrapper(wrapperOptions: IWrapperOptions): void; - templateManipulators: ITemplateManipulators; - } - - interface ITemplateScopeOptions { - formControl: ng.IFormController | ng.IFormController[]; - templateOptions: ITemplateOptions; - validation: Object; - } - - /** - * see http://docs.angular-formly.com/docs/custom-templates#templates-scope - */ - interface ITemplateScope { - options: ITemplateScopeOptions; - //Shortcut to options.formControl - fc: ng.IFormController | ng.IFormController[]; - //all the fields for the form - fields: IFieldArray; - //the form controller the field is in - form: any; - //The object passed as options.formState to the formly-form directive. Use this to share state between fields. - formState: Object; - //The id of the field. You shouldn't have to use this. - id: string; - //The index of the field the form is on (in ng-repeat) - index: number; - //the model of the form (or the model specified by the field if it was specified). - model?: string | { - [key: string]: any; - }; - //Shortcut to options.validation.errorExistsAndShouldBeVisible - showError: boolean; - //Shortcut to options.templateOptions - to: ITemplateOptions; - } - - /** - * see http://docs.angular-formly.com/docs/formlyvalidationmessages#addtemplateoptionvaluemessage - */ - interface IValidationMessages { - addTemplateOptionValueMessage(name: string, prop: string, prefix: string, suffix: string, alternate: string): void; - addStringMessage(name: string, string: string): void; - messages: { [key: string]: ($viewValue: any, $modelValue: any, scope: ITemplateScope) => string }; - } - -} diff --git a/angular-formly/index.d.ts b/angular-formly/index.d.ts new file mode 100644 index 0000000000..8d06554ed2 --- /dev/null +++ b/angular-formly/index.d.ts @@ -0,0 +1,637 @@ +// Type definitions for angular-formly 7.2.3 +// Project: https://github.com/formly-js/angular-formly +// Definitions by: Scott Hatcher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'AngularFormly' { + export = AngularFormly; +} + +declare module 'angular-formly' { + var angularFormlyDefaultExport: string; + export = angularFormlyDefaultExport; +} + +declare namespace AngularFormly { + + interface IFieldArray extends Array { + + } + + interface IFieldGroup { + data?: { + [key: string]: any; + }; + className?: string; + elementAttributes?: string; + fieldGroup?: IFieldArray; + form?: Object; + hide?: boolean; + hideExpression?: string | IExpressionFunction; + key?: string | number; + model?: string | { + [key: string]: any; + }; + options?: IFormOptionsAPI; + templateOptions?: ITemplateOptions; + wrapper?: string | string[]; + } + + + interface IFormOptionsAPI { + data?: { + [key: string]: any; + }; + fieldTransform?: Function; + formState?: Object; + removeChromeAutoComplete?: boolean; + resetModel?: Function; + templateManipulators?: ITemplateManipulators; + updateInitialValue?: Function; + wrapper?: string | string[]; + } + + + /** + * see http://docs.angular-formly.com/docs/formly-expressions#expressionproperties-validators--messages + */ + interface IExpressionFunction { + ($viewValue: any, $modelValue: any, scope: ITemplateScope): any; + } + + + interface IModelOptions { + updateOn?: string; + debounce?: number; + allowInvalid?: boolean; + getterSetter?: string; + timezone?: string; + } + + + interface ITemplateManipulator { + (template: string | HTMLElement, options: Object, scope: ITemplateScope): string | HTMLElement; + } + + + interface ITemplateManipulators { + preWrapper?: ITemplateManipulator[]; + postWrapper?: ITemplateManipulator[]; + } + + interface ISelectOption { + name: string; + value?: string; + group?: string; + } + + /** + * see http://docs.angular-formly.com/docs/ngmodelattrstemplatemanipulator + */ + interface ITemplateOptions { + + // both attribute or regular attribute + disabled?: boolean; + maxlength?: number; + minlength?: number; + pattern?: string; + required?: boolean; + + //attribute only + max?: number; + min?: number; + placeholder?: number | string; + tabindex?: number; + type?: string; + + //expression types + onBlur?: string | IExpressionFunction; + onChange?: string | IExpressionFunction; + onClick?: string | IExpressionFunction; + onFocus?: string | IExpressionFunction; + onKeydown?: string | IExpressionFunction; + onKeypress?: string | IExpressionFunction; + onKeyup?: string | IExpressionFunction; + + //Bootstrap types + label?: string; + description?: string; + [key: string]: any; + + // types for select/radio fields + options?: Array; + groupProp?: string; // default: group + valueProp?: string; // default: value + labelProp?: string; // default: name + + } + + + /** + * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object + */ + interface IValidator { + expression: string | IExpressionFunction; + message?: string | IExpressionFunction; + } + + + /** + * An object which has at least two properties called expression and listener. The watch.expression + * is added to the formly-form directive's scope (to allow it to run even when hide is true). You + * can specify a type ($watchCollection or $watchGroup) via the watcher.type property (defaults to + * $watch) and whether you want it to be a deep watch via the watcher.deep property (defaults to false). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches + */ + interface IWatcher { + deep?: boolean; //Defaults to false + expression?: string | { (field: string, scope: ITemplateScope): boolean }; + listener: (field: string, newValue: any, oldValue: any, scope: ITemplateScope, stopWatching: Function) => void; + type?: string; //Defaults to $watch but can be set to $watchCollection or $watchGroup + } + + + // see http://docs.angular-formly.com/docs/field-configuration-object + interface IFieldConfigurationObject { + + + /** + * Added in 6.18.0 + * + * Demo + * see http://angular-formly.com/#/example/other/unique-value-async-validation + */ + asyncValidators?: { + [key: string]: string | IExpressionFunction | IValidator; + }; + + /** + * This is a great way to add custom behavior to a specific field. It is injectable with the $scope of the + * field, and anything else you have in your injector. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#controller-controller-name-as-string--controller-f + */ + controller?: string | Function; + + + /** + * This is reserved for the developer. You have our guarantee to be able to use this and not worry about + * future versions of formly overriding your usage and preventing you from upgrading :-) + * + * see http://docs.angular-formly.com/docs/field-configuration-object#data-object + */ + data?: { + [key: string]: any; + }; + + + /** + * Use defaultValue to initialize it the model. If this is provided and the value of the + * model at compile-time is undefined, then the value of the model will be assigned to defaultValue. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#defaultvalue-any + */ + defaultValue?: any; + + + /** + * You can specify your own class that will be applied to the formly-field directive (or ng-form of + * a fieldGroup). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#classname-string + */ + className?: string; + + + elementAttributes?: { + [key: string]: string; + }; + + + /** + * An object where the key is a property to be set on the main field config and the value is an + * expression used to assign that property. The value is a formly expressions. The returned value is + * wrapped in $q.when so you can return a promise from your function :-) + * + * see http://docs.angular-formly.com/docs/field-configuration-object#expressionproperties-object + */ + expressionProperties?: { + [key: string]: string | IExpressionFunction | IValidator; + }; + + + /** + * Uses ng-if. Whether to hide the field. Defaults to false. If you wish this to be conditional, use + * hideExpression. See below. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#hide-boolean + */ + hide?: boolean; + + + /** + * This is similar to expressionProperties with a slight difference. You should (hopefully) never + * notice the difference with the most common use case. This is available due to limitations with + * expressionProperties and ng-if not working together very nicely. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#hideexpression-string--function + */ + hideExpression?: string | IExpressionFunction; + + + /** + * This allows you to specify the id of your field (which will be used for its name as well unless + * a name is provided). Note, you can also override the id generation code using the formlyConfig + * extra called getFieldId. + * + * AVOID THIS + * If you don't have to do this, don't. Specifying IDs makes it harder to re-use things and it's + * just extra work. Part of the beauty that angular-formly provides is the fact that you don't need + * to concern yourself with making sure that this is unique. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#id-string + */ + id?: string; + + + initialValue?: any; + + + /** + * Can be set instead of type or template to use a custom html template form field. Works + * just like a directive templateUrl and uses the $templateCache + * + * see http://docs.angular-formly.com/docs/field-configuration-object#key-string + */ + key?: string | number; + + + /** + * This allows you to specify a link function. It is invoked after your template has finished compiling. + * You are passed the normal arguments for a normal link function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#link-link-function + */ + link?: ng.IDirectiveLinkFn; + + + /** + * By default, the model passed to the formly-field directive is the same as the model passed to the + * formly-form. However, if the field has a model specified, then it is used for that field (and that + * field only). In addition, a deep watch is added to the formly-field directive's scope to run the + * expressionProperties when the specified model changes. + * + * Note, the formly-form directive will allow you to specify a string which is an (almost) formly + * expression which allows you to define the model as relative to the scope of the form. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#model-object--string + */ + model?: string | { + [key: string]: any; + }; + + + /** + * Allows you to take advantage of ng-model-options directive. Formly's built-in templateManipulator (see + * below) will add this attribute to your ng-model element automatically if this property exists. Note, + * if you use the getter/setter option, formly's templateManipulator will change the value of ng-model + * to options.value which is a getterSetter that formly adds to field options. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#modeloptions + */ + modelOptions?: IModelOptions; + + + /** + * If you wish to, you can specify a specific name for your ng-model. This is useful if you're posting + * the form to a server using techniques of yester-year. + * + * AVOID THIS + * If you don't have to do this, don't. It's just extra work. Part of the beauty that angular-formly + * provides is the fact that you don't need to concern yourself with stuff like this. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#name-string + */ + name?: string; + + + /** + * This is used by ngModelAttrsTemplateManipulator to automatically add attributes to the ng-model element + * of field templates. You will likely not use this often. This object is a little complex, but extremely + * powerful. It's best to explain this api via an example. For more information, see the guide on ngModelAttrs. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#ngmodelattrs-object + */ + ngModelAttrs?: { + attribute?: any; + bound?: any; + expression?: any; + value?: any; + [key: string]: any; + }; + + + /** + * This allows you to place attributes with string values on the ng-model element. + * Easy to use alternative to ngModelAttrs option. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#ngmodelelattrs-object + */ + ngModelElAttrs?: { + [key: string]: string; + }; + + + /** + * Used to tell angular-formly to not attempt to add the formControl property to your object. This is useful + * for things like validation, but not necessary if your "field" doesn't use ng-model (if it's just a horizontal + * line for example). Defaults to undefined. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#noformcontrol-boolean + */ + noFormControl?: boolean; + + + /** + * Allows you to specify extra types to get options from. Duplicate options are overridden in later priority + * (index 1 will override index 0 properties). Also, these are applied after the type's defaultOptions and + * hence will override any duplicates of those properties as well. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#optionstypes-string--array-of-strings + */ + optionsTypes?: string | string[]; + + + /** + * Can be set instead of type or templateUrl to use a custom html + * template form field. Recommended to be used with one-liners mostly + * (like a directive), or if you're using webpack with the ability to require templates :-) + * + * If a function is passed, it is invoked with the field configuration object and can return + * either a string for the template or a promise that resolves to a string. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#template-string--function + */ + template?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; + + + /** + * Allows you to specify custom template manipulators for this specific field. (use defaultOptions in a + * type configuration if you want it to apply to all fields of a certain type). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templatemanipulator-object-of-arrays-of-functions + */ + templateManipulators?: ITemplateManipulators; + + + /** + * This is reserved for the templates. Any template-specific options go in here. Look at your specific + * template implementation to know the options required for this. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templateoptions-object + */ + templateOptions?: ITemplateOptions; + + + /** + * Can be set instead of type or template to use a custom html template form field. Works + * just like a directive templateUrl and uses the $templateCache + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templateurl-string--function + */ + templateUrl?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; + + + /** + * The type of field to be rendered. This is the recommended method + * for defining fields. Types must be pre-defined using formlyConfig. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#type-string + */ + type?: string; + + + /** + * An object with a few useful properties mostly handy when used in combination with ng-messages + */ + validation?: { + + /** + * This is set by angular-formly. This is a boolean indicating whether an error message should be shown. Because + * you generally only want to show error messages when the user has interacted with a specific field, this value + * is set to true based on this rule: field invalid && (field touched || validation.show) (with slight difference + * for pre-angular 1.3 because it doesn't have touched support). + */ + errorExistsAndShouldBeVisible?: boolean; + + + /** + * A map of Formly Expressions mapped to message names. This is really useful when you're using ng-messages + * like in this example. + */ + messages?: { + [key: string]: IExpressionFunction | string; + } + + + /** + * A boolean you as the developer can set to specify to force options.validation.errorExistsAndShouldBeVisible + * to be set to true when there are $errors. This is useful when you're trying to call the user's attention to + * some fields for some reason. + */ + show?: boolean; + + }; + + + /** + * An object where the keys are the name of the validator and the values are Formly Expressions; + * + * Async Validation + * All function validators can return true/false/Promise. A validator passes if it returns true or a promise + * that is resolved. A validator fails if it returns false or a promise that is rejected. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object + */ + validators?: { + [key: string]: string | IExpressionFunction | IValidator; + }; + + + /** + * This is a getter/setter function for the value that your field is representing. Useful when using getterSetter: true + * in the modelOptions (in fact, if you don't disable the ngModelAttrsTemplateManipulator that comes built-in with formly, + * it will automagically change your field's ng-model attribute to use options.value. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#value-gettersetter-function + */ + value?(): any; //Getter + value?(val: any): void; //Setter + + + /** + * An object which has at least two properties called expression and listener. The watch.expression is added + * to the formly-form directive's scope (to allow it to run even when hide is true). You can specify a type + * ($watchCollection or $watchGroup) via the watcher.type property (defaults to $watch) and whether you want + * it to be a deep watch via the watcher.deep property (defaults to false). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches + */ + watcher?: IWatcher | IWatcher[]; + + + /** + * This makes reference to setWrapper in formlyConfig. It is expected to be the name of the wrapper. If + * given an array, the formly field template will be wrapped by the first wrapper, then the second, then + * the third, etc. You can also specify these as part of a type (which is the recommended approach). + * Specifying this property will override the wrappers for the type for this field. + * + * http://docs.angular-formly.com/docs/field-configuration-object#wrapper-string--array-of-strings + */ + wrapper?: string | string[]; + + + //ALL PROPERTIES BELOW ARE ADDED (So you should not be setting them yourself.) + + + /** + * This is the NgModelController for the field. It provides you with awesome stuff like $errors :-) + * + * see http://docs.angular-formly.com/docs/field-configuration-object#formcontrol-ngmodelcontroller + */ + formControl?: ng.IFormController | ng.IFormController[]; + + + /** + * Will reset the field's model and the field control to the last initialValue. This is used by the + * formly-form's options.resetModel function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#resetmodel-function + */ + resetModel?: () => void; + + + /** + * It is not likely that you'll ever want to invoke this function. It simply runs the expressionProperties expressions. + * It is used internally and you shouldn't have to use it, but you can if you want to, and any breaking changes to the + * way it works will result in a major version change, so you can rely on its api. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#runexpressions-function + */ + runExpressions?: () => void; + + + /** + * Will reset the field's initialValue to the current state of the model. Useful if you load the model asynchronously. + * Invoke this when the model gets set. This is used by the formly-form's options.updateInitialValue function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#updateinitialvalue-function + */ + updateInitialValue?: () => void; + + } + + /** + * + * + * see http://docs.angular-formly.com/docs/custom-templates#section-formlyconfig-settype-options + */ + interface ITypeOptions { + apiCheck?: { [key: string]: Function }; + apiCheckFunction?: string; //'throw' or 'warn + apiCheckInstance?: any; + apiCheckOptions?: Object; + defaultOptions?: IFieldConfigurationObject | Function; + controller?: Function | string | any[]; + data?: { + [key: string]: any; + }; + extends?: string; + link?: ng.IDirectiveLinkFn; + overwriteOk?: boolean; + name: string; + template?: Function | string; + templateUrl?: Function | string; + validateOptions?: Function; + wrapper?: string | string[]; + } + + interface IWrapperOptions { + apiCheck?: { [key: string]: Function }; + apiCheckFunction?: string; //'throw' or 'warn + apiCheckInstance?: any; + apiCheckOptions?: Object; + overwriteOk?: boolean; + name?: string; + template?: string; + templateUrl?: string; + types?: string[]; + validateOptions?: Function; + } + + interface IFormlyConfigExtras { + disableNgModelAttrsManipulator: boolean; + apiCheckInstance: any; + ngModelAttrsManipulatorPreferUnbound: boolean; + removeChromeAutoComplete: boolean; + defaultHideDirective: string; + errorExistsAndShouldBeVisibleExpression: any; + getFieldId: Function; + fieldTransform: Function; + explicitAsync: boolean; + } + + interface IFormlyConfig { + disableWarnings: boolean; + extras: IFormlyConfigExtras; + setType(typeOptions: ITypeOptions): void; + setWrapper(wrapperOptions: IWrapperOptions): void; + templateManipulators: ITemplateManipulators; + } + + interface ITemplateScopeOptions { + formControl: ng.IFormController | ng.IFormController[]; + templateOptions: ITemplateOptions; + validation: Object; + } + + /** + * see http://docs.angular-formly.com/docs/custom-templates#templates-scope + */ + interface ITemplateScope { + options: ITemplateScopeOptions; + //Shortcut to options.formControl + fc: ng.IFormController | ng.IFormController[]; + //all the fields for the form + fields: IFieldArray; + //the form controller the field is in + form: any; + //The object passed as options.formState to the formly-form directive. Use this to share state between fields. + formState: Object; + //The id of the field. You shouldn't have to use this. + id: string; + //The index of the field the form is on (in ng-repeat) + index: number; + //the model of the form (or the model specified by the field if it was specified). + model?: string | { + [key: string]: any; + }; + //Shortcut to options.validation.errorExistsAndShouldBeVisible + showError: boolean; + //Shortcut to options.templateOptions + to: ITemplateOptions; + } + + /** + * see http://docs.angular-formly.com/docs/formlyvalidationmessages#addtemplateoptionvaluemessage + */ + interface IValidationMessages { + addTemplateOptionValueMessage(name: string, prop: string, prefix: string, suffix: string, alternate: string): void; + addStringMessage(name: string, string: string): void; + messages: { [key: string]: ($viewValue: any, $modelValue: any, scope: ITemplateScope) => string }; + } + +} diff --git a/angular-formly/tsconfig.json b/angular-formly/tsconfig.json new file mode 100644 index 0000000000..40e004021f --- /dev/null +++ b/angular-formly/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-formly-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-fullscreen/angular-fullscreen-tests.ts b/angular-fullscreen/angular-fullscreen-tests.ts index f45202c0db..ea7c9821f8 100644 --- a/angular-fullscreen/angular-fullscreen-tests.ts +++ b/angular-fullscreen/angular-fullscreen-tests.ts @@ -1,4 +1,4 @@ -/// + angular .module('TestApp', ['FBAngular']) diff --git a/angular-fullscreen/angular-fullscreen.d.ts b/angular-fullscreen/angular-fullscreen.d.ts deleted file mode 100644 index 414754db43..0000000000 --- a/angular-fullscreen/angular-fullscreen.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Type definitions for AngularJS HTML5 Fullscreen v1.0.1 -// Project: https://github.com/fabiobiondi/angular-fullscreen -// Definitions by: Julien Paroche -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/angular-fullscreen - -/// - -declare namespace angular.fullscreen { - - /** - * Prefixing interface name with "I" is not recommended: http://www.typescriptlang.org/Handbook#writing-dts-files - * However, we let it here to keep consistency with all the other Angular-related definitions - */ - interface IFullscreen { - // enable document fullscreen - all(): void; - - // enable or disable the document fullscreen - toggleAll(): void; - - // enable fullscreen to a specific element - enable(element: Element|HTMLElement): void; - - // disable fullscreen - cancel(): void; - - // return true if fullscreen is enabled, otherwise false - isEnabled(): boolean; - - // return true if fullscreen API is supported by your browser - isSupported(): boolean; - } - -} diff --git a/angular-fullscreen/index.d.ts b/angular-fullscreen/index.d.ts new file mode 100644 index 0000000000..b58830952b --- /dev/null +++ b/angular-fullscreen/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for AngularJS HTML5 Fullscreen v1.0.1 +// Project: https://github.com/fabiobiondi/angular-fullscreen +// Definitions by: Julien Paroche +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/angular-fullscreen + +/// + +declare namespace angular.fullscreen { + + /** + * Prefixing interface name with "I" is not recommended: http://www.typescriptlang.org/Handbook#writing-dts-files + * However, we let it here to keep consistency with all the other Angular-related definitions + */ + interface IFullscreen { + // enable document fullscreen + all(): void; + + // enable or disable the document fullscreen + toggleAll(): void; + + // enable fullscreen to a specific element + enable(element: Element|HTMLElement): void; + + // disable fullscreen + cancel(): void; + + // return true if fullscreen is enabled, otherwise false + isEnabled(): boolean; + + // return true if fullscreen API is supported by your browser + isSupported(): boolean; + } + +} diff --git a/angular-fullscreen/tsconfig.json b/angular-fullscreen/tsconfig.json new file mode 100644 index 0000000000..88eccf263d --- /dev/null +++ b/angular-fullscreen/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-fullscreen-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-gettext/angular-gettext-tests.ts b/angular-gettext/angular-gettext-tests.ts index d15924331d..4529b97e4c 100644 --- a/angular-gettext/angular-gettext-tests.ts +++ b/angular-gettext/angular-gettext-tests.ts @@ -1,4 +1,4 @@ -/// + namespace angular_gettext_tests { diff --git a/angular-gettext/angular-gettext.d.ts b/angular-gettext/angular-gettext.d.ts deleted file mode 100644 index 48734d4433..0000000000 --- a/angular-gettext/angular-gettext.d.ts +++ /dev/null @@ -1,73 +0,0 @@ -// Type definitions for angular-gettext v2.1.0 -// Project: https://angular-gettext.rocketeer.be/ -// Definitions by: Ákos Lukács -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.gettext { - interface gettextCatalog { - - ////////////// - /// Fields /// - ////////////// - - /** (default: false): Whether or not to prefix untranslated strings with [MISSING]: or a custom prefix. */ - debug: boolean; - /** (default: [MISSING]:): Custom prefix for untranslated strings. */ - debugPrefix: string; - /** (default: false): Whether or not to wrap all processed text with markers.Example output: [Welcome] */ - showTranslatedMarkers: boolean; - /** (default: [): Custom prefix to mark strings that have been run through angular-gettext. */ - translatedMarkerPrefix: string; - /** (default: ]): Custom suffix to mark strings that have been run through angular-gettext. */ - translatedMarkerSuffix: string; - /** An object of loaded translation strings.Shouldn't be used directly. */ - strings: {}; - /** The default language, in which you're application is written. This defaults to English and it's generally a bad idea to use anything else: if your language has different pluralization rules you'll end up with incorrect translations. Deprecated - * @deprecreated - */ - baseLanguage: string; - - - /////////////// - /// Methods /// - /////////////// - - /** Sets the current language and makes sure that all translations get updated correctly. */ - setCurrentLanguage(lang: string): void; - - /** Returns the current language. */ - getCurrentLanguage(): string; - - /** Processes an object of string definitions. More details https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/ - * @param language A language code. - * @param strings A dictionary of strings. The format of this dictionary is: - * - Keys: Singular English strings (as defined in the source files) - * - Values: Either a single string for signular-only strings or an array of plural forms. - */ - setStrings(language: string, strings: { [key: string]: string|string[] }): void; - - /** Get the correct pluralized (but untranslated) string for the value of n. */ - getStringForm(string: string, n: number): string; - - /** Translate a string with the given context. Uses Angular.JS interpolation, so something like this will do what you expect: - * var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" }); - * // var hello will be "Hallo Ruben!" in Dutch. - * The context parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. - */ - getString(string: string, context?: any): string; - - /** Translate a plural string with the given context. */ - getPlural(n: number, string: string, stringPlural: string, context?: any): string; - - /** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */ - loadRemote(url: string): ng.IHttpPromise; - } - - /** If you have text that should be translated in your JavaScript code, wrap it with a call to a function named gettext. This module provides an injectable function to do so */ - interface gettextFunction { - (dummyString: string): string; - } -} - diff --git a/angular-gettext/index.d.ts b/angular-gettext/index.d.ts new file mode 100644 index 0000000000..7db351cfd1 --- /dev/null +++ b/angular-gettext/index.d.ts @@ -0,0 +1,73 @@ +// Type definitions for angular-gettext v2.1.0 +// Project: https://angular-gettext.rocketeer.be/ +// Definitions by: Ákos Lukács +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.gettext { + interface gettextCatalog { + + ////////////// + /// Fields /// + ////////////// + + /** (default: false): Whether or not to prefix untranslated strings with [MISSING]: or a custom prefix. */ + debug: boolean; + /** (default: [MISSING]:): Custom prefix for untranslated strings. */ + debugPrefix: string; + /** (default: false): Whether or not to wrap all processed text with markers.Example output: [Welcome] */ + showTranslatedMarkers: boolean; + /** (default: [): Custom prefix to mark strings that have been run through angular-gettext. */ + translatedMarkerPrefix: string; + /** (default: ]): Custom suffix to mark strings that have been run through angular-gettext. */ + translatedMarkerSuffix: string; + /** An object of loaded translation strings.Shouldn't be used directly. */ + strings: {}; + /** The default language, in which you're application is written. This defaults to English and it's generally a bad idea to use anything else: if your language has different pluralization rules you'll end up with incorrect translations. Deprecated + * @deprecreated + */ + baseLanguage: string; + + + /////////////// + /// Methods /// + /////////////// + + /** Sets the current language and makes sure that all translations get updated correctly. */ + setCurrentLanguage(lang: string): void; + + /** Returns the current language. */ + getCurrentLanguage(): string; + + /** Processes an object of string definitions. More details https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/ + * @param language A language code. + * @param strings A dictionary of strings. The format of this dictionary is: + * - Keys: Singular English strings (as defined in the source files) + * - Values: Either a single string for signular-only strings or an array of plural forms. + */ + setStrings(language: string, strings: { [key: string]: string|string[] }): void; + + /** Get the correct pluralized (but untranslated) string for the value of n. */ + getStringForm(string: string, n: number): string; + + /** Translate a string with the given context. Uses Angular.JS interpolation, so something like this will do what you expect: + * var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" }); + * // var hello will be "Hallo Ruben!" in Dutch. + * The context parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. + */ + getString(string: string, context?: any): string; + + /** Translate a plural string with the given context. */ + getPlural(n: number, string: string, stringPlural: string, context?: any): string; + + /** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */ + loadRemote(url: string): ng.IHttpPromise; + } + + /** If you have text that should be translated in your JavaScript code, wrap it with a call to a function named gettext. This module provides an injectable function to do so */ + interface gettextFunction { + (dummyString: string): string; + } +} + diff --git a/angular-gettext/tsconfig.json b/angular-gettext/tsconfig.json new file mode 100644 index 0000000000..16c1ecdbf7 --- /dev/null +++ b/angular-gettext/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-gettext-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-google-analytics/angular-google-analytics-tests.ts b/angular-google-analytics/angular-google-analytics-tests.ts index b8c40d64f5..42c7e1506c 100644 --- a/angular-google-analytics/angular-google-analytics-tests.ts +++ b/angular-google-analytics/angular-google-analytics-tests.ts @@ -1,6 +1,3 @@ -/// -/// - function ConfigurationMethodChaining(AnalyticsProvider: angular.google.analytics.AnalyticsProvider) { AnalyticsProvider .logAllCalls(true) diff --git a/angular-google-analytics/angular-google-analytics.d.ts b/angular-google-analytics/angular-google-analytics.d.ts deleted file mode 100644 index 03ef64ba75..0000000000 --- a/angular-google-analytics/angular-google-analytics.d.ts +++ /dev/null @@ -1,173 +0,0 @@ -// Type definitions for angular-google-analytics v1.1.0 -// Project: https://github.com/revolunet/angular-google-analytics -// Definitions by: Cyril Schumacher -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.google.analytics { - /** - * @summary Interface for {@link AnalysticsProvider}. - * @interface - */ - interface AnalyticsProvider { - /** - * @summary Use Delay Script Tag Insertion. - * @param {boolean} val If true, the delay script tag is inserted. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - delayScriptTag(val: boolean): AnalyticsProvider; - - /** - * @summary Activates the test mode. - */ - enterTestMode(): void; - - /** - * @summary Gets the global cookie configuration. - * @return {Object} The global cookie configuration. - */ - getCookieConfig(): Object; - - /** - * @summary Ignore first page view. - * @param {boolean} val If true, the first page view is ignored. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - ignoreFirstPageLoad(val: boolean): AnalyticsProvider; - - /** - * @summary Enable Service Logging. - * @param {boolean} val If true, log all outbound calls to an in-memory array accessible. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - logAllCalls(val: boolean): AnalyticsProvider; - - /** - * @summary Set Google Analytics Accounts. - * @param {Object} tracker The account identifier(s). - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - setAccount(tracker: string|Object|Array): AnalyticsProvider; - - /** - * @summary Set Cookie Configuration. - * @param {Object} config The custom cookie parameters. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - * @deprecated - */ - setCookieConfig(config: Object): AnalyticsProvider; - - /** - * @summary Set cross-linked domains. - * @param {Array} domains The domains. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - setCrossLinkDomains(domains: Array): AnalyticsProvider; - - /** - * @summary Set currency. - * @param {string} currencyCode The currency code. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - setCurrency(currencyCode: string): AnalyticsProvider; - - /** - * @summary Set Domain Name. - * @param {string} domain The domain name. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - setDomainName(domain: string): AnalyticsProvider; - - /** - * @summary Enable Experiment (universal analytics only). - * @param {string} id The experiment identifier. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - setExperimentId(id: string): AnalyticsProvider; - - /** - * @summary Support Hybrid Mobile Applications. - * @param {boolean} val If true, each account object will disable protocol checking and all injected scripts will use the HTTPS protocol. - */ - setHybridMobileSupport(val: boolean): AnalyticsProvider; - - /** - * @summary Set the default page event name. - * @param {string} name The default page event name. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - setPageEvent(name: string): AnalyticsProvider; - - /** - * @summary Sets the regex to scrub location before sending to analytics. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - * @param {RegExp} regex The regex. - */ - setRemoveRegExp(regex: RegExp): AnalyticsProvider; - - /** - * @summary Starts the offline mode. - * @param {boolean} val If true, the offline mode is started. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - startOffline(val: boolean): AnalyticsProvider; - - /** - * @summary Track all routes. - * @param {boolean} val If true, all routes are tracked. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - trackPages(doTrack: boolean): AnalyticsProvider; - - /** - * @summary Sets the URL prefix. - * @param {string} prefix The URL prefix. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - trackPrefix(prefix: string): AnalyticsProvider; - - /** - * @summary Track all URL query parameters. - * @param {boolean} val If true, all URL query parameters are tracked. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - trackUrlParams(val: boolean): AnalyticsProvider; - - /** - * @summary Use Classic Analytics. - * @param {boolean} val If true, use classic analytics. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - useAnalytics(val: boolean): AnalyticsProvider; - - /** - * @summary Use Cross Domain Linking. - * @param {boolean} val If true, the cross-linked domains are registered with Google Analytics. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - useCrossDomainLinker(val: boolean): AnalyticsProvider; - - /** - * @summary Use Display Features. - * @param {boolean} val If true, the display features module is loaded with Google Analytics. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - useDisplayFeatures(val: boolean): AnalyticsProvider; - - /** - * @summary Enable enhanced e-commerce module. - * @param {boolean} val If true, the enhanced e-commerce module is enabled. - * @param {boolean} enhanced If true, the "ec.js" file is used, otherwises, the "ecommerce.js" is used. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - useECommerce(val: boolean, enhanced: boolean): AnalyticsProvider; - - /** - * @summary Use Enhanced Link Attribution. - * @param {boolean} val If true, the enhanced link attribution module is loaded with Google Analytics. - * @return {angular.google.analytics.IAnalyticsProvider} The object instance. - */ - useEnhancedLinkAttribution(val: boolean): AnalyticsProvider; - } -} diff --git a/angular-google-analytics/index.d.ts b/angular-google-analytics/index.d.ts new file mode 100644 index 0000000000..403391f2e4 --- /dev/null +++ b/angular-google-analytics/index.d.ts @@ -0,0 +1,174 @@ +// Type definitions for angular-google-analytics v1.1.0 +// Project: https://github.com/revolunet/angular-google-analytics +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace angular.google.analytics { + /** + * @summary Interface for {@link AnalysticsProvider}. + * @interface + */ + interface AnalyticsProvider { + /** + * @summary Use Delay Script Tag Insertion. + * @param {boolean} val If true, the delay script tag is inserted. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + delayScriptTag(val: boolean): AnalyticsProvider; + + /** + * @summary Activates the test mode. + */ + enterTestMode(): void; + + /** + * @summary Gets the global cookie configuration. + * @return {Object} The global cookie configuration. + */ + getCookieConfig(): Object; + + /** + * @summary Ignore first page view. + * @param {boolean} val If true, the first page view is ignored. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + ignoreFirstPageLoad(val: boolean): AnalyticsProvider; + + /** + * @summary Enable Service Logging. + * @param {boolean} val If true, log all outbound calls to an in-memory array accessible. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + logAllCalls(val: boolean): AnalyticsProvider; + + /** + * @summary Set Google Analytics Accounts. + * @param {Object} tracker The account identifier(s). + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + setAccount(tracker: string|Object|Array): AnalyticsProvider; + + /** + * @summary Set Cookie Configuration. + * @param {Object} config The custom cookie parameters. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + * @deprecated + */ + setCookieConfig(config: Object): AnalyticsProvider; + + /** + * @summary Set cross-linked domains. + * @param {Array} domains The domains. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + setCrossLinkDomains(domains: Array): AnalyticsProvider; + + /** + * @summary Set currency. + * @param {string} currencyCode The currency code. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + setCurrency(currencyCode: string): AnalyticsProvider; + + /** + * @summary Set Domain Name. + * @param {string} domain The domain name. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + setDomainName(domain: string): AnalyticsProvider; + + /** + * @summary Enable Experiment (universal analytics only). + * @param {string} id The experiment identifier. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + setExperimentId(id: string): AnalyticsProvider; + + /** + * @summary Support Hybrid Mobile Applications. + * @param {boolean} val If true, each account object will disable protocol checking and all injected scripts will use the HTTPS protocol. + */ + setHybridMobileSupport(val: boolean): AnalyticsProvider; + + /** + * @summary Set the default page event name. + * @param {string} name The default page event name. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + setPageEvent(name: string): AnalyticsProvider; + + /** + * @summary Sets the regex to scrub location before sending to analytics. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + * @param {RegExp} regex The regex. + */ + setRemoveRegExp(regex: RegExp): AnalyticsProvider; + + /** + * @summary Starts the offline mode. + * @param {boolean} val If true, the offline mode is started. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + startOffline(val: boolean): AnalyticsProvider; + + /** + * @summary Track all routes. + * @param {boolean} val If true, all routes are tracked. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + trackPages(doTrack: boolean): AnalyticsProvider; + + /** + * @summary Sets the URL prefix. + * @param {string} prefix The URL prefix. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + trackPrefix(prefix: string): AnalyticsProvider; + + /** + * @summary Track all URL query parameters. + * @param {boolean} val If true, all URL query parameters are tracked. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + trackUrlParams(val: boolean): AnalyticsProvider; + + /** + * @summary Use Classic Analytics. + * @param {boolean} val If true, use classic analytics. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + useAnalytics(val: boolean): AnalyticsProvider; + + /** + * @summary Use Cross Domain Linking. + * @param {boolean} val If true, the cross-linked domains are registered with Google Analytics. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + useCrossDomainLinker(val: boolean): AnalyticsProvider; + + /** + * @summary Use Display Features. + * @param {boolean} val If true, the display features module is loaded with Google Analytics. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + useDisplayFeatures(val: boolean): AnalyticsProvider; + + /** + * @summary Enable enhanced e-commerce module. + * @param {boolean} val If true, the enhanced e-commerce module is enabled. + * @param {boolean} enhanced If true, the "ec.js" file is used, otherwises, the "ecommerce.js" is used. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + useECommerce(val: boolean, enhanced: boolean): AnalyticsProvider; + + /** + * @summary Use Enhanced Link Attribution. + * @param {boolean} val If true, the enhanced link attribution module is loaded with Google Analytics. + * @return {angular.google.analytics.IAnalyticsProvider} The object instance. + */ + useEnhancedLinkAttribution(val: boolean): AnalyticsProvider; + } +} diff --git a/angular-google-analytics/tsconfig.json b/angular-google-analytics/tsconfig.json new file mode 100644 index 0000000000..f53eeaec05 --- /dev/null +++ b/angular-google-analytics/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-google-analytics-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-growl-v2/angular-growl-v2-tests.ts b/angular-growl-v2/angular-growl-v2-tests.ts index 13c7cad2e5..b02c768add 100644 --- a/angular-growl-v2/angular-growl-v2-tests.ts +++ b/angular-growl-v2/angular-growl-v2-tests.ts @@ -1,4 +1,4 @@ -/// + var app = angular.module("ag", ["pascalprecht.translate", "$httpProvider"]); diff --git a/angular-growl-v2/angular-growl-v2.d.ts b/angular-growl-v2/angular-growl-v2.d.ts deleted file mode 100644 index 7b67678b85..0000000000 --- a/angular-growl-v2/angular-growl-v2.d.ts +++ /dev/null @@ -1,259 +0,0 @@ -// Type definitions for Angular Growl 2 v.0.7.5 -// Project: http://janstevens.github.io/angular-growl-2 -// Definitions by: Tadeusz Hucal -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.growl { - - /** - * Global Time-To-Leave configuration. - */ - interface IGrowlTTLConfig { - success?: number; - error?: number; - warning?: number; - info?: number; - } - - /** - * Custom configuration used in single message call. - */ - interface IGrowlMessageConfig { - title?: string; - ttl?: number; - disableCountDown?: boolean; - disableIcons?: boolean; - disableCloseButton?: boolean; - onclose?: Function; - onopen?: Function; - position?: string; - referenceId?: number; - translateMessage?: boolean; - variables?: { [variable: string]: any; }; - } - - /** - * Growl message with configuration. - */ - interface IGrowlMessage extends IGrowlMessageConfig { - text: string; - - /** - * Destroy the message. - */ - destroy(): void; - /** - * Update the message body. - * @param newText new message body - */ - setText(newText: string): void; - } - - /** - * Growl service provider. - */ - interface IGrowlProvider extends angular.IServiceProvider { - /** - * Pre-defined server error interceptor. - */ - serverMessagesInterceptor: (string|IHttpInterceptorFactory)[]; - - /** - * Set default TTL settings. - * @param ttl configuration of TTL for different type of message - */ - globalTimeToLive(ttl: IGrowlTTLConfig): IGrowlProvider; - /** - * Set default TTL settings. - * @param ttl ttl in milliseconds - */ - globalTimeToLive(ttl: number): IGrowlProvider; - /** - * Set default setting for disabling close button. - * @param disableCloseButton - */ - globalDisableCloseButton(disableCloseButton: boolean): IGrowlProvider; - /** - * Set default setting for disabling icons. - * @param disableIcons - */ - globalDisableIcons(disableIcons: boolean): IGrowlProvider; - /** - * Set reversing order of displaying new messages. - * @param reverseOrder - */ - globalReversedOrder(reverseOrder: boolean): IGrowlProvider; - /** - * Set default setting for displaying message disappear countdown. - * @param disableCountDown - */ - globalDisableCountDown(disableCountDown: boolean): IGrowlProvider; - /** - * Set default allowance for inline messages. - * @param inline - */ - globalInlineMessages(inline: boolean): IGrowlProvider; - /** - * Set default message position. - * @param position - */ - globalPosition(position: string): IGrowlProvider; - /** - * Enable/disable displaying only unique messages. - * @param onlyUniqueMessages - */ - onlyUniqueMessages(onlyUniqueMessages: boolean): IGrowlProvider; - - /** - * Set key where messages are stored (for http interceptor). - * @param messageVariableKey - */ - messagesKey(messageKey: string): IGrowlProvider; - /** - * Set key where message text is stored (for http interceptor). - * @param messageVariableKey - */ - messageTextKey(messageTextKey: string): IGrowlProvider; - /** - * Set key where title of message is stored (for http interceptor). - * @param messageVariableKey - */ - messageTitleKey(messageTitleKey: string): IGrowlProvider; - /** - * Set key where severity of message is stored (for http interceptor). - * @param messageVariableKey - */ - messageSeverityKey(messageSeverityKey: string): IGrowlProvider; - /** - * Set key where variables for message are stored (for http interceptor). - * @param messageVariableKey - */ - messageVariableKey(messageVariableKey: string): IGrowlProvider; - } - - /** - * Growl service. - */ - interface IGrowlService { - /** - * Show warning message. - * @param message text to display (or code for angular-translate) - */ - warning(message: string): IGrowlMessage; - /** - * Show warning message. - * @param message text to display (or code for angular-translate) - * @param config additional message configuration - */ - warning(message: string, config: IGrowlMessageConfig): IGrowlMessage; - - /** - * Show error message. - * @param message text to display (or code for angular-translate) - */ - error(message: string): IGrowlMessage; - /** - * Show error message. - * @param message text to display (or code for angular-translate) - * @param config additional message configuration - */ - error(message: string, config: IGrowlMessageConfig): IGrowlMessage; - - /** - * Show information message. - * @param message text to display (or code for angular-translate) - */ - info(message: string): IGrowlMessage; - /** - * Show information message. - * @param message text to display (or code for angular-translate) - * @param config additional message configuration - */ - info(message: string, config: IGrowlMessageConfig): IGrowlMessage; - - /** - * Show success message. - * @param message text to display (or code for angular-translate) - * @param config additional message configuration - */ - success(message: string): IGrowlMessage; - /** - * Show success message. - * @param message text to display (or code for angular-translate) - */ - success(message: string, config: IGrowlMessageConfig): IGrowlMessage; - - /** - * Show message (generic). - * @param message text to display (or code for angular-translate) - */ - general(message: string): IGrowlMessage; - /** - * Show message (generic). - * @param message text to display (or code for angular-translate) - * @param config additional message configuration - */ - general(message: string, config: IGrowlMessageConfig): IGrowlMessage; - /** - * Show message (generic). - * @param message text to display (or code for angular-translate) - * @param config additional message configuration - * @param severity message severity (error, warning, success, info). - */ - general(message: string, config: IGrowlMessageConfig, severity: string): IGrowlMessage; - - /** - * Get current setting for displaying only unique messages. - */ - onlyUnique(): boolean; - /** - * Get current setting for reversing messages order. - */ - reverseOrder(): boolean; - /** - * Get current allowance for inline messages. - */ - inlineMessages(): boolean; - /** - * Get current messages position. - */ - position(): string; - } - - /** - * GrowlMessages service. - */ - interface IGrowlMessagesService { - /** - * Initialize a directive - * We look at the preloaded directive and use this else we - * create a new blank object - * @param referenceId - * @param limitMessages - */ - initDirective(referenceId: number, limitMessages: number): angular.IDirective; - - /** - * Get current messages - */ - getAllMessages(referenceId?: number): IGrowlMessage[]; - - /** - * Destroy all messages - */ - destroyAllMessages(referenceId?: number): void; - - /** - * Add a message - */ - addMessage(message: IGrowlMessage): IGrowlMessage; - - /** - * Delete a message - */ - deleteMessage(message: IGrowlMessage): void; - - } -} diff --git a/angular-growl-v2/index.d.ts b/angular-growl-v2/index.d.ts new file mode 100644 index 0000000000..4f1eeb16b8 --- /dev/null +++ b/angular-growl-v2/index.d.ts @@ -0,0 +1,259 @@ +// Type definitions for Angular Growl 2 v.0.7.5 +// Project: http://janstevens.github.io/angular-growl-2 +// Definitions by: Tadeusz Hucal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.growl { + + /** + * Global Time-To-Leave configuration. + */ + interface IGrowlTTLConfig { + success?: number; + error?: number; + warning?: number; + info?: number; + } + + /** + * Custom configuration used in single message call. + */ + interface IGrowlMessageConfig { + title?: string; + ttl?: number; + disableCountDown?: boolean; + disableIcons?: boolean; + disableCloseButton?: boolean; + onclose?: Function; + onopen?: Function; + position?: string; + referenceId?: number; + translateMessage?: boolean; + variables?: { [variable: string]: any; }; + } + + /** + * Growl message with configuration. + */ + interface IGrowlMessage extends IGrowlMessageConfig { + text: string; + + /** + * Destroy the message. + */ + destroy(): void; + /** + * Update the message body. + * @param newText new message body + */ + setText(newText: string): void; + } + + /** + * Growl service provider. + */ + interface IGrowlProvider extends angular.IServiceProvider { + /** + * Pre-defined server error interceptor. + */ + serverMessagesInterceptor: (string|IHttpInterceptorFactory)[]; + + /** + * Set default TTL settings. + * @param ttl configuration of TTL for different type of message + */ + globalTimeToLive(ttl: IGrowlTTLConfig): IGrowlProvider; + /** + * Set default TTL settings. + * @param ttl ttl in milliseconds + */ + globalTimeToLive(ttl: number): IGrowlProvider; + /** + * Set default setting for disabling close button. + * @param disableCloseButton + */ + globalDisableCloseButton(disableCloseButton: boolean): IGrowlProvider; + /** + * Set default setting for disabling icons. + * @param disableIcons + */ + globalDisableIcons(disableIcons: boolean): IGrowlProvider; + /** + * Set reversing order of displaying new messages. + * @param reverseOrder + */ + globalReversedOrder(reverseOrder: boolean): IGrowlProvider; + /** + * Set default setting for displaying message disappear countdown. + * @param disableCountDown + */ + globalDisableCountDown(disableCountDown: boolean): IGrowlProvider; + /** + * Set default allowance for inline messages. + * @param inline + */ + globalInlineMessages(inline: boolean): IGrowlProvider; + /** + * Set default message position. + * @param position + */ + globalPosition(position: string): IGrowlProvider; + /** + * Enable/disable displaying only unique messages. + * @param onlyUniqueMessages + */ + onlyUniqueMessages(onlyUniqueMessages: boolean): IGrowlProvider; + + /** + * Set key where messages are stored (for http interceptor). + * @param messageVariableKey + */ + messagesKey(messageKey: string): IGrowlProvider; + /** + * Set key where message text is stored (for http interceptor). + * @param messageVariableKey + */ + messageTextKey(messageTextKey: string): IGrowlProvider; + /** + * Set key where title of message is stored (for http interceptor). + * @param messageVariableKey + */ + messageTitleKey(messageTitleKey: string): IGrowlProvider; + /** + * Set key where severity of message is stored (for http interceptor). + * @param messageVariableKey + */ + messageSeverityKey(messageSeverityKey: string): IGrowlProvider; + /** + * Set key where variables for message are stored (for http interceptor). + * @param messageVariableKey + */ + messageVariableKey(messageVariableKey: string): IGrowlProvider; + } + + /** + * Growl service. + */ + interface IGrowlService { + /** + * Show warning message. + * @param message text to display (or code for angular-translate) + */ + warning(message: string): IGrowlMessage; + /** + * Show warning message. + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + warning(message: string, config: IGrowlMessageConfig): IGrowlMessage; + + /** + * Show error message. + * @param message text to display (or code for angular-translate) + */ + error(message: string): IGrowlMessage; + /** + * Show error message. + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + error(message: string, config: IGrowlMessageConfig): IGrowlMessage; + + /** + * Show information message. + * @param message text to display (or code for angular-translate) + */ + info(message: string): IGrowlMessage; + /** + * Show information message. + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + info(message: string, config: IGrowlMessageConfig): IGrowlMessage; + + /** + * Show success message. + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + success(message: string): IGrowlMessage; + /** + * Show success message. + * @param message text to display (or code for angular-translate) + */ + success(message: string, config: IGrowlMessageConfig): IGrowlMessage; + + /** + * Show message (generic). + * @param message text to display (or code for angular-translate) + */ + general(message: string): IGrowlMessage; + /** + * Show message (generic). + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + general(message: string, config: IGrowlMessageConfig): IGrowlMessage; + /** + * Show message (generic). + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + * @param severity message severity (error, warning, success, info). + */ + general(message: string, config: IGrowlMessageConfig, severity: string): IGrowlMessage; + + /** + * Get current setting for displaying only unique messages. + */ + onlyUnique(): boolean; + /** + * Get current setting for reversing messages order. + */ + reverseOrder(): boolean; + /** + * Get current allowance for inline messages. + */ + inlineMessages(): boolean; + /** + * Get current messages position. + */ + position(): string; + } + + /** + * GrowlMessages service. + */ + interface IGrowlMessagesService { + /** + * Initialize a directive + * We look at the preloaded directive and use this else we + * create a new blank object + * @param referenceId + * @param limitMessages + */ + initDirective(referenceId: number, limitMessages: number): angular.IDirective; + + /** + * Get current messages + */ + getAllMessages(referenceId?: number): IGrowlMessage[]; + + /** + * Destroy all messages + */ + destroyAllMessages(referenceId?: number): void; + + /** + * Add a message + */ + addMessage(message: IGrowlMessage): IGrowlMessage; + + /** + * Delete a message + */ + deleteMessage(message: IGrowlMessage): void; + + } +} diff --git a/angular-growl-v2/tsconfig.json b/angular-growl-v2/tsconfig.json new file mode 100644 index 0000000000..b3c499263e --- /dev/null +++ b/angular-growl-v2/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-growl-v2-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-hotkeys/angular-hotkeys-tests.ts b/angular-hotkeys/angular-hotkeys-tests.ts index c683540a3a..098c84d710 100644 --- a/angular-hotkeys/angular-hotkeys-tests.ts +++ b/angular-hotkeys/angular-hotkeys-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + var scope: ng.IScope; var hotkeyProvider: ng.hotkeys.HotkeysProvider; diff --git a/angular-hotkeys/angular-hotkeys.d.ts b/angular-hotkeys/angular-hotkeys.d.ts deleted file mode 100644 index 407d1c7313..0000000000 --- a/angular-hotkeys/angular-hotkeys.d.ts +++ /dev/null @@ -1,50 +0,0 @@ -// Type definitions for angular-hotkeys -// Project: https://github.com/chieffancypants/angular-hotkeys -// Definitions by: Jason Zhao , Stefan Steinhart -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.hotkeys { - - interface HotkeysProvider { - template: string; - templateTitle:string; - includeCheatSheet: boolean; - cheatSheetHotkey: string; - cheatSheetDescription: string; - - add(combo: string|string[], callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array, persistent?: boolean): ng.hotkeys.Hotkey; - - add(combo: string|string[], description: string, callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array, persistent?: boolean): ng.hotkeys.Hotkey; - - add(hotkeyObj: ng.hotkeys.Hotkey): ng.hotkeys.Hotkey; - - bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProviderChained; - - del(combo: string|string[]): void; - - del(hotkeyObj: ng.hotkeys.Hotkey): void; - - get(combo: string|string[]): ng.hotkeys.Hotkey; - - toggleCheatSheet(): void; - - purgeHotkeys(): void; - } - - interface HotkeysProviderChained { - add(combo: string|string[], description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained; - - add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained; - } - - interface Hotkey { - combo: string|string[]; - description?: string; - callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void; - action?: string; - allowIn?: Array; - persistent?: boolean; - } -} diff --git a/angular-hotkeys/index.d.ts b/angular-hotkeys/index.d.ts new file mode 100644 index 0000000000..81bb773925 --- /dev/null +++ b/angular-hotkeys/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for angular-hotkeys +// Project: https://github.com/chieffancypants/angular-hotkeys +// Definitions by: Jason Zhao , Stefan Steinhart +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.hotkeys { + + interface HotkeysProvider { + template: string; + templateTitle:string; + includeCheatSheet: boolean; + cheatSheetHotkey: string; + cheatSheetDescription: string; + + add(combo: string|string[], callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array, persistent?: boolean): ng.hotkeys.Hotkey; + + add(combo: string|string[], description: string, callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array, persistent?: boolean): ng.hotkeys.Hotkey; + + add(hotkeyObj: ng.hotkeys.Hotkey): ng.hotkeys.Hotkey; + + bindTo(scope : ng.IScope): ng.hotkeys.HotkeysProviderChained; + + del(combo: string|string[]): void; + + del(hotkeyObj: ng.hotkeys.Hotkey): void; + + get(combo: string|string[]): ng.hotkeys.Hotkey; + + toggleCheatSheet(): void; + + purgeHotkeys(): void; + } + + interface HotkeysProviderChained { + add(combo: string|string[], description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained; + + add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained; + } + + interface Hotkey { + combo: string|string[]; + description?: string; + callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void; + action?: string; + allowIn?: Array; + persistent?: boolean; + } +} diff --git a/angular-hotkeys/tsconfig.json b/angular-hotkeys/tsconfig.json new file mode 100644 index 0000000000..879a86030b --- /dev/null +++ b/angular-hotkeys/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-hotkeys-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-http-auth/angular-http-auth-tests.ts b/angular-http-auth/angular-http-auth-tests.ts index 4d246d1907..e27c0199c5 100644 --- a/angular-http-auth/angular-http-auth-tests.ts +++ b/angular-http-auth/angular-http-auth-tests.ts @@ -1,4 +1,4 @@ -/// + (function () { 'use strict'; diff --git a/angular-http-auth/angular-http-auth.d.ts b/angular-http-auth/angular-http-auth.d.ts deleted file mode 100644 index d5fb52fd6c..0000000000 --- a/angular-http-auth/angular-http-auth.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Type definitions for angular-http-auth 1.2.1 -// Project: https://github.com/witoldsz/angular-http-auth -// Definitions by: vvakame -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.httpAuth { - interface IAuthService { - loginConfirmed(data?:any, configUpdater?:Function):void; - loginCancelled(data?:any, reason?:any):void; - } - - interface IHttpBuffer { - append(config:ng.IRequestConfig, deferred:{resolve(data:any):void; reject(data:any):void;}):void; - rejectAll(reason?:any):void; - retryAll(updater?:Function):void; - } -} diff --git a/angular-http-auth/index.d.ts b/angular-http-auth/index.d.ts new file mode 100644 index 0000000000..4918c5f4df --- /dev/null +++ b/angular-http-auth/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for angular-http-auth 1.2.1 +// Project: https://github.com/witoldsz/angular-http-auth +// Definitions by: vvakame +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.httpAuth { + interface IAuthService { + loginConfirmed(data?:any, configUpdater?:Function):void; + loginCancelled(data?:any, reason?:any):void; + } + + interface IHttpBuffer { + append(config:ng.IRequestConfig, deferred:{resolve(data:any):void; reject(data:any):void;}):void; + rejectAll(reason?:any):void; + retryAll(updater?:Function):void; + } +} diff --git a/angular-http-auth/tsconfig.json b/angular-http-auth/tsconfig.json new file mode 100644 index 0000000000..0085a9e38a --- /dev/null +++ b/angular-http-auth/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-http-auth-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-httpi/angular-httpi-tests.ts b/angular-httpi/angular-httpi-tests.ts index 47ac25228c..ff3caa0537 100644 --- a/angular-httpi/angular-httpi-tests.ts +++ b/angular-httpi/angular-httpi-tests.ts @@ -1,4 +1,4 @@ -/// + (function() { 'use strict'; diff --git a/angular-httpi/angular-httpi.d.ts b/angular-httpi/angular-httpi.d.ts deleted file mode 100644 index d9aa2b5609..0000000000 --- a/angular-httpi/angular-httpi.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -// Type definitions for angular-httpi -// Project: https://github.com/bennadel/httpi -// Definitions by: Andrew Camilleri -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Httpi { - export interface HttpiPayload extends ng.IRequestShortcutConfig { - method?: string; - url?: string; - params?: {}; - data?: {}; - keepTrailingSlash?: boolean; - } - - export interface HttpiFactory { - - (config: HttpiPayload): ng.IHttpPromise<{}>; - - resource(url: string): HttpiResource; - } - - export class HttpiResource { - - constructor(http: ng.IHttpService, url: string); - - delete(config: HttpiPayload): ng.IHttpPromise; - - get(config: HttpiPayload): ng.IHttpPromise; - - head(config: HttpiPayload): ng.IHttpPromise; - - jsonp(config: HttpiPayload): ng.IHttpPromise; - - post(config: HttpiPayload): ng.IHttpPromise; - - put(config: HttpiPayload): ng.IHttpPromise; - - setKeepTrailingSlash(newKeepTrailingSlash: boolean): HttpiResource; - } -} diff --git a/angular-httpi/index.d.ts b/angular-httpi/index.d.ts new file mode 100644 index 0000000000..f41fd76382 --- /dev/null +++ b/angular-httpi/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for angular-httpi +// Project: https://github.com/bennadel/httpi +// Definitions by: Andrew Camilleri +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace Httpi { + export interface HttpiPayload extends ng.IRequestShortcutConfig { + method?: string; + url?: string; + params?: {}; + data?: {}; + keepTrailingSlash?: boolean; + } + + export interface HttpiFactory { + + (config: HttpiPayload): ng.IHttpPromise<{}>; + + resource(url: string): HttpiResource; + } + + export class HttpiResource { + + constructor(http: ng.IHttpService, url: string); + + delete(config: HttpiPayload): ng.IHttpPromise; + + get(config: HttpiPayload): ng.IHttpPromise; + + head(config: HttpiPayload): ng.IHttpPromise; + + jsonp(config: HttpiPayload): ng.IHttpPromise; + + post(config: HttpiPayload): ng.IHttpPromise; + + put(config: HttpiPayload): ng.IHttpPromise; + + setKeepTrailingSlash(newKeepTrailingSlash: boolean): HttpiResource; + } +} diff --git a/angular-httpi/tsconfig.json b/angular-httpi/tsconfig.json new file mode 100644 index 0000000000..5d635609b7 --- /dev/null +++ b/angular-httpi/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-httpi-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-idle/angular-idle-tests.ts b/angular-idle/angular-idle-tests.ts index e6eb1a9f29..9f13f828a9 100644 --- a/angular-idle/angular-idle-tests.ts +++ b/angular-idle/angular-idle-tests.ts @@ -1,4 +1,4 @@ -/// + angular.module('app', ['ngIdle']) .config(['KeepaliveProvider', 'IdleProvider', 'TitleProvider', diff --git a/angular-idle/angular-idle.d.ts b/angular-idle/angular-idle.d.ts deleted file mode 100644 index 0a980204cb..0000000000 --- a/angular-idle/angular-idle.d.ts +++ /dev/null @@ -1,263 +0,0 @@ -// Type definitions for ng-idle v1.1.1 -// Project: http://hackedbychinese.github.io/ng-idle/ -// Definitions by: mthamil -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.idle { - - /** - * Used to configure the Title service. - */ - interface ITitleProvider extends IServiceProvider { - - /** - * Enables or disables the Title functionality. - * - * @param enabled Boolean, default is true. - */ - enabled(enabled: boolean): void; - } - - interface ITitleService { - - /** - * Allows the title functionality to be enabled or disabled on the fly. - */ - setEnabled(enabled: boolean): void; - - /** - * Returns whether or not the title functionality has been enabled. - */ - isEnabled(): boolean; - - /** - * Will store val as the "original" title of the document. - * - * Tracking the original title is important when restoring the title after displaying, for example, the idle warning message. - */ - original(val: string): void; - - /** - * Returns the "original" title value that has been previously set. - * - * Tracking the original title is important when restoring the title after displaying, for example, the idle warning message. - */ - original(): string; - - /** - * Changes the actual title of the document. - */ - value(val: string): void; - - /** - * Returns the current document title. - */ - value(): string; - - /** - * If overwrite is false or unspecified, updates the "original" title with the current document title - * if it has not already been stored. If overwrite is true, the current document title is stored regardless. - */ - store(overwrite?: boolean): void; - - /** - * Sets the title to the original value (if it was stored or set previously). - */ - restore(): void; - - /** - * Sets the text to use as the message displayed when the user is idle. - */ - idleMessage(val: string): void; - - /** - * Gets the text to use as the message displayed when the user is idle. - */ - idleMessage(): string; - - /** - * Sets the text to use as the message displayed when the user is timed out. - */ - timedOutMessage(val: string): void; - - /** - * Gets the text to use as the message displayed when the user is timed out. - */ - timedOutMessage(): string; - - /** - * Stores the original title if it hasn't been already, determines the number minutes, seconds, - * and total seconds from countdown, and displays the idleMessage with the aforementioned values interpolated. - */ - setAsIdle(countdown: number): void; - - /** - * Stores the original title if it hasn't been already, and displays the timedOutMessage. - */ - setAsTimedOut(): void; - } - - /** - * Used to configure the Keepalive service. - */ - interface IKeepAliveProvider extends IServiceProvider { - - /** - * If configured, options will be used to issue a request using $http. - * If the value is null, no HTTP request will be issued. - * You can specify a string, which it will assume to be a URL to a simple GET request. - * Otherwise, you can use the same options $http takes. However, cache will always be false. - * - * @param value May be string or IRequestConfig, default is null. - */ - http(value: string | IRequestConfig): void; - - /** - * This specifies how often the keepalive event is triggered and the - * HTTP request is issued. - * - * @param seconds Integer, default is 10 minutes. Must be greater than 0. - */ - interval(seconds: number): void; - } - - /** - * Keepalive will use a timeout to periodically wake, broadcast a Keepalive event on the root scope, - * and optionally make an $http request. By default, the Idle service will stop and start Keepalive - * when a user becomes idle or returns from idle, respectively. It is also started automatically when - * Idle.watch() is called. This can be disabled by configuring the IdleProvider. - */ - interface IKeepAliveService { - - /** - * Starts pinging periodically until stop() is called. - */ - start(): void; - - /** - * Stops pinging. - */ - stop(): void; - - /** - * Performs one ping only. - */ - ping(): void; - - /** - * Changes the interval value at runtime. - * You will need to restart the pinging process by calling start() manually for the changes to be reflected. - */ - setInterval(seconds: number): void; - } - - /** - * Used to configure the Idle service. - */ - interface IIdleProvider extends IServiceProvider { - /** - * Specifies the DOM events the service will watch to reset the idle timeout. - * Multiple events should be separated by a space. - * - * @param events string, default 'mousemove keydown DOMMouseScroll mousewheel mousedown' - */ - interrupt(events: string): void; - - /** - * The idle timeout duration in seconds. After this amount of time passes without the user - * performing an action that triggers one of the watched DOM events, the user is considered - * idle. - * - * @param seconds integer, default is 20min - */ - idle(seconds: number): void; - - /** - * The amount of time the user has to respond (in seconds) before they have been considered - * timed out. - * - * @param seconds integer, default is 30s - */ - timeout(seconds: number): void; - - /** - * When true or idle, user activity will automatically interrupt the warning countdown - * and reset the idle state. If false or off, you will need to manually call watch() - * when you want to start watching for idleness again. If notIdle, user activity will - * only automatically interrupt if the user is not yet idle. - * - * @param enabled boolean or string, possible values: off/false, idle/true, or notIdle - */ - autoResume(enabled: boolean | string): void; - - /** - * When true, the Keepalive service is automatically stopped and started as needed. - * - * @param enabled boolean, default is true - */ - keepalive(enabled: boolean): void; - } - - /** - * Idle, once watch() is called, will start a timeout which if expires, will enter a warning state - * countdown. Once the countdown reaches zero, idle will broadcast a timeout event indicating the - * user has timed out (where your app should log them out or whatever you like). If the user performs - * an action that triggers a watched DOM event that bubbles up to document.body, this will reset the - * idle/warning state and start the process over again. - */ - interface IIdleService { - /** - * Gets the current idle value - */ - getIdle(): number; - - /** - * Gets the current timeout value - */ - getTimeout(): number; - - /** - * Updates the idle value (see IdleProvider.idle()) and - * restarts the watch if its running. - */ - setIdle(idle: number): void; - - /** - * Updates the timeout value (see IdleProvider.timeout()) and - * restarts the watch if its running. - */ - setTimeout(timeout: number): void; - - /** - * Whether user has timed out (meaning idleDuration + timeout has passed without any activity) - */ - isExpired(): boolean; - - /** - * Whether or not the watch() has been called and it is watching for idleness. - */ - running(): boolean; - - /** - * Whether or not the user appears to be idle. - */ - idling(): boolean; - - /** - * Starts watching for idleness, or resets the idle/warning state and continues watching. - */ - watch(): void; - - /** - * Stops watching for idleness, and resets the idle/warning state. - */ - unwatch(): void; - - /** - * Manually trigger the idle interrupt that normally occurs during user activity. - */ - interrupt(): any; - } -} diff --git a/angular-idle/index.d.ts b/angular-idle/index.d.ts new file mode 100644 index 0000000000..2e1d132708 --- /dev/null +++ b/angular-idle/index.d.ts @@ -0,0 +1,263 @@ +// Type definitions for ng-idle v1.1.1 +// Project: http://hackedbychinese.github.io/ng-idle/ +// Definitions by: mthamil +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.idle { + + /** + * Used to configure the Title service. + */ + interface ITitleProvider extends IServiceProvider { + + /** + * Enables or disables the Title functionality. + * + * @param enabled Boolean, default is true. + */ + enabled(enabled: boolean): void; + } + + interface ITitleService { + + /** + * Allows the title functionality to be enabled or disabled on the fly. + */ + setEnabled(enabled: boolean): void; + + /** + * Returns whether or not the title functionality has been enabled. + */ + isEnabled(): boolean; + + /** + * Will store val as the "original" title of the document. + * + * Tracking the original title is important when restoring the title after displaying, for example, the idle warning message. + */ + original(val: string): void; + + /** + * Returns the "original" title value that has been previously set. + * + * Tracking the original title is important when restoring the title after displaying, for example, the idle warning message. + */ + original(): string; + + /** + * Changes the actual title of the document. + */ + value(val: string): void; + + /** + * Returns the current document title. + */ + value(): string; + + /** + * If overwrite is false or unspecified, updates the "original" title with the current document title + * if it has not already been stored. If overwrite is true, the current document title is stored regardless. + */ + store(overwrite?: boolean): void; + + /** + * Sets the title to the original value (if it was stored or set previously). + */ + restore(): void; + + /** + * Sets the text to use as the message displayed when the user is idle. + */ + idleMessage(val: string): void; + + /** + * Gets the text to use as the message displayed when the user is idle. + */ + idleMessage(): string; + + /** + * Sets the text to use as the message displayed when the user is timed out. + */ + timedOutMessage(val: string): void; + + /** + * Gets the text to use as the message displayed when the user is timed out. + */ + timedOutMessage(): string; + + /** + * Stores the original title if it hasn't been already, determines the number minutes, seconds, + * and total seconds from countdown, and displays the idleMessage with the aforementioned values interpolated. + */ + setAsIdle(countdown: number): void; + + /** + * Stores the original title if it hasn't been already, and displays the timedOutMessage. + */ + setAsTimedOut(): void; + } + + /** + * Used to configure the Keepalive service. + */ + interface IKeepAliveProvider extends IServiceProvider { + + /** + * If configured, options will be used to issue a request using $http. + * If the value is null, no HTTP request will be issued. + * You can specify a string, which it will assume to be a URL to a simple GET request. + * Otherwise, you can use the same options $http takes. However, cache will always be false. + * + * @param value May be string or IRequestConfig, default is null. + */ + http(value: string | IRequestConfig): void; + + /** + * This specifies how often the keepalive event is triggered and the + * HTTP request is issued. + * + * @param seconds Integer, default is 10 minutes. Must be greater than 0. + */ + interval(seconds: number): void; + } + + /** + * Keepalive will use a timeout to periodically wake, broadcast a Keepalive event on the root scope, + * and optionally make an $http request. By default, the Idle service will stop and start Keepalive + * when a user becomes idle or returns from idle, respectively. It is also started automatically when + * Idle.watch() is called. This can be disabled by configuring the IdleProvider. + */ + interface IKeepAliveService { + + /** + * Starts pinging periodically until stop() is called. + */ + start(): void; + + /** + * Stops pinging. + */ + stop(): void; + + /** + * Performs one ping only. + */ + ping(): void; + + /** + * Changes the interval value at runtime. + * You will need to restart the pinging process by calling start() manually for the changes to be reflected. + */ + setInterval(seconds: number): void; + } + + /** + * Used to configure the Idle service. + */ + interface IIdleProvider extends IServiceProvider { + /** + * Specifies the DOM events the service will watch to reset the idle timeout. + * Multiple events should be separated by a space. + * + * @param events string, default 'mousemove keydown DOMMouseScroll mousewheel mousedown' + */ + interrupt(events: string): void; + + /** + * The idle timeout duration in seconds. After this amount of time passes without the user + * performing an action that triggers one of the watched DOM events, the user is considered + * idle. + * + * @param seconds integer, default is 20min + */ + idle(seconds: number): void; + + /** + * The amount of time the user has to respond (in seconds) before they have been considered + * timed out. + * + * @param seconds integer, default is 30s + */ + timeout(seconds: number): void; + + /** + * When true or idle, user activity will automatically interrupt the warning countdown + * and reset the idle state. If false or off, you will need to manually call watch() + * when you want to start watching for idleness again. If notIdle, user activity will + * only automatically interrupt if the user is not yet idle. + * + * @param enabled boolean or string, possible values: off/false, idle/true, or notIdle + */ + autoResume(enabled: boolean | string): void; + + /** + * When true, the Keepalive service is automatically stopped and started as needed. + * + * @param enabled boolean, default is true + */ + keepalive(enabled: boolean): void; + } + + /** + * Idle, once watch() is called, will start a timeout which if expires, will enter a warning state + * countdown. Once the countdown reaches zero, idle will broadcast a timeout event indicating the + * user has timed out (where your app should log them out or whatever you like). If the user performs + * an action that triggers a watched DOM event that bubbles up to document.body, this will reset the + * idle/warning state and start the process over again. + */ + interface IIdleService { + /** + * Gets the current idle value + */ + getIdle(): number; + + /** + * Gets the current timeout value + */ + getTimeout(): number; + + /** + * Updates the idle value (see IdleProvider.idle()) and + * restarts the watch if its running. + */ + setIdle(idle: number): void; + + /** + * Updates the timeout value (see IdleProvider.timeout()) and + * restarts the watch if its running. + */ + setTimeout(timeout: number): void; + + /** + * Whether user has timed out (meaning idleDuration + timeout has passed without any activity) + */ + isExpired(): boolean; + + /** + * Whether or not the watch() has been called and it is watching for idleness. + */ + running(): boolean; + + /** + * Whether or not the user appears to be idle. + */ + idling(): boolean; + + /** + * Starts watching for idleness, or resets the idle/warning state and continues watching. + */ + watch(): void; + + /** + * Stops watching for idleness, and resets the idle/warning state. + */ + unwatch(): void; + + /** + * Manually trigger the idle interrupt that normally occurs during user activity. + */ + interrupt(): any; + } +} diff --git a/angular-idle/tsconfig.json b/angular-idle/tsconfig.json new file mode 100644 index 0000000000..a39a59b57f --- /dev/null +++ b/angular-idle/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-idle-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-jwt/angular-jwt-tests.ts b/angular-jwt/angular-jwt-tests.ts index 7f66f26114..a959992dfc 100644 --- a/angular-jwt/angular-jwt-tests.ts +++ b/angular-jwt/angular-jwt-tests.ts @@ -1,16 +1,16 @@ -/// -/// +/// + var app = angular.module("angular-jwt-tests", ["angular-jwt"]); -var $jwtHelper: angular.jwt.IJwtHelper; +var $jwtHelper: ng.jwt.IJwtHelper; var expToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NhbXBsZXMuYXV0aDAuY29tLyIsInN1YiI6ImZhY2Vib29rfDEwMTU0Mjg3MDI3NTEwMzAyIiwiYXVkIjoiQlVJSlNXOXg2MHNJSEJ3OEtkOUVtQ2JqOGVESUZ4REMiLCJleHAiOjE0MTIyMzQ3MzAsImlhdCI6MTQxMjE5ODczMH0.7M5sAV50fF1-_h9qVbdSgqAnXVF7mz3I6RjS6JiH0H8'; var tokenPayload = $jwtHelper.decodeToken(expToken); var date = $jwtHelper.getTokenExpirationDate(expToken); var bool = $jwtHelper.isTokenExpired(expToken); -var $jwtInterceptor: angular.jwt.IJwtInterceptor; +var $jwtInterceptor: ng.jwt.IJwtInterceptor; $jwtInterceptor.tokenGetter = () => { return expToken; diff --git a/angular-jwt/angular-jwt.d.ts b/angular-jwt/angular-jwt.d.ts deleted file mode 100644 index d8c719e2ef..0000000000 --- a/angular-jwt/angular-jwt.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Type definitions for angular-jwt 0.0.8 -// Project: https://github.com/auth0/angular-jwt -// Definitions by: Reto Rezzonico -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.jwt { - - interface JwtToken { - iss: string; - sub: string; - aud: string; - exp: number; - nbf: number; - iat: number; - jti: string; - unique_name: string; - } - - interface IJwtHelper { - decodeToken(token: string): JwtToken; - getTokenExpirationDate(token: any): Date; - isTokenExpired(token: any, offsetSeconds?: number): boolean; - } - - interface IJwtInterceptor { - tokenGetter(...params : any[]): string; - } -} diff --git a/angular-jwt/index.d.ts b/angular-jwt/index.d.ts new file mode 100644 index 0000000000..49247b2490 --- /dev/null +++ b/angular-jwt/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for angular-jwt 0.0.8 +// Project: https://github.com/auth0/angular-jwt +// Definitions by: Reto Rezzonico +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.jwt { + + interface JwtToken { + iss?: string; + sub?: string; + aud?: string; + exp?: number; + nbf?: number; + iat?: number; + jti?: string; + unique_name?: string; + } + + interface IJwtHelper { + decodeToken(token: string): JwtToken; + getTokenExpirationDate(token: any): Date; + isTokenExpired(token: any, offsetSeconds?: number): boolean; + } + + interface IJwtInterceptor { + tokenGetter(...params : any[]): string; + } +} diff --git a/angular-jwt/tsconfig.json b/angular-jwt/tsconfig.json new file mode 100644 index 0000000000..139ae337b7 --- /dev/null +++ b/angular-jwt/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-jwt-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-load/angular-load-tests.ts b/angular-load/angular-load-tests.ts index 7fea2d7924..ffb30dd4a7 100644 --- a/angular-load/angular-load-tests.ts +++ b/angular-load/angular-load-tests.ts @@ -1,4 +1,4 @@ -/// + angular.module('app',['angularLoad']) .run(['angularLoad',(angularLoad:angular.load.IAngularLoadService)=> { diff --git a/angular-load/angular-load.d.ts b/angular-load/angular-load.d.ts deleted file mode 100644 index cd806c31f3..0000000000 --- a/angular-load/angular-load.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Type definitions for angular-load v0.4.1 -// Project: https://github.com/urish/angular-load -// Definitions by: david-gang -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.load { - - interface IAngularLoadService { - loadScript(url:string): ng.IPromise; - loadCSS(url:string): ng.IPromise; - } - -} diff --git a/angular-load/index.d.ts b/angular-load/index.d.ts new file mode 100644 index 0000000000..14db33b816 --- /dev/null +++ b/angular-load/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for angular-load v0.4.1 +// Project: https://github.com/urish/angular-load +// Definitions by: david-gang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.load { + + interface IAngularLoadService { + loadScript(url:string): ng.IPromise; + loadCSS(url:string): ng.IPromise; + } + +} diff --git a/angular-load/tsconfig.json b/angular-load/tsconfig.json new file mode 100644 index 0000000000..74f2f6d253 --- /dev/null +++ b/angular-load/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-load-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-loading-bar/angular-loading-bar-tests.ts b/angular-loading-bar/angular-loading-bar-tests.ts index b8bde9e933..15435381f9 100644 --- a/angular-loading-bar/angular-loading-bar-tests.ts +++ b/angular-loading-bar/angular-loading-bar-tests.ts @@ -1,4 +1,4 @@ -/// + var app = angular.module('testModule', ['angular-loading-bar']); diff --git a/angular-loading-bar/angular-loading-bar.d.ts b/angular-loading-bar/angular-loading-bar.d.ts deleted file mode 100644 index 22a00f9ee7..0000000000 --- a/angular-loading-bar/angular-loading-bar.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Type definitions for angular-loading-bar -// Project: https://github.com/chieffancypants/angular-loading-bar -// Definitions by: Stephen Lautier -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - - -declare namespace angular { - - interface IRequestShortcutConfig { - /** - * Indicates that the loading bar should be hidden. - */ - ignoreLoadingBar?: boolean; - } -} - -declare namespace angular.loadingBar { - - interface ILoadingBarProvider{ - /** - * Turn the spinner on or off - */ - includeSpinner?: boolean; - - /** - * Turn the loading bar on or off - */ - includeBar?: boolean; - - /** - * HTML template - */ - spinnerTemplate?: string; - - /** - * Latency Threshold - */ - latencyThreshold?: number; - } - -} diff --git a/angular-loading-bar/index.d.ts b/angular-loading-bar/index.d.ts new file mode 100644 index 0000000000..3adca41eba --- /dev/null +++ b/angular-loading-bar/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for angular-loading-bar +// Project: https://github.com/chieffancypants/angular-loading-bar +// Definitions by: Stephen Lautier +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +declare namespace angular { + + interface IRequestShortcutConfig { + /** + * Indicates that the loading bar should be hidden. + */ + ignoreLoadingBar?: boolean; + } +} + +declare namespace angular.loadingBar { + + interface ILoadingBarProvider{ + /** + * Turn the spinner on or off + */ + includeSpinner?: boolean; + + /** + * Turn the loading bar on or off + */ + includeBar?: boolean; + + /** + * HTML template + */ + spinnerTemplate?: string; + + /** + * Latency Threshold + */ + latencyThreshold?: number; + } + +} diff --git a/angular-loading-bar/tsconfig.json b/angular-loading-bar/tsconfig.json new file mode 100644 index 0000000000..eef6c4a914 --- /dev/null +++ b/angular-loading-bar/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-loading-bar-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-local-storage/angular-local-storage-tests.ts b/angular-local-storage/angular-local-storage-tests.ts index 230a32dce1..439de2caff 100644 --- a/angular-local-storage/angular-local-storage-tests.ts +++ b/angular-local-storage/angular-local-storage-tests.ts @@ -1,6 +1,3 @@ -/// -/// - interface TestScope extends ng.IScope { submit: (key: string, value: string) => boolean; getItem: (key: string) => string; diff --git a/angular-local-storage/angular-local-storage.d.ts b/angular-local-storage/angular-local-storage.d.ts deleted file mode 100644 index b2bcf377d2..0000000000 --- a/angular-local-storage/angular-local-storage.d.ts +++ /dev/null @@ -1,149 +0,0 @@ -// Type definitions for angular-local-storage v0.1.5 -// Project: https://github.com/grevory/angular-local-storage -// Definitions by: Ken Fukuyama -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.local.storage { - interface ILocalStorageServiceProvider extends angular.IServiceProvider { - /** - * Setter for the prefix - * You should set a prefix to avoid overwriting any local storage variables from the rest of your app - * e.g. localStorageServiceProvider.setPrefix('youAppName'); - * With provider you can use config as this: - * myApp.config(function (localStorageServiceProvider) { - * localStorageServiceProvider.prefix = 'yourAppName'; - * }); - * @param prefix default: ls. - */ - setPrefix(prefix: string):ILocalStorageServiceProvider; - /** - * Setter for the storageType - * @param storageType localstorage or sessionStorage. default: localStorage - */ - setStorageType(storageType: string):ILocalStorageServiceProvider; - /** - * Setter for cookie config - * @param exp number of days before cookies expire (0 = does not expire). default: 30 - * @param path the web path the cookie represents. default: '/' - */ - setStorageCookie(exp: number, path: string):ILocalStorageServiceProvider; - /** - * Set the cookie domain, since this runs inside a the config() block, only providers and constants can be injected. As a result, $location service can't be used here, use a hardcoded string or window.location. - * No default value - */ - setStorageCookieDomain(domain: string):ILocalStorageServiceProvider; - /** - * Send signals for each of the following actions: - * @param setItem default: true - * @param removeItem default: false - */ - setNotify(setItem: boolean, removeItem: boolean):ILocalStorageServiceProvider; - } - - interface ICookie { - /** - * Checks if cookies are enabled in the browser. - * Returns: Boolean - */ - isSupported:boolean; - /** - * Directly adds a value to cookies. - * Note: Typically used as a fallback if local storage is not supported. - * Returns: Boolean - * @param key - * @param val - */ - set(key:string, val:string):boolean; - /** - * Directly get a value from a cookie. - * Returns: value from local storage - * @param key - */ - get(key:string):string; - /** - * Remove directly value from a cookie. - * Returns: Boolean - * @param key - */ - remove(key:string):boolean; - /** - * Remove all data for this app from cookie. - */ - clearAll():any; - - } - - interface ILocalStorageService { - /** - * Checks if the browser support the current storage type(e.g: localStorage, sessionStorage). - * Returns: Boolean - */ - isSupported:boolean; - /** - * Returns: String - */ - getStorageType():string; - /** - * Directly adds a value to local storage. - * If local storage is not supported, use cookies instead. - * Returns: Boolean - * @param key - * @param value - */ - set(key: string, value: T): boolean; - /** - * Directly get a value from local storage. - * If local storage is not supported, use cookies instead. - * Returns: value from local storage - * @param key - */ - get(key: string): T; - /** - * Return array of keys for local storage, ignore keys that not owned. - * Returns: value from local storage - */ - keys(): string[]; - /** - * Remove an item from local storage by key. - * If local storage is not supported, use cookies instead. - * Returns: Boolean - * @param key - */ - remove(key: string): boolean; - /** - * Remove all data for this app from local storage. - * If local storage is not supported, use cookies instead. - * Note: Optionally takes a regular expression string and removes matching. - * Returns: Boolean - * @param regularExpression - */ - clearAll(regularExpression?:RegExp):boolean; - /** - * Bind $scope key to localStorageService. - * Usage: localStorageService.bind(scope, property, value[optional], key[optional]) - * Returns: deregistration function for this listener. - * @param scope - * @param property - * @param value optional - * @param key The corresponding key used in local storage - */ - bind(scope: angular.IScope, property: string, value?: any, key?: string): Function; - /** - * Return the derive key - * Returns String - * @param key - */ - deriveKey(key:string):string; - /** - * Return localStorageService.length, ignore keys that not owned. - * Returns Number - */ - length():number; - /** - * Deal with browser's cookies directly. - */ - cookie:ICookie; - } -} diff --git a/angular-local-storage/index.d.ts b/angular-local-storage/index.d.ts new file mode 100644 index 0000000000..beb4208901 --- /dev/null +++ b/angular-local-storage/index.d.ts @@ -0,0 +1,149 @@ +// Type definitions for angular-local-storage v0.1.5 +// Project: https://github.com/grevory/angular-local-storage +// Definitions by: Ken Fukuyama +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.local.storage { + interface ILocalStorageServiceProvider extends angular.IServiceProvider { + /** + * Setter for the prefix + * You should set a prefix to avoid overwriting any local storage variables from the rest of your app + * e.g. localStorageServiceProvider.setPrefix('youAppName'); + * With provider you can use config as this: + * myApp.config(function (localStorageServiceProvider) { + * localStorageServiceProvider.prefix = 'yourAppName'; + * }); + * @param prefix default: ls. + */ + setPrefix(prefix: string):ILocalStorageServiceProvider; + /** + * Setter for the storageType + * @param storageType localstorage or sessionStorage. default: localStorage + */ + setStorageType(storageType: string):ILocalStorageServiceProvider; + /** + * Setter for cookie config + * @param exp number of days before cookies expire (0 = does not expire). default: 30 + * @param path the web path the cookie represents. default: '/' + */ + setStorageCookie(exp: number, path: string):ILocalStorageServiceProvider; + /** + * Set the cookie domain, since this runs inside a the config() block, only providers and constants can be injected. As a result, $location service can't be used here, use a hardcoded string or window.location. + * No default value + */ + setStorageCookieDomain(domain: string):ILocalStorageServiceProvider; + /** + * Send signals for each of the following actions: + * @param setItem default: true + * @param removeItem default: false + */ + setNotify(setItem: boolean, removeItem: boolean):ILocalStorageServiceProvider; + } + + interface ICookie { + /** + * Checks if cookies are enabled in the browser. + * Returns: Boolean + */ + isSupported:boolean; + /** + * Directly adds a value to cookies. + * Note: Typically used as a fallback if local storage is not supported. + * Returns: Boolean + * @param key + * @param val + */ + set(key:string, val:string):boolean; + /** + * Directly get a value from a cookie. + * Returns: value from local storage + * @param key + */ + get(key:string):string; + /** + * Remove directly value from a cookie. + * Returns: Boolean + * @param key + */ + remove(key:string):boolean; + /** + * Remove all data for this app from cookie. + */ + clearAll():any; + + } + + interface ILocalStorageService { + /** + * Checks if the browser support the current storage type(e.g: localStorage, sessionStorage). + * Returns: Boolean + */ + isSupported:boolean; + /** + * Returns: String + */ + getStorageType():string; + /** + * Directly adds a value to local storage. + * If local storage is not supported, use cookies instead. + * Returns: Boolean + * @param key + * @param value + */ + set(key: string, value: T): boolean; + /** + * Directly get a value from local storage. + * If local storage is not supported, use cookies instead. + * Returns: value from local storage + * @param key + */ + get(key: string): T; + /** + * Return array of keys for local storage, ignore keys that not owned. + * Returns: value from local storage + */ + keys(): string[]; + /** + * Remove an item from local storage by key. + * If local storage is not supported, use cookies instead. + * Returns: Boolean + * @param key + */ + remove(key: string): boolean; + /** + * Remove all data for this app from local storage. + * If local storage is not supported, use cookies instead. + * Note: Optionally takes a regular expression string and removes matching. + * Returns: Boolean + * @param regularExpression + */ + clearAll(regularExpression?:RegExp):boolean; + /** + * Bind $scope key to localStorageService. + * Usage: localStorageService.bind(scope, property, value[optional], key[optional]) + * Returns: deregistration function for this listener. + * @param scope + * @param property + * @param value optional + * @param key The corresponding key used in local storage + */ + bind(scope: angular.IScope, property: string, value?: any, key?: string): Function; + /** + * Return the derive key + * Returns String + * @param key + */ + deriveKey(key:string):string; + /** + * Return localStorageService.length, ignore keys that not owned. + * Returns Number + */ + length():number; + /** + * Deal with browser's cookies directly. + */ + cookie:ICookie; + } +} diff --git a/angular-local-storage/tsconfig.json b/angular-local-storage/tsconfig.json new file mode 100644 index 0000000000..60ebcbca49 --- /dev/null +++ b/angular-local-storage/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-local-storage-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-localForage/angular-localForage-tests.ts b/angular-localForage/angular-localForage-tests.ts index 3ea776ebf8..8f917f5ca6 100644 --- a/angular-localForage/angular-localForage-tests.ts +++ b/angular-localForage/angular-localForage-tests.ts @@ -1,6 +1,3 @@ -/// -/// - var app = angular.module('angular-localForage-tests', ['LocalForageModule']); app.config(function (localStorageServiceProvider:angular.localForage.ILocalForageProvider) { diff --git a/angular-localForage/angular-localForage.d.ts b/angular-localForage/angular-localForage.d.ts deleted file mode 100644 index edc4ca268d..0000000000 --- a/angular-localForage/angular-localForage.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -// Type definitions for angular-localForage 1.2.2 -// Project: https://github.com/ocombe/angular-localForage -// Definitions by: Stefan Steinhart -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare namespace angular.localForage { - - interface LocalForageConfig { - driver?:string; - name?:string | number; - version?:number; - storeName?:string; - description?:string; - } - - interface ILocalForageProvider { - config(config:LocalForageConfig):void; - setNotify(onItemSet:boolean, onItemRemove:boolean):void; - } - - interface ILocalForageService { - driver(): LocalForageDriver; - setDriver(name: string | string[]): angular.IPromise; - - setItem(key:string, value:any):angular.IPromise; - setItem(keys:Array, values:Array):angular.IPromise; - - getItem(key:string):angular.IPromise; - getItem(keys:Array):angular.IPromise>; - - removeItem(key:string | Array):angular.IPromise; - - pull(key:string):angular.IPromise; - pull(keys:Array):angular.IPromise>; - - clear():angular.IPromise; - - key(n:number):angular.IPromise; - - keys():angular.IPromise; - - length():angular.IPromise; - - iterate(iteratorCallback:(value:string | number, key:string)=>T):angular.IPromise; - - bind($scope:ng.IScope, key:string):angular.IPromise; - - bind($scope:ng.IScope, config:{ - key:string; - defaultValue?:any; - scopeKey?:string; - name?:string; - }):angular.IPromise; - - unbind($scope:ng.IScope, key:string, scopeKey?:string):void; - - createInstance(config:LocalForageConfig):ILocalForageService; - instance(name:string):ILocalForageService; - } -} diff --git a/angular-localForage/index.d.ts b/angular-localForage/index.d.ts new file mode 100644 index 0000000000..87d16c96f4 --- /dev/null +++ b/angular-localForage/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for angular-localForage 1.2.2 +// Project: https://github.com/ocombe/angular-localForage +// Definitions by: Stefan Steinhart +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace angular.localForage { + + interface LocalForageConfig { + driver?:string; + name?:string | number; + version?:number; + storeName?:string; + description?:string; + } + + interface ILocalForageProvider { + config(config:LocalForageConfig):void; + setNotify(onItemSet:boolean, onItemRemove:boolean):void; + } + + interface ILocalForageService { + driver(): LocalForageDriver; + setDriver(name: string | string[]): angular.IPromise; + + setItem(key:string, value:any):angular.IPromise; + setItem(keys:Array, values:Array):angular.IPromise; + + getItem(key:string):angular.IPromise; + getItem(keys:Array):angular.IPromise>; + + removeItem(key:string | Array):angular.IPromise; + + pull(key:string):angular.IPromise; + pull(keys:Array):angular.IPromise>; + + clear():angular.IPromise; + + key(n:number):angular.IPromise; + + keys():angular.IPromise; + + length():angular.IPromise; + + iterate(iteratorCallback:(value:string | number, key:string)=>T):angular.IPromise; + + bind($scope:ng.IScope, key:string):angular.IPromise; + + bind($scope:ng.IScope, config:{ + key:string; + defaultValue?:any; + scopeKey?:string; + name?:string; + }):angular.IPromise; + + unbind($scope:ng.IScope, key:string, scopeKey?:string):void; + + createInstance(config:LocalForageConfig):ILocalForageService; + instance(name:string):ILocalForageService; + } +} diff --git a/angular-localForage/tsconfig.json b/angular-localForage/tsconfig.json new file mode 100644 index 0000000000..41d4b4c19f --- /dev/null +++ b/angular-localForage/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-localForage-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-locker/angular-locker-tests.ts b/angular-locker/angular-locker-tests.ts index c3c280e776..e7076d11bd 100644 --- a/angular-locker/angular-locker-tests.ts +++ b/angular-locker/angular-locker-tests.ts @@ -1,8 +1,7 @@ -/// -/// +import * as angular from 'angularjs'; angular -.module('angular-locker-tests', ['angular-locker']) + .module('angular-locker-tests', ['angular-locker']) .config(['lockerProvider', function config(lockerProvider: angular.locker.ILockerProvider) { let lockerSettings: angular.locker.ILockerSettings = { driver: 'session', diff --git a/angular-locker/angular-locker.d.ts b/angular-locker/angular-locker.d.ts deleted file mode 100644 index 3327521f1a..0000000000 --- a/angular-locker/angular-locker.d.ts +++ /dev/null @@ -1,170 +0,0 @@ -// Type definitions for Angular Locker v2.0.3 -// Project: https://github.com/tymondesigns/angular-locker -// Definitions by: Niko Kovačič -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "angular-locker" { - var _: string; - export = _; -} - -declare namespace angular.locker { - interface ILockerServicePutFunction { - (current: any): any - } - - interface ILockerService { - /** - * Add an item to storage if it doesn't already exist - * - * @param {String} key The key to add - * @param {Mixed} value The value to add - */ - add(key: string, value: any): boolean; - /** - * Return all items in storage within the current namespace/driver - * - */ - all(): any; - /** - * Remove all items set within the current namespace/driver - */ - clean(): ILockerService; - /** - * Get the total number of items within the current namespace - */ - count(): number; - /** - * Retrieve the specified item from storage - * - * @param {String|Array} key The key to get - * @param {Mixed} def The default value if it does not exist - */ - get(key: string | Array, defaultValue?: any): any; - /** - * Determine whether the item exists in storage - * - * @param {String|Function} key - The key to remove - */ - has(key: string): boolean - /** - * Get the storage keys as an array - */ - keys(): Array; - /** - * Add a new item to storage (even if it already exists) - * - * @param {Object} keyValuePairs Key value object - */ - put(keyValuePairs: Object): ILockerService | boolean; - /** - * Add a new item to storage (even if it already exists) - * - * @param {Mixed} putFunction The default to pass to function if doesn't already exist - */ - put(putFunction: Function): ILockerService | boolean; - /** - * Add a new item to storage (even if it already exists) - * - * @param {Mixed} key The key to add - * @param {Mixed} value The value to add - */ - put(key: string, value: any): ILockerService | boolean; - /** - * Add a new item to storage (even if it already exists) - * - * @param {Mixed} key The key to add - * @param {Mixed} putFunction The default to pass to function if doesn't already exist - * @param {Mixed} value The value to add - */ - put(key: string, putFunction: ILockerServicePutFunction, value: any): ILockerService | boolean; - /** - * Remove specified item(s) from storage - * - * @param {String} key The key to remove - */ - forget(key: string): ILockerService; - /** - * Remove specified item(s) from storage - * - * @param {Array} keys The array of keys to remove - * - */ - forget(keys: Array): ILockerService; - /** - * Retrieve the specified item from storage and then remove it - * - * @param {String|Array} key The key to pull from storage - * @param {Mixed} def The default value if it does not exist - */ - pull(key: string | Array, defaultValue?: any): any; - /** - * Bind a storage key to a $scope property - * - * @param {Object} $scope The angular $scope object - * @param {String} key The key in storage to bind to - * @param {Mixed} def The default value to initially bind - */ - bind(scope: IScope, property: string, defaultPropertyValue?: any): ILockerService; - /** - * Set the storage driver on a new instance to enable overriding defaults - * - * @param {String} driver The driver to switch to - */ - driver(localStorageType: string): ILockerService; - /** - * Empty the current storage driver completely. careful now. - */ - empty(): ILockerService; - /** - * Get the currently set namespace - */ - getNamespace(): string; - /** - * Get a new instance of Locker - * - * @param {Object} options The config options to instantiate with - */ - instance(lockerSettings: ILockerSettings): ILockerService; - /** - * Set the namespace on a new instance to enable overriding defaults - * - * @param {String} namespace The namespace to switch to - */ - 'namespace'(name: string): ILockerService; - /** - * Check browser support - * - * @see github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js#L38-L47 - * - * @param {String} driver The driver to check support with - */ - supported(): boolean; - /** - * Unbind a storage key from a $scope property - * - * @param {Object} $scope The angular $scope object - * @param {String} key The key to remove from bindings - */ - unbind(scope: IScope, property: string): ILockerService; - } - - interface ILockerSettings { - driver?: string; - 'namespace'?: string | boolean; - separator?: string; - eventsEnabled?: boolean; - extend?: Object; - } - - interface ILockerProvider extends angular.IServiceProvider { - /** - * Allow the defaults to be specified via the `lockerProvider` - * - * @param {ILockerSettings} lockerSettings The defaults to override - */ - defaults(lockerSettings: ILockerSettings): void; - } -} diff --git a/angular-locker/index.d.ts b/angular-locker/index.d.ts new file mode 100644 index 0000000000..89816d97dd --- /dev/null +++ b/angular-locker/index.d.ts @@ -0,0 +1,169 @@ +// Type definitions for Angular Locker v2.0.3 +// Project: https://github.com/tymondesigns/angular-locker +// Definitions by: Niko Kovačič +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as angular from 'angularjs'; + +declare module 'angularjs' { + export namespace locker { + interface ILockerServicePutFunction { + (current: any): any + } + + interface ILockerService { + /** + * Add an item to storage if it doesn't already exist + * + * @param {String} key The key to add + * @param {Mixed} value The value to add + */ + add(key: string, value: any): boolean; + /** + * Return all items in storage within the current namespace/driver + * + */ + all(): any; + /** + * Remove all items set within the current namespace/driver + */ + clean(): ILockerService; + /** + * Get the total number of items within the current namespace + */ + count(): number; + /** + * Retrieve the specified item from storage + * + * @param {String|Array} key The key to get + * @param {Mixed} def The default value if it does not exist + */ + get(key: string | Array, defaultValue?: any): any; + /** + * Determine whether the item exists in storage + * + * @param {String|Function} key - The key to remove + */ + has(key: string): boolean + /** + * Get the storage keys as an array + */ + keys(): Array; + /** + * Add a new item to storage (even if it already exists) + * + * @param {Object} keyValuePairs Key value object + */ + put(keyValuePairs: Object): ILockerService | boolean; + /** + * Add a new item to storage (even if it already exists) + * + * @param {Mixed} putFunction The default to pass to function if doesn't already exist + */ + put(putFunction: Function): ILockerService | boolean; + /** + * Add a new item to storage (even if it already exists) + * + * @param {Mixed} key The key to add + * @param {Mixed} value The value to add + */ + put(key: string, value: any): ILockerService | boolean; + /** + * Add a new item to storage (even if it already exists) + * + * @param {Mixed} key The key to add + * @param {Mixed} putFunction The default to pass to function if doesn't already exist + * @param {Mixed} value The value to add + */ + put(key: string, putFunction: ILockerServicePutFunction, value: any): ILockerService | boolean; + /** + * Remove specified item(s) from storage + * + * @param {String} key The key to remove + */ + forget(key: string): ILockerService; + /** + * Remove specified item(s) from storage + * + * @param {Array} keys The array of keys to remove + * + */ + forget(keys: Array): ILockerService; + /** + * Retrieve the specified item from storage and then remove it + * + * @param {String|Array} key The key to pull from storage + * @param {Mixed} def The default value if it does not exist + */ + pull(key: string | Array, defaultValue?: any): any; + /** + * Bind a storage key to a $scope property + * + * @param {Object} $scope The angular $scope object + * @param {String} key The key in storage to bind to + * @param {Mixed} def The default value to initially bind + */ + bind(scope: IScope, property: string, defaultPropertyValue?: any): ILockerService; + /** + * Set the storage driver on a new instance to enable overriding defaults + * + * @param {String} driver The driver to switch to + */ + driver(localStorageType: string): ILockerService; + /** + * Empty the current storage driver completely. careful now. + */ + empty(): ILockerService; + /** + * Get the currently set namespace + */ + getNamespace(): string; + /** + * Get a new instance of Locker + * + * @param {Object} options The config options to instantiate with + */ + instance(lockerSettings: ILockerSettings): ILockerService; + /** + * Set the namespace on a new instance to enable overriding defaults + * + * @param {String} namespace The namespace to switch to + */ + 'namespace'(name: string): ILockerService; + /** + * Check browser support + * + * @see github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js#L38-L47 + * + * @param {String} driver The driver to check support with + */ + supported(): boolean; + /** + * Unbind a storage key from a $scope property + * + * @param {Object} $scope The angular $scope object + * @param {String} key The key to remove from bindings + */ + unbind(scope: IScope, property: string): ILockerService; + } + + interface ILockerSettings { + driver?: string; + 'namespace'?: string | boolean; + separator?: string; + eventsEnabled?: boolean; + extend?: Object; + } + + interface ILockerProvider extends angular.IServiceProvider { + /** + * Allow the defaults to be specified via the `lockerProvider` + * + * @param {ILockerSettings} lockerSettings The defaults to override + */ + defaults(lockerSettings: ILockerSettings): void; + } + } +} diff --git a/angular-locker/tsconfig.json b/angular-locker/tsconfig.json new file mode 100644 index 0000000000..4ab0e22b04 --- /dev/null +++ b/angular-locker/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-locker-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-material/angular-material-0.8.3.d.ts b/angular-material/angular-material-0.8.3.d.ts index 599a39ba9b..9a7359c6cc 100644 --- a/angular-material/angular-material-0.8.3.d.ts +++ b/angular-material/angular-material-0.8.3.d.ts @@ -3,7 +3,7 @@ // Definitions by: Matt Traynham // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace angular.material { interface MDBottomSheetOptions { diff --git a/angular-material/angular-material-0.9.0.d.ts b/angular-material/angular-material-0.9.0.d.ts index daeedc0085..320e24b438 100644 --- a/angular-material/angular-material-0.9.0.d.ts +++ b/angular-material/angular-material-0.9.0.d.ts @@ -3,7 +3,7 @@ // Definitions by: Matt Traynham // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace angular.material { interface MDBottomSheetOptions { diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index 3c70dd27e8..740a72d086 100644 --- a/angular-material/angular-material-tests.ts +++ b/angular-material/angular-material-tests.ts @@ -1,4 +1,4 @@ -/// + var myApp = angular.module('testModule', ['ngMaterial']); diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts deleted file mode 100644 index 6ba65473ed..0000000000 --- a/angular-material/angular-material.d.ts +++ /dev/null @@ -1,253 +0,0 @@ -// Type definitions for Angular Material 1.0.0-rc5+ (angular.material module) -// Project: https://github.com/angular/material -// Definitions by: Matt Traynham -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -declare namespace angular.material { - - interface IBottomSheetOptions { - templateUrl?: string; - template?: string; - scope?: angular.IScope; // default: new child scope - preserveScope?: boolean; // default: false - controller?: string|Function; - locals?: {[index: string]: any}; - targetEvent?: MouseEvent; - resolve?: {[index: string]: angular.IPromise} - controllerAs?: string; - bindToController?: boolean; - parent?: string|Element|JQuery; // default: root node - disableParentScroll?: boolean; // default: true - } - - interface IBottomSheetService { - show(options: IBottomSheetOptions): angular.IPromise; - hide(response?: any): void; - cancel(response?: any): void; - } - - interface IPresetDialog { - title(title: string): T; - textContent(textContent: string): T; - htmlContent(htmlContent: string): T; - ok(ok: string): T; - theme(theme: string): T; - templateUrl(templateUrl?: string): T; - template(template?: string): T; - targetEvent(targetEvent?: MouseEvent): T; - scope(scope?: angular.IScope): T; // default: new child scope - preserveScope(preserveScope?: boolean): T; // default: false - disableParentScroll(disableParentScroll?: boolean): T; // default: true - hasBackdrop(hasBackdrop?: boolean): T; // default: true - clickOutsideToClose(clickOutsideToClose?: boolean): T; // default: false - escapeToClose(escapeToClose?: boolean): T; // default: true - focusOnOpen(focusOnOpen?: boolean): T; // default: true - controller(controller?: string|Function): T; - locals(locals?: {[index: string]: any}): T; - bindToController(bindToController?: boolean): T; // default: false - resolve(resolve?: {[index: string]: angular.IPromise}): T; - controllerAs(controllerAs?: string): T; - parent(parent?: string|Element|JQuery): T; // default: root node - onComplete(onComplete?: Function): T; - ariaLabel(ariaLabel: string): T; - } - - interface IAlertDialog extends IPresetDialog { - } - - interface IConfirmDialog extends IPresetDialog { - cancel(cancel: string): IConfirmDialog; - } - - interface IDialogOptions { - templateUrl?: string; - template?: string; - autoWrap?: boolean; // default: true - targetEvent?: MouseEvent; - openFrom?: any; - closeTo?: any; - scope?: angular.IScope; // default: new child scope - preserveScope?: boolean; // default: false - disableParentScroll?: boolean; // default: true - hasBackdrop?: boolean // default: true - clickOutsideToClose?: boolean; // default: false - escapeToClose?: boolean; // default: true - focusOnOpen?: boolean; // default: true - controller?: string|Function; - locals?: {[index: string]: any}; - bindToController?: boolean; // default: false - resolve?: {[index: string]: angular.IPromise} - controllerAs?: string; - parent?: string|Element|JQuery; // default: root node - onShowing?: Function; - onComplete?: Function; - onRemoving?: Function; - fullscreen?: boolean; - } - - interface IDialogService { - show(dialog: IDialogOptions|IAlertDialog|IConfirmDialog): angular.IPromise; - confirm(): IConfirmDialog; - alert(): IAlertDialog; - hide(response?: any): angular.IPromise; - cancel(response?: any): void; - } - - interface IIcon { - (id: string): angular.IPromise; // id is a unique ID or URL - } - - interface IIconProvider { - icon(id: string, url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24 - iconSet(id: string, url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24 - defaultIconSet(url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24 - defaultViewBoxSize(viewBoxSize: number): IIconProvider; // default: 24 - defaultFontSet(name: string): IIconProvider; - } - - interface IMedia { - (media: string): boolean; - } - - interface ISidenavObject { - toggle(): angular.IPromise; - open(): angular.IPromise; - close(): angular.IPromise; - isOpen(): boolean; - isLockedOpen(): boolean; - } - - interface ISidenavService { - (component: string): ISidenavObject; - } - - interface IToastPreset { - textContent(content: string): T; - action(action: string): T; - highlightAction(highlightAction: boolean): T; - highlightClass(highlightClass: string): T; - capsule(capsule: boolean): T; - theme(theme: string): T; - hideDelay(delay: number): T; - position(position: string): T; - parent(parent?: string|Element|JQuery): T; // default: root node - } - - interface ISimpleToastPreset extends IToastPreset { - } - - interface IToastOptions { - templateUrl?: string; - template?: string; - autoWrap?:boolean; - scope?: angular.IScope; // default: new child scope - preserveScope?: boolean; // default: false - hideDelay?: number; // default (ms): 3000 - position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left' - controller?: string|Function; - locals?: {[index: string]: any}; - bindToController?: boolean; // default: false - resolve?: {[index: string]: angular.IPromise} - controllerAs?: string; - parent?: string|Element|JQuery; // default: root node - } - - interface IToastService { - show(optionsOrPreset: IToastOptions|IToastPreset): angular.IPromise; - showSimple(content: string): angular.IPromise; - simple(): ISimpleToastPreset; - build(): IToastPreset; - updateContent(): void; - hide(response?: any): void; - cancel(response?: any): void; - } - - interface IPalette { - 0?: string; - 50?: string; - 100?: string; - 200?: string; - 300?: string; - 400?: string; - 500?: string; - 600?: string; - 700?: string; - 800?: string; - 900?: string; - A100?: string; - A200?: string; - A400?: string; - A700?: string; - contrastDefaultColor?: string; - contrastDarkColors?: string|string[]; - contrastLightColors?: string|string[]; - } - - interface IThemeHues { - default?: string; - 'hue-1'?: string; - 'hue-2'?: string; - 'hue-3'?: string; - } - - interface IThemePalette { - name: string; - hues: IThemeHues; - } - - interface IThemeColors { - accent: IThemePalette; - background: IThemePalette; - primary: IThemePalette; - warn: IThemePalette; - } - - interface IThemeGrayScalePalette { - 1: string; - 2: string; - 3: string; - 4: string; - name: string; - } - - interface ITheme { - name: string; - isDark: boolean; - colors: IThemeColors; - foregroundPalette: IThemeGrayScalePalette; - foregroundShadow: string; - accentPalette(name: string, hues?: IThemeHues): ITheme; - primaryPalette(name: string, hues?: IThemeHues): ITheme; - warnPalette(name: string, hues?: IThemeHues): ITheme; - backgroundPalette(name: string, hues?: IThemeHues): ITheme; - dark(isDark?: boolean): ITheme; - } - - interface IThemingProvider { - theme(name: string, inheritFrom?: string): ITheme; - definePalette(name: string, palette: IPalette): IThemingProvider; - extendPalette(name: string, palette: IPalette): IPalette; - setDefaultTheme(theme: string): void; - alwaysWatchTheme(alwaysWatch: boolean): void; - } - - interface IDateLocaleProvider { - months: string[]; - shortMonths: string[]; - days: string[]; - shortDays: string[]; - dates: string[]; - firstDayOfWeek: number; - parseDate(dateString: string): Date; - formatDate(date: Date): string; - monthHeaderFormatter(date: Date): string; - weekNumberFormatter(weekNumber: number): string; - msgCalendar: string; - msgOpenCalendar: string; - } - - interface IMenuService { - hide(response?: any, options?: any): angular.IPromise; - } -} diff --git a/angular-material/index.d.ts b/angular-material/index.d.ts new file mode 100644 index 0000000000..dd4e7c1233 --- /dev/null +++ b/angular-material/index.d.ts @@ -0,0 +1,274 @@ +// Type definitions for Angular Material 1.0.0-rc5+ (angular.material module) +// Project: https://github.com/angular/material +// Definitions by: Matt Traynham +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +declare namespace angular.material { + + interface IBottomSheetOptions { + templateUrl?: string; + template?: string; + scope?: angular.IScope; // default: new child scope + preserveScope?: boolean; // default: false + controller?: string|Function; + locals?: {[index: string]: any}; + targetEvent?: MouseEvent; + resolve?: {[index: string]: angular.IPromise} + controllerAs?: string; + bindToController?: boolean; + parent?: string|Element|JQuery; // default: root node + disableParentScroll?: boolean; // default: true + } + + interface IBottomSheetService { + show(options: IBottomSheetOptions): angular.IPromise; + hide(response?: any): void; + cancel(response?: any): void; + } + + interface IPresetDialog { + title(title: string): T; + textContent(textContent: string): T; + htmlContent(htmlContent: string): T; + ok(ok: string): T; + theme(theme: string): T; + templateUrl(templateUrl?: string): T; + template(template?: string): T; + targetEvent(targetEvent?: MouseEvent): T; + scope(scope?: angular.IScope): T; // default: new child scope + preserveScope(preserveScope?: boolean): T; // default: false + disableParentScroll(disableParentScroll?: boolean): T; // default: true + hasBackdrop(hasBackdrop?: boolean): T; // default: true + clickOutsideToClose(clickOutsideToClose?: boolean): T; // default: false + escapeToClose(escapeToClose?: boolean): T; // default: true + focusOnOpen(focusOnOpen?: boolean): T; // default: true + controller(controller?: string|Function): T; + locals(locals?: {[index: string]: any}): T; + bindToController(bindToController?: boolean): T; // default: false + resolve(resolve?: {[index: string]: angular.IPromise}): T; + controllerAs(controllerAs?: string): T; + parent(parent?: string|Element|JQuery): T; // default: root node + onComplete(onComplete?: Function): T; + ariaLabel(ariaLabel: string): T; + } + + interface IAlertDialog extends IPresetDialog { + } + + interface IConfirmDialog extends IPresetDialog { + cancel(cancel: string): IConfirmDialog; + } + + interface IDialogOptions { + templateUrl?: string; + template?: string; + autoWrap?: boolean; // default: true + targetEvent?: MouseEvent; + openFrom?: any; + closeTo?: any; + scope?: angular.IScope; // default: new child scope + preserveScope?: boolean; // default: false + disableParentScroll?: boolean; // default: true + hasBackdrop?: boolean // default: true + clickOutsideToClose?: boolean; // default: false + escapeToClose?: boolean; // default: true + focusOnOpen?: boolean; // default: true + controller?: string|Function; + locals?: {[index: string]: any}; + bindToController?: boolean; // default: false + resolve?: {[index: string]: angular.IPromise} + controllerAs?: string; + parent?: string|Element|JQuery; // default: root node + onShowing?: Function; + onComplete?: Function; + onRemoving?: Function; + fullscreen?: boolean; + } + + interface IDialogService { + show(dialog: IDialogOptions|IAlertDialog|IConfirmDialog): angular.IPromise; + confirm(): IConfirmDialog; + alert(): IAlertDialog; + hide(response?: any): angular.IPromise; + cancel(response?: any): void; + } + + interface IIcon { + (id: string): angular.IPromise; // id is a unique ID or URL + } + + interface IIconProvider { + icon(id: string, url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24 + iconSet(id: string, url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24 + defaultIconSet(url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24 + defaultViewBoxSize(viewBoxSize: number): IIconProvider; // default: 24 + defaultFontSet(name: string): IIconProvider; + } + + interface IMedia { + (media: string): boolean; + } + + interface ISidenavObject { + toggle(): angular.IPromise; + open(): angular.IPromise; + close(): angular.IPromise; + isOpen(): boolean; + isLockedOpen(): boolean; + } + + interface ISidenavService { + (component: string): ISidenavObject; + } + + interface IToastPreset { + textContent(content: string): T; + action(action: string): T; + highlightAction(highlightAction: boolean): T; + highlightClass(highlightClass: string): T; + capsule(capsule: boolean): T; + theme(theme: string): T; + hideDelay(delay: number): T; + position(position: string): T; + parent(parent?: string|Element|JQuery): T; // default: root node + } + + interface ISimpleToastPreset extends IToastPreset { + } + + interface IToastOptions { + templateUrl?: string; + template?: string; + autoWrap?:boolean; + scope?: angular.IScope; // default: new child scope + preserveScope?: boolean; // default: false + hideDelay?: number; // default (ms): 3000 + position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left' + controller?: string|Function; + locals?: {[index: string]: any}; + bindToController?: boolean; // default: false + resolve?: {[index: string]: angular.IPromise} + controllerAs?: string; + parent?: string|Element|JQuery; // default: root node + } + + interface IToastService { + show(optionsOrPreset: IToastOptions|IToastPreset): angular.IPromise; + showSimple(content: string): angular.IPromise; + simple(): ISimpleToastPreset; + build(): IToastPreset; + updateContent(): void; + hide(response?: any): void; + cancel(response?: any): void; + } + + interface IPalette { + 0?: string; + 50?: string; + 100?: string; + 200?: string; + 300?: string; + 400?: string; + 500?: string; + 600?: string; + 700?: string; + 800?: string; + 900?: string; + A100?: string; + A200?: string; + A400?: string; + A700?: string; + contrastDefaultColor?: string; + contrastDarkColors?: string|string[]; + contrastLightColors?: string|string[]; + } + + interface IThemeHues { + default?: string; + 'hue-1'?: string; + 'hue-2'?: string; + 'hue-3'?: string; + } + + interface IThemePalette { + name: string; + hues: IThemeHues; + } + + interface IThemeColors { + accent: IThemePalette; + background: IThemePalette; + primary: IThemePalette; + warn: IThemePalette; + } + + interface IThemeGrayScalePalette { + 1: string; + 2: string; + 3: string; + 4: string; + name: string; + } + + interface ITheme { + name: string; + isDark: boolean; + colors: IThemeColors; + foregroundPalette: IThemeGrayScalePalette; + foregroundShadow: string; + accentPalette(name: string, hues?: IThemeHues): ITheme; + primaryPalette(name: string, hues?: IThemeHues): ITheme; + warnPalette(name: string, hues?: IThemeHues): ITheme; + backgroundPalette(name: string, hues?: IThemeHues): ITheme; + dark(isDark?: boolean): ITheme; + } + + interface IThemingProvider { + theme(name: string, inheritFrom?: string): ITheme; + definePalette(name: string, palette: IPalette): IThemingProvider; + extendPalette(name: string, palette: IPalette): IPalette; + setDefaultTheme(theme: string): void; + alwaysWatchTheme(alwaysWatch: boolean): void; + } + + interface IDateLocaleProvider { + months: string[]; + shortMonths: string[]; + days: string[]; + shortDays: string[]; + dates: string[]; + firstDayOfWeek: number; + parseDate(dateString: string): Date; + formatDate(date: Date): string; + monthHeaderFormatter(date: Date): string; + weekNumberFormatter(weekNumber: number): string; + msgCalendar: string; + msgOpenCalendar: string; + } + + interface IMenuService { + hide(response?: any, options?: any): angular.IPromise; + } + + interface IColorPalette { + red: IPalette; + pink: IPalette; + 'deep-purple': IPalette; + indigo: IPalette; + blue: IPalette; + 'light-blue': IPalette; + cyan: IPalette; + teal: IPalette; + green: IPalette; + 'light-green': IPalette; + lime: IPalette; + yellow: IPalette; + amber: IPalette; + orange: IPalette; + 'deep-orange': IPalette; + brown: IPalette; + grey: IPalette; + 'blue-grey': IPalette; + } +} diff --git a/angular-material/tsconfig.json b/angular-material/tsconfig.json new file mode 100644 index 0000000000..93ebf9d60b --- /dev/null +++ b/angular-material/tsconfig.json @@ -0,0 +1,17 @@ +{ + "files": [ + "index.d.ts", + "angular-material-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/angular-media-queries/index.d.ts b/angular-media-queries/index.d.ts new file mode 100644 index 0000000000..e1eb8dffc3 --- /dev/null +++ b/angular-media-queries/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for Angular matchMedia 0.6.0 (angular.matchMedia module) +// Project: https://github.com/jacopotarantino/angular-match-media +// Definitions by: Joao Monteiro +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +declare namespace angular.matchmedia { + + interface IScreenSize { + + // Returns a value indicating if the current device has a retina screen + isRetina: boolean; + + is(list: Array | string): boolean; + + // Executes the callback function on window resize with the match truthiness as the first argument. + // Returns the current match truthiness. + // The 'scope' parameter is optional. If it's not passed in, '$rootScope' is used. + on(list: Array | string, callback: (result: boolean) => void, scope?: angular.IScope): boolean; + + // Executes the callback function ONLY when the match differs from previous match. + // Returns the current match truthiness. + // The 'scope' parameter is required for cleanup reasons (destroy event). + onChange(scope: angular.IScope, list: Array | string, callback: (result: boolean) => void): boolean; + + // Executes the callback only when inside of the particular screensize. + // The 'scope' parameter is optional. If it's not passed in, '$rootScope' is used. + when(list: Array | string, callback: (result: boolean) => void, scope?: angular.IScope): boolean; + } +} \ No newline at end of file diff --git a/angular-media-queries/match-media-tests.ts b/angular-media-queries/match-media-tests.ts index a9331751ae..e24c43c073 100644 --- a/angular-media-queries/match-media-tests.ts +++ b/angular-media-queries/match-media-tests.ts @@ -1,4 +1,4 @@ -/// + var myApp = angular.module('testModule', ['matchMedia']); diff --git a/angular-media-queries/match-media.d.ts b/angular-media-queries/match-media.d.ts deleted file mode 100644 index 401c61f46c..0000000000 --- a/angular-media-queries/match-media.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Type definitions for Angular matchMedia 0.6.0 (angular.matchMedia module) -// Project: https://github.com/jacopotarantino/angular-match-media -// Definitions by: Joao Monteiro -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -declare namespace angular.matchmedia { - - interface IScreenSize { - - // Returns a value indicating if the current device has a retina screen - isRetina: boolean; - - is(list: Array | string): boolean; - - // Executes the callback function on window resize with the match truthiness as the first argument. - // Returns the current match truthiness. - // The 'scope' parameter is optional. If it's not passed in, '$rootScope' is used. - on(list: Array | string, callback: (result: boolean) => void, scope?: angular.IScope): boolean; - - // Executes the callback function ONLY when the match differs from previous match. - // Returns the current match truthiness. - // The 'scope' parameter is required for cleanup reasons (destroy event). - onChange(scope: angular.IScope, list: Array | string, callback: (result: boolean) => void): boolean; - - // Executes the callback only when inside of the particular screensize. - // The 'scope' parameter is optional. If it's not passed in, '$rootScope' is used. - when(list: Array | string, callback: (result: boolean) => void, scope?: angular.IScope): boolean; - } -} \ No newline at end of file diff --git a/angular-media-queries/tsconfig.json b/angular-media-queries/tsconfig.json new file mode 100644 index 0000000000..7b8dbc1875 --- /dev/null +++ b/angular-media-queries/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "match-media-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-meteor/angular-meteor-tests.ts b/angular-meteor/angular-meteor-tests.ts index cc2a62c8d7..8500a431e8 100644 --- a/angular-meteor/angular-meteor-tests.ts +++ b/angular-meteor/angular-meteor-tests.ts @@ -1,4 +1,4 @@ -/// + interface ITodo { _id?: string; diff --git a/angular-meteor/angular-meteor.d.ts b/angular-meteor/angular-meteor.d.ts deleted file mode 100644 index 1e14ae9659..0000000000 --- a/angular-meteor/angular-meteor.d.ts +++ /dev/null @@ -1,352 +0,0 @@ -// Type definitions for Angular JS Meteor v0.8.8 (angular.meteor module) -// Project: https://github.com/Urigo/angular-meteor -// Definitions by: Peter Grman -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare namespace angular.meteor { - interface IRootScopeService extends angular.IRootScopeService { - /** - * The current logged in user and it's data. it is null if the user is not logged in. A reactive data source. - */ - currentUser: Meteor.User; - - /** - * True if a login method (such as Meteor.loginWithPassword, Meteor.loginWithFacebook, or Accounts.createUser) is currently in progress. - * A reactive data source. Can be use to display animation while user is logging in. - */ - loggingIn: boolean; - } - - interface IScope extends angular.IScope, IRootScopeService { - /** - * A method to get a $scope variable and watch it reactivly - * - * @param scopeVariableName - The name of the scope's variable to bind to - * @param [objectEquality=false] - Watch the object equality using angular.equals instead of comparing for reference equality, deeper watch but also slower - */ - getReactively(scopeVariableName: string, objectEquality?: boolean): ReactiveResult; - - /** - * A service which is a wrapper for Meteor.subscribe. It subscribes to a Meteor.publish method in the client and returns a AngularJS promise when ready. - * Calling $scope.subscribe will automatically stop the subscription when the scope is destroyed. - * - * @param name - Name of the subscription. Matches the name of the server's publish() call. - * @param publisherArguments - Optional arguments passed to publisher function on server. - * - * @return The promise solved successfully when subscription is ready. The success promise holds the subscription handle. - */ - subscribe(name: string, ...publisherArguments: any[]): angular.IPromise; - - /** - * The helpers method is part of the ReactiveContext, and available on every context and $scope. - * These method are defined as Object, where each key is the name of the variable that will be available on the context we run, and each value is a function with a return value. - * Under the hood, each helper starts a new Tracker.autorun. When its reactive dependencies change, the helper is rerun. - * To trigger a rerun every time an specific Angular variable change, use getReactively](/api/1.3.1/get-reactively) to make your Angular variable reactive inside the helper its used in. - * Each helper function should return a MongoDB Cursor and the helpers will expose it as a normal array to the context. - * - * @param definitions - Object containing `name` => `function` definition, where each name is a string and each function is the helper function. Should return a [MongoDB Cursor](http://docs.meteor.com/#/full/mongo_cursor) - * @return This method returns this, which the the reactive context, in order to provide the ability to chain the logic. - */ - helpers(definitions : { [helperName : string] : () => Mongo.Cursor }): IScope; - - /** - * This method is a wrapper of Tracker.autorun and shares exactly the same API. - * The autorun method is part of the ReactiveContext, and available on every context and $scope. - * The argument of this method is a callback, which will be called each time Autorun will be used. - * The Autorun will stop automatically when when it's context ($scope) is destroyed. - * - * @param runFunc - The function to run. It receives one argument: the Computation object that will be returned. - */ - autorun(runFunc : () => void) : Tracker.Computation; - } - - /** - * $meteor in angularjs - */ - interface IMeteorService { - /** - * A service that wraps the Meteor collections to enable reactivity within AngularJS. - * - * @param collection - A Meteor Collection or a reactive function to bind to. - * - Reactive function can be used with $scope.getReactively to add $scope variable as reactive variable to the cursor. - * @param [autoClientSave=true] - By default, changes in the Angular collection will automatically update the Meteor collection. - * - However if set to false, changes in the client won't be automatically propagated back to the Meteor collection. - */ - collection(collection: Mongo.Collection|ReactiveResult|Function|(()=>T), autoClientSave?: boolean): AngularMeteorCollection; - - /** - * A service that wraps the Meteor collections to enable reactivity within AngularJS. - * - * @param collection - A Meteor Collection or a reactive function to bind to. - * - Reactive function can be used with $scope.getReactively to add $scope variable as reactive variable to the cursor. - * @param [autoClientSave=true] - By default, changes in the Angular collection will automatically update the Meteor collection. - * - However if set to false, changes in the client won't be automatically propagated back to the Meteor collection. - * @param [updateCollection] - A collection object which will be used for updates (insert, update, delete). - */ - collection(collection: Mongo.Collection|ReactiveResult|Function|(()=>T), autoClientSave: boolean, updateCollection: Mongo.Collection): AngularMeteorCollection2; - - /** - * A service that wraps a Meteor object to enable reactivity within AngularJS. - * Finds the first document that matches the selector, as ordered by sort and skip options. Wraps collection.findOne - * - * @param collection - A Meteor Collection to bind to. - * @param selector - A query describing the documents to find or just the ID of the document. - * - $meteor.object will find the first document that matches the selector, - * - as ordered by sort and skip options, exactly like Meteor's collection.findOne - * @param [autoClientSave=true] - By default, changes in the Angular object will automatically update the Meteor object. - * - However if set to false, changes in the client won't be automatically propagated back to the Meteor object. - */ - object(collection: Mongo.Collection, selector: Mongo.Selector|Mongo.ObjectID|string, autoClientSave?: boolean): AngularMeteorObject; - - /** - * A service which is a wrapper for Meteor.subscribe. It subscribes to a Meteor.publish method in the client and returns a AngularJS promise when ready. - * - * @param name - Name of the subscription. Matches the name of the server's publish() call. - * @param publisherArguments - Optional arguments passed to publisher function on server. - * - * @return The promise solved successfully when subscription is ready. The success promise holds the subscription handle. - */ - subscribe(name: string, ...publisherArguments: any[]): angular.IPromise; - - /** - * A service service which wraps up Meteor.methods with AngularJS promises. - * - * @param name - Name of method to invoke - * @param methodArguments - Optional method arguments - * - * @return The promise solves successfully with the return value of the method or return reject with the error from the method. - */ - call(name: string, ...methodArguments: any[]): angular.IPromise; - - // User Authentication BEGIN -> - - /** - * Returns a promise fulfilled with the currentUser when the user subscription is ready. - * This is useful when you want to grab the current user before the route is rendered. - * If there is no logged in user, it will return null. - * See the “Authentication with Routers” section of our tutorial for more information and a full example. - */ - waitForUser(): angular.IPromise; - - /** - * Resolves the promise successfully if a user is authenticated and rejects otherwise. - * This is useful in cases where you want to require a route to have an authenticated user. - * You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page. - * See the “Authentication with Routers” section of our tutorial for more information and a full example. - */ - requireUser(): angular.IPromise; - - /** - * Resolves the promise successfully if a user is authenticated and the validatorFn returns true; rejects otherwise. - * This is useful in cases where you want to require a route to have an authenticated user and do extra validation like the user's role or group. - * You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page. - * See the “Authentication with Routers” section of our tutorial for more information and a full example. - * - * The mandatory validator function will be called with the authenticated user as the single param and it's expected to return true in order to resolve. - * If it returns a string, the promise will be rejected using said string as the reason. - * Any other return (false, null, undefined) will be rejected with the default "FORBIDDEN" reason. - */ - requireValidUser(validatorFn: (user: Meteor.User) => boolean|string): angular.IPromise; - - /** - * Log the user in with a password. - * - * @param user - Either a string interpreted as a username or an email; or an object with a single key: email, username or id. - * @param password - The user's password. - */ - loginWithPassword(user: string|{email: string}|{username: string}|{id: string}, password: string): angular.IPromise; - - /** - * Create a new user. More information: http://docs.meteor.com/#/full/accounts_createuser - * - * @param options.username - A unique name for this user. Either this, or email is required. - * @param options.email - The user's email address. Either this, or username is required. - * @param options.password - The user's password. This is not sent in plain text over the wire. - * @param options.profile - The user's profile, typically including the name field. - */ - createUser(options: {username?: string; email?: string; password: string; profile?: Object}): angular.IPromise; - - /** - * Change the current user's password. Must be logged in. - * - * @param oldPassword - The user's current password. This is not sent in plain text over the wire. - * @param newPassword - A new password for the user. This is not sent in plain text over the wire. - */ - changePassword(oldPassword: string, newPassword: string): angular.IPromise; - - /** - * Request a forgot password email. - * - * @param options.email - The email address to send a password reset link. - */ - forgotPassword(options: {email: string}): angular.IPromise; - - /** - * Reset the password for a user using a token received in email. Logs the user in afterwards. - * - * @param token - The token retrieved from the reset password URL. - * @param newPassword - A new password for the user. This is not sent in plain text over the wire. - */ - resetPassword(token: string, newPassword: string): angular.IPromise; - - /** - * Marks the user's email address as verified. Logs the user in afterwards. - * - * @param token - The token retrieved from the reset password URL. - */ - verifyEmail(token: string): angular.IPromise; - - loginWithFacebook: ILoginWithExternalService; - loginWithTwitter: ILoginWithExternalService; - loginWithGoogle: ILoginWithExternalService; - loginWithGithub: ILoginWithExternalService; - loginWithMeetup: ILoginWithExternalService; - loginWithWeibo: ILoginWithExternalService; - - /** - * Log the user out. - * - * @return Resolves with no arguments on success, or reject with a Error argument on failure. - */ - logout(): angular.IPromise; - - /** - * Log out other clients logged in as the current user, but does not log out the client that calls this function. - * For example, when called in a user's browser, connections in that browser remain logged in, - * but any other browsers or DDP clients logged in as that user will be logged out. - * - * @return Resolves with no arguments on success, or reject with a Error argument on failure. - */ - logoutOtherClients(): angular.IPromise; - - // <- User Authentication END - // $meteorUtils BEGIN -> - - /** - * @param scope - The AngularJS scope you use the autorun on. - * @param fn - The function that will re-run every time a reactive variable changes inside it. - */ - autorun(scope: angular.IScope, fn: Function): void; - - /** - * @param collectionName - The name of the collection you want to get back - */ - getCollectionByName(collectionName: string): Mongo.Collection; - - // <- $meteorUtils END - // $meteorCamera BEGIN -> - - /** - * A helper service for taking pictures across platforms. - * Must add mdg:camera package to use! (meteor add mdg:camera) - * - * @param [options] - options is an optional argument that is an Object with the following possible keys: - * @param options.width - An integer that specifies the minimum width of the returned photo. - * @param options.height - An integer that specifies the minimum height of the returned photo. - * @param options.quality - A number from 0 to 100 specifying the desired quality of JPEG encoding. - * - * @return The promise solved successfully when the picture is taken with the data as a parameter or rejected with an error as a parameter in case of error. - */ - getPicture(options?: {width?: number; height?: number; quality?: number}): angular.IPromise; - - // <- $meteorCamera END - - /** - * A service that binds a scope variable to a Meteor Session variable. - * - * @param sessionKey - The name of the session variable - * @return An object with a single function bind - to bind to that variable. - */ - session(sessionKey: string): { - /** - * @param scope - The scope the document will be bound to. - * @param model - The name of the scope's model variable that the document will be bound to. - */ - bind: (scope: IScope, model: string) => void; - }; - } - - /** - * An object that connects a Meteor Object to an AngularJS scope variable. - * - * The object contains also all the properties from the generic type T, - * unfortunately TypeScript doesn't at the moment allow to extend a generic type (see https://github.com/Microsoft/TypeScript/issues/2225 for details and updates). - * For a workaround, you'll need to implement an interface which will merge AngularMeteorObject together with T and cast it, like this: - * - * interface TodoAngularMeteorObject extends ITodo, AngularMeteorObject { } - * var todo = $meteor.object(TodoCollection, 'TodoID'); - */ - interface AngularMeteorObject { - /** - * @param [doc] - The doc to save to the Meteor Object. If nothing is passed, the method saves everything in the AngularMeteorObject as is. - * - Unchanged properties will be overridden with their existing values, which may trigger hooks. - * - If doc is passed, the method only updates the Meteor Object with the properties passed, and no other changes will be saved. - * - * @return Returns a promise with an error in case for an error or a number of successful docs changed in case of success. - */ - save(doc?: T): angular.IPromise; - - /** - * Reset the current value of the object to the one in the server. - */ - reset(): void; - - /** - * Returns a copy of the AngularMeteorObject with all the AngularMeteor-specific internal properties removed. - * The returned object is then safe to use as a parameter for method calls, or anywhere else where the data needs to be converted to JSON. - */ - getRawObject(): T; - - /** - * A shorten (Syntactic sugar) function for the $meteor.subscribe function. - * Takes only one parameter and not returns a promise like $meteor.subscribe does. - * - * @param subscriptionName - The subscription name to subscribe to. Exactly like the first parameter in $meteor.subscribe service. - */ - subscribe(subscriptionName:string): AngularMeteorObject; - } - - /** - * An object that connects a Meteor Collection to an AngularJS scope variable - */ - interface AngularMeteorCollection extends AngularMeteorCollection2 { } - - /** - * An object that connects a Meteor Collection to an AngularJS scope variable, - * but can use a differen type for updates. - */ - interface AngularMeteorCollection2 extends Array { - /** - * @param [docs] - The docs to save to the Meteor Collection. - * - If the docs parameter is empty, the method saves everything in the AngularMeteorCollection as is. - * - If an object is passed, the method pushes that object into the AngularMeteorCollection. - * - If an array is passed, the method pushes all objects in the array into the AngularMeteorCollection. - */ - save(docs?: U|U[]): void; - - /** - * @param [keys] - The keys of the object to remove from the Meteor Collection. - * - If nothing is passed, the method removes all the documents from the AngularMeteorCollection. - * - If an object is passed, the method removes the object with that key from the AngularMeteorCollection. - * - If an array is passed, the method removes all objects that matches the keys in the array from the AngularMeteorCollection. - */ - remove(keys?: U|string|number|string[]|number[]): void; - - /** - * A shorten (Syntactic sugar) function for the $meteor.subscribe function. - * Takes only one parameter and not returns a promise like $meteor.subscribe does. - * - * @param subscriptionName - The subscription name to subscribe to. Exactly like the first parameter in $meteor.subscribe service. - */ - subscribe(subscriptionName:string): AngularMeteorCollection2; - } - - interface ILoginWithExternalService { - (options: Meteor.LoginWithExternalServiceOptions): angular.IPromise; - } - - interface ReactiveResult { } -} diff --git a/angular-meteor/index.d.ts b/angular-meteor/index.d.ts new file mode 100644 index 0000000000..347936e7a6 --- /dev/null +++ b/angular-meteor/index.d.ts @@ -0,0 +1,352 @@ +// Type definitions for Angular JS Meteor v0.8.8 (angular.meteor module) +// Project: https://github.com/Urigo/angular-meteor +// Definitions by: Peter Grman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace angular.meteor { + interface IRootScopeService extends angular.IRootScopeService { + /** + * The current logged in user and it's data. it is null if the user is not logged in. A reactive data source. + */ + currentUser: Meteor.User; + + /** + * True if a login method (such as Meteor.loginWithPassword, Meteor.loginWithFacebook, or Accounts.createUser) is currently in progress. + * A reactive data source. Can be use to display animation while user is logging in. + */ + loggingIn: boolean; + } + + interface IScope extends angular.IScope, IRootScopeService { + /** + * A method to get a $scope variable and watch it reactivly + * + * @param scopeVariableName - The name of the scope's variable to bind to + * @param [objectEquality=false] - Watch the object equality using angular.equals instead of comparing for reference equality, deeper watch but also slower + */ + getReactively(scopeVariableName: string, objectEquality?: boolean): ReactiveResult; + + /** + * A service which is a wrapper for Meteor.subscribe. It subscribes to a Meteor.publish method in the client and returns a AngularJS promise when ready. + * Calling $scope.subscribe will automatically stop the subscription when the scope is destroyed. + * + * @param name - Name of the subscription. Matches the name of the server's publish() call. + * @param publisherArguments - Optional arguments passed to publisher function on server. + * + * @return The promise solved successfully when subscription is ready. The success promise holds the subscription handle. + */ + subscribe(name: string, ...publisherArguments: any[]): angular.IPromise; + + /** + * The helpers method is part of the ReactiveContext, and available on every context and $scope. + * These method are defined as Object, where each key is the name of the variable that will be available on the context we run, and each value is a function with a return value. + * Under the hood, each helper starts a new Tracker.autorun. When its reactive dependencies change, the helper is rerun. + * To trigger a rerun every time an specific Angular variable change, use getReactively](/api/1.3.1/get-reactively) to make your Angular variable reactive inside the helper its used in. + * Each helper function should return a MongoDB Cursor and the helpers will expose it as a normal array to the context. + * + * @param definitions - Object containing `name` => `function` definition, where each name is a string and each function is the helper function. Should return a [MongoDB Cursor](http://docs.meteor.com/#/full/mongo_cursor) + * @return This method returns this, which the the reactive context, in order to provide the ability to chain the logic. + */ + helpers(definitions : { [helperName : string] : () => Mongo.Cursor }): IScope; + + /** + * This method is a wrapper of Tracker.autorun and shares exactly the same API. + * The autorun method is part of the ReactiveContext, and available on every context and $scope. + * The argument of this method is a callback, which will be called each time Autorun will be used. + * The Autorun will stop automatically when when it's context ($scope) is destroyed. + * + * @param runFunc - The function to run. It receives one argument: the Computation object that will be returned. + */ + autorun(runFunc : () => void) : Tracker.Computation; + } + + /** + * $meteor in angularjs + */ + interface IMeteorService { + /** + * A service that wraps the Meteor collections to enable reactivity within AngularJS. + * + * @param collection - A Meteor Collection or a reactive function to bind to. + * - Reactive function can be used with $scope.getReactively to add $scope variable as reactive variable to the cursor. + * @param [autoClientSave=true] - By default, changes in the Angular collection will automatically update the Meteor collection. + * - However if set to false, changes in the client won't be automatically propagated back to the Meteor collection. + */ + collection(collection: Mongo.Collection|ReactiveResult|Function|(()=>T), autoClientSave?: boolean): AngularMeteorCollection; + + /** + * A service that wraps the Meteor collections to enable reactivity within AngularJS. + * + * @param collection - A Meteor Collection or a reactive function to bind to. + * - Reactive function can be used with $scope.getReactively to add $scope variable as reactive variable to the cursor. + * @param [autoClientSave=true] - By default, changes in the Angular collection will automatically update the Meteor collection. + * - However if set to false, changes in the client won't be automatically propagated back to the Meteor collection. + * @param [updateCollection] - A collection object which will be used for updates (insert, update, delete). + */ + collection(collection: Mongo.Collection|ReactiveResult|Function|(()=>T), autoClientSave: boolean, updateCollection: Mongo.Collection): AngularMeteorCollection2; + + /** + * A service that wraps a Meteor object to enable reactivity within AngularJS. + * Finds the first document that matches the selector, as ordered by sort and skip options. Wraps collection.findOne + * + * @param collection - A Meteor Collection to bind to. + * @param selector - A query describing the documents to find or just the ID of the document. + * - $meteor.object will find the first document that matches the selector, + * - as ordered by sort and skip options, exactly like Meteor's collection.findOne + * @param [autoClientSave=true] - By default, changes in the Angular object will automatically update the Meteor object. + * - However if set to false, changes in the client won't be automatically propagated back to the Meteor object. + */ + object(collection: Mongo.Collection, selector: Mongo.Selector|Mongo.ObjectID|string, autoClientSave?: boolean): AngularMeteorObject; + + /** + * A service which is a wrapper for Meteor.subscribe. It subscribes to a Meteor.publish method in the client and returns a AngularJS promise when ready. + * + * @param name - Name of the subscription. Matches the name of the server's publish() call. + * @param publisherArguments - Optional arguments passed to publisher function on server. + * + * @return The promise solved successfully when subscription is ready. The success promise holds the subscription handle. + */ + subscribe(name: string, ...publisherArguments: any[]): angular.IPromise; + + /** + * A service service which wraps up Meteor.methods with AngularJS promises. + * + * @param name - Name of method to invoke + * @param methodArguments - Optional method arguments + * + * @return The promise solves successfully with the return value of the method or return reject with the error from the method. + */ + call(name: string, ...methodArguments: any[]): angular.IPromise; + + // User Authentication BEGIN -> + + /** + * Returns a promise fulfilled with the currentUser when the user subscription is ready. + * This is useful when you want to grab the current user before the route is rendered. + * If there is no logged in user, it will return null. + * See the “Authentication with Routers” section of our tutorial for more information and a full example. + */ + waitForUser(): angular.IPromise; + + /** + * Resolves the promise successfully if a user is authenticated and rejects otherwise. + * This is useful in cases where you want to require a route to have an authenticated user. + * You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page. + * See the “Authentication with Routers” section of our tutorial for more information and a full example. + */ + requireUser(): angular.IPromise; + + /** + * Resolves the promise successfully if a user is authenticated and the validatorFn returns true; rejects otherwise. + * This is useful in cases where you want to require a route to have an authenticated user and do extra validation like the user's role or group. + * You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page. + * See the “Authentication with Routers” section of our tutorial for more information and a full example. + * + * The mandatory validator function will be called with the authenticated user as the single param and it's expected to return true in order to resolve. + * If it returns a string, the promise will be rejected using said string as the reason. + * Any other return (false, null, undefined) will be rejected with the default "FORBIDDEN" reason. + */ + requireValidUser(validatorFn: (user: Meteor.User) => boolean|string): angular.IPromise; + + /** + * Log the user in with a password. + * + * @param user - Either a string interpreted as a username or an email; or an object with a single key: email, username or id. + * @param password - The user's password. + */ + loginWithPassword(user: string|{email: string}|{username: string}|{id: string}, password: string): angular.IPromise; + + /** + * Create a new user. More information: http://docs.meteor.com/#/full/accounts_createuser + * + * @param options.username - A unique name for this user. Either this, or email is required. + * @param options.email - The user's email address. Either this, or username is required. + * @param options.password - The user's password. This is not sent in plain text over the wire. + * @param options.profile - The user's profile, typically including the name field. + */ + createUser(options: {username?: string; email?: string; password: string; profile?: Object}): angular.IPromise; + + /** + * Change the current user's password. Must be logged in. + * + * @param oldPassword - The user's current password. This is not sent in plain text over the wire. + * @param newPassword - A new password for the user. This is not sent in plain text over the wire. + */ + changePassword(oldPassword: string, newPassword: string): angular.IPromise; + + /** + * Request a forgot password email. + * + * @param options.email - The email address to send a password reset link. + */ + forgotPassword(options: {email: string}): angular.IPromise; + + /** + * Reset the password for a user using a token received in email. Logs the user in afterwards. + * + * @param token - The token retrieved from the reset password URL. + * @param newPassword - A new password for the user. This is not sent in plain text over the wire. + */ + resetPassword(token: string, newPassword: string): angular.IPromise; + + /** + * Marks the user's email address as verified. Logs the user in afterwards. + * + * @param token - The token retrieved from the reset password URL. + */ + verifyEmail(token: string): angular.IPromise; + + loginWithFacebook: ILoginWithExternalService; + loginWithTwitter: ILoginWithExternalService; + loginWithGoogle: ILoginWithExternalService; + loginWithGithub: ILoginWithExternalService; + loginWithMeetup: ILoginWithExternalService; + loginWithWeibo: ILoginWithExternalService; + + /** + * Log the user out. + * + * @return Resolves with no arguments on success, or reject with a Error argument on failure. + */ + logout(): angular.IPromise; + + /** + * Log out other clients logged in as the current user, but does not log out the client that calls this function. + * For example, when called in a user's browser, connections in that browser remain logged in, + * but any other browsers or DDP clients logged in as that user will be logged out. + * + * @return Resolves with no arguments on success, or reject with a Error argument on failure. + */ + logoutOtherClients(): angular.IPromise; + + // <- User Authentication END + // $meteorUtils BEGIN -> + + /** + * @param scope - The AngularJS scope you use the autorun on. + * @param fn - The function that will re-run every time a reactive variable changes inside it. + */ + autorun(scope: angular.IScope, fn: Function): void; + + /** + * @param collectionName - The name of the collection you want to get back + */ + getCollectionByName(collectionName: string): Mongo.Collection; + + // <- $meteorUtils END + // $meteorCamera BEGIN -> + + /** + * A helper service for taking pictures across platforms. + * Must add mdg:camera package to use! (meteor add mdg:camera) + * + * @param [options] - options is an optional argument that is an Object with the following possible keys: + * @param options.width - An integer that specifies the minimum width of the returned photo. + * @param options.height - An integer that specifies the minimum height of the returned photo. + * @param options.quality - A number from 0 to 100 specifying the desired quality of JPEG encoding. + * + * @return The promise solved successfully when the picture is taken with the data as a parameter or rejected with an error as a parameter in case of error. + */ + getPicture(options?: {width?: number; height?: number; quality?: number}): angular.IPromise; + + // <- $meteorCamera END + + /** + * A service that binds a scope variable to a Meteor Session variable. + * + * @param sessionKey - The name of the session variable + * @return An object with a single function bind - to bind to that variable. + */ + session(sessionKey: string): { + /** + * @param scope - The scope the document will be bound to. + * @param model - The name of the scope's model variable that the document will be bound to. + */ + bind: (scope: IScope, model: string) => void; + }; + } + + /** + * An object that connects a Meteor Object to an AngularJS scope variable. + * + * The object contains also all the properties from the generic type T, + * unfortunately TypeScript doesn't at the moment allow to extend a generic type (see https://github.com/Microsoft/TypeScript/issues/2225 for details and updates). + * For a workaround, you'll need to implement an interface which will merge AngularMeteorObject together with T and cast it, like this: + * + * interface TodoAngularMeteorObject extends ITodo, AngularMeteorObject { } + * var todo = $meteor.object(TodoCollection, 'TodoID'); + */ + interface AngularMeteorObject { + /** + * @param [doc] - The doc to save to the Meteor Object. If nothing is passed, the method saves everything in the AngularMeteorObject as is. + * - Unchanged properties will be overridden with their existing values, which may trigger hooks. + * - If doc is passed, the method only updates the Meteor Object with the properties passed, and no other changes will be saved. + * + * @return Returns a promise with an error in case for an error or a number of successful docs changed in case of success. + */ + save(doc?: T): angular.IPromise; + + /** + * Reset the current value of the object to the one in the server. + */ + reset(): void; + + /** + * Returns a copy of the AngularMeteorObject with all the AngularMeteor-specific internal properties removed. + * The returned object is then safe to use as a parameter for method calls, or anywhere else where the data needs to be converted to JSON. + */ + getRawObject(): T; + + /** + * A shorten (Syntactic sugar) function for the $meteor.subscribe function. + * Takes only one parameter and not returns a promise like $meteor.subscribe does. + * + * @param subscriptionName - The subscription name to subscribe to. Exactly like the first parameter in $meteor.subscribe service. + */ + subscribe(subscriptionName:string): AngularMeteorObject; + } + + /** + * An object that connects a Meteor Collection to an AngularJS scope variable + */ + interface AngularMeteorCollection extends AngularMeteorCollection2 { } + + /** + * An object that connects a Meteor Collection to an AngularJS scope variable, + * but can use a differen type for updates. + */ + interface AngularMeteorCollection2 extends Array { + /** + * @param [docs] - The docs to save to the Meteor Collection. + * - If the docs parameter is empty, the method saves everything in the AngularMeteorCollection as is. + * - If an object is passed, the method pushes that object into the AngularMeteorCollection. + * - If an array is passed, the method pushes all objects in the array into the AngularMeteorCollection. + */ + save(docs?: U|U[]): void; + + /** + * @param [keys] - The keys of the object to remove from the Meteor Collection. + * - If nothing is passed, the method removes all the documents from the AngularMeteorCollection. + * - If an object is passed, the method removes the object with that key from the AngularMeteorCollection. + * - If an array is passed, the method removes all objects that matches the keys in the array from the AngularMeteorCollection. + */ + remove(keys?: U|string|number|string[]|number[]): void; + + /** + * A shorten (Syntactic sugar) function for the $meteor.subscribe function. + * Takes only one parameter and not returns a promise like $meteor.subscribe does. + * + * @param subscriptionName - The subscription name to subscribe to. Exactly like the first parameter in $meteor.subscribe service. + */ + subscribe(subscriptionName:string): AngularMeteorCollection2; + } + + interface ILoginWithExternalService { + (options: Meteor.LoginWithExternalServiceOptions): angular.IPromise; + } + + interface ReactiveResult { } +} diff --git a/angular-meteor/tsconfig.json b/angular-meteor/tsconfig.json new file mode 100644 index 0000000000..af97c65dfb --- /dev/null +++ b/angular-meteor/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-meteor-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-modal/angular-modal-tests.ts b/angular-modal/angular-modal-tests.ts index cbb090cee9..45b64debc8 100644 --- a/angular-modal/angular-modal-tests.ts +++ b/angular-modal/angular-modal-tests.ts @@ -1,6 +1,6 @@ -/// -/// -/// +/// +/// + var btfModal: angularModal.AngularModalFactory; diff --git a/angular-modal/angular-modal.d.ts b/angular-modal/angular-modal.d.ts deleted file mode 100644 index 0bc46ee1f1..0000000000 --- a/angular-modal/angular-modal.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Type definitions for angular-modal 0.5.0 -// Project: https://github.com/btford/angular-modal -// Definitions by: Paul Lessing -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare namespace angularModal { - - type AngularModalControllerDefinition = (new (...args: any[]) => any) | Function | string; // Possible arguments to IControllerService - - type AngularModalJQuerySelector = string | Element | Element[] | JQuery | Function | any[] | {}; // Possible arguments to IAugmentedJQueryStatic - - interface AngularModalSettings { - controller?: AngularModalControllerDefinition; - controllerAs?: string; - container?: AngularModalJQuerySelector; - } - - export interface AngularModalSettingsWithTemplate extends AngularModalSettings { - template: any; - } - - export interface AngularModalSettingsWithTemplateUrl extends AngularModalSettings { - templateUrl: string; - } - - export interface AngularModal { - activate(): angular.IPromise; - deactivate(): angular.IPromise; - active(): boolean; - } - - export interface AngularModalFactory { - (settings: AngularModalSettingsWithTemplate | AngularModalSettingsWithTemplateUrl): AngularModal; - } -} diff --git a/angular-modal/index.d.ts b/angular-modal/index.d.ts new file mode 100644 index 0000000000..c6f4ca8085 --- /dev/null +++ b/angular-modal/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for angular-modal 0.5.0 +// Project: https://github.com/btford/angular-modal +// Definitions by: Paul Lessing +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace angularModal { + + type AngularModalControllerDefinition = (new (...args: any[]) => any) | Function | string; // Possible arguments to IControllerService + + type AngularModalJQuerySelector = string | Element | Element[] | JQuery | Function | any[] | {}; // Possible arguments to IAugmentedJQueryStatic + + interface AngularModalSettings { + controller?: AngularModalControllerDefinition; + controllerAs?: string; + container?: AngularModalJQuerySelector; + } + + export interface AngularModalSettingsWithTemplate extends AngularModalSettings { + template: any; + } + + export interface AngularModalSettingsWithTemplateUrl extends AngularModalSettings { + templateUrl: string; + } + + export interface AngularModal { + activate(): angular.IPromise; + deactivate(): angular.IPromise; + active(): boolean; + } + + export interface AngularModalFactory { + (settings: AngularModalSettingsWithTemplate | AngularModalSettingsWithTemplateUrl): AngularModal; + } +} diff --git a/angular-modal/tsconfig.json b/angular-modal/tsconfig.json new file mode 100644 index 0000000000..860eb1ef78 --- /dev/null +++ b/angular-modal/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-modal-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-notifications/angular-notifications-tests.ts b/angular-notifications/angular-notifications-tests.ts index 1632ff1e7d..668f0fb82f 100644 --- a/angular-notifications/angular-notifications-tests.ts +++ b/angular-notifications/angular-notifications-tests.ts @@ -1,4 +1,4 @@ -/// + var myapp = angular.module("myapp", ["notifications"]); diff --git a/angular-notifications/angular-notifications.d.ts b/angular-notifications/angular-notifications.d.ts deleted file mode 100644 index 58a388e580..0000000000 --- a/angular-notifications/angular-notifications.d.ts +++ /dev/null @@ -1,82 +0,0 @@ -// Type definitions for angular-notifications -// Project: https://github.com/DerekRies/angular-notifications -// Definitions by: Tomasz Ducin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.notifications { - - interface IAnimation { - duration: number; - enabled: boolean; - } - - interface ISettings { - info: IAnimation; - warning: IAnimation; - error: IAnimation; - success: IAnimation; - progress: IAnimation; - custom: IAnimation; - details: boolean; - localStorage: boolean; - html5Mode: boolean; - html5DefaultIcon: string; - } - - interface INotification { - type: string; - image: string; - icon: string; - title: string; - content: string; - timestamp: string; - userData: string; - } - - interface INotificationFactory extends angular.IModule { - - /* ========== SETTINGS RELATED METHODS =============*/ - - disableHtml5Mode(): void; - disableType(notificationType: string): void; - enableHtml5Mode(): void; - enableType(notificationType: string): void; - getSettings(): ISettings; - toggleType(notificationType: string): void; - toggleHtml5Mode(): void; - requestHtml5ModePermissions(): boolean; - - /* ============ QUERYING RELATED METHODS ============*/ - - getAll(): Array; - getQueue(): Array; - - /* ============== NOTIFICATION METHODS ==============*/ - - info(title: string): INotification; - info(title: string, content: string): INotification; - info(title: string, content: string, userData: any): INotification; - error(title: string): INotification; - error(title: string, content: string): INotification; - error(title: string, content: string, userData: any): INotification; - success(title: string): INotification; - success(title: string, content: string): INotification; - success(title: string, content: string, userData: any): INotification; - warning(title: string): INotification; - warning(title: string, content: string): INotification; - warning(title: string, content: string, userData: any): INotification; - awesomeNotify(type: string, icon: string, title: string, content: string, userData: any): INotification; - notify(image: string, title: string, content: string, userData: any): INotification; - makeNotification(type: string, image: string, icon: string, title: string, content: string, userData: any): INotification; - - /* ============ PERSISTENCE METHODS ============ */ - - save(): void; - restore(): void; - clear(): void; - } - -} - diff --git a/angular-notifications/index.d.ts b/angular-notifications/index.d.ts new file mode 100644 index 0000000000..72ceff3f96 --- /dev/null +++ b/angular-notifications/index.d.ts @@ -0,0 +1,82 @@ +// Type definitions for angular-notifications +// Project: https://github.com/DerekRies/angular-notifications +// Definitions by: Tomasz Ducin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.notifications { + + interface IAnimation { + duration: number; + enabled: boolean; + } + + interface ISettings { + info: IAnimation; + warning: IAnimation; + error: IAnimation; + success: IAnimation; + progress: IAnimation; + custom: IAnimation; + details: boolean; + localStorage: boolean; + html5Mode: boolean; + html5DefaultIcon: string; + } + + interface INotification { + type: string; + image: string; + icon: string; + title: string; + content: string; + timestamp: string; + userData: string; + } + + interface INotificationFactory extends angular.IModule { + + /* ========== SETTINGS RELATED METHODS =============*/ + + disableHtml5Mode(): void; + disableType(notificationType: string): void; + enableHtml5Mode(): void; + enableType(notificationType: string): void; + getSettings(): ISettings; + toggleType(notificationType: string): void; + toggleHtml5Mode(): void; + requestHtml5ModePermissions(): boolean; + + /* ============ QUERYING RELATED METHODS ============*/ + + getAll(): Array; + getQueue(): Array; + + /* ============== NOTIFICATION METHODS ==============*/ + + info(title: string): INotification; + info(title: string, content: string): INotification; + info(title: string, content: string, userData: any): INotification; + error(title: string): INotification; + error(title: string, content: string): INotification; + error(title: string, content: string, userData: any): INotification; + success(title: string): INotification; + success(title: string, content: string): INotification; + success(title: string, content: string, userData: any): INotification; + warning(title: string): INotification; + warning(title: string, content: string): INotification; + warning(title: string, content: string, userData: any): INotification; + awesomeNotify(type: string, icon: string, title: string, content: string, userData: any): INotification; + notify(image: string, title: string, content: string, userData: any): INotification; + makeNotification(type: string, image: string, icon: string, title: string, content: string, userData: any): INotification; + + /* ============ PERSISTENCE METHODS ============ */ + + save(): void; + restore(): void; + clear(): void; + } + +} + diff --git a/angular-notifications/tsconfig.json b/angular-notifications/tsconfig.json new file mode 100644 index 0000000000..c52cf81112 --- /dev/null +++ b/angular-notifications/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-notifications-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-notify/angular-notify-tests.ts b/angular-notify/angular-notify-tests.ts index d5e52b1d17..06dd1a6014 100644 --- a/angular-notify/angular-notify-tests.ts +++ b/angular-notify/angular-notify-tests.ts @@ -1,4 +1,4 @@ -/// + var myapp = angular.module("myapp", ["cgNotify"]); diff --git a/angular-notify/angular-notify.d.ts b/angular-notify/angular-notify.d.ts deleted file mode 100644 index 541d06d720..0000000000 --- a/angular-notify/angular-notify.d.ts +++ /dev/null @@ -1,126 +0,0 @@ -// Type definitions for angular-notify 2.5.0 -// Project: https://github.com/cgross/angular-notify -// Definitions by: Suwato -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.cgNotify { - - interface INotifyService { - - /** - * The notify function can either be passed a string or an object. - * This function will return an object with a close() method and a message property. - * @param message - */ - (message:string):INotify; - - /** - * When passing an object, the object parameters can be: - * @param option - */ - (option:{ - /** - * Required. The message to show. - */ - message : string; - - /** - * Optional. A custom template for the UI of the message. - */ - templateUrl? : string; - - /** - * Optional. A list of custom CSS classes to apply to the message element. - */ - classes? : string; - - /** - * Optional. A string containing any valid Angular HTML which will be shown instead of the regular message text. - * The string must contain one root element like all valid Angular HTML templates (so wrap everything in a ). - */ - messageTemplate? : string; - - /** - * Optional. A valid Angular scope object. The scope of the template will be created by calling $new() on this scope. - */ - $scope? : ng.IScope; - - /** - * Optional. Currently center and right are the only acceptable values. - */ - position? : string; - - /** - * Optional. The duration (in milliseconds) of the message. A duration of 0 will prevent the message from closing automatically. - */ - duration? : number; - - /** - * Optional. Element that contains each notification. Defaults to document.body. - */ - container? : any; - }):INotify; - - - /** - * Call config to set the default configuration options for angular-notify. - * The following options may be specified in the given object: - * @param option - */ - config(option:{ - /** - * The default duration (in milliseconds) of each message. A duration of 0 will prevent messages from closing automatically. - */ - duration? : number; - - /** - * The Y pixel value where messages will be shown. - */ - startTop? : number; - - /** - * The number of pixels that should be reserved between messages vertically. - */ - verticalSpacing? : number; - - /** - * The default message template. - */ - templateUrl? : string; - - /** - * The default position of each message. Currently only center and right are the supported values. - */ - position? : string; - - /** - * The default element that contains each notification. Defaults to document.body. - */ - container? : any; - - /** - * The maximum number of total notifications that can be visible at one time. Older notifications will be closed when the maximum is reached. - */ - maximumOpen? : number; - }):void; - - /** - * Closes all currently open notifications. - */ - closeAll():void; - } - - interface INotify{ - /** - * The message to show. - */ - message:string; - - /** - * Close this open notifications. - */ - close():void; - } -} diff --git a/angular-notify/index.d.ts b/angular-notify/index.d.ts new file mode 100644 index 0000000000..58f680a09b --- /dev/null +++ b/angular-notify/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for angular-notify 2.5.0 +// Project: https://github.com/cgross/angular-notify +// Definitions by: Suwato +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.cgNotify { + + interface INotifyService { + + /** + * The notify function can either be passed a string or an object. + * This function will return an object with a close() method and a message property. + * @param message + */ + (message:string):INotify; + + /** + * When passing an object, the object parameters can be: + * @param option + */ + (option:{ + /** + * Required. The message to show. + */ + message : string; + + /** + * Optional. A custom template for the UI of the message. + */ + templateUrl? : string; + + /** + * Optional. A list of custom CSS classes to apply to the message element. + */ + classes? : string; + + /** + * Optional. A string containing any valid Angular HTML which will be shown instead of the regular message text. + * The string must contain one root element like all valid Angular HTML templates (so wrap everything in a ). + */ + messageTemplate? : string; + + /** + * Optional. A valid Angular scope object. The scope of the template will be created by calling $new() on this scope. + */ + $scope? : ng.IScope; + + /** + * Optional. Currently center and right are the only acceptable values. + */ + position? : string; + + /** + * Optional. The duration (in milliseconds) of the message. A duration of 0 will prevent the message from closing automatically. + */ + duration? : number; + + /** + * Optional. Element that contains each notification. Defaults to document.body. + */ + container? : any; + }):INotify; + + + /** + * Call config to set the default configuration options for angular-notify. + * The following options may be specified in the given object: + * @param option + */ + config(option:{ + /** + * The default duration (in milliseconds) of each message. A duration of 0 will prevent messages from closing automatically. + */ + duration? : number; + + /** + * The Y pixel value where messages will be shown. + */ + startTop? : number; + + /** + * The number of pixels that should be reserved between messages vertically. + */ + verticalSpacing? : number; + + /** + * The default message template. + */ + templateUrl? : string; + + /** + * The default position of each message. Currently only center and right are the supported values. + */ + position? : string; + + /** + * The default element that contains each notification. Defaults to document.body. + */ + container? : any; + + /** + * The maximum number of total notifications that can be visible at one time. Older notifications will be closed when the maximum is reached. + */ + maximumOpen? : number; + }):void; + + /** + * Closes all currently open notifications. + */ + closeAll():void; + } + + interface INotify{ + /** + * The message to show. + */ + message:string; + + /** + * Close this open notifications. + */ + close():void; + } +} diff --git a/angular-notify/tsconfig.json b/angular-notify/tsconfig.json new file mode 100644 index 0000000000..8d8eb60b9f --- /dev/null +++ b/angular-notify/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-notify-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-odata-resources/angular-odata-resources-tests.ts b/angular-odata-resources/angular-odata-resources-tests.ts index a9194b0067..15c6bd1540 100644 --- a/angular-odata-resources/angular-odata-resources-tests.ts +++ b/angular-odata-resources/angular-odata-resources-tests.ts @@ -1,4 +1,4 @@ -/// + interface IMyResource extends OData.IResource { }; interface IMyResourceClass extends OData.IResourceClass { }; diff --git a/angular-odata-resources/angular-odata-resources.d.ts b/angular-odata-resources/angular-odata-resources.d.ts deleted file mode 100644 index 04c9ef3cfe..0000000000 --- a/angular-odata-resources/angular-odata-resources.d.ts +++ /dev/null @@ -1,327 +0,0 @@ -// Type definitions for OData Angular Resources -// Project: https://github.com/devnixs/ODataAngularResources -// Definitions by: Raphael ATALLAH -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace OData { - - /** - * Currently supported options for the $resource factory options argument. - */ - interface IResourceOptions { - /** - * If true then the trailing slashes from any calculated URL will be stripped (defaults to true) - */ - stripTrailingSlashes?: boolean; - odata?: { - url?: string; - method?: string; - }; - isodatav4?: boolean; - } - - - /////////////////////////////////////////////////////////////////////////// - // ResourceService - // see http://docs.angularjs.org/api/ngResource.$resource - // Most part of the following definitions were achieved by analyzing the - // actual implementation, since the documentation doesn't seem to cover - // that deeply. - /////////////////////////////////////////////////////////////////////////// - interface IResourceService { - (url: string, paramDefaults?: any, - /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } - where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): IResourceClass>; - (url: string, paramDefaults?: any, - /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } - where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): U; - (url: string, paramDefaults?: any, - /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } - where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): IResourceClass; - } - - // Just a reference to facilitate describing new actions - interface IActionDescriptor { - url?: string; - method: string; - isArray?: boolean; - params?: any; - headers?: any; - } - - // Baseclass for everyresource with default actions. - // If you define your new actions for the resource, you will need - // to extend this interface and typecast the ResourceClass to it. - // - // In case of passing the first argument as anything but a function, - // it's gonna be considered data if the action method is POST, PUT or - // PATCH (in other words, methods with body). Otherwise, it's going - // to be considered as parameters to the request. - // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L461-L465 - // - // Only those methods with an HTTP body do have 'data' as first parameter: - // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L463 - // More specifically, those methods are POST, PUT and PATCH: - // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L432 - // - // Also, static calls always return the IResource (or IResourceArray) retrieved - // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L549 - interface IResourceClass { - new(dataOrParams? : any) : IResource; - get(): IResource; - get(params: Object): IResource; - get(success: Function, error?: Function): IResource; - get(params: Object, success: Function, error?: Function): IResource; - get(params: Object, data: Object, success?: Function, error?: Function): IResource; - - query(): IResourceArray; - query(params: Object): IResourceArray; - query(success: Function, error?: Function): IResourceArray; - query(params: Object, success: Function, error?: Function): IResourceArray; - query(params: Object, data: Object, success?: Function, error?: Function): IResourceArray; - - save(): IResource; - save(data: Object): IResource; - save(success: Function, error?: Function): IResource; - save(data: Object, success: Function, error?: Function): IResource; - save(params: Object, data: Object, success?: Function, error?: Function): IResource; - - update(): IResource; - update(data: Object): IResource; - update(success: Function, error?: Function): IResource; - update(data: Object, success: Function, error?: Function): IResource; - update(params: Object, data: Object, success?: Function, error?: Function): IResource; - - remove(): IResource; - remove(params: Object): IResource; - remove(success: Function, error?: Function): IResource; - remove(params: Object, success: Function, error?: Function): IResource; - remove(params: Object, data: Object, success?: Function, error?: Function): IResource; - - delete(): IResource; - delete(params: Object): IResource; - delete(success: Function, error?: Function): IResource; - delete(params: Object, success: Function, error?: Function): IResource; - delete(params: Object, data: Object, success?: Function, error?: Function): IResource; - - odata(): OData.Provider; - } - - // Instance calls always return the the promise of the request which retrieved the object - // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L546 - interface IResource { - $get(): angular.IPromise; - $get(params?: Object, success?: Function, error?: Function): angular.IPromise; - $get(success: Function, error?: Function): angular.IPromise; - - $query(): angular.IPromise>; - $query(params?: Object, success?: Function, error?: Function): angular.IPromise>; - $query(success: Function, error?: Function): angular.IPromise>; - - $save(): angular.IPromise; - $save(params?: Object, success?: Function, error?: Function): angular.IPromise; - $save(success: Function, error?: Function): angular.IPromise; - - $update(): angular.IPromise; - $update(params?: Object, success?: Function, error?: Function): angular.IPromise; - $update(success: Function, error?: Function): angular.IPromise; - - $remove(): angular.IPromise; - $remove(params?: Object, success?: Function, error?: Function): angular.IPromise; - $remove(success: Function, error?: Function): angular.IPromise; - - $delete(): angular.IPromise; - $delete(params?: Object, success?: Function, error?: Function): angular.IPromise; - $delete(success: Function, error?: Function): angular.IPromise; - - /** the promise of the original server interaction that created this instance. **/ - $promise: angular.IPromise; - $resolved: boolean; - } - - /** - * Really just a regular Array object with $promise and $resolve attached to it - */ - interface IResourceArray extends Array { - /** the promise of the original server interaction that created this collection. **/ - $promise: angular.IPromise>; - $resolved: boolean; - } - - /** when creating a resource factory via IModule.factory */ - interface IResourceServiceFactoryFunction { - ($resource: OData.IResourceService): IResourceClass; - >($resource: OData.IResourceService): U; - } - - // IResourceServiceProvider used to configure global settings - interface IResourceServiceProvider extends angular.IServiceProvider { - - defaults: IResourceOptions; - } - - - interface IExecutable { - execute(noParenthesis?: any): string; - } - class Global { - static $inject: string[]; - constructor(ODataBinaryOperation: any, ODataProvider: any, ODataValue: any, ODataProperty: any, ODataMethodCall: any, ODataPredicate: any, ODataOrderByStatement: any); - Provider: Provider; - BinaryOperation: typeof BinaryOperation; - Value: typeof Value; - Property: typeof Property; - Func: typeof MethodCall; - Predicate: typeof Predicate; - OrderBy: typeof OrderByStatement; - } - - interface BinaryOperationFactory { - new (propertyOrPredicate: any, valueOrOperator?: any, value?: any): BinaryOperation; - } - class BinaryOperation implements IExecutable { - private operandA; - private operandB; - private filterOperator; - constructor(propertyOrPredicate: any, valueOrOperator?: any, value?: any); - execute(noParenthesis?: any): string; - or(propertyOrPredicate: any, operatorOrValue?: any, value?: any): BinaryOperation; - and(propertyOrPredicate: any, operatorOrValue?: any, value?: any): BinaryOperation; - } - - interface MethodCallFactory { - new (methodName: string, ...args: any[]): MethodCall; - } - class MethodCall implements IExecutable { - private methodName; - private params; - execute(): string; - constructor(methodName: string, ...args: any[]); - } - - class Operators { - operators: { - 'eq': string[]; - 'ne': string[]; - 'gt': string[]; - 'ge': string[]; - 'lt': string[]; - 'le': string[]; - 'and': string[]; - 'or': string[]; - 'not': string[]; - 'add': string[]; - 'sub': string[]; - 'mul': string[]; - 'div': string[]; - 'mod': string[]; - }; - private rtrim; - private trim(value); - convert(from: string): any; - } - - interface OrderByStatementFactory { - new (propertyName: string, sortOrder?: string): OrderByStatement; - } - class OrderByStatement implements IExecutable { - private propertyName; - private direction; - execute(): string; - constructor(propertyName: string, sortOrder?: string); - } - - interface PredicateFactory { - new (propertyOrValueOrPredicate: any, valueOrOperator?: any, value?: any): Predicate; - or(orStatements: any[]): IExecutable; - create(propertyOrPredicate: any, operatorOrValue?: any, value?: any): IExecutable; - and(andStatements: any): IExecutable; - } - class Predicate extends BinaryOperation { - constructor(propertyOrValueOrPredicate: any, valueOrOperator?: any, value?: any); - static or(orStatements: any[]): IExecutable; - static create(propertyOrPredicate: any, operatorOrValue?: any, value?: any): IExecutable; - static and(andStatements: any): IExecutable; - } - - interface PropertyFactory { - new (value: string): Property; - } - class Property implements IExecutable { - private value; - constructor(value: string); - execute(): string; - } - - interface ProviderFactory { - new (callback: ProviderCallback): Provider; - } - interface ProviderCallback { - (queryString: string, success: () => any, error: () => any): T[]; - (queryString: string, success: () => any, error: () => any, isSingleElement?: boolean, forceSingleElement?: boolean): T; - } - - interface ICountResult{ - result: number; - $promise: angular.IPromise; - } - - class Provider { - private callback; - private filters; - private sortOrders; - private takeAmount; - private skipAmount; - private expandables; - constructor(callback: ProviderCallback); - filter(operand1: any, operand2?: any, operand3?: any): Provider; - orderBy(arg1: string, arg2?: string): Provider; - transformUrl(transformMethod : (url:string)=>string): Provider; - take(amount: number): Provider; - skip(amount: number): Provider; - private execute(); - query(success?: ((p:T[])=>void), error?: (()=>void)): T[]; - single(success?: ((p:T)=>void), error?: (()=>void)): T; - get(key: any, success?: ((p:T)=>void), error?: (()=>void)): T; - expand(...params: string[]): Provider; - expand(params: string[]): Provider; - select(...params: string[]): Provider; - select(params: string[]): Provider; - count(success?: (result: ICountResult) => any, error?: () => any):ICountResult; - withInlineCount(): Provider; - } - - interface ValueFactory { - new (value: any, type?: string): Value; - } - class ValueTypes { - static Boolean: string; - static Byte: string; - static DateTime: string; - static Decimal: string; - static Double: string; - static Single: string; - static Guid: string; - static Int32: string; - static String: string; - } - class Value { - private value; - private type; - private illegalChars; - private escapeIllegalChars(haystack); - private generateDate(date); - executeWithUndefinedType(): any; - executeWithType(): any; - execute(): string; - constructor(value: any, type?: string); - } - - - -} diff --git a/angular-odata-resources/index.d.ts b/angular-odata-resources/index.d.ts new file mode 100644 index 0000000000..894e801796 --- /dev/null +++ b/angular-odata-resources/index.d.ts @@ -0,0 +1,327 @@ +// Type definitions for OData Angular Resources +// Project: https://github.com/devnixs/ODataAngularResources +// Definitions by: Raphael ATALLAH +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace OData { + + /** + * Currently supported options for the $resource factory options argument. + */ + interface IResourceOptions { + /** + * If true then the trailing slashes from any calculated URL will be stripped (defaults to true) + */ + stripTrailingSlashes?: boolean; + odata?: { + url?: string; + method?: string; + }; + isodatav4?: boolean; + } + + + /////////////////////////////////////////////////////////////////////////// + // ResourceService + // see http://docs.angularjs.org/api/ngResource.$resource + // Most part of the following definitions were achieved by analyzing the + // actual implementation, since the documentation doesn't seem to cover + // that deeply. + /////////////////////////////////////////////////////////////////////////// + interface IResourceService { + (url: string, paramDefaults?: any, + /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } + where deleteDescriptor : IActionDescriptor */ + actions?: any, options?: IResourceOptions): IResourceClass>; + (url: string, paramDefaults?: any, + /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } + where deleteDescriptor : IActionDescriptor */ + actions?: any, options?: IResourceOptions): U; + (url: string, paramDefaults?: any, + /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } + where deleteDescriptor : IActionDescriptor */ + actions?: any, options?: IResourceOptions): IResourceClass; + } + + // Just a reference to facilitate describing new actions + interface IActionDescriptor { + url?: string; + method: string; + isArray?: boolean; + params?: any; + headers?: any; + } + + // Baseclass for everyresource with default actions. + // If you define your new actions for the resource, you will need + // to extend this interface and typecast the ResourceClass to it. + // + // In case of passing the first argument as anything but a function, + // it's gonna be considered data if the action method is POST, PUT or + // PATCH (in other words, methods with body). Otherwise, it's going + // to be considered as parameters to the request. + // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L461-L465 + // + // Only those methods with an HTTP body do have 'data' as first parameter: + // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L463 + // More specifically, those methods are POST, PUT and PATCH: + // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L432 + // + // Also, static calls always return the IResource (or IResourceArray) retrieved + // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L549 + interface IResourceClass { + new(dataOrParams? : any) : IResource; + get(): IResource; + get(params: Object): IResource; + get(success: Function, error?: Function): IResource; + get(params: Object, success: Function, error?: Function): IResource; + get(params: Object, data: Object, success?: Function, error?: Function): IResource; + + query(): IResourceArray; + query(params: Object): IResourceArray; + query(success: Function, error?: Function): IResourceArray; + query(params: Object, success: Function, error?: Function): IResourceArray; + query(params: Object, data: Object, success?: Function, error?: Function): IResourceArray; + + save(): IResource; + save(data: Object): IResource; + save(success: Function, error?: Function): IResource; + save(data: Object, success: Function, error?: Function): IResource; + save(params: Object, data: Object, success?: Function, error?: Function): IResource; + + update(): IResource; + update(data: Object): IResource; + update(success: Function, error?: Function): IResource; + update(data: Object, success: Function, error?: Function): IResource; + update(params: Object, data: Object, success?: Function, error?: Function): IResource; + + remove(): IResource; + remove(params: Object): IResource; + remove(success: Function, error?: Function): IResource; + remove(params: Object, success: Function, error?: Function): IResource; + remove(params: Object, data: Object, success?: Function, error?: Function): IResource; + + delete(): IResource; + delete(params: Object): IResource; + delete(success: Function, error?: Function): IResource; + delete(params: Object, success: Function, error?: Function): IResource; + delete(params: Object, data: Object, success?: Function, error?: Function): IResource; + + odata(): OData.Provider; + } + + // Instance calls always return the the promise of the request which retrieved the object + // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L546 + interface IResource { + $get(): angular.IPromise; + $get(params?: Object, success?: Function, error?: Function): angular.IPromise; + $get(success: Function, error?: Function): angular.IPromise; + + $query(): angular.IPromise>; + $query(params?: Object, success?: Function, error?: Function): angular.IPromise>; + $query(success: Function, error?: Function): angular.IPromise>; + + $save(): angular.IPromise; + $save(params?: Object, success?: Function, error?: Function): angular.IPromise; + $save(success: Function, error?: Function): angular.IPromise; + + $update(): angular.IPromise; + $update(params?: Object, success?: Function, error?: Function): angular.IPromise; + $update(success: Function, error?: Function): angular.IPromise; + + $remove(): angular.IPromise; + $remove(params?: Object, success?: Function, error?: Function): angular.IPromise; + $remove(success: Function, error?: Function): angular.IPromise; + + $delete(): angular.IPromise; + $delete(params?: Object, success?: Function, error?: Function): angular.IPromise; + $delete(success: Function, error?: Function): angular.IPromise; + + /** the promise of the original server interaction that created this instance. **/ + $promise: angular.IPromise; + $resolved: boolean; + } + + /** + * Really just a regular Array object with $promise and $resolve attached to it + */ + interface IResourceArray extends Array { + /** the promise of the original server interaction that created this collection. **/ + $promise: angular.IPromise>; + $resolved: boolean; + } + + /** when creating a resource factory via IModule.factory */ + interface IResourceServiceFactoryFunction { + ($resource: OData.IResourceService): IResourceClass; + >($resource: OData.IResourceService): U; + } + + // IResourceServiceProvider used to configure global settings + interface IResourceServiceProvider extends angular.IServiceProvider { + + defaults: IResourceOptions; + } + + + interface IExecutable { + execute(noParenthesis?: any): string; + } + class Global { + static $inject: string[]; + constructor(ODataBinaryOperation: any, ODataProvider: any, ODataValue: any, ODataProperty: any, ODataMethodCall: any, ODataPredicate: any, ODataOrderByStatement: any); + Provider: Provider; + BinaryOperation: typeof BinaryOperation; + Value: typeof Value; + Property: typeof Property; + Func: typeof MethodCall; + Predicate: typeof Predicate; + OrderBy: typeof OrderByStatement; + } + + interface BinaryOperationFactory { + new (propertyOrPredicate: any, valueOrOperator?: any, value?: any): BinaryOperation; + } + class BinaryOperation implements IExecutable { + private operandA; + private operandB; + private filterOperator; + constructor(propertyOrPredicate: any, valueOrOperator?: any, value?: any); + execute(noParenthesis?: any): string; + or(propertyOrPredicate: any, operatorOrValue?: any, value?: any): BinaryOperation; + and(propertyOrPredicate: any, operatorOrValue?: any, value?: any): BinaryOperation; + } + + interface MethodCallFactory { + new (methodName: string, ...args: any[]): MethodCall; + } + class MethodCall implements IExecutable { + private methodName; + private params; + execute(): string; + constructor(methodName: string, ...args: any[]); + } + + class Operators { + operators: { + 'eq': string[]; + 'ne': string[]; + 'gt': string[]; + 'ge': string[]; + 'lt': string[]; + 'le': string[]; + 'and': string[]; + 'or': string[]; + 'not': string[]; + 'add': string[]; + 'sub': string[]; + 'mul': string[]; + 'div': string[]; + 'mod': string[]; + }; + private rtrim; + private trim(value); + convert(from: string): any; + } + + interface OrderByStatementFactory { + new (propertyName: string, sortOrder?: string): OrderByStatement; + } + class OrderByStatement implements IExecutable { + private propertyName; + private direction; + execute(): string; + constructor(propertyName: string, sortOrder?: string); + } + + interface PredicateFactory { + new (propertyOrValueOrPredicate: any, valueOrOperator?: any, value?: any): Predicate; + or(orStatements: any[]): IExecutable; + create(propertyOrPredicate: any, operatorOrValue?: any, value?: any): IExecutable; + and(andStatements: any): IExecutable; + } + class Predicate extends BinaryOperation { + constructor(propertyOrValueOrPredicate: any, valueOrOperator?: any, value?: any); + static or(orStatements: any[]): IExecutable; + static create(propertyOrPredicate: any, operatorOrValue?: any, value?: any): IExecutable; + static and(andStatements: any): IExecutable; + } + + interface PropertyFactory { + new (value: string): Property; + } + class Property implements IExecutable { + private value; + constructor(value: string); + execute(): string; + } + + interface ProviderFactory { + new (callback: ProviderCallback): Provider; + } + interface ProviderCallback { + (queryString: string, success: () => any, error: () => any): T[]; + (queryString: string, success: () => any, error: () => any, isSingleElement?: boolean, forceSingleElement?: boolean): T; + } + + interface ICountResult{ + result: number; + $promise: angular.IPromise; + } + + class Provider { + private callback; + private filters; + private sortOrders; + private takeAmount; + private skipAmount; + private expandables; + constructor(callback: ProviderCallback); + filter(operand1: any, operand2?: any, operand3?: any): Provider; + orderBy(arg1: string, arg2?: string): Provider; + transformUrl(transformMethod : (url:string)=>string): Provider; + take(amount: number): Provider; + skip(amount: number): Provider; + private execute(); + query(success?: ((p:T[])=>void), error?: (()=>void)): T[]; + single(success?: ((p:T)=>void), error?: (()=>void)): T; + get(key: any, success?: ((p:T)=>void), error?: (()=>void)): T; + expand(...params: string[]): Provider; + expand(params: string[]): Provider; + select(...params: string[]): Provider; + select(params: string[]): Provider; + count(success?: (result: ICountResult) => any, error?: () => any):ICountResult; + withInlineCount(): Provider; + } + + interface ValueFactory { + new (value: any, type?: string): Value; + } + class ValueTypes { + static Boolean: string; + static Byte: string; + static DateTime: string; + static Decimal: string; + static Double: string; + static Single: string; + static Guid: string; + static Int32: string; + static String: string; + } + class Value { + private value; + private type; + private illegalChars; + private escapeIllegalChars(haystack); + private generateDate(date); + executeWithUndefinedType(): any; + executeWithType(): any; + execute(): string; + constructor(value: any, type?: string); + } + + + +} diff --git a/angular-odata-resources/tsconfig.json b/angular-odata-resources/tsconfig.json new file mode 100644 index 0000000000..f790a82c4f --- /dev/null +++ b/angular-odata-resources/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-odata-resources-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-permission/angular-permission-2.3.1-tests.ts b/angular-permission/angular-permission-2.3.1-tests.ts new file mode 100644 index 0000000000..f0a3176d97 --- /dev/null +++ b/angular-permission/angular-permission-2.3.1-tests.ts @@ -0,0 +1,92 @@ + + +import permission = angular.permission; + +angular + .module('fooModule', ['permission', 'user']) + .run(function (PermissionStore: permission.PermissionStore, User: any) { + // Define anonymous permission + PermissionStore + .definePermission('anonymous', function (stateParams) { + // If the returned value is *truthy* then the user has the permission, otherwise they don't + if (!User) { + return true; // Is anonymous + } + return false; + }); + }); + + interface BackendUserService { + checkSession(): angular.IPromise; + getAccessLevel(): angular.IPromise<{accessLevel: string}>; + hasPermissionDefinition(permission: string) : angular.IPromise; + } + + angular.module('barModule', ['permission', 'user']) + .run(function (PermissionStore: permission.PermissionStore, User: BackendUserService, $q: angular.IQService) { + PermissionStore + // Define user permission calling back-end + .definePermission('user', function (stateParams) { + // This time we will return a promise + // If the promise *resolves* then the user has the permission, if it *rejects* (you guessed it) + + // Let's assume this returns a promise that resolves or rejects if session is active + return User.checkSession(); + }); + + PermissionStore + // A different example for admin + .definePermission('admin', function (stateParams) { + var deferred = $q.defer(); + + User.getAccessLevel() + .then(function (data) { + if (data.accessLevel === 'admin') { + deferred.resolve(); + } else { + deferred.reject(); + } + }) + .catch(function () { + // Error with request + deferred.reject(); + }); + + return deferred.promise; + }); + + let arrayOfPermissionNames = ['p1', 'p2']; + PermissionStore.defineManyPermissions(arrayOfPermissionNames, function (stateParams: angular.ui.IStateParamsService, permissionName: string) { + return User.hasPermissionDefinition(permissionName); + }); + + PermissionStore.clearStore(); + + PermissionStore.removePermissionDefinition('user'); + + let permissions: Array = PermissionStore.getStore(); + + + }); + +angular + .module('fooModule', ['permission', 'user']) + .run(function (RoleStore: permission.RoleStore, User: any) { + RoleStore + // Permission array validated role + // Library will internally validate if 'user' and 'editor' permissions are valid when checking if role is valid + .defineRole('admin', ['user', 'editor']); + + RoleStore + // Server side validated role + .defineRole('accountant', [], function (stateParams) { + // Let's assume that we are making a request to server here and return response as promise + return User.hasRole('accountant'); + }); + + RoleStore.clearStore(); + + RoleStore.removeRoleDefinition('user'); + + let roles: Array = RoleStore.getStore(); + }); diff --git a/angular-permission/angular-permission-2.3.1.d.ts b/angular-permission/angular-permission-2.3.1.d.ts new file mode 100644 index 0000000000..015ee62801 --- /dev/null +++ b/angular-permission/angular-permission-2.3.1.d.ts @@ -0,0 +1,165 @@ +// Type definitions for angular-permission 2.3.1 +// Project: https://github.com/Narzerus/angular-permission +// Definitions by: Voislav Mishevski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +declare namespace angular.permission { + + export interface PermissionStore { + /** + * Allows to define permission on application configuration + * @method + * + * @param permissionName {String} Name of defined permission + * @param validationFunction {Function} Function used to validate if permission is valid + */ + definePermission( + name: string, + validationFunction: (stateParams?: angular.ui.IStateParamsService, permission?: string) => boolean | angular.IPromise + ): void; + + /** + * Allows to define set of permissionNames with shared validation function on application configuration + * @method + * @throws {TypeError} + * + * @param permissionNames {Array} Set of permission names + * @param validationFunction {Function} Function used to validate if permission is valid + */ + defineManyPermissions( + permissions: string[], + validationFunction: (stateParams?: angular.ui.IStateParamsService, permission?: string) => boolean | angular.IPromise + ): void; + + clearStore(): void; + + /** + * Deletes permission + * @method + * + * @param permissionName {String} Name of defined permission + */ + removePermissionDefinition(permission: string): void; + + /** + * Checks if permission exists + * @method + * + * @param permissionName {String} Name of defined permission + * @returns {Boolean} + */ + hasPermissionDefinition(permissionName: string): boolean; + + /** + * Returns all permissions + * @method + * + * @returns {Object} Permissions collection + */ + getStore(): Permission[]; + } + + export interface RoleStore { + /** + * Allows to define role + * @method + * + * @param roleName {String} Name of defined role + * @param permissions {Array} Set of permission names + * @param [validationFunction] {Function} Function used to validate if permissions in role are valid + */ + defineRole( + role: string, + permissions: Array, + validationFunction: RoleValidationFunction + ): void; + + /** + * Allows to define role + * @method + * + * @param roleName {String} Name of defined role + * @param permissions {Array} Set of permission names + */ + defineRole(role: string, permissions: Array): void; + + /** + * Checks if role is defined in store + * @method + * + * @param roleName {String} Name of role + * @returns {Boolean} + */ + hasRoleDefinition(role: string): boolean; + + /** + * Returns role definition object by it's name + * @method + * + * @returns {permission.Role} Role definition object + */ + getRoleDefinition(roleName: string): Role; + + /** + * Removes all role definitions + * @method + */ + clearStore(): void; + + /** + * Deletes role from store + * @method + * + * @param roleName {String} Name of defined permission + */ + removeRoleDefinition(roleName: string): void; + + /** + * Returns all role definitions + * @method + * + * @returns {Object} Defined roles collection + */ + getStore(): Role[]; + } + + export interface Role { + roleName: string; + permissionNames: string[]; + validationFunction?: RoleValidationFunction; + } + + export interface Permission { + permissionName: string; + validationFunction?: PermissionValidationFunction; + } + + interface RoleValidationFunction { + (stateParams?: angular.ui.IStateParamsService, permission?: string): boolean | angular.IPromise; + } + + interface PermissionValidationFunction { + (stateParams?: angular.ui.IStateParamsService, permission?: string): boolean | angular.IPromise; + } + + export interface IPermissionState extends angular.ui.IState { + data?: any | DataWithPermissions; + } + + export interface DataWithPermissions { + permissions?: { + only?: (() => void) | Array | angular.IPromise; + except?: (() => void) | Array | angular.IPromise; + redirectTo: string | (() => string) | (() => PermissionRedirectConfigation) | {[index: string]: PermissionRedirectConfigation} + }; + } + + export interface PermissionRedirectConfigation { + state: string; + params?: {}; + options?: angular.ui.IStateOptions; + } +} diff --git a/angular-permission/angular-permission-tests.ts b/angular-permission/angular-permission-tests.ts index d14f7ac7e3..674b07340c 100644 --- a/angular-permission/angular-permission-tests.ts +++ b/angular-permission/angular-permission-tests.ts @@ -1,6 +1,6 @@ -/// -import * as permission from 'angular-permission'; + +import permission = angular.permission; angular .module('fooModule', ['permission', 'user']) @@ -36,7 +36,7 @@ angular PermissionStore // A different example for admin - .definePermission('admin', function (stateParams) { + .definePermission('admin', function (permission: string, stateParams: angular.permission.TransitionProperties) { var deferred = $q.defer(); User.getAccessLevel() @@ -56,7 +56,7 @@ angular }); let arrayOfPermissionNames = ['p1', 'p2']; - PermissionStore.defineManyPermissions(arrayOfPermissionNames, function (stateParams: angular.ui.IStateParamsService, permissionName: string) { + PermissionStore.defineManyPermissions(arrayOfPermissionNames, function (permissionName: string, stateParams: angular.permission.TransitionProperties) { return User.hasPermissionDefinition(permissionName); }); @@ -79,7 +79,7 @@ angular RoleStore // Server side validated role - .defineRole('accountant', [], function (stateParams) { + .defineRole('accountant', [], function (permission, stateParams) { // Let's assume that we are making a request to server here and return response as promise return User.hasRole('accountant'); }); diff --git a/angular-permission/angular-permission.d.ts b/angular-permission/angular-permission.d.ts deleted file mode 100644 index 0a1a28188f..0000000000 --- a/angular-permission/angular-permission.d.ts +++ /dev/null @@ -1,164 +0,0 @@ -// Type definitions for angular-permission 2.3.1 -// Project: https://github.com/Narzerus/angular-permission -// Definitions by: Voislav Mishevski -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare module 'angular-permission' { - export interface PermissionStore { - /** - * Allows to define permission on application configuration - * @method - * - * @param permissionName {String} Name of defined permission - * @param validationFunction {Function} Function used to validate if permission is valid - */ - definePermission( - name: string, - validationFunction: (stateParams?: angular.ui.IStateParamsService, permission?: string) => boolean | angular.IPromise - ): void; - - /** - * Allows to define set of permissionNames with shared validation function on application configuration - * @method - * @throws {TypeError} - * - * @param permissionNames {Array} Set of permission names - * @param validationFunction {Function} Function used to validate if permission is valid - */ - defineManyPermissions( - permissions: string[], - validationFunction: (stateParams?: angular.ui.IStateParamsService, permission?: string) => boolean | angular.IPromise - ): void; - - clearStore(): void; - - /** - * Deletes permission - * @method - * - * @param permissionName {String} Name of defined permission - */ - removePermissionDefinition(permission: string): void; - - /** - * Checks if permission exists - * @method - * - * @param permissionName {String} Name of defined permission - * @returns {Boolean} - */ - hasPermissionDefinition(permissionName: string): boolean; - - /** - * Returns all permissions - * @method - * - * @returns {Object} Permissions collection - */ - getStore(): Permission[]; - } - - export interface RoleStore { - /** - * Allows to define role - * @method - * - * @param roleName {String} Name of defined role - * @param permissions {Array} Set of permission names - * @param [validationFunction] {Function} Function used to validate if permissions in role are valid - */ - defineRole( - role: string, - permissions: Array, - validationFunction: RoleValidationFunction - ): void; - - /** - * Allows to define role - * @method - * - * @param roleName {String} Name of defined role - * @param permissions {Array} Set of permission names - */ - defineRole(role: string, permissions: Array): void; - - /** - * Checks if role is defined in store - * @method - * - * @param roleName {String} Name of role - * @returns {Boolean} - */ - hasRoleDefinition(role: string): boolean; - - /** - * Returns role definition object by it's name - * @method - * - * @returns {permission.Role} Role definition object - */ - getRoleDefinition(roleName: string): Role; - - /** - * Removes all role definitions - * @method - */ - clearStore(): void; - - /** - * Deletes role from store - * @method - * - * @param roleName {String} Name of defined permission - */ - removeRoleDefinition(roleName: string): void; - - /** - * Returns all role definitions - * @method - * - * @returns {Object} Defined roles collection - */ - getStore(): Role[]; - } - - export interface Role { - roleName: string; - permissionNames: string[]; - validationFunction?: RoleValidationFunction; - } - - export interface Permission { - permissionName: string; - validationFunction?: PermissionValidationFunction; - } - - interface RoleValidationFunction { - (stateParams?: angular.ui.IStateParamsService, permission?: string): boolean | angular.IPromise; - } - - interface PermissionValidationFunction { - (stateParams?: angular.ui.IStateParamsService, permission?: string): boolean | angular.IPromise; - } - - export interface IPermissionState extends angular.ui.IState { - data?: any | DataWithPermissions; - } - - export interface DataWithPermissions { - permissions?: { - only?: (() => void) | Array | angular.IPromise; - except?: (() => void) | Array | angular.IPromise; - redirectTo: string | (() => string) | (() => PermissionRedirectConfigation) | {[index: string]: PermissionRedirectConfigation} - }; - } - - export interface PermissionRedirectConfigation { - state: string; - params?: {}; - options?: angular.ui.IStateOptions; - } -} diff --git a/angular-permission/index.d.ts b/angular-permission/index.d.ts new file mode 100644 index 0000000000..a32366b218 --- /dev/null +++ b/angular-permission/index.d.ts @@ -0,0 +1,175 @@ +// Type definitions for angular-permission 2.3.6 +// Project: https://github.com/Narzerus/angular-permission +// Definitions by: Voislav Mishevski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace angular.permission { + /** + * Used as optional parameter provided on definitions of permissions and roles + */ + export interface TransitionProperties { + fromState?: angular.ui.IState; + fromParams?: angular.ui.IStateParamsService; + toState?: angular.ui.IState; + toParams?: angular.ui.IStateParamsService; + options?: angular.ui.IStateOptions; + } + + export interface PermissionStore { + /** + * Allows to define permission on application configuration + * @method + * + * @param permissionName {String} Name of defined permission + * @param validationFunction {Function} Function used to validate if permission is valid + */ + definePermission( + name: string, + validationFunction: (permission?: string, transitionProperties?: TransitionProperties) => boolean | angular.IPromise + ): void; + + /** + * Allows to define set of permissionNames with shared validation function on application configuration + * @method + * @throws {TypeError} + * + * @param permissionNames {Array} Set of permission names + * @param validationFunction {Function} Function used to validate if permission is valid + */ + defineManyPermissions( + permissions: string[], + validationFunction: (permission?: string, transitionProperties?: TransitionProperties) => boolean | angular.IPromise + ): void; + + clearStore(): void; + + /** + * Deletes permission + * @method + * + * @param permissionName {String} Name of defined permission + */ + removePermissionDefinition(permission: string): void; + + /** + * Checks if permission exists + * @method + * + * @param permissionName {String} Name of defined permission + * @returns {Boolean} + */ + hasPermissionDefinition(permissionName: string): boolean; + + /** + * Returns all permissions + * @method + * + * @returns {Object} Permissions collection + */ + getStore(): Permission[]; + } + + export interface RoleStore { + /** + * Allows to define role + * @method + * + * @param roleName {String} Name of defined role + * @param permissions {Array} Set of permission names + * @param [validationFunction] {Function} Function used to validate if permissions in role are valid + */ + defineRole( + role: string, + permissions: Array, + validationFunction: RoleValidationFunction + ): void; + + /** + * Allows to define role + * @method + * + * @param roleName {String} Name of defined role + * @param permissions {Array} Set of permission names + */ + defineRole(role: string, permissions: Array): void; + + /** + * Checks if role is defined in store + * @method + * + * @param roleName {String} Name of role + * @returns {Boolean} + */ + hasRoleDefinition(role: string): boolean; + + /** + * Returns role definition object by it's name + * @method + * + * @returns {permission.Role} Role definition object + */ + getRoleDefinition(roleName: string): Role; + + /** + * Removes all role definitions + * @method + */ + clearStore(): void; + + /** + * Deletes role from store + * @method + * + * @param roleName {String} Name of defined permission + */ + removeRoleDefinition(roleName: string): void; + + /** + * Returns all role definitions + * @method + * + * @returns {Object} Defined roles collection + */ + getStore(): Role[]; + } + + export interface Role { + roleName: string; + permissionNames: string[]; + validationFunction?: RoleValidationFunction; + } + + export interface Permission { + permissionName: string; + validationFunction?: PermissionValidationFunction; + } + + interface RoleValidationFunction { + (permission?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise; + } + + interface PermissionValidationFunction { + (permission?: string, transitionProperties?: TransitionProperties): boolean | angular.IPromise; + } + + export interface IPermissionState extends angular.ui.IState { + data?: any | DataWithPermissions; + } + + export interface DataWithPermissions { + permissions?: { + only?: (() => void) | Array | angular.IPromise; + except?: (() => void) | Array | angular.IPromise; + redirectTo: string | (() => string) | (() => PermissionRedirectConfigation) | {[index: string]: PermissionRedirectConfigation} + }; + } + + export interface PermissionRedirectConfigation { + state: string; + params?: {}; + options?: angular.ui.IStateOptions; + } +} diff --git a/angular-permission/tsconfig.json b/angular-permission/tsconfig.json new file mode 100644 index 0000000000..18277a0408 --- /dev/null +++ b/angular-permission/tsconfig.json @@ -0,0 +1,17 @@ +{ + "files": [ + "index.d.ts", + "angular-permission-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts deleted file mode 100644 index fa2928c136..0000000000 --- a/angular-protractor/angular-protractor.d.ts +++ /dev/null @@ -1,1849 +0,0 @@ -// Type definitions for Angular Protractor 1.5.0 -// Project: https://github.com/angular/protractor -// Definitions by: Bill Armstrong -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace protractor { - //region Wrapped webdriver Items - - class ActionSequence extends webdriver.ActionSequence {} - class Builder extends webdriver.Builder {} - class Capabilities extends webdriver.Capabilities {} - class Command extends webdriver.Command {} - class EventEmitter extends webdriver.EventEmitter {} - class Session extends webdriver.Session {} - class WebDriver extends webdriver.WebDriver {} - class WebElement extends webdriver.WebElement {} - class WebElementPromise extends webdriver.WebElementPromise { } - - var Browser: webdriver.IBrowser; - var Button: webdriver.IButton; - var Capability: webdriver.ICapability; - var CommandName: webdriver.ICommandName; - var Key: webdriver.IKey; - - namespace error { - class Error extends webdriver.error.Error {} - var ErrorCode: webdriver.error.IErrorCode; - } - - namespace logging { - class Preferences extends webdriver.logging.Preferences { } - class Entry extends webdriver.logging.Entry { } - - var Type: webdriver.logging.IType; - var Level: webdriver.logging.ILevelValues; - - function getLevel(nameOrValue: string): webdriver.logging.ILevel; - function getLevel(nameOrValue: number): webdriver.logging.ILevel; - } - - namespace promise { - class Thenable extends webdriver.promise.Thenable { } - class Promise extends webdriver.promise.Promise { } - class Deferred extends webdriver.promise.Deferred { } - class ControlFlow extends webdriver.promise.ControlFlow { } - class CancellationError extends webdriver.promise.CancellationError { } - - /** - * Given an array of promises, will return a promise that will be fulfilled - * with the fulfillment values of the input array's values. If any of the - * input array's promises are rejected, the returned promise will be rejected - * with the same reason. - * - * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of - * promises to wait on. - * @return {!webdriver.promise.Promise.>} A promise that is - * fulfilled with an array containing the fulfilled values of the - * input array, or rejected with the same reason as the first - * rejected value. - * @template T - */ - function all(arr: webdriver.promise.Promise[]): webdriver.promise.Promise; - - /** - * Invokes the appropriate callback function as soon as a promised - * {@code value} is resolved. This function is similar to - * {@link 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: Function, opt_errback?: Function): void; - - /** - * @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) => R): 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; - - /** - * Tests is a function is a generator. - * @param {!Function} fn The function to test. - * @return {boolean} Whether the function is a generator. - */ - function isGenerator(fn: Function): 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; - - /** - * Calls a function for each element in an array, and if the function returns - * true adds the element to a new array. - * - *

If the return value of the filter function is a promise, this function - * will wait for it to be fulfilled before determining whether to insert the - * element into the new array. - * - *

If the filter function throws or returns a rejected promise, the promise - * returned by this function will be rejected with the same reason. Only the - * first failure will be reported; all subsequent errors will be silently - * ignored. - * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The - * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ( - * boolean|webdriver.promise.Promise.)} fn The function - * to call for each element in the array. - * @param {SELF=} opt_self The object to be used as the value of 'this' within - * {@code fn}. - * @template TYPE, SELF - */ - function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise; - function filter(arr: webdriver.promise.Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise - - /** - * Creates a new deferred object. - * @return {!webdriver.promise.Deferred} The new deferred object. - */ - function defer(): 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?: T): webdriver.promise.Promise; - - /** - * Calls a function for each element in an array and inserts the result into a - * new array, which is used as the fulfillment value of the promise returned - * by this function. - * - *

If the return value of the mapping function is a promise, this function - * will wait for it to be fulfilled before inserting it into the new array. - * - *

If the mapping function throws or returns a rejected promise, the - * promise returned by this function will be rejected with the same reason. - * Only the first failure will be reported; all subsequent errors will be - * silently ignored. - * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The - * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The - * function to call for each element in the array. This function should - * expect three arguments (the element, the index, and the array itself. - * @param {SELF=} opt_self The object to be used as the value of 'this' within - * {@code fn}. - * @template TYPE, SELF - */ - function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise - function map(arr: webdriver.promise.Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: 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: Function, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Consumes a {@code GeneratorFunction}. Each time the generator yields a - * promise, this function will wait for it to be fulfilled before feeding the - * fulfilled value back into {@code next}. Likewise, if a yielded promise is - * rejected, the rejection error will be passed to {@code throw}. - * - *

Example 1: the Fibonacci Sequence. - *


-         * webdriver.promise.consume(function* fibonacci() {
-         *   var n1 = 1, n2 = 1;
-         *   for (var i = 0; i < 4; ++i) {
-         *     var tmp = yield n1 + n2;
-         *     n1 = n2;
-         *     n2 = tmp;
-         *   }
-         *   return n1 + n2;
-         * }).then(function(result) {
-         *   console.log(result);  // 13
-         * });
-         * 
- * - *

Example 2: a generator that throws. - *


-         * webdriver.promise.consume(function* () {
-         *   yield webdriver.promise.delayed(250).then(function() {
-         *     throw Error('boom');
-         *   });
-         * }).thenCatch(function(e) {
-         *   console.log(e.toString());  // Error: boom
-         * });
-         * 
- * - * @param {!Function} generatorFn The generator function to execute. - * @param {Object=} opt_self The object to use as "this" when invoking the - * initial generator. - * @param {...*} var_args Any arguments to pass to the initial generator. - * @return {!webdriver.promise.Promise.} A promise that will resolve to the - * generator's final result. - * @throws {TypeError} If the given function is not a generator. - */ - function consume(generatorFn: Function, opt_self?: any, ...var_args: 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: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; - function when(value: webdriver.promise.Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; - - /** - * 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; - } - - namespace stacktrace { - class Frame extends webdriver.stacktrace.Frame { } - class Snapshot extends webdriver.stacktrace.Snapshot { } - - /** - * Formats an error's stack trace. - * @param {!(Error|goog.testing.JsUnitException)} error The error to format. - * @return {!(Error|goog.testing.JsUnitException)} The formatted error. - */ - function format(error: any): any; - - /** - * Gets the native stack trace if available otherwise follows the call chain. - * The generated trace will exclude all frames up to and including the call to - * this function. - * @return {!Array.} The frames of the stack trace. - */ - function get(): webdriver.stacktrace.Frame[]; - - /** - * Whether the current browser supports stack traces. - * - * @type {boolean} - * @const - */ - var BROWSER_SUPPORTED: boolean; - } - - namespace until { - class Condition extends webdriver.until.Condition { } - - /** - * Creates a condition that will wait until the input driver is able to switch - * to the designated frame. The target frame may be specified as: - *
    - *
  1. A numeric index into {@code window.frames} for the currently selected - * frame. - *
  2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME - * element on the current page. - *
  3. A locator which may be used to first locate a FRAME or IFRAME on the - * current page before attempting to switch to it. - *
- * - *

Upon successful resolution of this condition, the driver will be left - * focused on the new frame. - * - * @param {!(number|webdriver.WebElement| - * webdriver.Locator|webdriver.By.Hash| - * function(!webdriver.WebDriver): !webdriver.WebElement)} frame - * The frame identifier. - * @return {!until.Condition.} A new condition. - */ - function ableToSwitchToFrame(frame: number): webdriver.until.Condition; - function ableToSwitchToFrame(frame: webdriver.IWebElement): webdriver.until.Condition; - function ableToSwitchToFrame(frame: webdriver.Locator): webdriver.until.Condition; - function ableToSwitchToFrame(frame: (webdriver: webdriver.WebDriver) => webdriver.IWebElement): webdriver.until.Condition; - function ableToSwitchToFrame(frame: any): webdriver.until.Condition; - - /** - * Creates a condition that waits for an alert to be opened. Upon success, the - * returned promise will be fulfilled with the handle for the opened alert. - * - * @return {!until.Condition.} The new condition. - */ - function alertIsPresent(): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be disabled. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isEnabled - */ - function elementIsDisabled(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be enabled. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isEnabled - */ - function elementIsEnabled(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be deselected. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isSelected - */ - function elementIsNotSelected(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be in the DOM, - * yet not visible to the user. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isDisplayed - */ - function elementIsNotVisible(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be selected. - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isSelected - */ - function elementIsSelected(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to become visible. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isDisplayed - */ - function elementIsVisible(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will loop until an element is - * {@link webdriver.WebDriver#findElement found} with the given locator. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. - * @return {!until.Condition.} The new condition. - */ - function elementLocated(locator: webdriver.Locator): webdriver.until.Condition; - function elementLocated(locator: any): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to contain the given - * substring. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {string} substr The substring to search for. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextContains(element: webdriver.IWebElement, substr: string): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to match the given - * {@code text} exactly. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {string} text The expected text. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextIs(element: webdriver.IWebElement, text: string): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to match a regular - * expression. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextMatches(element: webdriver.IWebElement, regex: RegExp): webdriver.until.Condition; - - /** - * Creates a condition that will loop until at least one element is - * {@link webdriver.WebDriver#findElement found} with the given locator. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. - * @return {!until.Condition.>} The new - * condition. - */ - function elementsLocated(locator: webdriver.Locator): webdriver.until.Condition; - function elementsLocated(locator: any): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to become stale. An - * element is considered stale once it is removed from the DOM, or a new page - * has loaded. - * - * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition.} The new condition. - */ - function stalenessOf(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the current page's title to contain - * the given substring. - * - * @param {string} substr The substring that should be present in the page - * title. - * @return {!until.Condition.} The new condition. - */ - function titleContains(substr: string): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the current page's title to match the - * given value. - * - * @param {string} title The expected page title. - * @return {!until.Condition.} The new condition. - */ - function titleIs(title: string): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the current page's title to match the - * given regular expression. - * - * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. - */ - function titleMatches(regex: RegExp): webdriver.until.Condition; - } - - namespace ExpectedConditions { - /** - * Negates the result of a promise. - * - * @param {webdriver.until.Condition} expectedCondition - * @return {!webdriver.until.Condition} An expected condition that returns the negated value. - */ - function not(expectedCondition: webdriver.until.Condition): webdriver.until.Condition; - - /** - * Chain a number of expected conditions using logical_and, short circuiting at the - * first expected condition that evaluates to false. - * - * @param {...webdriver.until.Condition[]} fns An array of expected conditions to 'and' together. - * @return {!webdriver.until.Condition} An expected condition that returns a promise which evaluates - * to the result of the logical and. - */ - function and(...fns: webdriver.until.Condition[]): webdriver.until.Condition; - - /** - * Chain a number of expected conditions using logical_or, short circuiting at the - * first expected condition that evaluates to true. - * - * @param {...webdriver.until.Condition[]} fns An array of expected conditions to 'or' together. - * @return {!webdriver.until.Condition} An expected condition that returns a promise which - * evaluates to the result of the logical or. - */ - function or(...fns: webdriver.until.Condition[]): webdriver.until.Condition; - - /** - * Expect an alert to be present. - * - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether an alert is present. - */ - function alertIsPresent(): webdriver.until.Condition; - - /** - * An Expectation for checking an element is visible and enabled such that you can click it. - * - * @param {ElementFinder} element The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is clickable. - */ - function elementToBeClickable(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking if the given text is present in the element. - * Returns false if the elementFinder does not find an element. - * - * @param {ElementFinder} element The element to check - * @param {string} text The text to verify against - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the text is present in the element. - */ - function textToBePresentInElement(element: ElementFinder, text: string): webdriver.until.Condition; - - /** - * An expectation for checking if the given text is present in the element’s value. - * Returns false if the elementFinder does not find an element. - * - * @param {ElementFinder} element The element to check - * @param {string} text The text to verify against - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the text is present in the element's value. - */ - function textToBePresentInElementValue( - element: ElementFinder, text: string - ): webdriver.until.Condition; - - /** - * An expectation for checking that the title contains a case-sensitive substring. - * - * @param {string} title The fragment of title expected - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the title contains the string. - */ - function titleContains(title: string): webdriver.until.Condition; - - /** - * An expectation for checking the title of a page. - * - * @param {string} title The expected title, which must be an exact match. - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the title equals the string. - */ - function titleIs(title: string): webdriver.until.Condition; - - /** - * An expectation for checking that an element is present on the DOM of a page. This does not necessarily - * mean that the element is visible. This is the opposite of 'stalenessOf'. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise - * representing whether the element is present. - */ - function presenceOf(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking that an element is not attached to the DOM of a page. - * This is the opposite of 'presenceOf'. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is stale. - */ - function stalenessOf(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking that an element is present on the DOM of a page and visible. - * Visibility means that the element is not only displayed but also has a height and width that is - * greater than 0. This is the opposite of 'invisibilityOf'. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is visible. - */ - function visibilityOf(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking that an element is present on the DOM of a page. This does not necessarily - * mean that the element is visible. This is the opposite of 'stalenessOf'. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is invisible. - */ - function invisibilityOf(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking the selection is selected. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is selected. - */ - function elementToBeSelected(element: ElementFinder): webdriver.until.Condition; - } - - //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 extends webdriver.IWebElement, webdriver.promise.IThenable { - /** - * Calls to element may be chained to find elements within a parent. - * - * @alias element(locator).element(locator) - * @view - *

- *
- * Child text - *
{{person.phone}}
- *
- *
- * - * @example - * // Chain 2 element calls. - * var child = element(by.css('.parent')). - * element(by.css('.child')); - * expect(child.getText()).toBe('Child text\n555-123-4567'); - * - * // Chain 3 element calls. - * var triple = element(by.css('.parent')). - * element(by.css('.child')). - * element(by.binding('person.phone')); - * expect(triple.getText()).toBe('555-123-4567'); - * - * @param {webdriver.Locator} subLocator - * @return {ElementFinder} - */ - element(subLocator: webdriver.Locator): ElementFinder; - - /** - * Calls to element may be chained to find an array of elements within a parent. - * - * @alias element(locator).all(locator) - * @view - *
- *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- *
- * - * @example - * var items = element(by.css('.parent')).all(by.tagName('li')) - * - * @param {webdriver.Locator} subLocator - * @return {ElementArrayFinder} - */ - all(subLocator: webdriver.Locator): ElementArrayFinder; - - /** - * Shortcut for querying the document directly with css. - * - * @alias $(cssSelector) - * @view - *
- * First - * Second - *
- * - * @example - * var item = $('.count .two'); - * expect(item.getText()).toBe('Second'); - * - * @param {string} selector A css selector - * @return {ElementFinder} which identifies the located - * {@link webdriver.WebElement} - */ - $(selector: string): ElementFinder; - - /** - * Shortcut for querying the document directly with css. - * - * @alias $$(cssSelector) - * @view - *
- * First - * Second - *
- * - * @example - * // The following protractor expressions are equivalent. - * var list = element.all(by.css('.count span')); - * expect(list.count()).toBe(2); - * - * list = $$('.count span'); - * expect(list.count()).toBe(2); - * expect(list.get(0).getText()).toBe('First'); - * expect(list.get(1).getText()).toBe('Second'); - * - * @param {string} selector a css selector - * @return {ElementArrayFinder} which identifies the - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): ElementArrayFinder; - - /** - * Determine whether the element is present on the page. - * - * @view - * {{person.name}} - * - * @example - * // Element exists. - * expect(element(by.binding('person.name')).isPresent()).toBe(true); - * - * // Element not present. - * expect(element(by.binding('notPresent')).isPresent()).toBe(false); - * - * @return {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 - * - * @param {webdriver.Locator} subLocator Locator for element to look for. - * @return {ElementFinder} which resolves to whether - * the element is present on the page. - */ - isElementPresent(subLocator: webdriver.Locator): webdriver.promise.Promise; - - /** - * @see ElementArrayFinder.prototype.locator - * - * @return {webdriver.Locator} - */ - locator(): webdriver.Locator; - - /** - * Returns the WebElement represented by this ElementFinder. - * Throws the WebDriver error if the element doesn't exist. - * - * @example - * The following three expressions are equivalent. - * element(by.css('.parent')).getWebElement(); - * browser.waitForAngular(); browser.driver.findElement(by.css('.parent')); - * browser.findElement(by.css('.parent')); - * - * @alias element(locator).getWebElement() - * @return {webdriver.WebElement} - */ - getWebElement(): webdriver.WebElement; - - /** - * Evaluates the input as if it were on the scope of the current element. - * @see ElementArrayFinder.evaluate - * - * @param {string} expression - * - * @return {ElementFinder} which resolves to the evaluated expression. - */ - evaluate(expression: string): ElementFinder; - - /** - * @see ElementArrayFinder.prototype.allowAnimations. - * @param {string} value - * - * @return {ElementFinder} which resolves to whether animation is allowed. - */ - allowAnimations(value: string): ElementFinder; - - /** - * Create a shallow copy of ElementFinder. - * - * @return {!ElementFinder} A shallow copy of this. - */ - clone(): ElementFinder; - } - - interface ElementArrayFinder extends webdriver.promise.IThenable { - /** - * Returns the elements as an array of WebElements. - */ - getWebElements(): webdriver.WebElement[]; - - - /** - * Get an element within the ElementArrayFinder by index. The index starts at 0. - * Negative indices are wrapped (i.e. -i means ith element from last) - * This does not actually retrieve the underlying element. - * - * @alias element.all(locator).get(index) - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * var list = element.all(by.css('.items li')); - * expect(list.get(0).getText()).toBe('First'); - * expect(list.get(1).getText()).toBe('Second'); - * - * @param {number} index Element index. - * @return {ElementFinder} finder representing element at the given index. - */ - get(index: number): ElementFinder; - - /** - * Get the first matching element for the ElementArrayFinder. This does not - * actually retrieve the underlying element. - * - * @alias element.all(locator).first() - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * var first = element.all(by.css('.items li')).first(); - * expect(first.getText()).toBe('First'); - * - * @return {ElementFinder} finder representing the first matching element - */ - first(): ElementFinder; - - /** - * Get the last matching element for the ElementArrayFinder. This does not - * actually retrieve the underlying element. - * - * @alias element.all(locator).last() - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * var last = element.all(by.css('.items li')).last(); - * expect(last.getText()).toBe('Third'); - * - * @return {ElementFinder} finder representing the last matching element - */ - last(): ElementFinder; - - /** - * Count the number of elements represented by the ElementArrayFinder. - * - * @alias element.all(locator).count() - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * var list = element.all(by.css('.items li')); - * expect(list.count()).toBe(3); - * - * @return {!webdriver.promise.Promise} A promise which resolves to the - * number of elements matching the locator. - */ - count(): webdriver.promise.Promise; - - /** - * Calls the input function on each ElementFinder represented by the ElementArrayFinder. - * - * @alias element.all(locator).each(eachFunction) - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * element.all(by.css('.items li')).each(function(element) { - * // Will print First, Second, Third. - * element.getText().then(console.log); - * }); - * - * @param {function(ElementFinder)} fn Input function - */ - each(fn: (element: ElementFinder, index: number) => void): void; - - /** - * Apply a map function to each element within the ElementArrayFinder. The - * callback receives the ElementFinder as the first argument and the index as - * a second arg. - * - * @alias element.all(locator).map(mapFunction) - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * var items = element.all(by.css('.items li')).map(function(elm, index) { - * return { - * index: index, - * text: elm.getText(), - * class: elm.getAttribute('class') - * }; - * }); - * expect(items).toEqual([ - * {index: 0, text: 'First', class: 'one'}, - * {index: 1, text: 'Second', class: 'two'}, - * {index: 2, text: 'Third', class: 'three'} - * ]); - * - * @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: (element: ElementFinder, index: number) => T): webdriver.promise.Promise; - map(mapFn: (element: ElementFinder, index: number) => T2): webdriver.promise.Promise; - - /** - * Apply a filter function to each element within the ElementArrayFinder. Returns - * a new ElementArrayFinder 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. - * This does not actually retrieve the underlying list of elements, so it can - * be used in page objects. - * - * @alias element.all(locator).filter(filterFn) - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * element.all(by.css('.items li')).filter(function(elem, index) { - * return elem.getText().then(function(text) { - * return text === 'Third'; - * }); - * }).then(function(filteredElements) { - * filteredElements[0].click(); - * }); - * - * @param {function(ElementFinder, number): webdriver.WebElement.Promise} filterFn - * Filter function that will test if an element should be returned. - * filterFn can either return a boolean or a promise that resolves to a boolean. - * @return {!ElementArrayFinder} A ElementArrayFinder that represents an array - * of element that satisfy the filter function. - */ - filter(filterFn: (element: ElementFinder, index: number) => any): ElementArrayFinder; - - /** - * 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. - * - * @alias element.all(locator).reduce(reduceFn) - * @view - *
    - *
  • First
  • - *
  • Second
  • - *
  • Third
  • - *
- * - * @example - * var value = element.all(by.css('.items li')).reduce(function(acc, elem) { - * return elem.getText().then(function(text) { - * return acc + text + ' '; - * }); - * }); - * - * expect(value).toEqual('First Second Third '); - * - * @param {function(number, ElementFinder, number, Array.)} - * 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(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => webdriver.promise.Promise, initialValue: T): webdriver.promise.Promise; - reduce(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => T, initialValue: T): webdriver.promise.Promise; - - /** - * Represents the ElementArrayFinder as an array of ElementFinders. - * - * @return {Array.} Return a promise, which resolves to a list - * of ElementFinders specified by the locator. - */ - asElementFinders_(): webdriver.promise.Promise; - - /** - * Create a shallow copy of ElementArrayFinder. - * - * @return {!ElementArrayFinder} A shallow copy of this. - */ - clone(): ElementArrayFinder; - - /** - * Calls to ElementArrayFinder may be chained to find an array of elements - * using the current elements in this ElementArrayFinder as the starting point. - * This function returns a new ElementArrayFinder which would contain the - * children elements found (and could also be empty). - * - * @alias element.all(locator).all(locator) - * @view - *
- *
    - *
  • 1a
  • - *
  • 1b
  • - *
- *
- *
- *
    - *
  • 2a
  • - *
  • 2b
  • - *
- *
- * - * @example - * var foo = element.all(by.css('.parent')).all(by.css('.foo')) - * expect(foo.getText()).toEqual(['1a', '2a']) - * var baz = element.all(by.css('.parent')).all(by.css('.baz')) - * expect(baz.getText()).toEqual(['1b']) - * var nonexistent = element.all(by.css('.parent')).all(by.css('.NONEXISTENT')) - * expect(nonexistent.getText()).toEqual(['']) - * - * @param {webdriver.Locator} subLocator - * @return {ElementArrayFinder} - */ - all(locator: webdriver.Locator): ElementArrayFinder; - - /** - * Shorthand function for finding arrays of elements by css. - * - * @type {function(string): ElementArrayFinder} - */ - $$(selector: string): ElementArrayFinder; - - /** - * Returns an ElementFinder representation of ElementArrayFinder. It ensures - * that the ElementArrayFinder resolves to one and only one underlying element. - * - * @return {ElementFinder} An ElementFinder representation - * @private - */ - toElementFinder_(): ElementFinder; - - /** - * Returns the most relevant locator. - * - * @example - * $('#ID1').locator() // returns by.css('#ID1') - * $('#ID1').$('#ID2').locator() // returns by.css('#ID2') - * $$('#ID1').filter(filterFn).get(0).click().locator() // returns by.css('#ID1') - * - * @return {webdriver.Locator} - */ - locator(): webdriver.Locator; - - /** - * Evaluates the input as if it were on the scope of the current underlying - * elements. - * - * @view - * {{variableInScope}} - * - * @example - * var value = element(by.id('foo')).evaluate('variableInScope'); - * - * @param {string} expression - * - * @return {ElementArrayFinder} which resolves to the - * evaluated expression for each underlying element. - * 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): ElementArrayFinder; - - /** - * Determine if animation is allowed on the current underlying elements. - * @param {string} value - * - * @example - * // Turns off ng-animate animations for all elements in the - * element(by.css('body')).allowAnimations(false); - * - * @return {ElementArrayFinder} which resolves to whether animation is allowed. - */ - allowAnimations(value: boolean): ElementArrayFinder; - - /** - * 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; - - /** - * @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 - */ - getId(): 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; - } - - interface LocatorWithColumn extends webdriver.Locator { - column(index: number): webdriver.Locator; - column(name: string): webdriver.Locator; - } - - interface RepeaterLocator extends LocatorWithColumn { - row(index: number): LocatorWithColumn; - } - - interface IProtractorLocatorStrategy { - /** - * webdriver's By is an enum of locator functions, so we must set it to - * a prototype before inheriting from it. - */ - className: typeof webdriver.By.className; - css: typeof webdriver.By.css; - id: typeof webdriver.By.id; - linkText: typeof webdriver.By.linkText; - js: typeof webdriver.By.js; - name: typeof webdriver.By.name; - partialLinkText: typeof webdriver.By.partialLinkText; - tagName: typeof webdriver.By.tagName; - xpath: typeof webdriver.By.xpath; - - /** - * Add a locator to this instance of ProtractorBy. This locator can then be - * used with element(by.locatorName(args)). - * - * @view - * - * - * @example - * // Add the custom locator. - * by.addLocator('buttonTextSimple', - * function(buttonText, opt_parentElement, opt_rootSelector) { - * // This function will be serialized as a string and will execute in the - * // browser. The first argument is the text for the button. The second - * // argument is the parent element, if any. - * var using = opt_parentElement, - * buttons = using.querySelectorAll('button'); - * - * // Return an array of buttons with the text. - * return Array.prototype.filter.call(buttons, function(button) { - * return button.textContent === buttonText; - * }); - * }); - * - * // Use the custom locator. - * element(by.buttonTextSimple('Go!')).click(); - * - * @alias by.addLocator(locatorName, functionOrScript) - * @param {string} name The name of the new locator. - * @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 contains any args passed into the locator followed by the - * element scoping the search and the css selector for the root angular - * element. It should return an array of elements. - */ - addLocator(name: string, script: string): void; - addLocator(name: string, script: Function): void; - - /** - * Find an element by binding. - * - * @view - * {{person.name}} - * - * - * @example - * var span1 = element(by.binding('person.name')); - * expect(span1.getText()).toBe('Foo'); - * - * var span2 = element(by.binding('person.email')); - * expect(span2.getText()).toBe('foo@bar.com'); - * - * @param {string} bindingDescriptor - * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} - */ - binding(bindingDescriptor: string): webdriver.Locator; - - /** - * Find an element by exact binding. - * - * @view - * {{ person.name }} - * - * {{person_phone|uppercase}} - * - * @example - * 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 {{findElementsOverride: findElementsOverride, toString: Function|string}} - */ - exactBinding(bindingDescriptor: string): webdriver.Locator; - - /** - * Find an element by ng-model expression. - * - * @alias by.model(modelName) - * @view - * - * - * @example - * var input = element(by.model('person.name')); - * input.sendKeys('123'); - * expect(input.getAttribute('value')).toBe('Foo123'); - * - * @param {string} model ng-model expression. - */ - model(model: string): webdriver.Locator; - - /** - * Find a button by text. - * - * @view - * - * - * @example - * element(by.buttonText('Save')); - * - * @param {string} searchText - * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} - */ - buttonText(searchText: string): webdriver.Locator; - - /** - * Find a button by partial text. - * - * @view - * - * - * @example - * element(by.partialButtonText('Save')); - * - * @param {string} searchText - * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} - */ - partialButtonText(searchText: string): webdriver.Locator; - - - /** - * Find elements inside an ng-repeat. - * - * @view - *
- * {{cat.name}} - * {{cat.age}} - *
- * - *
- * {{$index}} - *
- *
- *

{{book.name}}

- *

{{book.blurb}}

- *
- * - * @example - * // 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')); - */ - cssContainingText(cssSelector: string, searchText: string): webdriver.Locator; - - /** - * Find an element by ng-options expression. - * - * @alias by.options(optionsDescriptor) - * @view - * - * - * @example - * 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. - */ - options(optionsDescriptor: string): webdriver.Locator; - } - - var By: IProtractorLocatorStrategy; - - interface Protractor extends webdriver.WebDriver { - - /** - * 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; - - /** - * Helper function for finding elements. - * - * @type {function(webdriver.Locator): ElementFinder} - */ - element(locator: webdriver.Locator): ElementFinder; - - /** - * Shorthand function for finding elements by css. - * - * @type {function(string): ElementFinder} - */ - $(selector: string): ElementFinder; - - /** - * Shorthand function for finding arrays of elements by css. - * - * @type {function(string): ElementArrayFinder} - */ - $$(selector: string): ElementArrayFinder; - - /** - * 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; - - /** - * Timeout in milliseconds to wait for pages to load when calling `get`. - * - * @type {number} - */ - getPageTimeout: number; - - /** - * An object that holds custom test parameters. - * - * @type {Object} - */ - params: any; - - /** - * The reset URL to use between page loads. - * - * @type {string} - */ - resetUrl: string; - - /** - * 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; - - /** - * 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. - * - * @example - * browser.addMockModule('modName', function() { - * angular.module('modName', []).value('foo', 'bar'); - * }); - * - * @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, ...varArgs: any[]): void; - addMockModule(name: string, script: Function, ...varArgs: any[]): void; - - /** - * Clear the list of registered mock modules. - */ - clearMockModules(): void; - - /** - * Remove a registered mock module. - * - * @example - * browser.removeMockModule('modName'); - * - * @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 milliseconds 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): webdriver.promise.Promise; - - /** - * 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. - */ - 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 - * - * @example - * 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; - - /** - * 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'). - * - * @example - * element(by.id('foo')).click(); - * browser.pause(); - * // Execution will stop before the next click action. - * element(by.id('bar')).click(); - * - * @param {number=} opt_debugPort Optional port to use for the debugging process - */ - pause(opt_debugPort?: number): void; - } - - // Interface for the global browser object. - interface IBrowser extends Protractor { - /** - * Fork another instance of protractor for use in interactive tests. - * - * @param {boolean} opt_useSameUrl Whether to navigate to current url on creation - * @param {boolean} opt_copyMockModules Whether to apply same mock modules on creation - * @return {Protractor} a protractor instance. - */ - forkNewDriverInstance(opt_useSameUrl?: boolean, opt_copyMockModules?: boolean): Protractor; - - /** - * Get the processed configuration object that is currently being run. This will contain - * the specs and capabilities properties of the current runner instance. - * - * Set by the runner. - * - * @return {webdriver.promise.Promise} A promise which resolves to the capabilities object. - */ - getProcessedConfig(): webdriver.promise.Promise; - } - - /** - * 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; -} - -interface cssSelectorHelper { - (cssLocator: string): protractor.ElementFinder; -} - -interface cssArraySelectorHelper { - (cssLocator: string): protractor.ElementArrayFinder; -} - -declare var browser: protractor.IBrowser; -declare var by: protractor.IProtractorLocatorStrategy; -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-scenario/angular-scenario.d.ts b/angular-scenario/angular-scenario.d.ts deleted file mode 100644 index f405a0a9c0..0000000000 --- a/angular-scenario/angular-scenario.d.ts +++ /dev/null @@ -1,166 +0,0 @@ -// Type definitions for Angular Scenario Testing 1.3 (ngScenario module) -// Project: http://angularjs.org -// Definitions by: RomanoLindano -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace ng { - export interface IAngularStatic { - scenario: any; - } -} - -declare namespace angularScenario { - - export interface RunFunction { - (functionToRun: any): any; - } - export interface RunFunctionWithDescription { - (description: string, functionToRun: any): any; - } - - export interface PauseFunction { - (): any; - } - - export interface SleepFunction { - (seconds: number): any; - } - - export interface Future { - } - - export interface testWindow { - href(): Future; - path(): Future; - search(): Future; - hash(): Future; - } - - export interface testLocation { - url(): Future; - path(): Future; - search(): Future; - hash(): Future; - } - - export interface Browser { - navigateTo(url: string): void; - navigateTo(urlDescription: string, urlFunction: () => string): void; - reload(): void; - window(): testWindow; - location(): testLocation; - } - - export interface Matchers { - toEqual(value: any): void; - toBe(value: any): void; - toBeDefined(): void; - toBeTruthy(): void; - toBeFalsy(): void; - toMatch(regularExpression: any): void; - toBeNull(): void; - toContain(value: any): void; - toBeLessThan(value: any): void; - toBeGreaterThan(value: any): void; - } - - export interface CustomMatchers extends Matchers { - } - - export interface Expect extends CustomMatchers { - not(): angularScenario.CustomMatchers; - } - - export interface UsingFunction { - (selector: string, selectorDescription?: string): void; - } - - export interface BindingFunction { - (bracketBindingExpression: string): Future; - } - - export interface Input { - enter(value: any): any; - check(): any; - select(radioButtonValue: any): any; - val(): Future; - } - - export interface Repeater { - count(): Future; - row(index: number): Future; - column(ngBindingExpression: string): Future; - } - - export interface Select { - option(value: any): any; - option(...listOfValues: any[]): any; - } - - export interface Element { - count(): Future; - click(): any; - dblclick(): any; - mouseover(): any; - mousedown(): any; - mouseup(): any; - query(callback: (selectedDOMElements: JQuery, callbackWhenDone: (objNull: any, futureValue: any) => any) => any): any; - val(): Future; - text(): Future; - html(): Future; - height(): Future; - innerHeight(): Future; - outerHeight(): Future; - width(): Future; - innerWidth(): Future; - outerWidth(): Future; - position(): Future; - scrollLeft(): Future; - scrollTop(): Future; - offset(): Future; - - val(value: any): void; - text(value: any): void; - html(value: any): void; - height(value: any): void; - innerHeight(value: any): void; - outerHeight(value: any): void; - width(value: any): void; - innerWidth(value: any): void; - outerWidth(value: any): void; - position(value: any): void; - scrollLeft(value: any): void; - scrollTop(value: any): void; - offset(value: any): void; - - attr(key: any): Future; - prop(key: any): Future; - css(key: any): Future; - - attr(key: any, value: any): void; - prop(key: any, value: any): void; - css(key: any, value: any): void; - } -} - -declare var describe: angularScenario.RunFunctionWithDescription; -declare var ddescribe: angularScenario.RunFunctionWithDescription; -declare var xdescribe: angularScenario.RunFunctionWithDescription; -declare var beforeEach: angularScenario.RunFunction; -declare var afterEach: angularScenario.RunFunction; -declare var it: angularScenario.RunFunctionWithDescription; -declare var iit: angularScenario.RunFunctionWithDescription; -declare var xit: angularScenario.RunFunctionWithDescription; -declare var pause: angularScenario.PauseFunction; -declare var sleep: angularScenario.SleepFunction; -declare function browser(): angularScenario.Browser; -declare function expect(expectation: angularScenario.Future): angularScenario.Expect; -declare var using: angularScenario.UsingFunction; -declare var binding: angularScenario.BindingFunction; -declare function input(ngModelBinding: string): angularScenario.Input; -declare function repeater(selector: string, repeaterDescription?: string): angularScenario.Repeater; -declare function select(ngModelBinding: string): angularScenario.Select; -declare function element(selector: string, elementDescription?: string): angularScenario.Element; -declare var angular: ng.IAngularStatic; diff --git a/angular-scenario/index.d.ts b/angular-scenario/index.d.ts new file mode 100644 index 0000000000..698649a8d8 --- /dev/null +++ b/angular-scenario/index.d.ts @@ -0,0 +1,166 @@ +// Type definitions for Angular Scenario Testing 1.3 (ngScenario module) +// Project: http://angularjs.org +// Definitions by: RomanoLindano +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ng { + export interface IAngularStatic { + scenario: any; + } +} + +declare namespace angularScenario { + + export interface RunFunction { + (functionToRun: any): any; + } + export interface RunFunctionWithDescription { + (description: string, functionToRun: any): any; + } + + export interface PauseFunction { + (): any; + } + + export interface SleepFunction { + (seconds: number): any; + } + + export interface Future { + } + + export interface testWindow { + href(): Future; + path(): Future; + search(): Future; + hash(): Future; + } + + export interface testLocation { + url(): Future; + path(): Future; + search(): Future; + hash(): Future; + } + + export interface Browser { + navigateTo(url: string): void; + navigateTo(urlDescription: string, urlFunction: () => string): void; + reload(): void; + window(): testWindow; + location(): testLocation; + } + + export interface Matchers { + toEqual(value: any): void; + toBe(value: any): void; + toBeDefined(): void; + toBeTruthy(): void; + toBeFalsy(): void; + toMatch(regularExpression: any): void; + toBeNull(): void; + toContain(value: any): void; + toBeLessThan(value: any): void; + toBeGreaterThan(value: any): void; + } + + export interface CustomMatchers extends Matchers { + } + + export interface Expect extends CustomMatchers { + not(): angularScenario.CustomMatchers; + } + + export interface UsingFunction { + (selector: string, selectorDescription?: string): void; + } + + export interface BindingFunction { + (bracketBindingExpression: string): Future; + } + + export interface Input { + enter(value: any): any; + check(): any; + select(radioButtonValue: any): any; + val(): Future; + } + + export interface Repeater { + count(): Future; + row(index: number): Future; + column(ngBindingExpression: string): Future; + } + + export interface Select { + option(value: any): any; + option(...listOfValues: any[]): any; + } + + export interface Element { + count(): Future; + click(): any; + dblclick(): any; + mouseover(): any; + mousedown(): any; + mouseup(): any; + query(callback: (selectedDOMElements: JQuery, callbackWhenDone: (objNull: any, futureValue: any) => any) => any): any; + val(): Future; + text(): Future; + html(): Future; + height(): Future; + innerHeight(): Future; + outerHeight(): Future; + width(): Future; + innerWidth(): Future; + outerWidth(): Future; + position(): Future; + scrollLeft(): Future; + scrollTop(): Future; + offset(): Future; + + val(value: any): void; + text(value: any): void; + html(value: any): void; + height(value: any): void; + innerHeight(value: any): void; + outerHeight(value: any): void; + width(value: any): void; + innerWidth(value: any): void; + outerWidth(value: any): void; + position(value: any): void; + scrollLeft(value: any): void; + scrollTop(value: any): void; + offset(value: any): void; + + attr(key: any): Future; + prop(key: any): Future; + css(key: any): Future; + + attr(key: any, value: any): void; + prop(key: any, value: any): void; + css(key: any, value: any): void; + } +} + +declare var describe: angularScenario.RunFunctionWithDescription; +declare var ddescribe: angularScenario.RunFunctionWithDescription; +declare var xdescribe: angularScenario.RunFunctionWithDescription; +declare var beforeEach: angularScenario.RunFunction; +declare var afterEach: angularScenario.RunFunction; +declare var it: angularScenario.RunFunctionWithDescription; +declare var iit: angularScenario.RunFunctionWithDescription; +declare var xit: angularScenario.RunFunctionWithDescription; +declare var pause: angularScenario.PauseFunction; +declare var sleep: angularScenario.SleepFunction; +declare function browser(): angularScenario.Browser; +declare function expect(expectation: angularScenario.Future): angularScenario.Expect; +declare var using: angularScenario.UsingFunction; +declare var binding: angularScenario.BindingFunction; +declare function input(ngModelBinding: string): angularScenario.Input; +declare function repeater(selector: string, repeaterDescription?: string): angularScenario.Repeater; +declare function select(ngModelBinding: string): angularScenario.Select; +declare function element(selector: string, elementDescription?: string): angularScenario.Element; +declare var angular: ng.IAngularStatic; diff --git a/angular-scenario/tsconfig.json b/angular-scenario/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/angular-scenario/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/angular-scroll/angular-scroll-tests.ts b/angular-scroll/angular-scroll-tests.ts index d7c319df9a..fbc1c01642 100644 --- a/angular-scroll/angular-scroll-tests.ts +++ b/angular-scroll/angular-scroll-tests.ts @@ -1,4 +1,4 @@ -/// + namespace TestApp { diff --git a/angular-scroll/angular-scroll.d.ts b/angular-scroll/angular-scroll.d.ts deleted file mode 100644 index 1c96194e8b..0000000000 --- a/angular-scroll/angular-scroll.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Type definitions for angular-scroll -// Project: https://github.com/oblador/angular-scroll -// Definitions by: Sam Herrmann -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -/// - -declare namespace duScroll { - - /** - * Extends the angular.element object returned by the $document sercive with a few jQuery like functions. - * see https://github.com/oblador/angular-scroll#angularelement-scroll-api - */ - interface IDocumentService extends ng.IDocumentService { - - duScrollTo(left: number, top: number): void; - duScrollTo(left: number, top: number, duration: number, easing?: Function): ng.IPromise; - - duScrollTo(element: ng.IAugmentedJQuery, offset?: number): void; - duScrollTo(element: ng.IAugmentedJQuery, offset: number, duration: number, easing?: Function): ng.IPromise; - - duScrollToElement(element: ng.IAugmentedJQuery, offset?: number): void; - duScrollToElement(element: ng.IAugmentedJQuery, offset: number, duration: number, easing?: Function): ng.IPromise; - - duScrollToElementAnimated(element: ng.IAugmentedJQuery, offset?: number): ng.IPromise; - duScrollToElementAnimated(element: ng.IAugmentedJQuery, offset: number, duration: number, easing?: Function): ng.IPromise; - - duScrollTop(top: number): void; - duScrollTop(top: number, duration: number, easing?: Function): ng.IPromise; - - duScrollTopAnimated(top: number): ng.IPromise; - duScrollTopAnimated(top: number, duration: number, easing?: Function): ng.IPromise; - - duScrollLeft(left: number): void; - duScrollLeft(left: number, duration: number, easing?: Function): ng.IPromise; - - duScrollLeftAnimated(left: number): ng.IPromise; - duScrollLeftAnimated(left: number, duration: number, easing?: Function): ng.IPromise; - - duScrollTop(): number; - duScrollLeft(): number; - } -} diff --git a/angular-scroll/index.d.ts b/angular-scroll/index.d.ts new file mode 100644 index 0000000000..22f98a0ee4 --- /dev/null +++ b/angular-scroll/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for angular-scroll +// Project: https://github.com/oblador/angular-scroll +// Definitions by: Sam Herrmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +declare namespace duScroll { + + /** + * Extends the angular.element object returned by the $document sercive with a few jQuery like functions. + * see https://github.com/oblador/angular-scroll#angularelement-scroll-api + */ + interface IDocumentService extends ng.IDocumentService { + + duScrollTo(left: number, top: number): void; + duScrollTo(left: number, top: number, duration: number, easing?: Function): ng.IPromise; + + duScrollTo(element: ng.IAugmentedJQuery, offset?: number): void; + duScrollTo(element: ng.IAugmentedJQuery, offset: number, duration: number, easing?: Function): ng.IPromise; + + duScrollToElement(element: ng.IAugmentedJQuery, offset?: number): void; + duScrollToElement(element: ng.IAugmentedJQuery, offset: number, duration: number, easing?: Function): ng.IPromise; + + duScrollToElementAnimated(element: ng.IAugmentedJQuery, offset?: number): ng.IPromise; + duScrollToElementAnimated(element: ng.IAugmentedJQuery, offset: number, duration: number, easing?: Function): ng.IPromise; + + duScrollTop(top: number): void; + duScrollTop(top: number, duration: number, easing?: Function): ng.IPromise; + + duScrollTopAnimated(top: number): ng.IPromise; + duScrollTopAnimated(top: number, duration: number, easing?: Function): ng.IPromise; + + duScrollLeft(left: number): void; + duScrollLeft(left: number, duration: number, easing?: Function): ng.IPromise; + + duScrollLeftAnimated(left: number): ng.IPromise; + duScrollLeftAnimated(left: number, duration: number, easing?: Function): ng.IPromise; + + duScrollTop(): number; + duScrollLeft(): number; + } +} diff --git a/angular-scroll/tsconfig.json b/angular-scroll/tsconfig.json new file mode 100644 index 0000000000..9452024e8b --- /dev/null +++ b/angular-scroll/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-scroll-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-signalr-hub/angular-signalr-hub-tests.ts b/angular-signalr-hub/angular-signalr-hub-tests.ts index d20457bcdc..771e49cdff 100644 --- a/angular-signalr-hub/angular-signalr-hub-tests.ts +++ b/angular-signalr-hub/angular-signalr-hub-tests.ts @@ -1,6 +1,3 @@ -/// -/// - angular .module('app', ['SignalR']) .factory('Employees', ngSignalrTest.EmployeesFactory); diff --git a/angular-signalr-hub/angular-signalr-hub.d.ts b/angular-signalr-hub/angular-signalr-hub.d.ts deleted file mode 100644 index 03fa6427eb..0000000000 --- a/angular-signalr-hub/angular-signalr-hub.d.ts +++ /dev/null @@ -1,73 +0,0 @@ -// Type definitions for angular-signalr-hub v1.5.0 -// Project: https://github.com/JustMaier/angular-signalr-hub -// Definitions by: Adam Santaniello -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace ngSignalr { - interface HubFactory { - /** - * Creates a new Hub connection - */ - new (hubName: string, options: HubOptions): Hub - } - - class Hub { - hubName: string; - connection: SignalR.Connection; - proxy: SignalR.Hub.Proxy; - - on(event: string, fn: (...args: any[]) => void): void; - invoke(method: string, ...args: any[]): JQueryDeferred; - disconnect(): void; - connect(): JQueryPromise; - } - - interface HubOptions { - /** - * Collection of client side callbacks - */ - listeners?: { [index: string]: (...args: any[]) => void }; - - /** - * String array of server side methods which the client can call - */ - methods?: Array; - - /** - * Sets the root path for the SignalR web service - */ - rootPath?: string; - - /** - * Object representing additional query params to be sent on connection - */ - queryParams?: { [index: string]: string }; - - /** - * Function to handle hub connection errors - */ - errorHandler?: (error: string) => void; - - /** - * Enable/disable logging - */ - logging?: boolean; - - /** - * Use a shared global connection or create a new one just for this hub, defaults to true - */ - useSharedConnection?: boolean; - - /** - * Sets transport method (e.g 'longPolling' or ['webSockets', 'longPolling'] ) - */ - transport?: any; - - /** - * Function to handle hub connection state changed event - */ - stateChanged?: (state: SignalR.StateChanged) => void; - } -} diff --git a/angular-signalr-hub/index.d.ts b/angular-signalr-hub/index.d.ts new file mode 100644 index 0000000000..9fe894afa6 --- /dev/null +++ b/angular-signalr-hub/index.d.ts @@ -0,0 +1,74 @@ +// Type definitions for angular-signalr-hub v1.5.0 +// Project: https://github.com/JustMaier/angular-signalr-hub +// Definitions by: Adam Santaniello +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace ngSignalr { + interface HubFactory { + /** + * Creates a new Hub connection + */ + new (hubName: string, options: HubOptions): Hub + } + + class Hub { + hubName: string; + connection: SignalR.Connection; + proxy: SignalR.Hub.Proxy; + + on(event: string, fn: (...args: any[]) => void): void; + invoke(method: string, ...args: any[]): JQueryDeferred; + disconnect(): void; + connect(): JQueryPromise; + } + + interface HubOptions { + /** + * Collection of client side callbacks + */ + listeners?: { [index: string]: (...args: any[]) => void }; + + /** + * String array of server side methods which the client can call + */ + methods?: Array; + + /** + * Sets the root path for the SignalR web service + */ + rootPath?: string; + + /** + * Object representing additional query params to be sent on connection + */ + queryParams?: { [index: string]: string }; + + /** + * Function to handle hub connection errors + */ + errorHandler?: (error: string) => void; + + /** + * Enable/disable logging + */ + logging?: boolean; + + /** + * Use a shared global connection or create a new one just for this hub, defaults to true + */ + useSharedConnection?: boolean; + + /** + * Sets transport method (e.g 'longPolling' or ['webSockets', 'longPolling'] ) + */ + transport?: any; + + /** + * Function to handle hub connection state changed event + */ + stateChanged?: (state: SignalR.StateChanged) => void; + } +} diff --git a/angular-signalr-hub/tsconfig.json b/angular-signalr-hub/tsconfig.json new file mode 100644 index 0000000000..04501eb594 --- /dev/null +++ b/angular-signalr-hub/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-signalr-hub-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-spinner/angular-spinner-tests.ts b/angular-spinner/angular-spinner-tests.ts index 4f3f870233..9ac20eed0c 100644 --- a/angular-spinner/angular-spinner-tests.ts +++ b/angular-spinner/angular-spinner-tests.ts @@ -1,4 +1,4 @@ -/// + var myApp = angular.module('testModule'); diff --git a/angular-spinner/angular-spinner.d.ts b/angular-spinner/angular-spinner.d.ts deleted file mode 100644 index ba85d0e53c..0000000000 --- a/angular-spinner/angular-spinner.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Type definitions for angular-spinner.js 0.5.1 -// Project: https://github.com/urish/angular-spinner -// Definitions by: Marcin Biegała -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -/** -* SpinnerService -* see https://github.com/urish/angular-spinner -*/ -interface ISpinnerService { - /** - * Start selected spinner - * - * @param spinner key - */ - spin(key: string): void; - - /** - * Stop selected spinner - * - * @param spinner key - */ - stop(key: string): void; -} diff --git a/angular-spinner/index.d.ts b/angular-spinner/index.d.ts new file mode 100644 index 0000000000..ac0efa0cc4 --- /dev/null +++ b/angular-spinner/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for angular-spinner.js 0.5.1 +// Project: https://github.com/urish/angular-spinner +// Definitions by: Marcin Biegała +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** +* SpinnerService +* see https://github.com/urish/angular-spinner +*/ +interface ISpinnerService { + /** + * Start selected spinner + * + * @param spinner key + */ + spin(key: string): void; + + /** + * Stop selected spinner + * + * @param spinner key + */ + stop(key: string): void; +} diff --git a/angular-spinner/tsconfig.json b/angular-spinner/tsconfig.json new file mode 100644 index 0000000000..94f2479cce --- /dev/null +++ b/angular-spinner/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-spinner-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-storage/angular-storage-tests.ts b/angular-storage/angular-storage-tests.ts index 1455bbd643..0b5a48f12c 100644 --- a/angular-storage/angular-storage-tests.ts +++ b/angular-storage/angular-storage-tests.ts @@ -1,6 +1,3 @@ -/// -/// - // Samples taken from the a0-angular-storage Readme.md var app = angular.module('angular-storage-tests', ['angular-storage']); diff --git a/angular-storage/angular-storage.d.ts b/angular-storage/angular-storage.d.ts deleted file mode 100644 index cb46cd1d7c..0000000000 --- a/angular-storage/angular-storage.d.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Type definitions for angular-storage v0.0.11 -// Project: https://github.com/auth0/angular-storage -// Definitions by: Matthew DeKrey -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace angular.a0.storage { - interface IStoreService extends INamespacedStoreService { - /** - * Returns a namespaced store - * - * @param {String} namespace - The namespace - * @param {String} storage - The name of the storage service. Defaults to local storage. - * @param {String} delimiter - The delimiter to use to separate the namespace and the keys. - * @returns {INamespacedStoreService} - */ - getNamespacedStore(namespace: string, storage?: string, delimiter?: string): INamespacedStoreService; - } - - interface INamespacedStoreService { - /** - * Sets a new value to the storage with the key name. It can be any object. - * - * @param {String} name - The key name for the location of the value - * @param value - The value to store - */ - set(name: string, value: any): void; - - /** - * Returns the saved value with they key name. - * - * @param {String} name - The key name for the location of the value - * @returns The saved value; if you saved an object, you get an object - */ - get(name: string): any; - - /** - * Deletes the saved value with the key name - * - * @param {String} name - The key name for the location of the value to remove - */ - remove(name: string): void; - } - - interface IStoreProvider { - - /** - * Sets the storage. - * - * @param {String} storage - The storage name - */ - setStore(storage: string): void; - } -} diff --git a/angular-storage/index.d.ts b/angular-storage/index.d.ts new file mode 100644 index 0000000000..b9e57edf26 --- /dev/null +++ b/angular-storage/index.d.ts @@ -0,0 +1,55 @@ +// Type definitions for angular-storage v0.0.11 +// Project: https://github.com/auth0/angular-storage +// Definitions by: Matthew DeKrey +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.a0.storage { + interface IStoreService extends INamespacedStoreService { + /** + * Returns a namespaced store + * + * @param {String} namespace - The namespace + * @param {String} storage - The name of the storage service. Defaults to local storage. + * @param {String} delimiter - The delimiter to use to separate the namespace and the keys. + * @returns {INamespacedStoreService} + */ + getNamespacedStore(namespace: string, storage?: string, delimiter?: string): INamespacedStoreService; + } + + interface INamespacedStoreService { + /** + * Sets a new value to the storage with the key name. It can be any object. + * + * @param {String} name - The key name for the location of the value + * @param value - The value to store + */ + set(name: string, value: any): void; + + /** + * Returns the saved value with they key name. + * + * @param {String} name - The key name for the location of the value + * @returns The saved value; if you saved an object, you get an object + */ + get(name: string): any; + + /** + * Deletes the saved value with the key name + * + * @param {String} name - The key name for the location of the value to remove + */ + remove(name: string): void; + } + + interface IStoreProvider { + + /** + * Sets the storage. + * + * @param {String} storage - The storage name + */ + setStore(storage: string): void; + } +} diff --git a/angular-storage/tsconfig.json b/angular-storage/tsconfig.json new file mode 100644 index 0000000000..c81578da03 --- /dev/null +++ b/angular-storage/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-storage-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-strap/angular-strap-tests.ts b/angular-strap/angular-strap-tests.ts index c052ffad4f..c37d6d103b 100644 --- a/angular-strap/angular-strap-tests.ts +++ b/angular-strap/angular-strap-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// namespace angularStrapTests { diff --git a/angular-strap/angular-strap.d.ts b/angular-strap/angular-strap.d.ts deleted file mode 100644 index 5b85f77de1..0000000000 --- a/angular-strap/angular-strap.d.ts +++ /dev/null @@ -1,600 +0,0 @@ -// Type definitions for angular-strap v2.2.x -// Project: http://mgcrea.github.io/angular-strap/ -// Definitions by: Sam Herrmann -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -/// - -declare namespace mgcrea.ngStrap { - - /////////////////////////////////////////////////////////////////////////// - // Modal - // see http://mgcrea.github.io/angular-strap/#/modals - /////////////////////////////////////////////////////////////////////////// - - namespace modal { - - interface IModalService { - (config?: IModalOptions): IModal; - } - - interface IModalProvider { - defaults: IModalOptions; - } - - interface IModal { - $promise: ng.IPromise; - show: () => void; - hide: () => void; - toggle: () => void; - } - - interface IModalOptions { - animation?: string; - backdropAnimation?: string; - placement?: string; - title?: string; - content?: string; - html?: boolean; - backdrop?: boolean | string; - keyboard?: boolean; - show?: boolean; - container?: string | boolean; - template?: string; - contentTemplate?: string; - prefixEvent?: string; - id?: string; - scope?: ng.IScope; - } - - interface IModalScope extends ng.IScope { - $show: () => void; - $hide: () => void; - $toggle: () => void; - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Aside - // see http://mgcrea.github.io/angular-strap/#/asides - /////////////////////////////////////////////////////////////////////////// - - namespace aside { - - interface IAsideService { - (config?: IAsideOptions): IAside; - } - - interface IAsideProvider { - defaults: IAsideOptions; - } - - interface IAside { - $promise: ng.IPromise; - show: () => void; - hide: () => void; - toggle: () => void; - } - - interface IAsideOptions { - animation?: string; - placement?: string; - title?: string; - content?: string; - html?: boolean; - backdrop?: boolean | string; - keyboard?: boolean; - show?: boolean; - container?: string | boolean; - template?: string; - contentTemplate?: string; - scope?: ng.IScope; - } - - interface IAsideScope extends ng.IScope { - $show: () => void; - $hide: () => void; - $toggle: () => void; - } - } - - - - /////////////////////////////////////////////////////////////////////////// - // Alert - // see http://mgcrea.github.io/angular-strap/#/alerts - /////////////////////////////////////////////////////////////////////////// - - namespace alert { - - interface IAlertService { - (config?: IAlertOptions): IAlert; - } - - interface IAlertProvider { - defaults: IAlertOptions; - } - - interface IAlert { - $promise: ng.IPromise; - show: () => void; - hide: () => void; - toggle: () => void; - } - - interface IAlertOptions { - animation?: string; - placement?: string; - title?: string; - content?: string; - type?: string; - keyboard?: boolean; - show?: boolean; - container?: string | boolean; - template?: string; - duration?: number | boolean; - dismissable?: boolean; - } - - interface IAlertScope extends ng.IScope { - $show: () => void; - $hide: () => void; - $toggle: () => void; - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Tooltip - // see http://mgcrea.github.io/angular-strap/#/tooltips - /////////////////////////////////////////////////////////////////////////// - - namespace tooltip { - - interface ITooltipService { - (element: ng.IAugmentedJQuery, config?: ITooltipOptions): ITooltip; - } - - interface ITooltipProvider { - defaults: ITooltipOptions; - } - - interface ITooltip { - $promise: ng.IPromise; - show: () => void; - hide: () => void; - toggle: () => void; - } - - interface ITooltipOptions { - animation?: string; - placement?: string; - trigger?: string; - title?: string; - html?: boolean; - delay?: number | { show: number; hide: number}; - container?: string | boolean; - target?: string | ng.IAugmentedJQuery | boolean; - template?: string; - contentTemplate?: string; - prefixEvent?: string; - id?: string; - viewport?: string | { selector: string; padding: string | number }; - } - - interface ITooltipScope extends ng.IScope { - $show: () => void; - $hide: () => void; - $toggle: () => void; - $setEnabled: (isEnabled: boolean) => void; - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Popover - // see http://mgcrea.github.io/angular-strap/#/popovers - /////////////////////////////////////////////////////////////////////////// - - namespace popover { - - interface IPopoverService { - (element: ng.IAugmentedJQuery, config?: IPopoverOptions): IPopover; - } - - interface IPopoverProvider { - defaults: IPopoverOptions; - } - - interface IPopover { - $promise: ng.IPromise; - show: () => void; - hide: () => void; - toggle: () => void; - } - - interface IPopoverOptions { - animation?: string; - placement?: string; - trigger?: string; - title?: string; - content?: string; - html?: boolean; - delay?: number | { show: number; hide: number }; - container?: string | boolean; - target?: string | ng.IAugmentedJQuery | boolean; - template?: string; - contentTemplate?: string; - autoClose?: boolean; - id?: string; - viewport?: string | { selector: string; padding: string | number }; - } - - interface IPopoverScope extends ng.IScope { - $show: () => void; - $hide: () => void; - $toggle: () => void; - } - } - - - - /////////////////////////////////////////////////////////////////////////// - // Typeahead - // see http://mgcrea.github.io/angular-strap/#/typeaheads - /////////////////////////////////////////////////////////////////////////// - - namespace typeahead { - - interface ITypeaheadService { - (element: ng.IAugmentedJQuery, controller: any, config?: ITypeaheadOptions): ITypeahead; - } - - interface ITypeaheadProvider { - defaults: ITypeaheadOptions; - } - - interface ITypeahead { - $promise: ng.IPromise; - show: () => void; - hide: () => void; - toggle: () => void; - } - - interface ITypeaheadOptions { - animation?: string; - placement?: string; - trigger?: string; - html?: boolean; - delay?: number | { show: number; hide: number }; - container?: string | boolean; - template?: string; - limit?: number; - minLength?: number; - autoSelect?: boolean; - comparator?: string; - id?: string; - watchOptions?: boolean; - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Datepicker - // see http://mgcrea.github.io/angular-strap/#/datepickers - /////////////////////////////////////////////////////////////////////////// - - namespace datepicker { - - interface IDatepickerService { - (element: ng.IAugmentedJQuery, controller: any, config?: IDatepickerOptions): IDatepicker; - } - - interface IDatepickerProvider { - defaults: IDatepickerOptions; - } - - interface IDatepicker { - update: (date: Date) => void; - updateDisabledDates: (dateRanges: IDatepickerDateRange[]) => void; - select: (dateConstructorArg: string | number | number[], keep: boolean) => void; - setMode: (mode: any) => void; - int: () => void; - destroy: () => void; - show: () => void; - hide: () => void; - } - - interface IDatepickerDateRange { - start: Date; - end: Date; - } - - interface IDatepickerOptions { - animation?: string; - placement?: string; - trigger?: string; - html?: boolean; - delay?: number | { show: number; hide: number }; - container?: string | boolean; - template?: string; - dateFormat?: string; - modelDateFormat?: string; - dateType?: string; - timezone?: string; - autoclose?: boolean; - useNative?: boolean; - minDate?: Date; - maxDate?: Date; - startView?: number; - minView?: number; - startWeek?: number; - startDate?: Date; - iconLeft?: string; - iconRight?: string; - daysOfWeekDisabled?: string; - disabledDates?: IDatepickerDateRange[]; - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Timepicker - // see http://mgcrea.github.io/angular-strap/#/timepickers - /////////////////////////////////////////////////////////////////////////// - - namespace timepicker { - - interface ITimepickerService { - (element: ng.IAugmentedJQuery, controller: any, config?: ITimepickerOptions): ITimepicker; - } - - interface ITimepickerProvider { - defaults: ITimepickerOptions; - } - - interface ITimepicker { - - } - - interface ITimepickerOptions { - animation?: string; - placement?: string; - trigger?: string; - html?: boolean; - delay?: number | { show: number; hide: number; }; - container?: string | boolean; - template?: string; - timeFormat?: string; - modelTimeFormat?: string; - timeType?: string; - autoclose?: boolean; - useNative?: boolean; - minTime?: Date; // TODO - maxTime?: Date; // TODO - length?: number; - hourStep?: number; - minuteStep?: number; - secondStep?: number; - roundDisplay?: boolean; - iconUp?: string; - iconDown?: string; - arrowBehaviour?: string; - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Button - // see http://mgcrea.github.io/angular-strap/#/buttons - /////////////////////////////////////////////////////////////////////////// - - // No definitions for this module - - - /////////////////////////////////////////////////////////////////////////// - // Select - // see http://mgcrea.github.io/angular-strap/#/selects - /////////////////////////////////////////////////////////////////////////// - - namespace select { - - interface ISelectService { - (element: ng.IAugmentedJQuery, controller: any, config: ISelectOptions): ISelect; - } - - interface ISelectProvider { - defaults: ISelectOptions; - } - - interface ISelect { - update: (matches: any) => void; - active: (index: number) => number; - select: (index: number) => void; - show: () => void; - hide: () => void; - } - - interface ISelectOptions { - animation?: string; - placement?: string; - trigger?: string; - html?: boolean; - delay?: number | { show: number; hide: number; }; - container?: string | boolean; - template?: string; - multiple?: boolean; - allNoneButtons?: boolean; - allText?: string; - noneText?: string; - maxLength?: number; - maxLengthHtml?: string; - sort?: boolean; - placeholder?: string; - iconCheckmark?: string; - id?: string; - } - } - - /////////////////////////////////////////////////////////////////////////// - // Tabs - // see http://mgcrea.github.io/angular-strap/#/tabs - /////////////////////////////////////////////////////////////////////////// - - namespace tab { - - interface ITabProvider { - defaults: ITabOptions; - } - - interface ITabService { - defaults: ITabOptions; - controller: any; - } - - interface ITabOptions { - animation?: string; - template?: string; - navClass?: string; - activeClass?: string; - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Collapses - // see http://mgcrea.github.io/angular-strap/#/collapses - /////////////////////////////////////////////////////////////////////////// - - namespace collapse { - - interface ICollapseProvider { - defaults: ICollapseOptions; - } - - interface ICollapseOptions { - animation?: string; - activeClass?: string; - disallowToggle?: boolean; - startCollapsed?: boolean; - allowMultiple?: boolean; - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Dropdowsn - // see http://mgcrea.github.io/angular-strap/#/dropdowns - /////////////////////////////////////////////////////////////////////////// - - namespace dropdown { - - interface IDropdownProvider { - defaults: IDropdownOptions; - } - - interface IDropdownService { - (element: ng.IAugmentedJQuery, config: IDropdownOptions): IDropdown; - } - - interface IDropdown { - show: () => void; - hide: () => void; - destroy: () => void; - } - - interface IDropdownOptions { - animation?: string; - placement?: string; - trigger?: string; - html?: boolean; - delay?: number | { show: number; hide: number; }; - container?: string | boolean; - template?: string; - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Navbar - // see http://mgcrea.github.io/angular-strap/#/navbars - /////////////////////////////////////////////////////////////////////////// - - namespace navbar { - - interface INavbarProvider { - defaults: INavbarOptions; - } - - interface INavbarOptions { - activeClass?: string; - routeAttr?: string; - } - - interface INavbarService { - defaults: INavbarOptions; - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Scrollspy - // see http://mgcrea.github.io/angular-strap/#/scrollspy - /////////////////////////////////////////////////////////////////////////// - - namespace scrollspy { - - interface IScrollspyProvider { - defaults: IScrollspyOptions; - } - - interface IScrollspyService { - (element: ng.IAugmentedJQuery, options: IScrollspyOptions): IScrollspy; - } - - interface IScrollspy { - checkOffsets: () => void; - trackElement: (target: any, source: any) => void; - untrackElement: (target: any, source: any) => void; - activate: (index: number) => void; - } - - interface IScrollspyOptions { - target?: string; - offset?: number; - } - } - - - /////////////////////////////////////////////////////////////////////////// - // Affix - // see http://mgcrea.github.io/angular-strap/#/affix - /////////////////////////////////////////////////////////////////////////// - - namespace affix { - - interface IAffixProvider { - defaults: IAffixOptions; - } - - interface IAffixService { - (element: ng.IAugmentedJQuery, options: IAffixOptions): IAffix; - } - - interface IAffix { - init: () => void; - destroy: () => void; - checkPositionWithEventLoop: () => void; - checkPosition: () => void; - } - - interface IAffixOptions { - offsetTop?: number; - offsetBottom?: number; - offsetParent?: number; - offsetUnpin?: number; - } - } -} diff --git a/angular-strap/index.d.ts b/angular-strap/index.d.ts new file mode 100644 index 0000000000..d23a2f4fa8 --- /dev/null +++ b/angular-strap/index.d.ts @@ -0,0 +1,600 @@ +// Type definitions for angular-strap v2.2.x +// Project: http://mgcrea.github.io/angular-strap/ +// Definitions by: Sam Herrmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +declare namespace mgcrea.ngStrap { + + /////////////////////////////////////////////////////////////////////////// + // Modal + // see http://mgcrea.github.io/angular-strap/#/modals + /////////////////////////////////////////////////////////////////////////// + + namespace modal { + + interface IModalService { + (config?: IModalOptions): IModal; + } + + interface IModalProvider { + defaults: IModalOptions; + } + + interface IModal { + $promise: ng.IPromise; + show: () => void; + hide: () => void; + toggle: () => void; + } + + interface IModalOptions { + animation?: string; + backdropAnimation?: string; + placement?: string; + title?: string; + content?: string; + html?: boolean; + backdrop?: boolean | string; + keyboard?: boolean; + show?: boolean; + container?: string | boolean; + template?: string; + contentTemplate?: string; + prefixEvent?: string; + id?: string; + scope?: ng.IScope; + } + + interface IModalScope extends ng.IScope { + $show: () => void; + $hide: () => void; + $toggle: () => void; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Aside + // see http://mgcrea.github.io/angular-strap/#/asides + /////////////////////////////////////////////////////////////////////////// + + namespace aside { + + interface IAsideService { + (config?: IAsideOptions): IAside; + } + + interface IAsideProvider { + defaults: IAsideOptions; + } + + interface IAside { + $promise: ng.IPromise; + show: () => void; + hide: () => void; + toggle: () => void; + } + + interface IAsideOptions { + animation?: string; + placement?: string; + title?: string; + content?: string; + html?: boolean; + backdrop?: boolean | string; + keyboard?: boolean; + show?: boolean; + container?: string | boolean; + template?: string; + contentTemplate?: string; + scope?: ng.IScope; + } + + interface IAsideScope extends ng.IScope { + $show: () => void; + $hide: () => void; + $toggle: () => void; + } + } + + + + /////////////////////////////////////////////////////////////////////////// + // Alert + // see http://mgcrea.github.io/angular-strap/#/alerts + /////////////////////////////////////////////////////////////////////////// + + namespace alert { + + interface IAlertService { + (config?: IAlertOptions): IAlert; + } + + interface IAlertProvider { + defaults: IAlertOptions; + } + + interface IAlert { + $promise: ng.IPromise; + show: () => void; + hide: () => void; + toggle: () => void; + } + + interface IAlertOptions { + animation?: string; + placement?: string; + title?: string; + content?: string; + type?: string; + keyboard?: boolean; + show?: boolean; + container?: string | boolean; + template?: string; + duration?: number | boolean; + dismissable?: boolean; + } + + interface IAlertScope extends ng.IScope { + $show: () => void; + $hide: () => void; + $toggle: () => void; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Tooltip + // see http://mgcrea.github.io/angular-strap/#/tooltips + /////////////////////////////////////////////////////////////////////////// + + namespace tooltip { + + interface ITooltipService { + (element: ng.IAugmentedJQuery, config?: ITooltipOptions): ITooltip; + } + + interface ITooltipProvider { + defaults: ITooltipOptions; + } + + interface ITooltip { + $promise: ng.IPromise; + show: () => void; + hide: () => void; + toggle: () => void; + } + + interface ITooltipOptions { + animation?: string; + placement?: string; + trigger?: string; + title?: string; + html?: boolean; + delay?: number | { show: number; hide: number}; + container?: string | boolean; + target?: string | ng.IAugmentedJQuery | boolean; + template?: string; + contentTemplate?: string; + prefixEvent?: string; + id?: string; + viewport?: string | { selector: string; padding: string | number }; + } + + interface ITooltipScope extends ng.IScope { + $show: () => void; + $hide: () => void; + $toggle: () => void; + $setEnabled: (isEnabled: boolean) => void; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Popover + // see http://mgcrea.github.io/angular-strap/#/popovers + /////////////////////////////////////////////////////////////////////////// + + namespace popover { + + interface IPopoverService { + (element: ng.IAugmentedJQuery, config?: IPopoverOptions): IPopover; + } + + interface IPopoverProvider { + defaults: IPopoverOptions; + } + + interface IPopover { + $promise: ng.IPromise; + show: () => void; + hide: () => void; + toggle: () => void; + } + + interface IPopoverOptions { + animation?: string; + placement?: string; + trigger?: string; + title?: string; + content?: string; + html?: boolean; + delay?: number | { show: number; hide: number }; + container?: string | boolean; + target?: string | ng.IAugmentedJQuery | boolean; + template?: string; + contentTemplate?: string; + autoClose?: boolean; + id?: string; + viewport?: string | { selector: string; padding: string | number }; + } + + interface IPopoverScope extends ng.IScope { + $show: () => void; + $hide: () => void; + $toggle: () => void; + } + } + + + + /////////////////////////////////////////////////////////////////////////// + // Typeahead + // see http://mgcrea.github.io/angular-strap/#/typeaheads + /////////////////////////////////////////////////////////////////////////// + + namespace typeahead { + + interface ITypeaheadService { + (element: ng.IAugmentedJQuery, controller: any, config?: ITypeaheadOptions): ITypeahead; + } + + interface ITypeaheadProvider { + defaults: ITypeaheadOptions; + } + + interface ITypeahead { + $promise: ng.IPromise; + show: () => void; + hide: () => void; + toggle: () => void; + } + + interface ITypeaheadOptions { + animation?: string; + placement?: string; + trigger?: string; + html?: boolean; + delay?: number | { show: number; hide: number }; + container?: string | boolean; + template?: string; + limit?: number; + minLength?: number; + autoSelect?: boolean; + comparator?: string; + id?: string; + watchOptions?: boolean; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Datepicker + // see http://mgcrea.github.io/angular-strap/#/datepickers + /////////////////////////////////////////////////////////////////////////// + + namespace datepicker { + + interface IDatepickerService { + (element: ng.IAugmentedJQuery, controller: any, config?: IDatepickerOptions): IDatepicker; + } + + interface IDatepickerProvider { + defaults: IDatepickerOptions; + } + + interface IDatepicker { + update: (date: Date) => void; + updateDisabledDates: (dateRanges: IDatepickerDateRange[]) => void; + select: (dateConstructorArg: string | number | number[], keep: boolean) => void; + setMode: (mode: any) => void; + int: () => void; + destroy: () => void; + show: () => void; + hide: () => void; + } + + interface IDatepickerDateRange { + start: Date; + end: Date; + } + + interface IDatepickerOptions { + animation?: string; + placement?: string; + trigger?: string; + html?: boolean; + delay?: number | { show: number; hide: number }; + container?: string | boolean; + template?: string; + dateFormat?: string; + modelDateFormat?: string; + dateType?: string; + timezone?: string; + autoclose?: boolean; + useNative?: boolean; + minDate?: Date; + maxDate?: Date; + startView?: number; + minView?: number; + startWeek?: number; + startDate?: Date; + iconLeft?: string; + iconRight?: string; + daysOfWeekDisabled?: string; + disabledDates?: IDatepickerDateRange[]; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Timepicker + // see http://mgcrea.github.io/angular-strap/#/timepickers + /////////////////////////////////////////////////////////////////////////// + + namespace timepicker { + + interface ITimepickerService { + (element: ng.IAugmentedJQuery, controller: any, config?: ITimepickerOptions): ITimepicker; + } + + interface ITimepickerProvider { + defaults: ITimepickerOptions; + } + + interface ITimepicker { + + } + + interface ITimepickerOptions { + animation?: string; + placement?: string; + trigger?: string; + html?: boolean; + delay?: number | { show: number; hide: number; }; + container?: string | boolean; + template?: string; + timeFormat?: string; + modelTimeFormat?: string; + timeType?: string; + autoclose?: boolean; + useNative?: boolean; + minTime?: Date; // TODO + maxTime?: Date; // TODO + length?: number; + hourStep?: number; + minuteStep?: number; + secondStep?: number; + roundDisplay?: boolean; + iconUp?: string; + iconDown?: string; + arrowBehaviour?: string; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Button + // see http://mgcrea.github.io/angular-strap/#/buttons + /////////////////////////////////////////////////////////////////////////// + + // No definitions for this module + + + /////////////////////////////////////////////////////////////////////////// + // Select + // see http://mgcrea.github.io/angular-strap/#/selects + /////////////////////////////////////////////////////////////////////////// + + namespace select { + + interface ISelectService { + (element: ng.IAugmentedJQuery, controller: any, config: ISelectOptions): ISelect; + } + + interface ISelectProvider { + defaults: ISelectOptions; + } + + interface ISelect { + update: (matches: any) => void; + active: (index: number) => number; + select: (index: number) => void; + show: () => void; + hide: () => void; + } + + interface ISelectOptions { + animation?: string; + placement?: string; + trigger?: string; + html?: boolean; + delay?: number | { show: number; hide: number; }; + container?: string | boolean; + template?: string; + multiple?: boolean; + allNoneButtons?: boolean; + allText?: string; + noneText?: string; + maxLength?: number; + maxLengthHtml?: string; + sort?: boolean; + placeholder?: string; + iconCheckmark?: string; + id?: string; + } + } + + /////////////////////////////////////////////////////////////////////////// + // Tabs + // see http://mgcrea.github.io/angular-strap/#/tabs + /////////////////////////////////////////////////////////////////////////// + + namespace tab { + + interface ITabProvider { + defaults: ITabOptions; + } + + interface ITabService { + defaults: ITabOptions; + controller: any; + } + + interface ITabOptions { + animation?: string; + template?: string; + navClass?: string; + activeClass?: string; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Collapses + // see http://mgcrea.github.io/angular-strap/#/collapses + /////////////////////////////////////////////////////////////////////////// + + namespace collapse { + + interface ICollapseProvider { + defaults: ICollapseOptions; + } + + interface ICollapseOptions { + animation?: string; + activeClass?: string; + disallowToggle?: boolean; + startCollapsed?: boolean; + allowMultiple?: boolean; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Dropdowsn + // see http://mgcrea.github.io/angular-strap/#/dropdowns + /////////////////////////////////////////////////////////////////////////// + + namespace dropdown { + + interface IDropdownProvider { + defaults: IDropdownOptions; + } + + interface IDropdownService { + (element: ng.IAugmentedJQuery, config: IDropdownOptions): IDropdown; + } + + interface IDropdown { + show: () => void; + hide: () => void; + destroy: () => void; + } + + interface IDropdownOptions { + animation?: string; + placement?: string; + trigger?: string; + html?: boolean; + delay?: number | { show: number; hide: number; }; + container?: string | boolean; + template?: string; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Navbar + // see http://mgcrea.github.io/angular-strap/#/navbars + /////////////////////////////////////////////////////////////////////////// + + namespace navbar { + + interface INavbarProvider { + defaults: INavbarOptions; + } + + interface INavbarOptions { + activeClass?: string; + routeAttr?: string; + } + + interface INavbarService { + defaults: INavbarOptions; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Scrollspy + // see http://mgcrea.github.io/angular-strap/#/scrollspy + /////////////////////////////////////////////////////////////////////////// + + namespace scrollspy { + + interface IScrollspyProvider { + defaults: IScrollspyOptions; + } + + interface IScrollspyService { + (element: ng.IAugmentedJQuery, options: IScrollspyOptions): IScrollspy; + } + + interface IScrollspy { + checkOffsets: () => void; + trackElement: (target: any, source: any) => void; + untrackElement: (target: any, source: any) => void; + activate: (index: number) => void; + } + + interface IScrollspyOptions { + target?: string; + offset?: number; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Affix + // see http://mgcrea.github.io/angular-strap/#/affix + /////////////////////////////////////////////////////////////////////////// + + namespace affix { + + interface IAffixProvider { + defaults: IAffixOptions; + } + + interface IAffixService { + (element: ng.IAugmentedJQuery, options: IAffixOptions): IAffix; + } + + interface IAffix { + init: () => void; + destroy: () => void; + checkPositionWithEventLoop: () => void; + checkPosition: () => void; + } + + interface IAffixOptions { + offsetTop?: number; + offsetBottom?: number; + offsetParent?: number; + offsetUnpin?: number; + } + } +} diff --git a/angular-strap/tsconfig.json b/angular-strap/tsconfig.json new file mode 100644 index 0000000000..8b426c8c0e --- /dev/null +++ b/angular-strap/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-strap-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-toastr/angular-toastr-tests.ts b/angular-toastr/angular-toastr-tests.ts index e5701746f7..ba11179df0 100644 --- a/angular-toastr/angular-toastr-tests.ts +++ b/angular-toastr/angular-toastr-tests.ts @@ -1,6 +1,4 @@ -/// -/// - +import * as angular from 'angularjs'; angular .module('toastr-tests', ['toastr']) diff --git a/angular-toastr/angular-toastr.d.ts b/angular-toastr/angular-toastr.d.ts deleted file mode 100644 index 698ced16cc..0000000000 --- a/angular-toastr/angular-toastr.d.ts +++ /dev/null @@ -1,122 +0,0 @@ -// Type definitions for Angular Toastr v1.6.0 -// Project: https://github.com/Foxandxss/angular-toastr -// Definitions by: Niko Kovačič -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "angular-toastr" { - var _: string; - export = _; -} - -declare namespace angular.toastr { - interface IToastBaseConfig { - allowHtml?: boolean; - closeButton?: boolean; - closeHtml?: string; - extendedTimeOut?: number; - messageClass?: string; - onHidden?: Function; - onShown?: Function; - onTap?: Function; - progressBar?: boolean; - tapToDismiss?: boolean; - templates?: { - toast?: string; - progressbar?: string; - }; - timeOut?: number; - titleClass?: string; - toastClass?: string; - } - - interface IToastContainerConfig { - autoDismiss?: boolean; - containerId?: string; - maxOpened?: number; - newestOnTop?: boolean; - positionClass?: string; - preventDuplicates?: boolean; - preventOpenDuplicates?: boolean; - target?: string; - } - - interface IToastConfig extends IToastBaseConfig { - iconClasses?: { - error?: string; - info?: string; - success?: string; - warning?: string; - }; - } - - interface IToastrConfig extends IToastContainerConfig, IToastConfig { } - - interface IToastScope extends angular.IScope { - message: string; - options: IToastConfig; - title: string; - toastId: number; - toastType: string; - } - - interface IToast { - el: angular.IAugmentedJQuery; - iconClass: string; - isOpened: boolean; - open: angular.IPromise; - scope: IToastScope; - toastId: number; - } - - interface IToastOptions extends IToastBaseConfig { - iconClass?: string; - target?: string; - } - - interface IToastrService { - /** - * Return the number of active toasts in screen. - */ - active(): number; - /** - * Remove toast from screen. If no toast is passed in, all toasts will be closed. - * - * @param {IToast} toast Optional toast object to delete - */ - clear(toast?: IToast): void; - /** - * Create error toast notification message. - * - * @param {String} message Message to show on toast - * @param {String} title Title to show on toast - * @param {IToastOptions} options Override default toast options - */ - error(message: string, title?: string, options?: IToastOptions): IToast; - /** - * Create info toast notification message. - * - * @param {String} message Message to show on toast - * @param {String} title Title to show on toast - * @param {IToastOptions} options Override default toast options - */ - info(message: string, title?: string, options?: IToastOptions): IToast; - /** - * Create success toast notification message. - * - * @param {String} message Message to show on toast - * @param {String} title Title to show on toast - * @param {IToastOptions} options Override default toast options - */ - success(message: string, title?: string, options?: IToastOptions): IToast; - /** - * Create warning toast notification message. - * - * @param {String} message Message to show on toast - * @param {String} title Title to show on toast - * @param {IToastOptions} options Override default toast options - */ - warning(message: string, title?: string, options?: IToastOptions): IToast; - } -} diff --git a/angular-toastr/index.d.ts b/angular-toastr/index.d.ts new file mode 100644 index 0000000000..7c9e40a420 --- /dev/null +++ b/angular-toastr/index.d.ts @@ -0,0 +1,121 @@ +// Type definitions for Angular Toastr v1.6.0 +// Project: https://github.com/Foxandxss/angular-toastr +// Definitions by: Niko Kovačič +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as angular from 'angularjs'; + +declare module 'angularjs' { + export namespace toastr { + interface IToastBaseConfig { + allowHtml?: boolean; + closeButton?: boolean; + closeHtml?: string; + extendedTimeOut?: number; + messageClass?: string; + onHidden?: Function; + onShown?: Function; + onTap?: Function; + progressBar?: boolean; + tapToDismiss?: boolean; + templates?: { + toast?: string; + progressbar?: string; + }; + timeOut?: number; + titleClass?: string; + toastClass?: string; + } + + interface IToastContainerConfig { + autoDismiss?: boolean; + containerId?: string; + maxOpened?: number; + newestOnTop?: boolean; + positionClass?: string; + preventDuplicates?: boolean; + preventOpenDuplicates?: boolean; + target?: string; + } + + interface IToastConfig extends IToastBaseConfig { + iconClasses?: { + error?: string; + info?: string; + success?: string; + warning?: string; + }; + } + + interface IToastrConfig extends IToastContainerConfig, IToastConfig { } + + interface IToastScope extends angular.IScope { + message: string; + options: IToastConfig; + title: string; + toastId: number; + toastType: string; + } + + interface IToast { + el: angular.IAugmentedJQuery; + iconClass: string; + isOpened: boolean; + open: angular.IPromise; + scope: IToastScope; + toastId: number; + } + + interface IToastOptions extends IToastBaseConfig { + iconClass?: string; + target?: string; + } + + interface IToastrService { + /** + * Return the number of active toasts in screen. + */ + active(): number; + /** + * Remove toast from screen. If no toast is passed in, all toasts will be closed. + * + * @param {IToast} toast Optional toast object to delete + */ + clear(toast?: IToast): void; + /** + * Create error toast notification message. + * + * @param {String} message Message to show on toast + * @param {String} title Title to show on toast + * @param {IToastOptions} options Override default toast options + */ + error(message: string, title?: string, options?: IToastOptions): IToast; + /** + * Create info toast notification message. + * + * @param {String} message Message to show on toast + * @param {String} title Title to show on toast + * @param {IToastOptions} options Override default toast options + */ + info(message: string, title?: string, options?: IToastOptions): IToast; + /** + * Create success toast notification message. + * + * @param {String} message Message to show on toast + * @param {String} title Title to show on toast + * @param {IToastOptions} options Override default toast options + */ + success(message: string, title?: string, options?: IToastOptions): IToast; + /** + * Create warning toast notification message. + * + * @param {String} message Message to show on toast + * @param {String} title Title to show on toast + * @param {IToastOptions} options Override default toast options + */ + warning(message: string, title?: string, options?: IToastOptions): IToast; + } + } +} diff --git a/angular-toastr/tsconfig.json b/angular-toastr/tsconfig.json new file mode 100644 index 0000000000..569756aadd --- /dev/null +++ b/angular-toastr/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-toastr-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-toasty/angular-toasty-tests.ts b/angular-toasty/angular-toasty-tests.ts index 017d821720..ac636e75f6 100644 --- a/angular-toasty/angular-toasty-tests.ts +++ b/angular-toasty/angular-toasty-tests.ts @@ -1,4 +1,4 @@ -/// + interface AngularToastyTestControllerScope extends ng.IScope { button:string; diff --git a/angular-toasty/angular-toasty.d.ts b/angular-toasty/angular-toasty.d.ts deleted file mode 100644 index bec5bb32f1..0000000000 --- a/angular-toasty/angular-toasty.d.ts +++ /dev/null @@ -1,251 +0,0 @@ -// Type definitions for Angular Toasty v1.0.2 -// Project: https://github.com/invertase/angular-toasty -// Definitions by: Dominik Muench -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace toasty { - - interface IToastyService { - /** - * Create a toast with the given options and type. - * @param options - * @param type - */ - (options: IToastyConfig, type?: string): void; - - /** - * Create a default "quick toast" with the given title. - * @param title - */ - (title: string|number): void; - - /** - * Create a default toast with the given options. - * @param options - */ - default(options: IToastyConfig): void; - - /** - * Create a default "quick toast" with the given title. - * @param title - */ - default(title: string|number): void; - - /** - * Create an info toast with the given options. - * @param options - */ - info(options: IToastyConfig): void; - - /** - * Create an info "quick toast" with the given title. - * @param title - */ - info(title: string|number): void; - - /** - * Create a wait toast with the given options. - * @param options - */ - wait(options: IToastyConfig): void; - - /** - * Create a wait "quick toast" with the given title. - * @param title - */ - wait(title: string|number): void; - - /** - * Create a success toast with the given options. - * @param options - */ - success(options: IToastyConfig): void; - - /** - * Create a success "quick toast" with the given title. - * @param title - */ - success(title: string|number): void; - - /** - * Create an error toast with the given options. - * @param options - */ - error(options: IToastyConfig): void; - - /** - * Create an error "quick toast" with the given title. - * @param title - */ - error(title: string|number): void; - - /** - * Create a warning toast with the given options. - * @param options - */ - warning(options: IToastyConfig): void; - - /** - * Create a warning "quick toast" with the given title. - * @param title - */ - warning(title: string|number): void; - - /** - * Clear toast(s). - * @param id Optional ID to clear a specific toast. - */ - clear(id?: number): void; - - /** - * Get the global config. - */ - getGlobalConfig(): IGlobalConfig; - - } - - interface IToastyConfig { - /** - * The toast's title. - */ - title: string; - - /** - * The toast's message. - */ - msg?: string; - - /** - * Whether to show the 'X' icon to close the toast. - */ - showClose?: boolean; - - /** - * Whether clicking the toast closes it. - */ - clickToClose?: boolean; - - /** - * How long (in milliseconds) the toast shows before it's removed. Set to false to disable. - */ - timeout?: number; - - /** - * Whether to play a sound when a toast is added. - */ - sound?: boolean; - - /** - * Whether HTML is allowed in toasts. - */ - html?: boolean; - - /** - * Whether to shake the toasts. - */ - shake?: boolean; - - /** - * What theme to use. - * - 'default' - * - 'material' - * - 'bootstrap' - */ - theme?: string; - - /** - * The toast's type: - * - 'default' - * - 'info' - * - 'success' - * - 'wait' - * - 'error' - * - 'warning' - */ - type?: string; - - /** - * Add event handler. - */ - onAdd?: Function; - - /** - * Remove event handler. - */ - onRemove?: Function; - - /** - * Click event handler. - */ - onClick?: Function; - } - - interface IGlobalConfig { - - /** - * Maximum number of toasts to show at once. - */ - limit?: number; - - /** - * The toast's title. - */ - title?: string; - - /** - * The toast's message. - */ - msg?: string; - - /** - * Whether to show the 'X' icon to close the toast. - */ - showClose?: boolean; - - /** - * Whether clicking the toast closes it. - */ - clickToClose?: boolean; - - /** - * The window position where the toast pops up. - * - */ - position?: string; - - /** - * How long (in miliseconds) the toast shows before it's removed. Set to false to disable. - */ - timeout?: number|boolean; - - /** - * Whether to play a sound when a toast is added. - */ - sound?: boolean; - - /** - * Whether HTML is allowed in toast. - */ - html?: boolean; - - /** - * Whether to shake the toast. - */ - shake?: boolean; - - /** - * What theme to use. - * - 'default' - * - 'material' - * - 'bootstrap' - */ - theme?: string; - } - - interface IToastyConfigProvider { - setConfig(override: IGlobalConfig): void; - $get(): IGlobalConfig; - } -} diff --git a/angular-toasty/index.d.ts b/angular-toasty/index.d.ts new file mode 100644 index 0000000000..a57574b29d --- /dev/null +++ b/angular-toasty/index.d.ts @@ -0,0 +1,251 @@ +// Type definitions for Angular Toasty v1.0.2 +// Project: https://github.com/invertase/angular-toasty +// Definitions by: Dominik Muench +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace toasty { + + interface IToastyService { + /** + * Create a toast with the given options and type. + * @param options + * @param type + */ + (options: IToastyConfig, type?: string): void; + + /** + * Create a default "quick toast" with the given title. + * @param title + */ + (title: string|number): void; + + /** + * Create a default toast with the given options. + * @param options + */ + default(options: IToastyConfig): void; + + /** + * Create a default "quick toast" with the given title. + * @param title + */ + default(title: string|number): void; + + /** + * Create an info toast with the given options. + * @param options + */ + info(options: IToastyConfig): void; + + /** + * Create an info "quick toast" with the given title. + * @param title + */ + info(title: string|number): void; + + /** + * Create a wait toast with the given options. + * @param options + */ + wait(options: IToastyConfig): void; + + /** + * Create a wait "quick toast" with the given title. + * @param title + */ + wait(title: string|number): void; + + /** + * Create a success toast with the given options. + * @param options + */ + success(options: IToastyConfig): void; + + /** + * Create a success "quick toast" with the given title. + * @param title + */ + success(title: string|number): void; + + /** + * Create an error toast with the given options. + * @param options + */ + error(options: IToastyConfig): void; + + /** + * Create an error "quick toast" with the given title. + * @param title + */ + error(title: string|number): void; + + /** + * Create a warning toast with the given options. + * @param options + */ + warning(options: IToastyConfig): void; + + /** + * Create a warning "quick toast" with the given title. + * @param title + */ + warning(title: string|number): void; + + /** + * Clear toast(s). + * @param id Optional ID to clear a specific toast. + */ + clear(id?: number): void; + + /** + * Get the global config. + */ + getGlobalConfig(): IGlobalConfig; + + } + + interface IToastyConfig { + /** + * The toast's title. + */ + title: string; + + /** + * The toast's message. + */ + msg?: string; + + /** + * Whether to show the 'X' icon to close the toast. + */ + showClose?: boolean; + + /** + * Whether clicking the toast closes it. + */ + clickToClose?: boolean; + + /** + * How long (in milliseconds) the toast shows before it's removed. Set to false to disable. + */ + timeout?: number; + + /** + * Whether to play a sound when a toast is added. + */ + sound?: boolean; + + /** + * Whether HTML is allowed in toasts. + */ + html?: boolean; + + /** + * Whether to shake the toasts. + */ + shake?: boolean; + + /** + * What theme to use. + * - 'default' + * - 'material' + * - 'bootstrap' + */ + theme?: string; + + /** + * The toast's type: + * - 'default' + * - 'info' + * - 'success' + * - 'wait' + * - 'error' + * - 'warning' + */ + type?: string; + + /** + * Add event handler. + */ + onAdd?: Function; + + /** + * Remove event handler. + */ + onRemove?: Function; + + /** + * Click event handler. + */ + onClick?: Function; + } + + interface IGlobalConfig { + + /** + * Maximum number of toasts to show at once. + */ + limit?: number; + + /** + * The toast's title. + */ + title?: string; + + /** + * The toast's message. + */ + msg?: string; + + /** + * Whether to show the 'X' icon to close the toast. + */ + showClose?: boolean; + + /** + * Whether clicking the toast closes it. + */ + clickToClose?: boolean; + + /** + * The window position where the toast pops up. + * + */ + position?: string; + + /** + * How long (in miliseconds) the toast shows before it's removed. Set to false to disable. + */ + timeout?: number|boolean; + + /** + * Whether to play a sound when a toast is added. + */ + sound?: boolean; + + /** + * Whether HTML is allowed in toast. + */ + html?: boolean; + + /** + * Whether to shake the toast. + */ + shake?: boolean; + + /** + * What theme to use. + * - 'default' + * - 'material' + * - 'bootstrap' + */ + theme?: string; + } + + interface IToastyConfigProvider { + setConfig(override: IGlobalConfig): void; + $get(): IGlobalConfig; + } +} diff --git a/angular-toasty/tsconfig.json b/angular-toasty/tsconfig.json new file mode 100644 index 0000000000..83f62ee2fb --- /dev/null +++ b/angular-toasty/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-toasty-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-touchspin/angular-touchspin-tests.ts b/angular-touchspin/angular-touchspin-tests.ts index c6e229c7f5..ed7fd0a2ca 100644 --- a/angular-touchspin/angular-touchspin-tests.ts +++ b/angular-touchspin/angular-touchspin-tests.ts @@ -1,5 +1,4 @@ -/// -/// +import angularTouchSpin = require("angular-touchspin"); angular .module('touchspin-tests', ['lm.touchspin']) diff --git a/angular-touchspin/angular-touchspin.d.ts b/angular-touchspin/angular-touchspin.d.ts deleted file mode 100644 index 5423b17e55..0000000000 --- a/angular-touchspin/angular-touchspin.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Type definitions for Angular Touchspin v1.0.0 -// Project: https://github.com/nkovacic/angular-touchspin -// Definitions by: Niko Kovačič -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -//// - - -declare module "angular-touchspin" { - let _: string; - export = _; -} - -declare namespace angularTouchSpin { - interface ITouchSpinOptions { - min?: number; - max?: number; - step?: number; - decimals?: number; - stepInterval?: number; - forceStepDivisibility?: string; // none | floor | round | ceil - stepIntervalDelay?: number; - verticalButtons?: boolean; - verticalUpClass?: string; - verticalDownClass?: string; - initVal?: number; - prefix?: string; - postfix?: string; - prefixExtraClass?: string; - postfixExtraClass?: string; - mousewheel?: boolean; - buttonDownClass?: string; - buttonUpClass?: string; - buttonDownTxt?: string; - buttonUpTxt?: string; - } - - interface ITouchSpinConfig extends ITouchSpinOptions { } - - interface ITouchSpinConfigProvider { - defaults(touchSpinOptions: ITouchSpinOptions): void; - } -} diff --git a/angular-touchspin/index.d.ts b/angular-touchspin/index.d.ts new file mode 100644 index 0000000000..f4ad318a77 --- /dev/null +++ b/angular-touchspin/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for Angular Touchspin v1.0.0 +// Project: https://github.com/nkovacic/angular-touchspin +// Definitions by: Niko Kovačič +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare let angularTouchSpin: string; +export = angularTouchSpin; + +declare namespace angularTouchSpin { + interface ITouchSpinOptions { + min?: number; + max?: number; + step?: number; + decimals?: number; + stepInterval?: number; + forceStepDivisibility?: string; // none | floor | round | ceil + stepIntervalDelay?: number; + verticalButtons?: boolean; + verticalUpClass?: string; + verticalDownClass?: string; + initVal?: number; + prefix?: string; + postfix?: string; + prefixExtraClass?: string; + postfixExtraClass?: string; + mousewheel?: boolean; + buttonDownClass?: string; + buttonUpClass?: string; + buttonDownTxt?: string; + buttonUpTxt?: string; + } + + interface ITouchSpinConfig extends ITouchSpinOptions { } + + interface ITouchSpinConfigProvider { + defaults(touchSpinOptions: ITouchSpinOptions): void; + } +} diff --git a/angular-touchspin/tsconfig.json b/angular-touchspin/tsconfig.json new file mode 100644 index 0000000000..9473c51847 --- /dev/null +++ b/angular-touchspin/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-touchspin-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-translate/angular-translate-tests.ts b/angular-translate/angular-translate-tests.ts index 8ef1ab2e39..cc1d65afe9 100644 --- a/angular-translate/angular-translate-tests.ts +++ b/angular-translate/angular-translate-tests.ts @@ -1,4 +1,4 @@ -/// + var app = angular.module('at', ['pascalprecht.translate']); @@ -35,7 +35,11 @@ interface Scope extends ng.IScope { app.controller('Ctrl', ($scope: Scope, $translate: angular.translate.ITranslateService) => { $scope['changeLanguage'] = function (key: any) { - $translate.use(key); + $translate.onReady().then(() => { + if($translate.isReady()) { + $translate.use(key); + } + }); }; }).run(($filter: ng.IFilterService) => { var x: string; diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts deleted file mode 100644 index 9d9eeb98a1..0000000000 --- a/angular-translate/angular-translate.d.ts +++ /dev/null @@ -1,121 +0,0 @@ -// Type definitions for Angular Translate v2.4.0 (pascalprecht.translate module) -// Project: https://github.com/PascalPrecht/angular-translate -// Definitions by: Michel Salib -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "angular-translate" { - import ngt = angular.translate; - export = ngt; -} - -declare namespace angular.translate { - - interface ITranslationTable { - [key: string]: any; - } - - interface ILanguageKeyAlias { - [key: string]: string; - } - - interface IStorage { - get(name: string): string; - put(name: string, value: string): void; - } - - interface IStaticFilesLoaderOptions { - prefix: string; - suffix: string; - key?: string; - } - - interface IPartialLoader { - addPart(name : string, priority? : number) : T; - deletePart(name : string) : T; - isPartAvailable(name : string) : boolean; - } - - interface ITranslatePartialLoaderService extends IPartialLoader { - getRegisteredParts() : Array; - isPartLoaded(name : string, lang : string) : boolean; - } - - interface ITranslatePartialLoaderProvider extends angular.IServiceProvider, IPartialLoader { - setPart(lang : string, part : string, table : ITranslationTable) : ITranslatePartialLoaderProvider; - } - - interface ITranslateService { - (translationId: string, interpolateParams?: any, interpolationId?: string): angular.IPromise; - (translationId: string[], interpolateParams?: any, interpolationId?: string): angular.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): { [key: string]: string }; - isPostCompilingEnabled(): boolean; - preferredLanguage(langKey?: string): string; - proposedLanguage(): string; - refresh(langKey?: string): angular.IPromise; - storage(): IStorage; - storageKey(): string; - use(): string; - use(key: string): angular.IPromise; - useFallbackLanguage(langKey?: string): void; - versionInfo(): string; - loaderCache(): any; - } - - interface ITranslateProvider extends angular.IServiceProvider { - translations(): ITranslationTable; - translations(key: string, translationTable: ITranslationTable): ITranslateProvider; - cloakClassName(): string; - cloakClassName(name: string): ITranslateProvider; - addInterpolation(factory: any): ITranslateProvider; - useMessageFormatInterpolation(): ITranslateProvider; - useInterpolation(factory: string): ITranslateProvider; - useSanitizeValueStrategy(value: string): ITranslateProvider; - preferredLanguage(): ITranslateProvider; - preferredLanguage(language: string): ITranslateProvider; - translationNotFoundIndicator(indicator: string): ITranslateProvider; - translationNotFoundIndicatorLeft(): string; - translationNotFoundIndicatorLeft(indicator: string): ITranslateProvider; - translationNotFoundIndicatorRight(): string; - translationNotFoundIndicatorRight(indicator: string): ITranslateProvider; - fallbackLanguage(): ITranslateProvider; - fallbackLanguage(language: string): ITranslateProvider; - fallbackLanguage(languages: string[]): ITranslateProvider; - forceAsyncReload(value: boolean): ITranslateProvider; - use(): string; - use(key: string): ITranslateProvider; - storageKey(): string; - storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here - useUrlLoader(url: string): ITranslateProvider; - useStaticFilesLoader(options: IStaticFilesLoaderOptions): ITranslateProvider; - useLoader(loaderFactory: string, options?: any): ITranslateProvider; - useLocalStorage(): ITranslateProvider; - useCookieStorage(): ITranslateProvider; - useStorage(storageFactory: any): ITranslateProvider; - storagePrefix(): string; - storagePrefix(prefix: string): ITranslateProvider; - useMissingTranslationHandlerLog(): ITranslateProvider; - useMissingTranslationHandler(factory: string): ITranslateProvider; - usePostCompiling(value: boolean): ITranslateProvider; - directivePriority(): number; - directivePriority(priority: number): ITranslateProvider; - determinePreferredLanguage(fn?: () => void): ITranslateProvider; - registerAvailableLanguageKeys(): string[]; - registerAvailableLanguageKeys(languageKeys: string[], aliases?: ILanguageKeyAlias): ITranslateProvider; - useLoaderCache(cache?: any): ITranslateProvider; - } -} - -declare namespace angular { - interface IFilterService { - (name:'translate'): { - (translationId: string, interpolateParams?: any, interpolation?: string): string; - }; - } -} diff --git a/angular-translate/index.d.ts b/angular-translate/index.d.ts new file mode 100644 index 0000000000..e2e72cced9 --- /dev/null +++ b/angular-translate/index.d.ts @@ -0,0 +1,123 @@ +// Type definitions for Angular Translate v2.4.0 (pascalprecht.translate module) +// Project: https://github.com/PascalPrecht/angular-translate +// Definitions by: Michel Salib +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "angular-translate" { + import ngt = angular.translate; + export = ngt; +} + +declare namespace angular.translate { + + interface ITranslationTable { + [key: string]: any; + } + + interface ILanguageKeyAlias { + [key: string]: string; + } + + interface IStorage { + get(name: string): string; + put(name: string, value: string): void; + } + + interface IStaticFilesLoaderOptions { + prefix: string; + suffix: string; + key?: string; + } + + interface IPartialLoader { + addPart(name : string, priority? : number) : T; + deletePart(name : string) : T; + isPartAvailable(name : string) : boolean; + } + + interface ITranslatePartialLoaderService extends IPartialLoader { + getRegisteredParts() : Array; + isPartLoaded(name : string, lang : string) : boolean; + } + + interface ITranslatePartialLoaderProvider extends angular.IServiceProvider, IPartialLoader { + setPart(lang : string, part : string, table : ITranslationTable) : ITranslatePartialLoaderProvider; + } + + interface ITranslateService { + (translationId: string, interpolateParams?: any, interpolationId?: string): angular.IPromise; + (translationId: string[], interpolateParams?: any, interpolationId?: string): angular.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): { [key: string]: string }; + isPostCompilingEnabled(): boolean; + preferredLanguage(langKey?: string): string; + proposedLanguage(): string; + refresh(langKey?: string): angular.IPromise; + storage(): IStorage; + storageKey(): string; + use(): string; + use(key: string): angular.IPromise; + useFallbackLanguage(langKey?: string): void; + versionInfo(): string; + loaderCache(): any; + isReady(): boolean; + onReady(): angular.IPromise; + } + + interface ITranslateProvider extends angular.IServiceProvider { + translations(): ITranslationTable; + translations(key: string, translationTable: ITranslationTable): ITranslateProvider; + cloakClassName(): string; + cloakClassName(name: string): ITranslateProvider; + addInterpolation(factory: any): ITranslateProvider; + useMessageFormatInterpolation(): ITranslateProvider; + useInterpolation(factory: string): ITranslateProvider; + useSanitizeValueStrategy(value: string): ITranslateProvider; + preferredLanguage(): ITranslateProvider; + preferredLanguage(language: string): ITranslateProvider; + translationNotFoundIndicator(indicator: string): ITranslateProvider; + translationNotFoundIndicatorLeft(): string; + translationNotFoundIndicatorLeft(indicator: string): ITranslateProvider; + translationNotFoundIndicatorRight(): string; + translationNotFoundIndicatorRight(indicator: string): ITranslateProvider; + fallbackLanguage(): ITranslateProvider; + fallbackLanguage(language: string): ITranslateProvider; + fallbackLanguage(languages: string[]): ITranslateProvider; + forceAsyncReload(value: boolean): ITranslateProvider; + use(): string; + use(key: string): ITranslateProvider; + storageKey(): string; + storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here + useUrlLoader(url: string): ITranslateProvider; + useStaticFilesLoader(options: IStaticFilesLoaderOptions): ITranslateProvider; + useLoader(loaderFactory: string, options?: any): ITranslateProvider; + useLocalStorage(): ITranslateProvider; + useCookieStorage(): ITranslateProvider; + useStorage(storageFactory: any): ITranslateProvider; + storagePrefix(): string; + storagePrefix(prefix: string): ITranslateProvider; + useMissingTranslationHandlerLog(): ITranslateProvider; + useMissingTranslationHandler(factory: string): ITranslateProvider; + usePostCompiling(value: boolean): ITranslateProvider; + directivePriority(): number; + directivePriority(priority: number): ITranslateProvider; + determinePreferredLanguage(fn?: () => void): ITranslateProvider; + registerAvailableLanguageKeys(): string[]; + registerAvailableLanguageKeys(languageKeys: string[], aliases?: ILanguageKeyAlias): ITranslateProvider; + useLoaderCache(cache?: any): ITranslateProvider; + } +} + +declare namespace angular { + interface IFilterService { + (name:'translate'): { + (translationId: string, interpolateParams?: any, interpolation?: string): string; + }; + } +} diff --git a/angular-translate/tsconfig.json b/angular-translate/tsconfig.json new file mode 100644 index 0000000000..12dd2b5342 --- /dev/null +++ b/angular-translate/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-translate-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts index 7851d2da37..499078fa19 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts @@ -1,4 +1,4 @@ -/// + var testApp = angular.module('testApp'); diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts deleted file mode 100644 index 29ad03485b..0000000000 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ /dev/null @@ -1,752 +0,0 @@ -// Type definitions for Angular UI Bootstrap 0.13.3 -// Project: https://github.com/angular-ui/bootstrap -// Definitions by: Brian Surowiec -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -// Support for AMD require -declare module 'angular-bootstrap' { - let _: string; - export = _; -} - -declare module 'angular-ui-bootstrap' { - let _: string; - export = _; -} - -declare namespace angular.ui.bootstrap { - - interface IAccordionConfig { - /** - * Controls whether expanding an item will cause the other items to close. - * - * @default true - */ - closeOthers?: boolean; - } - - - interface IButtonConfig { - /** - * @default: 'active' - */ - activeClass?: string; - - /** - * @default: 'Click' - */ - toggleEvent?: string; - } - - - interface IDatepickerConfig { - /** - * Format of day in month. - * - * @default 'dd' - */ - formatDay?: string; - - /** - * Format of month in year. - * - * @default 'MMM' - */ - formatMonth?: string; - - /** - * Format of year in year range. - * - * @default 'yyyy' - */ - formatYear?: string; - - /** - * Format of day in week header. - * - * @default 'EEE' - */ - formatDayHeader?: string; - - /** - * Format of title when selecting day. - * - * @default 'MMM yyyy' - */ - formatDayTitle?: string; - - /** - * Format of title when selecting month. - * - * @default 'yyyy' - */ - formatMonthTitle?: string; - - /** - * Current mode of the datepicker (day|month|year). Can be used to initialize datepicker to specific mode. - * - * @default 'day' - */ - datepickerMode?: string; - - /** - * Set a lower limit for mode. - * - * @default 'day' - */ - minMode?: string; - - /** - * Set an upper limit for mode. - * - * @default 'year' - */ - maxMode?: string; - - /** - * Whether to display week numbers. - * - * @default true - */ - showWeeks?: boolean; - - /** - * Starting day of the week from 0-6 where 0=Sunday and 6=Saturday. - * - * @default 0 - */ - startingDay?: number; - - /** - * Number of years displayed in year selection. - * - * @default 20 - */ - yearRange?: number; - - /** - * Defines the minimum available date. - * - * @default null - */ - minDate?: any; - - /** - * Defines the maximum available date. - * - * @default null - */ - maxDate?: any; - - /** - * An option to disable or enable shortcut's event propagation - * - * @default false - */ - shortcutPropagation?: boolean; - } - - interface IDatepickerPopupConfig { - /** - * The format for displayed dates. - * - * @default 'yyyy-MM-dd' - */ - datepickerPopup?: string; - - /** - * Allows overriding of default template of the popup. - * - * @default 'template/datepicker/popup.html' - */ - datepickerPopupTemplateUrl?: string; - - /** - * Allows overriding of default template of the datepicker used in popup. - * - * @default 'template/datepicker/popup.html' - */ - datepickerTemplateUrl?: string; - - /** - * Allows overriding of the default format for html5 date inputs. - */ - html5Types?: { - date?: string; - 'datetime-local'?: string; - month?: string; - }; - - /** - * The text to display for the current day button. - * - * @default 'Today' - */ - currentText?: string; - - /** - * The text to display for the clear button. - * - * @default 'Clear' - */ - clearText?: string; - - /** - * The text to display for the close button. - * - * @default 'Done' - */ - closeText?: string; - - /** - * Whether to close calendar when a date is chosen. - * - * @default true - */ - closeOnDateSelection?: boolean; - - /** - * Append the datepicker popup element to `body`, rather than inserting after `datepicker-popup`. - * - * @default false - */ - appendToBody?: boolean; - - /** - * Whether to display a button bar underneath the datepicker. - * - * @default true - */ - showButtonBar?: boolean; - - /** - * Whether to focus the datepicker popup upon opening. - * - * @default true - */ - onOpenFocus?: boolean; - } - - - interface IModalProvider { - /** - * Default options all modals will use. - */ - options: IModalSettings; - } - - interface IModalService { - /** - * @param {IModalSettings} options - * @returns {IModalServiceInstance} - */ - open(options: IModalSettings): IModalServiceInstance; - } - - interface IModalServiceInstance { - /** - * A method that can be used to close a modal, passing a result. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. - */ - close(result?: any): void; - - /** - * A method that can be used to dismiss a modal, passing a reason. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. - */ - dismiss(reason?: any): void; - - /** - * A promise that is resolved when a modal is closed and rejected when a modal is dismissed. - */ - result: angular.IPromise; - - /** - * A promise that is resolved when a modal gets opened after downloading content's template and resolving all variables. - */ - opened: angular.IPromise; - - /** - * A promise that is resolved when a modal is rendered. - */ - rendered: angular.IPromise; - } - - interface IModalScope extends angular.IScope { - /** - * Dismiss the dialog without assigning a value to the promise output. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. - * - * @returns true if the modal was closed; otherwise false - */ - $dismiss(reason?: any): boolean; - - /** - * Close the dialog resolving the promise to the given value. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. - * - * @returns true if the modal was closed; otherwise false - */ - $close(result?: any): boolean; - } - - interface IModalSettings { - /** - * a path to a template representing modal's content - */ - templateUrl?: string | (() => string); - - /** - * inline template representing the modal's content - */ - template?: string; - - /** - * a scope instance to be used for the modal's content (actually the $modal service is going to create a child scope of a provided scope). - * Defaults to `$rootScope`. - */ - scope?: angular.IScope|IModalScope; - - /** - * a controller for a modal instance - it can initialize scope used by modal. - * A controller can be injected with `$modalInstance` - * If value is an array, it must be in Inline Array Annotation format for injection (strings followed by factory method) - */ - controller?: string | Function | Array; - - /** - * an alternative to the controller-as syntax, matching the API of directive definitions. - * Requires the controller option to be provided as well - */ - controllerAs?: string; - - /** - * When used with controllerAs and set to true, it will bind the controller properties onto the $scope directly. - * - * @default false - */ - bindToController?: boolean; - - /** - * members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes - * If property value is an array, it must be in Inline Array Annotation format for injection (strings followed by factory method) - */ - resolve?: { [ key: string ]: string | Function | Array | Object }; - - /** - * Set to false to disable animations on new modal/backdrop. Does not toggle animations for modals/backdrops that are already displayed. - * - * @default true - */ - animation?: boolean; - - /** - * controls the presence of a backdrop - * Allowed values: - * - true (default) - * - false (no backdrop) - * - 'static' backdrop is present but modal window is not closed when clicking outside of the modal window - * - * @default true - */ - backdrop?: boolean | string; - - /** - * indicates whether the dialog should be closable by hitting the ESC key - * - * @default true - */ - keyboard?: boolean; - - /** - * additional CSS class(es) to be added to a modal backdrop template - */ - backdropClass?: string; - - /** - * additional CSS class(es) to be added to a modal window template - */ - windowClass?: string; - - /** - * Optional suffix of modal window class. The value used is appended to the `modal-` class, i.e. a value of `sm` gives `modal-sm`. - */ - size?: string; - - /** - * a path to a template overriding modal's window template - */ - windowTemplateUrl?: string; - - /** - * The class added to the body element when the modal is opened. - * - * @default 'model-open' - */ - openedClass?: string; - } - - interface IModalStackService { - /** - * Opens a new modal instance. - */ - open(modalInstance: IModalServiceInstance, modal: any): void; - - /** - * Closes a modal instance with an optional result. - */ - close(modalInstance: IModalServiceInstance, result?: any): void; - - /** - * Dismisses a modal instance with an optional reason. - */ - dismiss(modalInstance: IModalServiceInstance, reason?: any): void; - - /** - * Dismiss all open modal instances with an optional reason that will be passed to each instance. - */ - dismissAll(reason?: any): void; - - /** - * Gets the topmost modal instance that is open. - */ - getTop(): IModalStackedMapKeyValuePair; - } - - interface IModalStackedMapKeyValuePair { - key: IModalServiceInstance; - value: any; - } - - - interface IPaginationConfig { - /** - * Total number of items in all pages. - */ - totalItems?: number; - - /** - * Maximum number of items per page. A value less than one indicates all items on one page. - * - * @default 10 - */ - itemsPerPage?: number; - - /** - * Limit number for pagination size. - * - * @default: null - */ - maxSize?: number; - - /** - * An optional expression assigned the total number of pages to display. - * - * @default angular.noop - */ - numPages?: number; - - /** - * Whether to keep current page in the middle of the visible ones. - * - * @default true - */ - rotate?: boolean; - - /** - * Whether to display Previous / Next buttons. - * - * @default true - */ - directionLinks?: boolean; - - /** - * Text for Previous button. - * - * @default 'Previous' - */ - previousText?: string; - - /** - * Text for Next button. - * - * @default 'Next' - */ - nextText?: string; - - /** - * Whether to display First / Last buttons. - * - * @default false - */ - boundaryLinks?: boolean; - - /** - * Text for First button. - * - * @default 'First' - */ - firstText?: string; - - /** - * Text for Last button. - * - * @default 'Last' - */ - lastText?: string; - - /** - * Override the template for the component with a custom provided template. - * - * @default 'template/pagination/pagination.html' - */ - templateUrl?: string; - } - - interface IPagerConfig { - /** - * Whether to align each link to the sides. - * - * @default true - */ - align?: boolean; - - /** - * Maximum number of items per page. A value less than one indicates all items on one page. - * - * @default 10 - */ - itemsPerPage?: number; - - /** - * Text for Previous button. - * - * @default '« Previous' - */ - previousText?: string; - - /** - * Text for Next button. - * - * @default 'Next »' - */ - nextText?: string; - } - - - interface IPositionCoordinates { - width?: number; - height?: number; - top?: number; - left?: number; - } - - interface IPositionService { - /** - * Provides a read-only equivalent of jQuery's position function. - */ - position(element: JQuery): IPositionCoordinates; - - /** - * Provides a read-only equivalent of jQuery's offset function. - */ - offset(element: JQuery): IPositionCoordinates; - } - - - interface IProgressConfig { - /** - * Whether bars use transitions to achieve the width change. - * - * @default: true - */ - animate?: boolean; - - /** - * A number that specifies the total value of bars that is required. - * - * @default: 100 - */ - max?: number; - } - - - interface IRatingConfig { - /** - * Changes the number of icons. - * - * @default: 5 - */ - max?: number; - - /** - * A variable used in the template to specify the state for selected icons. - * - * @default: null - */ - stateOn?: string; - - /** - * A variable used in the template to specify the state for unselected icons. - * - * @default: null - */ - stateOff?: string; - - /** - * An array of strings defining titles for all icons. - * - * @default: ["one", "two", "three", "four", "five"] - */ - titles?: Array; - } - - - interface ITimepickerConfig { - /** - * Number of hours to increase or decrease when using a button. - * - * @default 1 - */ - hourStep?: number; - - /** - * Number of minutes to increase or decrease when using a button. - * - * @default 1 - */ - minuteStep?: number; - - /** - * Whether to display 12H or 24H mode. - * - * @default true - */ - showMeridian?: boolean; - - /** - * Meridian labels based on locale. To override you must supply an array like ['AM', 'PM']. - * - * @default null - */ - meridians?: Array; - - /** - * Whether the user can type inside the hours & minutes input. - * - * @default false - */ - readonlyInput?: boolean; - - /** - * Whether the user can scroll inside the hours & minutes input to increase or decrease it's values. - * - * @default true - */ - mousewheel?: boolean; - - /** - * Whether the user can use up/down arrowkeys inside the hours & minutes input to increase or decrease it's values. - * - * @default true - */ - arrowkeys?: boolean; - - /** - * Shows spinner arrows above and below the inputs. - * - * @default true - */ - showSpinners?: boolean; - } - - - interface ITooltipOptions { - /** - * Where to place it? Defaults to 'top', but also accepts 'right', 'bottom', or 'left'. - * - * @default 'top' - */ - placement?: string; - - /** - * Should the modal fade in and out? - * - * @default true - */ - animation?: boolean; - - /** - * For how long should the user have to have the mouse over the element before the tooltip shows (in milliseconds)? - * - * @default 0 - */ - popupDelay?: number; - - /** - * Should the tooltip be appended to `$body` instead of the parent element? - * - * @default false - */ - appendToBody?: boolean; - - /** - * What should trigger a show of the tooltip? Supports a space separated list of event names. - * - * @default 'mouseenter' for tooltip, 'click' for popover - */ - trigger?: string; - - /** - * Should an expression on the scope be used to load the content? - * - * @default false - */ - useContentExp?: boolean; - } - - interface ITooltipProvider { - /** - * Provide a set of defaults for certain tooltip and popover attributes. - */ - options(value: ITooltipOptions): void; - - /** - * Extends the default trigger mappings with mappings of your own. E.g. `{ 'openTrigger': 'closeTrigger' }`. - */ - setTriggers(triggers: Object): void; - } - - - /** - * WARNING: $transition is now deprecated. Use $animate from ngAnimate instead. - */ - interface ITransitionService { - /** - * The browser specific animation event name. - */ - animationEndEventName: string; - - /** - * The browser specific transition event name. - */ - transitionEndEventName: string; - - /** - * Provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete. - * - * @param element The DOMElement that will be animated - * @param trigger The thing that will cause the transition to start: - * - As a string, it represents the css class to be added to the element. - * - As an object, it represents a hash of style attributes to be applied to the element. - * - As a function, it represents a function to be called that will cause the transition to occur. - * @param options Optional settings for the transition. - * - * @return A promise that is resolved when the transition finishes. - */ - (element: angular.IAugmentedJQuery, trigger: any, options?: ITransitionServiceOptions): angular.IPromise; - } - - interface ITransitionServiceOptions { - animation?: boolean; - } - -} diff --git a/angular-ui-bootstrap/index.d.ts b/angular-ui-bootstrap/index.d.ts new file mode 100644 index 0000000000..65dee80e5a --- /dev/null +++ b/angular-ui-bootstrap/index.d.ts @@ -0,0 +1,752 @@ +// Type definitions for Angular UI Bootstrap 0.13.3 +// Project: https://github.com/angular-ui/bootstrap +// Definitions by: Brian Surowiec +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +// Support for AMD require +declare module 'angular-bootstrap' { + let _: string; + export = _; +} + +declare module 'angular-ui-bootstrap' { + let _: string; + export = _; +} + +declare namespace angular.ui.bootstrap { + + interface IAccordionConfig { + /** + * Controls whether expanding an item will cause the other items to close. + * + * @default true + */ + closeOthers?: boolean; + } + + + interface IButtonConfig { + /** + * @default: 'active' + */ + activeClass?: string; + + /** + * @default: 'Click' + */ + toggleEvent?: string; + } + + + interface IDatepickerConfig { + /** + * Format of day in month. + * + * @default 'dd' + */ + formatDay?: string; + + /** + * Format of month in year. + * + * @default 'MMM' + */ + formatMonth?: string; + + /** + * Format of year in year range. + * + * @default 'yyyy' + */ + formatYear?: string; + + /** + * Format of day in week header. + * + * @default 'EEE' + */ + formatDayHeader?: string; + + /** + * Format of title when selecting day. + * + * @default 'MMM yyyy' + */ + formatDayTitle?: string; + + /** + * Format of title when selecting month. + * + * @default 'yyyy' + */ + formatMonthTitle?: string; + + /** + * Current mode of the datepicker (day|month|year). Can be used to initialize datepicker to specific mode. + * + * @default 'day' + */ + datepickerMode?: string; + + /** + * Set a lower limit for mode. + * + * @default 'day' + */ + minMode?: string; + + /** + * Set an upper limit for mode. + * + * @default 'year' + */ + maxMode?: string; + + /** + * Whether to display week numbers. + * + * @default true + */ + showWeeks?: boolean; + + /** + * Starting day of the week from 0-6 where 0=Sunday and 6=Saturday. + * + * @default 0 + */ + startingDay?: number; + + /** + * Number of years displayed in year selection. + * + * @default 20 + */ + yearRange?: number; + + /** + * Defines the minimum available date. + * + * @default null + */ + minDate?: any; + + /** + * Defines the maximum available date. + * + * @default null + */ + maxDate?: any; + + /** + * An option to disable or enable shortcut's event propagation + * + * @default false + */ + shortcutPropagation?: boolean; + } + + interface IDatepickerPopupConfig { + /** + * The format for displayed dates. + * + * @default 'yyyy-MM-dd' + */ + datepickerPopup?: string; + + /** + * Allows overriding of default template of the popup. + * + * @default 'template/datepicker/popup.html' + */ + datepickerPopupTemplateUrl?: string; + + /** + * Allows overriding of default template of the datepicker used in popup. + * + * @default 'template/datepicker/popup.html' + */ + datepickerTemplateUrl?: string; + + /** + * Allows overriding of the default format for html5 date inputs. + */ + html5Types?: { + date?: string; + 'datetime-local'?: string; + month?: string; + }; + + /** + * The text to display for the current day button. + * + * @default 'Today' + */ + currentText?: string; + + /** + * The text to display for the clear button. + * + * @default 'Clear' + */ + clearText?: string; + + /** + * The text to display for the close button. + * + * @default 'Done' + */ + closeText?: string; + + /** + * Whether to close calendar when a date is chosen. + * + * @default true + */ + closeOnDateSelection?: boolean; + + /** + * Append the datepicker popup element to `body`, rather than inserting after `datepicker-popup`. + * + * @default false + */ + appendToBody?: boolean; + + /** + * Whether to display a button bar underneath the datepicker. + * + * @default true + */ + showButtonBar?: boolean; + + /** + * Whether to focus the datepicker popup upon opening. + * + * @default true + */ + onOpenFocus?: boolean; + } + + + interface IModalProvider { + /** + * Default options all modals will use. + */ + options: IModalSettings; + } + + interface IModalService { + /** + * @param {IModalSettings} options + * @returns {IModalServiceInstance} + */ + open(options: IModalSettings): IModalServiceInstance; + } + + interface IModalServiceInstance { + /** + * A method that can be used to close a modal, passing a result. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. + */ + close(result?: any): void; + + /** + * A method that can be used to dismiss a modal, passing a reason. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. + */ + dismiss(reason?: any): void; + + /** + * A promise that is resolved when a modal is closed and rejected when a modal is dismissed. + */ + result: angular.IPromise; + + /** + * A promise that is resolved when a modal gets opened after downloading content's template and resolving all variables. + */ + opened: angular.IPromise; + + /** + * A promise that is resolved when a modal is rendered. + */ + rendered: angular.IPromise; + } + + interface IModalScope extends angular.IScope { + /** + * Dismiss the dialog without assigning a value to the promise output. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. + * + * @returns true if the modal was closed; otherwise false + */ + $dismiss(reason?: any): boolean; + + /** + * Close the dialog resolving the promise to the given value. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. + * + * @returns true if the modal was closed; otherwise false + */ + $close(result?: any): boolean; + } + + interface IModalSettings { + /** + * a path to a template representing modal's content + */ + templateUrl?: string | (() => string); + + /** + * inline template representing the modal's content + */ + template?: string; + + /** + * a scope instance to be used for the modal's content (actually the $modal service is going to create a child scope of a provided scope). + * Defaults to `$rootScope`. + */ + scope?: angular.IScope|IModalScope; + + /** + * a controller for a modal instance - it can initialize scope used by modal. + * A controller can be injected with `$modalInstance` + * If value is an array, it must be in Inline Array Annotation format for injection (strings followed by factory method) + */ + controller?: string | Function | Array; + + /** + * an alternative to the controller-as syntax, matching the API of directive definitions. + * Requires the controller option to be provided as well + */ + controllerAs?: string; + + /** + * When used with controllerAs and set to true, it will bind the controller properties onto the $scope directly. + * + * @default false + */ + bindToController?: boolean; + + /** + * members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes + * If property value is an array, it must be in Inline Array Annotation format for injection (strings followed by factory method) + */ + resolve?: { [ key: string ]: string | Function | Array | Object }; + + /** + * Set to false to disable animations on new modal/backdrop. Does not toggle animations for modals/backdrops that are already displayed. + * + * @default true + */ + animation?: boolean; + + /** + * controls the presence of a backdrop + * Allowed values: + * - true (default) + * - false (no backdrop) + * - 'static' backdrop is present but modal window is not closed when clicking outside of the modal window + * + * @default true + */ + backdrop?: boolean | string; + + /** + * indicates whether the dialog should be closable by hitting the ESC key + * + * @default true + */ + keyboard?: boolean; + + /** + * additional CSS class(es) to be added to a modal backdrop template + */ + backdropClass?: string; + + /** + * additional CSS class(es) to be added to a modal window template + */ + windowClass?: string; + + /** + * Optional suffix of modal window class. The value used is appended to the `modal-` class, i.e. a value of `sm` gives `modal-sm`. + */ + size?: string; + + /** + * a path to a template overriding modal's window template + */ + windowTemplateUrl?: string; + + /** + * The class added to the body element when the modal is opened. + * + * @default 'model-open' + */ + openedClass?: string; + } + + interface IModalStackService { + /** + * Opens a new modal instance. + */ + open(modalInstance: IModalServiceInstance, modal: any): void; + + /** + * Closes a modal instance with an optional result. + */ + close(modalInstance: IModalServiceInstance, result?: any): void; + + /** + * Dismisses a modal instance with an optional reason. + */ + dismiss(modalInstance: IModalServiceInstance, reason?: any): void; + + /** + * Dismiss all open modal instances with an optional reason that will be passed to each instance. + */ + dismissAll(reason?: any): void; + + /** + * Gets the topmost modal instance that is open. + */ + getTop(): IModalStackedMapKeyValuePair; + } + + interface IModalStackedMapKeyValuePair { + key: IModalServiceInstance; + value: any; + } + + + interface IPaginationConfig { + /** + * Total number of items in all pages. + */ + totalItems?: number; + + /** + * Maximum number of items per page. A value less than one indicates all items on one page. + * + * @default 10 + */ + itemsPerPage?: number; + + /** + * Limit number for pagination size. + * + * @default: null + */ + maxSize?: number; + + /** + * An optional expression assigned the total number of pages to display. + * + * @default angular.noop + */ + numPages?: number; + + /** + * Whether to keep current page in the middle of the visible ones. + * + * @default true + */ + rotate?: boolean; + + /** + * Whether to display Previous / Next buttons. + * + * @default true + */ + directionLinks?: boolean; + + /** + * Text for Previous button. + * + * @default 'Previous' + */ + previousText?: string; + + /** + * Text for Next button. + * + * @default 'Next' + */ + nextText?: string; + + /** + * Whether to display First / Last buttons. + * + * @default false + */ + boundaryLinks?: boolean; + + /** + * Text for First button. + * + * @default 'First' + */ + firstText?: string; + + /** + * Text for Last button. + * + * @default 'Last' + */ + lastText?: string; + + /** + * Override the template for the component with a custom provided template. + * + * @default 'template/pagination/pagination.html' + */ + templateUrl?: string; + } + + interface IPagerConfig { + /** + * Whether to align each link to the sides. + * + * @default true + */ + align?: boolean; + + /** + * Maximum number of items per page. A value less than one indicates all items on one page. + * + * @default 10 + */ + itemsPerPage?: number; + + /** + * Text for Previous button. + * + * @default '« Previous' + */ + previousText?: string; + + /** + * Text for Next button. + * + * @default 'Next »' + */ + nextText?: string; + } + + + interface IPositionCoordinates { + width?: number; + height?: number; + top?: number; + left?: number; + } + + interface IPositionService { + /** + * Provides a read-only equivalent of jQuery's position function. + */ + position(element: JQuery): IPositionCoordinates; + + /** + * Provides a read-only equivalent of jQuery's offset function. + */ + offset(element: JQuery): IPositionCoordinates; + } + + + interface IProgressConfig { + /** + * Whether bars use transitions to achieve the width change. + * + * @default: true + */ + animate?: boolean; + + /** + * A number that specifies the total value of bars that is required. + * + * @default: 100 + */ + max?: number; + } + + + interface IRatingConfig { + /** + * Changes the number of icons. + * + * @default: 5 + */ + max?: number; + + /** + * A variable used in the template to specify the state for selected icons. + * + * @default: null + */ + stateOn?: string; + + /** + * A variable used in the template to specify the state for unselected icons. + * + * @default: null + */ + stateOff?: string; + + /** + * An array of strings defining titles for all icons. + * + * @default: ["one", "two", "three", "four", "five"] + */ + titles?: Array; + } + + + interface ITimepickerConfig { + /** + * Number of hours to increase or decrease when using a button. + * + * @default 1 + */ + hourStep?: number; + + /** + * Number of minutes to increase or decrease when using a button. + * + * @default 1 + */ + minuteStep?: number; + + /** + * Whether to display 12H or 24H mode. + * + * @default true + */ + showMeridian?: boolean; + + /** + * Meridian labels based on locale. To override you must supply an array like ['AM', 'PM']. + * + * @default null + */ + meridians?: Array; + + /** + * Whether the user can type inside the hours & minutes input. + * + * @default false + */ + readonlyInput?: boolean; + + /** + * Whether the user can scroll inside the hours & minutes input to increase or decrease it's values. + * + * @default true + */ + mousewheel?: boolean; + + /** + * Whether the user can use up/down arrowkeys inside the hours & minutes input to increase or decrease it's values. + * + * @default true + */ + arrowkeys?: boolean; + + /** + * Shows spinner arrows above and below the inputs. + * + * @default true + */ + showSpinners?: boolean; + } + + + interface ITooltipOptions { + /** + * Where to place it? Defaults to 'top', but also accepts 'right', 'bottom', or 'left'. + * + * @default 'top' + */ + placement?: string; + + /** + * Should the modal fade in and out? + * + * @default true + */ + animation?: boolean; + + /** + * For how long should the user have to have the mouse over the element before the tooltip shows (in milliseconds)? + * + * @default 0 + */ + popupDelay?: number; + + /** + * Should the tooltip be appended to `$body` instead of the parent element? + * + * @default false + */ + appendToBody?: boolean; + + /** + * What should trigger a show of the tooltip? Supports a space separated list of event names. + * + * @default 'mouseenter' for tooltip, 'click' for popover + */ + trigger?: string; + + /** + * Should an expression on the scope be used to load the content? + * + * @default false + */ + useContentExp?: boolean; + } + + interface ITooltipProvider { + /** + * Provide a set of defaults for certain tooltip and popover attributes. + */ + options(value: ITooltipOptions): void; + + /** + * Extends the default trigger mappings with mappings of your own. E.g. `{ 'openTrigger': 'closeTrigger' }`. + */ + setTriggers(triggers: Object): void; + } + + + /** + * WARNING: $transition is now deprecated. Use $animate from ngAnimate instead. + */ + interface ITransitionService { + /** + * The browser specific animation event name. + */ + animationEndEventName: string; + + /** + * The browser specific transition event name. + */ + transitionEndEventName: string; + + /** + * Provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete. + * + * @param element The DOMElement that will be animated + * @param trigger The thing that will cause the transition to start: + * - As a string, it represents the css class to be added to the element. + * - As an object, it represents a hash of style attributes to be applied to the element. + * - As a function, it represents a function to be called that will cause the transition to occur. + * @param options Optional settings for the transition. + * + * @return A promise that is resolved when the transition finishes. + */ + (element: angular.IAugmentedJQuery, trigger: any, options?: ITransitionServiceOptions): angular.IPromise; + } + + interface ITransitionServiceOptions { + animation?: boolean; + } + +} diff --git a/angular-ui-bootstrap/tsconfig.json b/angular-ui-bootstrap/tsconfig.json new file mode 100644 index 0000000000..e76f1b5c61 --- /dev/null +++ b/angular-ui-bootstrap/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-ui-bootstrap-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-ui-router/angular-ui-router-tests.ts b/angular-ui-router/angular-ui-router-tests.ts index ba42f16cf4..f1ab855e63 100644 --- a/angular-ui-router/angular-ui-router-tests.ts +++ b/angular-ui-router/angular-ui-router-tests.ts @@ -1,4 +1,5 @@ -/// +import * as ng from 'angularjs'; +import * as angular from 'angularjs'; var myApp = angular.module('testModule'); @@ -141,6 +142,8 @@ class UrlLocatorTestService implements IUrlLocatorTestService { private $state: ng.ui.IStateService ) { $rootScope.$on("$locationChangeSuccess", (event: ng.IAngularEvent) => this.onLocationChangeSuccess(event)); + $rootScope.$on('$stateNotFound', (event: ng.IAngularEvent, unfoundState: ng.ui.IUnfoundState, fromState: ng.ui.IState, fromParams: {}) => + this.onStateNotFound(event, unfoundState, fromState, fromParams)); } public currentUser: any; @@ -162,6 +165,15 @@ class UrlLocatorTestService implements IUrlLocatorTestService { }); } } + + private onStateNotFound(event: ng.IAngularEvent, + unfoundState: ng.ui.IUnfoundState, + fromState: ng.ui.IState, + fromParams: {}) { + var unfoundTo: string = unfoundState.to; + var unfoundToParams: {} = unfoundState.toParams; + var unfoundOptions: ng.ui.IStateOptions = unfoundState.options + } private stateServiceTest() { this.$state.go("myState"); diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts deleted file mode 100644 index 17d1570983..0000000000 --- a/angular-ui-router/angular-ui-router.d.ts +++ /dev/null @@ -1,363 +0,0 @@ -// Type definitions for Angular JS 1.1.5+ (ui.router module) -// Project: https://github.com/angular-ui/ui-router -// Definitions by: Michel Salib -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -// Support for AMD require and CommonJS -declare module 'angular-ui-router' { - // Since angular-ui-router adds providers for a bunch of - // injectable dependencies, it doesn't really return any - // actual data except the plain string 'ui.router'. - // - // As such, I don't think anybody will ever use the actual - // default value of the module. So I've only included the - // the types. (@xogeny) - export type IState = angular.ui.IState; - export type IStateProvider = angular.ui.IStateProvider; - export type IUrlMatcher = angular.ui.IUrlMatcher; - export type IUrlRouterProvider = angular.ui.IUrlRouterProvider; - export type IStateOptions = angular.ui.IStateOptions; - export type IHrefOptions = angular.ui.IHrefOptions; - export type IStateService = angular.ui.IStateService; - export type IResolvedState = angular.ui.IResolvedState; - export type IStateParamsService = angular.ui.IStateParamsService; - export type IUrlRouterService = angular.ui.IUrlRouterService; - export type IUiViewScrollProvider = angular.ui.IUiViewScrollProvider; - export type IType = angular.ui.IType; -} - -declare namespace angular.ui { - - interface IState { - name?: string; - /** - * String HTML content, or function that returns an HTML string - */ - template?: string | {(): string}; - /** - * String URL path to template file OR Function, returns URL path string - */ - templateUrl?: string | {(params: IStateParamsService): string}; - /** - * Function, returns HTML content string - */ - templateProvider?: Function | Array; - /** - * A controller paired to the state. Function, annotated array or name as String - */ - controller?: Function|string|Array; - controllerAs?: string; - /** - * Function (injectable), returns the actual controller function or string. - */ - controllerProvider?: Function|Array; - - /** - * Specifies the parent state of this state - */ - parent?: string | IState; - - - resolve?: { [name:string]: any }; - /** - * A url with optional parameters. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed. - */ - url?: string | IUrlMatcher; - /** - * A map which optionally configures parameters declared in the url, or defines additional non-url parameters. Only use this within a state if you are not using url. Otherwise you can specify your parameters within the url. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed. - */ - params?: any; - /** - * Use the views property to set up multiple views. If you don't need multiple views within a single state this property is not needed. Tip: remember that often nested views are more useful and powerful than multiple sibling views. - */ - views?: { [name:string]: IState }; - abstract?: boolean; - /** - * Callback function for when a state is entered. Good way to trigger an action or dispatch an event, such as opening a dialog. - * If minifying your scripts, make sure to explicitly annotate this function, because it won't be automatically annotated by your build tools. - */ - onEnter?: Function|Array; - /** - * Callback functions for when a state is entered and exited. Good way to trigger an action or dispatch an event, such as opening a dialog. - * If minifying your scripts, make sure to explicitly annotate this function, because it won't be automatically annotated by your build tools. - */ - onExit?: Function|Array; - /** - * Arbitrary data object, useful for custom configuration. - */ - data?: any; - - /** - * Boolean (default true). If false will not re-trigger the same state just because a search/query parameter has changed. Useful for when you'd like to modify $location.search() without triggering a reload. - */ - reloadOnSearch?: boolean; - - /** - * Boolean (default true). If false will reload state on everytransitions. Useful for when you'd like to restore all data to its initial state. - */ - cache?: boolean; - } - - interface IStateProvider extends angular.IServiceProvider { - state(name:string, config:IState): IStateProvider; - state(config:IState): IStateProvider; - decorator(name?: string, decorator?: (state: IState, parent: Function) => any): any; - } - - interface IUrlMatcher { - concat(pattern: string): IUrlMatcher; - exec(path: string, searchParams: {}): {}; - parameters(): string[]; - format(values: {}): string; - } - - interface IUrlMatcherFactory { - /** - * Creates a UrlMatcher for the specified pattern. - * - * @param pattern {string} The URL pattern. - * - * @returns {IUrlMatcher} The UrlMatcher. - */ - compile(pattern: string): IUrlMatcher; - /** - * Returns true if the specified object is a UrlMatcher, or false otherwise. - * - * @param o {any} The object to perform the type check against. - * - * @returns {boolean} Returns true if the object matches the IUrlMatcher interface, by implementing all the same methods. - */ - isMatcher(o: any): boolean; - /** - * Returns a type definition for the specified name - * - * @param name {string} The type definition name - * - * @returns {IType} The type definition - */ - type(name: string): IType; - /** - * Registers a custom Type object that can be used to generate URLs with typed parameters. - * - * @param {IType} definition The type definition. - * @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition. - * - * @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider. - */ - type(name: string, definition: IType, inlineAnnotedDefinitionFn?: any[]): IUrlMatcherFactory; - /** - * Registers a custom Type object that can be used to generate URLs with typed parameters. - * - * @param {IType} definition The type definition. - * @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition. - * - * @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider. - */ - type(name: string, definition: IType, definitionFn?: (...args:any[]) => IType): IUrlMatcherFactory; - /** - * Defines whether URL matching should be case sensitive (the default behavior), or not. - * - * @param value {boolean} false to match URL in a case sensitive manner; otherwise true; - * - * @returns {boolean} the current value of caseInsensitive - */ - caseInsensitive(value?: boolean): boolean; - /** - * Sets the default behavior when generating or matching URLs with default parameter values - * - * @param value {string} A string that defines the default parameter URL squashing behavior. nosquash: When generating an href with a default parameter value, do not squash the parameter value from the URL slash: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the parameter is surrounded by slashes, squash (remove) one slash from the URL any other string, e.g. "~": When generating an href with a default parameter value, squash (remove) the parameter value from the URL and replace it with this string. - */ - defaultSquashPolicy(value: string): void; - /** - * Defines whether URLs should match trailing slashes, or not (the default behavior). - * - * @param value {boolean} false to match trailing slashes in URLs, otherwise true. - * - * @returns {boolean} the current value of strictMode - */ - strictMode(value?: boolean): boolean; - } - - interface IUrlRouterProvider extends angular.IServiceProvider { - when(whenPath: RegExp, handler: Function): IUrlRouterProvider; - when(whenPath: RegExp, handler: any[]): IUrlRouterProvider; - when(whenPath: RegExp, toPath: string): IUrlRouterProvider; - when(whenPath: IUrlMatcher, hanlder: Function): IUrlRouterProvider; - when(whenPath: IUrlMatcher, handler: any[]): IUrlRouterProvider; - when(whenPath: IUrlMatcher, toPath: string): IUrlRouterProvider; - when(whenPath: string, handler: Function): IUrlRouterProvider; - when(whenPath: string, handler: any[]): IUrlRouterProvider; - when(whenPath: string, toPath: string): IUrlRouterProvider; - otherwise(handler: Function): IUrlRouterProvider; - otherwise(handler: any[]): IUrlRouterProvider; - otherwise(path: string): IUrlRouterProvider; - rule(handler: Function): IUrlRouterProvider; - rule(handler: any[]): IUrlRouterProvider; - /** - * Disables (or enables) deferring location change interception. - * - * If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain the current URL), call this method at configuration time. Then, at run time, call $urlRouter.listen() after you have configured your own $locationChangeSuccess event handler. - * - * @param {boolean} defer Indicates whether to defer location change interception. Passing no parameter is equivalent to true. - */ - deferIntercept(defer?: boolean): void; - } - - interface IStateOptions { - /** - * {boolean=true|string=} - If true will update the url in the location bar, if false will not. If string, must be "replace", which will update url and also replace last history record. - */ - location?: boolean | string; - /** - * {boolean=true}, If true will inherit url parameters from current url. - */ - inherit?: boolean; - /** - * {object=$state.$current}, When transitioning with relative path (e.g '^'), defines which state to be relative from. - */ - relative?: IState; - /** - * {boolean=true}, If true will broadcast $stateChangeStart and $stateChangeSuccess events. - */ - notify?: boolean; - /** - * {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params. - */ - reload?: boolean; - } - - interface IHrefOptions { - lossy?: boolean; - inherit?: boolean; - relative?: IState; - absolute?: boolean; - } - - interface IStateService { - /** - * Convenience method for transitioning to a new state. $state.go calls $state.transitionTo internally but automatically sets options to { location: true, inherit: true, relative: $state.$current, notify: true }. This allows you to easily use an absolute or relative to path and specify only the parameters you'd like to update (while letting unspecified parameters inherit from the currently active ancestor states). - * - * @param to Absolute state name or relative state path. Some examples: - * - * $state.go('contact.detail') - will go to the contact.detail state - * $state.go('^') - will go to a parent state - * $state.go('^.sibling') - will go to a sibling state - * $state.go('.child.grandchild') - will go to grandchild state - * - * @param params A map of the parameters that will be sent to the state, will populate $stateParams. Any parameters that are not specified will be inherited from currently defined parameters. This allows, for example, going to a sibling state that shares parameters specified in a parent state. Parameter inheritance only works between common ancestor states, I.e. transitioning to a sibling will get you the parameters for all parents, transitioning to a child will get you all current parameters, etc. - * - * @param options Options object. - */ - go(to: string, params?: {}, options?: IStateOptions): angular.IPromise; - go(to: IState, params?: {}, options?: IStateOptions): angular.IPromise; - transitionTo(state: string, params?: {}, updateLocation?: boolean): angular.IPromise; - transitionTo(state: IState, params?: {}, updateLocation?: boolean): angular.IPromise; - transitionTo(state: string, params?: {}, options?: IStateOptions): angular.IPromise; - transitionTo(state: IState, params?: {}, options?: IStateOptions): angular.IPromise; - includes(state: string, params?: {}): boolean; - includes(state: string, params?: {}, options?:any): boolean; - is(state:string, params?: {}): boolean; - is(state: IState, params?: {}): boolean; - href(state: IState, params?: {}, options?: IHrefOptions): string; - href(state: string, params?: {}, options?: IHrefOptions): string; - get(state: string, context?: string): IState; - get(state: IState, context?: string): IState; - get(state: string, context?: IState): IState; - get(state: IState, context?: IState): IState; - get(): IState[]; - /** A reference to the state's config object. However you passed it in. Useful for accessing custom data. */ - current: IState; - /** A param object, e.g. {sectionId: section.id)}, that you'd like to test against the current active state. */ - params: IStateParamsService; - reload(): angular.IPromise; - - /** Currently pending transition. A promise that'll resolve or reject. */ - transition: angular.IPromise<{}>; - - $current: IResolvedState; - } - - interface IResolvedState { - locals: { - /** - * Currently resolved "resolve" values from the current state - */ - globals: { [key: string]: any; }; - }; - } - - interface IStateParamsService { - [key: string]: any; - } - - interface IUrlRouterService { - /* - * Triggers an update; the same update that happens when the address bar - * url changes, aka $locationChangeSuccess. - * - * This method is useful when you need to use preventDefault() on the - * $locationChangeSuccess event, perform some custom logic (route protection, - * auth, config, redirection, etc) and then finally proceed with the transition - * by calling $urlRouter.sync(). - * - */ - sync(): void; - listen(): Function; - href(urlMatcher: IUrlMatcher, params?: IStateParamsService, options?: IHrefOptions): string; - update(read?: boolean): void; - push(urlMatcher: IUrlMatcher, params?: IStateParamsService, options?: IHrefOptions): void; - } - - interface IUiViewScrollProvider { - /* - * Reverts back to using the core $anchorScroll service for scrolling - * based on the url anchor. - */ - useAnchorScroll(): void; - } - - interface IType { - /** - * Converts a parameter value (from URL string or transition param) to a custom/native value. - * - * @param val {string} The URL parameter value to decode. - * @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects. - * - * @returns {any} Returns a custom representation of the URL parameter value. - */ - decode(val: string, key: string): any; - /** - * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the return value does not need to be URL-safe (i.e. passed through encodeURIComponent()), it only needs to be a representation of val that has been coerced to a string. - * - * @param val {any} The value to encode. - * @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects. - * - * @returns {string} Returns a string representation of val that can be encoded in a URL. - */ - encode(val: any, key: string): string; - /** - * Determines whether two decoded values are equivalent. - * - * @param a {any} A value to compare against. - * @param b {any} A value to compare against. - * - * @returns {boolean} Returns true if the values are equivalent/equal, otherwise false. - */ - equals? (a: any, b: any): boolean; - /** - * Detects whether a value is of a particular type. Accepts a native (decoded) value and determines whether it matches the current Type object. - * - * @param val {any} The value to check. - * @param key {any} Optional. If the type check is happening in the context of a specific UrlMatcher object, this is the name of the parameter in which val is stored. Can be used for meta-programming of Type objects. - * - * @returns {boolean} Returns true if the value matches the type, otherwise false. - */ - is(val: any, key: string): boolean; - /** - * The regular expression pattern used to match values of this type when coming from a substring of a URL. - */ - pattern?: RegExp; - } -} diff --git a/angular-ui-router/index.d.ts b/angular-ui-router/index.d.ts new file mode 100644 index 0000000000..7d36968165 --- /dev/null +++ b/angular-ui-router/index.d.ts @@ -0,0 +1,370 @@ +// Type definitions for Angular JS 1.1.5+ (ui.router module) +// Project: https://github.com/angular-ui/ui-router +// Definitions by: Michel Salib +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as angular from 'angularjs'; + +// Support for AMD require and CommonJS +// Since angular-ui-router adds providers for a bunch of +// injectable dependencies, it doesn't really return any +// actual data except the plain string 'ui.router'. +// +// As such, I don't think anybody will ever use the actual +// default value of the module. So I've only included the +// the types. (@xogeny) +export type IState = angular.ui.IState; +export type IStateProvider = angular.ui.IStateProvider; +export type IUrlMatcher = angular.ui.IUrlMatcher; +export type IUrlRouterProvider = angular.ui.IUrlRouterProvider; +export type IStateOptions = angular.ui.IStateOptions; +export type IHrefOptions = angular.ui.IHrefOptions; +export type IStateService = angular.ui.IStateService; +export type IResolvedState = angular.ui.IResolvedState; +export type IStateParamsService = angular.ui.IStateParamsService; +export type IUrlRouterService = angular.ui.IUrlRouterService; +export type IUiViewScrollProvider = angular.ui.IUiViewScrollProvider; +export type IType = angular.ui.IType; + +declare module 'angularjs' { + export namespace ui { + interface IState { + name?: string; + /** + * String HTML content, or function that returns an HTML string + */ + template?: string | {(): string}; + /** + * String URL path to template file OR Function, returns URL path string + */ + templateUrl?: string | {(params: IStateParamsService): string}; + /** + * Function, returns HTML content string + */ + templateProvider?: Function | Array; + /** + * A controller paired to the state. Function, annotated array or name as String + */ + controller?: Function|string|Array; + controllerAs?: string; + /** + * Function (injectable), returns the actual controller function or string. + */ + controllerProvider?: Function|Array; + + /** + * Specifies the parent state of this state + */ + parent?: string | IState; + + + resolve?: { [name:string]: any }; + /** + * A url with optional parameters. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed. + */ + url?: string | IUrlMatcher; + /** + * A map which optionally configures parameters declared in the url, or defines additional non-url parameters. Only use this within a state if you are not using url. Otherwise you can specify your parameters within the url. When a state is navigated or transitioned to, the $stateParams service will be populated with any parameters that were passed. + */ + params?: any; + /** + * Use the views property to set up multiple views. If you don't need multiple views within a single state this property is not needed. Tip: remember that often nested views are more useful and powerful than multiple sibling views. + */ + views?: { [name:string]: IState }; + abstract?: boolean; + /** + * Callback function for when a state is entered. Good way to trigger an action or dispatch an event, such as opening a dialog. + * If minifying your scripts, make sure to explicitly annotate this function, because it won't be automatically annotated by your build tools. + */ + onEnter?: Function|Array; + /** + * Callback functions for when a state is entered and exited. Good way to trigger an action or dispatch an event, such as opening a dialog. + * If minifying your scripts, make sure to explicitly annotate this function, because it won't be automatically annotated by your build tools. + */ + onExit?: Function|Array; + /** + * Arbitrary data object, useful for custom configuration. + */ + data?: any; + + /** + * Boolean (default true). If false will not re-trigger the same state just because a search/query parameter has changed. Useful for when you'd like to modify $location.search() without triggering a reload. + */ + reloadOnSearch?: boolean; + + /** + * Boolean (default true). If false will reload state on everytransitions. Useful for when you'd like to restore all data to its initial state. + */ + cache?: boolean; + } + + interface IUnfoundState { + to: string, + toParams: {}, + options: IStateOptions + } + + interface IStateProvider extends angular.IServiceProvider { + state(name:string, config:IState): IStateProvider; + state(config:IState): IStateProvider; + decorator(name?: string, decorator?: (state: IState, parent: Function) => any): any; + } + + interface IUrlMatcher { + concat(pattern: string): IUrlMatcher; + exec(path: string, searchParams: {}): {}; + parameters(): string[]; + format(values: {}): string; + } + + interface IUrlMatcherFactory { + /** + * Creates a UrlMatcher for the specified pattern. + * + * @param pattern {string} The URL pattern. + * + * @returns {IUrlMatcher} The UrlMatcher. + */ + compile(pattern: string): IUrlMatcher; + /** + * Returns true if the specified object is a UrlMatcher, or false otherwise. + * + * @param o {any} The object to perform the type check against. + * + * @returns {boolean} Returns true if the object matches the IUrlMatcher interface, by implementing all the same methods. + */ + isMatcher(o: any): boolean; + /** + * Returns a type definition for the specified name + * + * @param name {string} The type definition name + * + * @returns {IType} The type definition + */ + type(name: string): IType; + /** + * Registers a custom Type object that can be used to generate URLs with typed parameters. + * + * @param {IType} definition The type definition. + * @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition. + * + * @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider. + */ + type(name: string, definition: IType, inlineAnnotedDefinitionFn?: any[]): IUrlMatcherFactory; + /** + * Registers a custom Type object that can be used to generate URLs with typed parameters. + * + * @param {IType} definition The type definition. + * @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition. + * + * @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider. + */ + type(name: string, definition: IType, definitionFn?: (...args:any[]) => IType): IUrlMatcherFactory; + /** + * Defines whether URL matching should be case sensitive (the default behavior), or not. + * + * @param value {boolean} false to match URL in a case sensitive manner; otherwise true; + * + * @returns {boolean} the current value of caseInsensitive + */ + caseInsensitive(value?: boolean): boolean; + /** + * Sets the default behavior when generating or matching URLs with default parameter values + * + * @param value {string} A string that defines the default parameter URL squashing behavior. nosquash: When generating an href with a default parameter value, do not squash the parameter value from the URL slash: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the parameter is surrounded by slashes, squash (remove) one slash from the URL any other string, e.g. "~": When generating an href with a default parameter value, squash (remove) the parameter value from the URL and replace it with this string. + */ + defaultSquashPolicy(value: string): void; + /** + * Defines whether URLs should match trailing slashes, or not (the default behavior). + * + * @param value {boolean} false to match trailing slashes in URLs, otherwise true. + * + * @returns {boolean} the current value of strictMode + */ + strictMode(value?: boolean): boolean; + } + + interface IUrlRouterProvider extends angular.IServiceProvider { + when(whenPath: RegExp, handler: Function): IUrlRouterProvider; + when(whenPath: RegExp, handler: any[]): IUrlRouterProvider; + when(whenPath: RegExp, toPath: string): IUrlRouterProvider; + when(whenPath: IUrlMatcher, hanlder: Function): IUrlRouterProvider; + when(whenPath: IUrlMatcher, handler: any[]): IUrlRouterProvider; + when(whenPath: IUrlMatcher, toPath: string): IUrlRouterProvider; + when(whenPath: string, handler: Function): IUrlRouterProvider; + when(whenPath: string, handler: any[]): IUrlRouterProvider; + when(whenPath: string, toPath: string): IUrlRouterProvider; + otherwise(handler: Function): IUrlRouterProvider; + otherwise(handler: any[]): IUrlRouterProvider; + otherwise(path: string): IUrlRouterProvider; + rule(handler: Function): IUrlRouterProvider; + rule(handler: any[]): IUrlRouterProvider; + /** + * Disables (or enables) deferring location change interception. + * + * If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain the current URL), call this method at configuration time. Then, at run time, call $urlRouter.listen() after you have configured your own $locationChangeSuccess event handler. + * + * @param {boolean} defer Indicates whether to defer location change interception. Passing no parameter is equivalent to true. + */ + deferIntercept(defer?: boolean): void; + } + + interface IStateOptions { + /** + * {boolean=true|string=} - If true will update the url in the location bar, if false will not. If string, must be "replace", which will update url and also replace last history record. + */ + location?: boolean | string; + /** + * {boolean=true}, If true will inherit url parameters from current url. + */ + inherit?: boolean; + /** + * {object=$state.$current}, When transitioning with relative path (e.g '^'), defines which state to be relative from. + */ + relative?: IState; + /** + * {boolean=true}, If true will broadcast $stateChangeStart and $stateChangeSuccess events. + */ + notify?: boolean; + /** + * {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params. + */ + reload?: boolean; + } + + interface IHrefOptions { + lossy?: boolean; + inherit?: boolean; + relative?: IState; + absolute?: boolean; + } + + interface IStateService { + /** + * Convenience method for transitioning to a new state. $state.go calls $state.transitionTo internally but automatically sets options to { location: true, inherit: true, relative: $state.$current, notify: true }. This allows you to easily use an absolute or relative to path and specify only the parameters you'd like to update (while letting unspecified parameters inherit from the currently active ancestor states). + * + * @param to Absolute state name or relative state path. Some examples: + * + * $state.go('contact.detail') - will go to the contact.detail state + * $state.go('^') - will go to a parent state + * $state.go('^.sibling') - will go to a sibling state + * $state.go('.child.grandchild') - will go to grandchild state + * + * @param params A map of the parameters that will be sent to the state, will populate $stateParams. Any parameters that are not specified will be inherited from currently defined parameters. This allows, for example, going to a sibling state that shares parameters specified in a parent state. Parameter inheritance only works between common ancestor states, I.e. transitioning to a sibling will get you the parameters for all parents, transitioning to a child will get you all current parameters, etc. + * + * @param options Options object. + */ + go(to: string, params?: {}, options?: IStateOptions): angular.IPromise; + go(to: IState, params?: {}, options?: IStateOptions): angular.IPromise; + transitionTo(state: string, params?: {}, updateLocation?: boolean): angular.IPromise; + transitionTo(state: IState, params?: {}, updateLocation?: boolean): angular.IPromise; + transitionTo(state: string, params?: {}, options?: IStateOptions): angular.IPromise; + transitionTo(state: IState, params?: {}, options?: IStateOptions): angular.IPromise; + includes(state: string, params?: {}): boolean; + includes(state: string, params?: {}, options?:any): boolean; + is(state:string, params?: {}): boolean; + is(state: IState, params?: {}): boolean; + href(state: IState, params?: {}, options?: IHrefOptions): string; + href(state: string, params?: {}, options?: IHrefOptions): string; + get(state: string, context?: string): IState; + get(state: IState, context?: string): IState; + get(state: string, context?: IState): IState; + get(state: IState, context?: IState): IState; + get(): IState[]; + /** A reference to the state's config object. However you passed it in. Useful for accessing custom data. */ + current: IState; + /** A param object, e.g. {sectionId: section.id)}, that you'd like to test against the current active state. */ + params: IStateParamsService; + reload(): angular.IPromise; + + /** Currently pending transition. A promise that'll resolve or reject. */ + transition: angular.IPromise<{}>; + + $current: IResolvedState; + } + + interface IResolvedState { + locals: { + /** + * Currently resolved "resolve" values from the current state + */ + globals: { [key: string]: any; }; + }; + } + + interface IStateParamsService { + [key: string]: any; + } + + interface IUrlRouterService { + /* + * Triggers an update; the same update that happens when the address bar + * url changes, aka $locationChangeSuccess. + * + * This method is useful when you need to use preventDefault() on the + * $locationChangeSuccess event, perform some custom logic (route protection, + * auth, config, redirection, etc) and then finally proceed with the transition + * by calling $urlRouter.sync(). + * + */ + sync(): void; + listen(): Function; + href(urlMatcher: IUrlMatcher, params?: IStateParamsService, options?: IHrefOptions): string; + update(read?: boolean): void; + push(urlMatcher: IUrlMatcher, params?: IStateParamsService, options?: IHrefOptions): void; + } + + interface IUiViewScrollProvider { + /* + * Reverts back to using the core $anchorScroll service for scrolling + * based on the url anchor. + */ + useAnchorScroll(): void; + } + + interface IType { + /** + * Converts a parameter value (from URL string or transition param) to a custom/native value. + * + * @param val {string} The URL parameter value to decode. + * @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects. + * + * @returns {any} Returns a custom representation of the URL parameter value. + */ + decode(val: string, key: string): any; + /** + * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the return value does not need to be URL-safe (i.e. passed through encodeURIComponent()), it only needs to be a representation of val that has been coerced to a string. + * + * @param val {any} The value to encode. + * @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects. + * + * @returns {string} Returns a string representation of val that can be encoded in a URL. + */ + encode(val: any, key: string): string; + /** + * Determines whether two decoded values are equivalent. + * + * @param a {any} A value to compare against. + * @param b {any} A value to compare against. + * + * @returns {boolean} Returns true if the values are equivalent/equal, otherwise false. + */ + equals? (a: any, b: any): boolean; + /** + * Detects whether a value is of a particular type. Accepts a native (decoded) value and determines whether it matches the current Type object. + * + * @param val {any} The value to check. + * @param key {any} Optional. If the type check is happening in the context of a specific UrlMatcher object, this is the name of the parameter in which val is stored. Can be used for meta-programming of Type objects. + * + * @returns {boolean} Returns true if the value matches the type, otherwise false. + */ + is(val: any, key: string): boolean; + /** + * The regular expression pattern used to match values of this type when coming from a substring of a URL. + */ + pattern?: RegExp; + } + } + +} + diff --git a/angular-ui-router/tsconfig.json b/angular-ui-router/tsconfig.json new file mode 100644 index 0000000000..a09480fa34 --- /dev/null +++ b/angular-ui-router/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-ui-router-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-ui-scroll/angular-ui-scroll-tests.ts b/angular-ui-scroll/angular-ui-scroll-tests.ts index 528d39e552..e226b664bc 100644 --- a/angular-ui-scroll/angular-ui-scroll-tests.ts +++ b/angular-ui-scroll/angular-ui-scroll-tests.ts @@ -1,4 +1,4 @@ -/// + var myApp = angular.module('application', ['ui.scroll', 'ui.scroll.jqlite']); namespace application { diff --git a/angular-ui-scroll/angular-ui-scroll.d.ts b/angular-ui-scroll/angular-ui-scroll.d.ts deleted file mode 100644 index 168c6ba271..0000000000 --- a/angular-ui-scroll/angular-ui-scroll.d.ts +++ /dev/null @@ -1,85 +0,0 @@ -// Type definitions for Angular JS 1.3.1+ (ui.scroll module) -// Project: https://github.com/angular-ui/ui-scroll -// Definitions by: Mark Nadig -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.ui { - interface IScrollDatasource { - /** - * The datasource object implements methods and properties to be used by the directive to access the data - * - * @param index indicates the first data row requested - * - * @param count indicates number of data rows requested - * - * @param success function to call when the data are retrieved. The implementation of the service has to call - * this function when the data are retrieved and pass it an array of the items retrieved. If no items are - * retrieved, an empty array has to be passed. - * - * Important: Make sure to respect the index and count parameters of the request. The array passed to the - * success method should have exactly count elements unless it hit eof/bof - */ - get(index: number, count: number, success: (results: Array) => any): void; - } - - interface IScrollAdapter { - /** - * a boolean value indicating whether there are any pending load requests. - */ - isLoading: boolean; - /** - * a reference to the item currently in the topmost visible position. - */ - topVisible: any; - /** - * a reference to the DOM element currently in the topmost visible position. - */ - topVisibleElement: ng.IAugmentedJQueryStatic; - /** - * a reference to the scope created for the item currently in the topmost visible position. - */ - topVisibleScope: ng.IRepeatScope; - /** - * calling this method reinitializes and reloads the scroller content. - */ - reload(): void; - /** - * Replaces the item in the buffer at the given index with the new items. - * - * @param index provides position of the item to be affected in the dataset (not in the buffer). If the item with - * the given index currently is not in the buffer no updates will be applied. $index property of the item $scope - * can be used to access the index value for a given item - * - * @param newItems is an array of items to replace the affected item. If the array is empty ([]) the item will - * be deleted, otherwise the items in the array replace the item. If the newItem array contains the old item, - * the old item stays in place. - */ - applyUpdates(index: number, newItems: any[]): void; - /** - * Replaces the item in the buffer at the given index with the new items. - * - * @param updater is a function to be applied to every item currently in the buffer. The function will receive - * 3 parameters: item, scope, and element. Here item is the item to be affected, scope is the item $scope, and - * element is the html element for the item. The return value of the function should be an array of items. - * Similarly to the newItem parameter (see above), if the array is empty([]), the item is deleted, otherwise - * the item is replaced by the items in the array. If the return value is not an array, the item remains - * unaffected, unless some updates were made to the item in the updater function. This can be thought of as - * in place update. - */ - applyUpdates(updater: (item: any, scope: ng.IRepeatScope) => any): void; - /** - * Adds new items after the last item in the buffer - * - * @param newItems provides an array of items to be appended. - */ - append(newItems: any[]): void; - /** - * Adds new items before the first item in the buffer - * - * @param newItems provides an array of items to be prepended. - */ - prepend(newItems: any[]): void; - } -} diff --git a/angular-ui-scroll/index.d.ts b/angular-ui-scroll/index.d.ts new file mode 100644 index 0000000000..e8a04c4eeb --- /dev/null +++ b/angular-ui-scroll/index.d.ts @@ -0,0 +1,85 @@ +// Type definitions for Angular JS 1.3.1+ (ui.scroll module) +// Project: https://github.com/angular-ui/ui-scroll +// Definitions by: Mark Nadig +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.ui { + interface IScrollDatasource { + /** + * The datasource object implements methods and properties to be used by the directive to access the data + * + * @param index indicates the first data row requested + * + * @param count indicates number of data rows requested + * + * @param success function to call when the data are retrieved. The implementation of the service has to call + * this function when the data are retrieved and pass it an array of the items retrieved. If no items are + * retrieved, an empty array has to be passed. + * + * Important: Make sure to respect the index and count parameters of the request. The array passed to the + * success method should have exactly count elements unless it hit eof/bof + */ + get(index: number, count: number, success: (results: Array) => any): void; + } + + interface IScrollAdapter { + /** + * a boolean value indicating whether there are any pending load requests. + */ + isLoading: boolean; + /** + * a reference to the item currently in the topmost visible position. + */ + topVisible: any; + /** + * a reference to the DOM element currently in the topmost visible position. + */ + topVisibleElement: ng.IAugmentedJQueryStatic; + /** + * a reference to the scope created for the item currently in the topmost visible position. + */ + topVisibleScope: ng.IRepeatScope; + /** + * calling this method reinitializes and reloads the scroller content. + */ + reload(): void; + /** + * Replaces the item in the buffer at the given index with the new items. + * + * @param index provides position of the item to be affected in the dataset (not in the buffer). If the item with + * the given index currently is not in the buffer no updates will be applied. $index property of the item $scope + * can be used to access the index value for a given item + * + * @param newItems is an array of items to replace the affected item. If the array is empty ([]) the item will + * be deleted, otherwise the items in the array replace the item. If the newItem array contains the old item, + * the old item stays in place. + */ + applyUpdates(index: number, newItems: any[]): void; + /** + * Replaces the item in the buffer at the given index with the new items. + * + * @param updater is a function to be applied to every item currently in the buffer. The function will receive + * 3 parameters: item, scope, and element. Here item is the item to be affected, scope is the item $scope, and + * element is the html element for the item. The return value of the function should be an array of items. + * Similarly to the newItem parameter (see above), if the array is empty([]), the item is deleted, otherwise + * the item is replaced by the items in the array. If the return value is not an array, the item remains + * unaffected, unless some updates were made to the item in the updater function. This can be thought of as + * in place update. + */ + applyUpdates(updater: (item: any, scope: ng.IRepeatScope) => any): void; + /** + * Adds new items after the last item in the buffer + * + * @param newItems provides an array of items to be appended. + */ + append(newItems: any[]): void; + /** + * Adds new items before the first item in the buffer + * + * @param newItems provides an array of items to be prepended. + */ + prepend(newItems: any[]): void; + } +} diff --git a/angular-ui-scroll/tsconfig.json b/angular-ui-scroll/tsconfig.json new file mode 100644 index 0000000000..259649411d --- /dev/null +++ b/angular-ui-scroll/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-ui-scroll-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-ui-sortable/angular-ui-sortable-tests.ts b/angular-ui-sortable/angular-ui-sortable-tests.ts index 836dc71e9a..70a2745289 100644 --- a/angular-ui-sortable/angular-ui-sortable-tests.ts +++ b/angular-ui-sortable/angular-ui-sortable-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + var myApp = angular.module('testModule'); diff --git a/angular-ui-sortable/angular-ui-sortable.d.ts b/angular-ui-sortable/angular-ui-sortable.d.ts deleted file mode 100644 index ac3ac89fc7..0000000000 --- a/angular-ui-sortable/angular-ui-sortable.d.ts +++ /dev/null @@ -1,210 +0,0 @@ -// Type definitions for angular.ui.sortable module v0.13+ -// Project: https://github.com/angular-ui/ui-sortable -// Definitions by: Thodoris Greasidis -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.ui { - - interface UISortableOptions extends SortableOptions { - 'ui-floating'?: string|boolean; - } - - interface UISortableProperties { - /** - * Holds the index of the drop target that the dragged item was dropped. - */ - dropindex: number; - - /** - * Holds the ui-sortable element that the dragged item was dropped on. - */ - droptarget: number; - - /** - * Holds the array that is specified by the `ng-model` attribute of the [`droptarget`](#droptarget) ui-sortable element. - */ - droptargetModel: Array; - - /** - * Holds the original index of the item dragged. - */ - index: number; - - /** - * Holds the JavaScript object that is used as the model of the dragged item, as specified by the ng-repeat of the [`source`](#source) ui-sortable element and the item's [`index`](#index). - */ - model: T; - - /** - * Holds the model of the dragged item only when a sorting happens between two connected ui-sortable elements. - * In other words: `'moved' in ui.item.sortable` will return false only when a sorting is withing the same ui-sortable element ([`source`](#source) equals to the [`droptarget`](#droptarget)). - */ - moved?: T; - - /** - * When sorting between two connected sortables, it will be set to true inside the `update` callback of the [`droptarget`](#droptarget). - */ - received: Boolean; - - /** - * Holds the ui-sortable element that the dragged item originated from. - */ - source: ng.IAugmentedJQuery - - /** - * Holds the array that is specified by the `ng-model` of the [`source`](#source) ui-sortable element. - */ - sourceModel: Array; - - /** - * Can be called inside the `update` callback, in order to prevent/revert a sorting. - * Should be used instead of the [jquery-ui-sortable cancel()](http://api.jqueryui.com/sortable/#method-cancel) method. - */ - cancel(): void; - - /** - * Returns whether the current sorting is marked as canceled, by an earlier call to [`ui.item.sortable.cancel()`](#cancel). - */ - isCanceled(): Boolean; - - /** - * Returns whether the [`helper`](http://api.jqueryui.com/sortable/#option-helper) element used for the current sorting, is one of the original ui-sortable list elements. - */ - isCustomHelperUsed(): Boolean; - } - - interface UISortableUIItem extends ng.IAugmentedJQuery { - sortable: UISortableProperties; - } - - interface UISortableUIParams extends SortableUIParams { - item: UISortableUIItem; - } - - // Base Sortable ////////////////////////////////////////////////// - - interface SortableCursorAtOptions { - top?: number; - left?: number; - right?: number; - bottom?: number; - } - - interface SortableHelperFunctionOption { - (event: JQueryEventObject, ui: ng.IAugmentedJQuery): JQuery; - } - - interface SortableOptions extends SortableEvents { - /** - * jQuery, Element, Selector or string - * Default: "parent" - */ - appendTo?: any; - /** - * "X", "Y" or false - * Default: false - */ - axis?: string|boolean; - /** - * Selector - * Default: "input,textarea,button,select,option" - */ - cancel?: string; - /** - * Selector or false - * Default: false - */ - connectWith?: string|boolean; - /** - * Element, Selector, string or false - * Default: false - */ - containment?: any; - cursor?: string; - /** - * Moves the sorting element or helper so the cursor always appears to drag from the same position. Coordinates can be given as a hash using a combination of one or two keys SortableCursorAtOptions: { top, left, right, bottom } - * Default: false - */ - cursorAt?: SortableCursorAtOptions|boolean; - delay?: number; - disabled?: boolean; - distance?: number; - dropOnEmpty?: boolean; - forceHelperSize?: boolean; - forcePlaceholderSize?: boolean; - /** - * Array of numbers or false - * Default: false - */ - grid?: number[]|boolean; - /** - * Selector or Element - */ - handle?: any; - /** - * "original", "clone" or Function() - * Default: "original" - */ - helper?: string|SortableHelperFunctionOption; - /** - * Selector - */ - items?: string; - /** - * Number or false - * Default: false - */ - opacity?: number|boolean; - /** - * string or false - * Default: false - */ - placeholder?: string|boolean; - /** - * boolean or number - * Default: false - */ - revert?: number|boolean; - scroll?: boolean; - scrollSensitivity?: number; - scrollSpeed?: number; - /** - * "intersect" or "pointer" - * Default: "intersect" - */ - tolerance?: string; - zIndex?: number; - } - - interface SortableUIParams { - helper: ng.IAugmentedJQuery; - item: ng.IAugmentedJQuery; - offset: any; - position: any; - originalPosition: any; - sender: ng.IAugmentedJQuery; - placeholder: ng.IAugmentedJQuery; - } - - interface SortableEvent { - (event: JQueryEventObject, ui: UISortableUIParams): void; - } - - interface SortableEvents { - activate?: SortableEvent; - beforeStop?: SortableEvent; - change?: SortableEvent; - deactivate?: SortableEvent; - out?: SortableEvent; - over?: SortableEvent; - receive?: SortableEvent; - remove?: SortableEvent; - sort?: SortableEvent; - start?: SortableEvent; - stop?: SortableEvent; - update?: SortableEvent; - } - -} diff --git a/angular-ui-sortable/index.d.ts b/angular-ui-sortable/index.d.ts new file mode 100644 index 0000000000..1b3508143d --- /dev/null +++ b/angular-ui-sortable/index.d.ts @@ -0,0 +1,210 @@ +// Type definitions for angular.ui.sortable module v0.13+ +// Project: https://github.com/angular-ui/ui-sortable +// Definitions by: Thodoris Greasidis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.ui { + + interface UISortableOptions extends SortableOptions { + 'ui-floating'?: string|boolean; + } + + interface UISortableProperties { + /** + * Holds the index of the drop target that the dragged item was dropped. + */ + dropindex: number; + + /** + * Holds the ui-sortable element that the dragged item was dropped on. + */ + droptarget: number; + + /** + * Holds the array that is specified by the `ng-model` attribute of the [`droptarget`](#droptarget) ui-sortable element. + */ + droptargetModel: Array; + + /** + * Holds the original index of the item dragged. + */ + index: number; + + /** + * Holds the JavaScript object that is used as the model of the dragged item, as specified by the ng-repeat of the [`source`](#source) ui-sortable element and the item's [`index`](#index). + */ + model: T; + + /** + * Holds the model of the dragged item only when a sorting happens between two connected ui-sortable elements. + * In other words: `'moved' in ui.item.sortable` will return false only when a sorting is withing the same ui-sortable element ([`source`](#source) equals to the [`droptarget`](#droptarget)). + */ + moved?: T; + + /** + * When sorting between two connected sortables, it will be set to true inside the `update` callback of the [`droptarget`](#droptarget). + */ + received: Boolean; + + /** + * Holds the ui-sortable element that the dragged item originated from. + */ + source: ng.IAugmentedJQuery + + /** + * Holds the array that is specified by the `ng-model` of the [`source`](#source) ui-sortable element. + */ + sourceModel: Array; + + /** + * Can be called inside the `update` callback, in order to prevent/revert a sorting. + * Should be used instead of the [jquery-ui-sortable cancel()](http://api.jqueryui.com/sortable/#method-cancel) method. + */ + cancel(): void; + + /** + * Returns whether the current sorting is marked as canceled, by an earlier call to [`ui.item.sortable.cancel()`](#cancel). + */ + isCanceled(): Boolean; + + /** + * Returns whether the [`helper`](http://api.jqueryui.com/sortable/#option-helper) element used for the current sorting, is one of the original ui-sortable list elements. + */ + isCustomHelperUsed(): Boolean; + } + + interface UISortableUIItem extends ng.IAugmentedJQuery { + sortable: UISortableProperties; + } + + interface UISortableUIParams extends SortableUIParams { + item: UISortableUIItem; + } + + // Base Sortable ////////////////////////////////////////////////// + + interface SortableCursorAtOptions { + top?: number; + left?: number; + right?: number; + bottom?: number; + } + + interface SortableHelperFunctionOption { + (event: JQueryEventObject, ui: ng.IAugmentedJQuery): JQuery; + } + + interface SortableOptions extends SortableEvents { + /** + * jQuery, Element, Selector or string + * Default: "parent" + */ + appendTo?: any; + /** + * "X", "Y" or false + * Default: false + */ + axis?: string|boolean; + /** + * Selector + * Default: "input,textarea,button,select,option" + */ + cancel?: string; + /** + * Selector or false + * Default: false + */ + connectWith?: string|boolean; + /** + * Element, Selector, string or false + * Default: false + */ + containment?: any; + cursor?: string; + /** + * Moves the sorting element or helper so the cursor always appears to drag from the same position. Coordinates can be given as a hash using a combination of one or two keys SortableCursorAtOptions: { top, left, right, bottom } + * Default: false + */ + cursorAt?: SortableCursorAtOptions|boolean; + delay?: number; + disabled?: boolean; + distance?: number; + dropOnEmpty?: boolean; + forceHelperSize?: boolean; + forcePlaceholderSize?: boolean; + /** + * Array of numbers or false + * Default: false + */ + grid?: number[]|boolean; + /** + * Selector or Element + */ + handle?: any; + /** + * "original", "clone" or Function() + * Default: "original" + */ + helper?: string|SortableHelperFunctionOption; + /** + * Selector + */ + items?: string; + /** + * Number or false + * Default: false + */ + opacity?: number|boolean; + /** + * string or false + * Default: false + */ + placeholder?: string|boolean; + /** + * boolean or number + * Default: false + */ + revert?: number|boolean; + scroll?: boolean; + scrollSensitivity?: number; + scrollSpeed?: number; + /** + * "intersect" or "pointer" + * Default: "intersect" + */ + tolerance?: string; + zIndex?: number; + } + + interface SortableUIParams { + helper: ng.IAugmentedJQuery; + item: ng.IAugmentedJQuery; + offset: any; + position: any; + originalPosition: any; + sender: ng.IAugmentedJQuery; + placeholder: ng.IAugmentedJQuery; + } + + interface SortableEvent { + (event: JQueryEventObject, ui: UISortableUIParams): void; + } + + interface SortableEvents { + activate?: SortableEvent; + beforeStop?: SortableEvent; + change?: SortableEvent; + deactivate?: SortableEvent; + out?: SortableEvent; + over?: SortableEvent; + receive?: SortableEvent; + remove?: SortableEvent; + sort?: SortableEvent; + start?: SortableEvent; + stop?: SortableEvent; + update?: SortableEvent; + } + +} diff --git a/angular-ui-sortable/tsconfig.json b/angular-ui-sortable/tsconfig.json new file mode 100644 index 0000000000..56343d3c56 --- /dev/null +++ b/angular-ui-sortable/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-ui-sortable-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-ui-tree/angular-ui-tree-tests.ts b/angular-ui-tree/angular-ui-tree-tests.ts index 718fada2ce..d3c1bad2cb 100644 --- a/angular-ui-tree/angular-ui-tree-tests.ts +++ b/angular-ui-tree/angular-ui-tree-tests.ts @@ -1,4 +1,4 @@ -/// + var treeNode: AngularUITree.ITreeNode = { id: 0, diff --git a/angular-ui-tree/angular-ui-tree.d.ts b/angular-ui-tree/angular-ui-tree.d.ts deleted file mode 100644 index 66909cf90f..0000000000 --- a/angular-ui-tree/angular-ui-tree.d.ts +++ /dev/null @@ -1,80 +0,0 @@ -// Type definitions for angular-ui-tree v2.8.0 -// Project: https://github.com/angular-ui-tree/angular-ui-tree -// Definitions by: Calvin Fernandez -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace AngularUITree { - interface IEventSourceInfo { - cloneModel: any; - index: number; - nodeScope: ITreeNodeScope; - nodesScope: ITreeNodeScope; - } - - interface IPosition { - dirAx: number; - dirX: number; - dirY: number; - distAxX: number; - distAxY: number; - distX: number; - distY: number; - lastDirX: number; - lastDirY: number; - lastX: number; - lastY: number; - moving: boolean; - nowX: number; - nowY: number; - offsetX: number; - offsetY: number; - startX: number; - startY: number; - } - - interface IEventInfo { - dest: { - index: number; - nodesScope: IParentTreeNodeScope; - }; - elements: any; - pos: IPosition; - source: IEventSourceInfo; - } - - interface IAcceptCallback { - (source: ITreeNodeScope, destination: ITreeNodeScope, destinationIndex: number): boolean; - } - - interface IDroppedCallback { - (eventInfo: IEventInfo): void; - } - - interface ICallbacks { - accept: IAcceptCallback; - dragStart: IDroppedCallback; - dropped: IDroppedCallback; - } - - /** - * Internal representation of node in the UI - */ - interface ITreeNodeScope extends ng.IScope { - node: ITreeNode; - } - - interface IParentTreeNodeScope extends ITreeNodeScope { - isParent(nodeScope: ITreeNodeScope): boolean; - } - - /** - * Node in list - */ - interface ITreeNode { - id: number | string; - nodes: ITreeNode[]; - title: string; - } -} diff --git a/angular-ui-tree/index.d.ts b/angular-ui-tree/index.d.ts new file mode 100644 index 0000000000..1cededaa53 --- /dev/null +++ b/angular-ui-tree/index.d.ts @@ -0,0 +1,80 @@ +// Type definitions for angular-ui-tree v2.8.0 +// Project: https://github.com/angular-ui-tree/angular-ui-tree +// Definitions by: Calvin Fernandez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace AngularUITree { + interface IEventSourceInfo { + cloneModel: any; + index: number; + nodeScope: ITreeNodeScope; + nodesScope: ITreeNodeScope; + } + + interface IPosition { + dirAx: number; + dirX: number; + dirY: number; + distAxX: number; + distAxY: number; + distX: number; + distY: number; + lastDirX: number; + lastDirY: number; + lastX: number; + lastY: number; + moving: boolean; + nowX: number; + nowY: number; + offsetX: number; + offsetY: number; + startX: number; + startY: number; + } + + interface IEventInfo { + dest: { + index: number; + nodesScope: IParentTreeNodeScope; + }; + elements: any; + pos: IPosition; + source: IEventSourceInfo; + } + + interface IAcceptCallback { + (source: ITreeNodeScope, destination: ITreeNodeScope, destinationIndex: number): boolean; + } + + interface IDroppedCallback { + (eventInfo: IEventInfo): void; + } + + interface ICallbacks { + accept: IAcceptCallback; + dragStart: IDroppedCallback; + dropped: IDroppedCallback; + } + + /** + * Internal representation of node in the UI + */ + interface ITreeNodeScope extends ng.IScope { + node: ITreeNode; + } + + interface IParentTreeNodeScope extends ITreeNodeScope { + isParent(nodeScope: ITreeNodeScope): boolean; + } + + /** + * Node in list + */ + interface ITreeNode { + id: number | string; + nodes: ITreeNode[]; + title: string; + } +} diff --git a/angular-ui-tree/tsconfig.json b/angular-ui-tree/tsconfig.json new file mode 100644 index 0000000000..66c0316b4c --- /dev/null +++ b/angular-ui-tree/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-ui-tree-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-wizard/angular-wizard-tests.ts b/angular-wizard/angular-wizard-tests.ts index 05a5d574f1..71cd1cbbc2 100644 --- a/angular-wizard/angular-wizard-tests.ts +++ b/angular-wizard/angular-wizard-tests.ts @@ -1,8 +1,5 @@ -/// -/// -/// - -/// +/// +/// // test file taken from https://github.com/mgonto/angular-wizard diff --git a/angular-wizard/angular-wizard.d.ts b/angular-wizard/index.d.ts similarity index 100% rename from angular-wizard/angular-wizard.d.ts rename to angular-wizard/index.d.ts diff --git a/angular-wizard/tsconfig.json b/angular-wizard/tsconfig.json new file mode 100644 index 0000000000..951b5e0e0e --- /dev/null +++ b/angular-wizard/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-wizard-tests.ts" + ] +} \ No newline at end of file diff --git a/angular.throttle/angular.throttle-tests.ts b/angular.throttle/angular.throttle-tests.ts index 2234adbc37..5bc81cebca 100644 --- a/angular.throttle/angular.throttle-tests.ts +++ b/angular.throttle/angular.throttle-tests.ts @@ -1,5 +1,4 @@ -/// -/// + var throttledFn = angular.throttle(function (someArg:any) { return someArg; diff --git a/angular.throttle/angular.throttle.d.ts b/angular.throttle/angular.throttle.d.ts deleted file mode 100644 index 354d6b3f98..0000000000 --- a/angular.throttle/angular.throttle.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Type definitions for angular.throttle -// Project: https://github.com/BaggersIO/angular.throttle -// Definitions by: Stefan Steinhart -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular { - interface IAngularStatic { - throttle:( fn:Function, throttle:number, options?:{leading?:boolean; trailing?:boolean;} ) => Function; - } -} diff --git a/angular.throttle/index.d.ts b/angular.throttle/index.d.ts new file mode 100644 index 0000000000..ee70e42eb8 --- /dev/null +++ b/angular.throttle/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for angular.throttle +// Project: https://github.com/BaggersIO/angular.throttle +// Definitions by: Stefan Steinhart +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular { + interface IAngularStatic { + throttle:( fn:Function, throttle:number, options?:{leading?:boolean; trailing?:boolean;} ) => Function; + } +} diff --git a/angular.throttle/tsconfig.json b/angular.throttle/tsconfig.json new file mode 100644 index 0000000000..59cc3ee465 --- /dev/null +++ b/angular.throttle/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular.throttle-tests.ts" + ] +} \ No newline at end of file diff --git a/angularLocalStorage/angularLocalStorage-tests.ts b/angularLocalStorage/angularLocalStorage-tests.ts index 366ab6e44a..409dcde292 100644 --- a/angularLocalStorage/angularLocalStorage-tests.ts +++ b/angularLocalStorage/angularLocalStorage-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// interface TestScope extends ng.IScope { viewType: string; diff --git a/angularLocalStorage/angularLocalStorage.d.ts b/angularLocalStorage/angularLocalStorage.d.ts deleted file mode 100644 index 35bb5928c1..0000000000 --- a/angularLocalStorage/angularLocalStorage.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Type definitions for AngularLocalStorage 0.1.7 -// Project: https://github.com/agrublev/angularLocalStorage -// Definitions by: Horiuchi_H -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace angular.localStorage { - interface ILocalStorageService { - set(key: string, value: any): any; - get(key: string): any; - remove(key: string): boolean; - clearAll(): void; - - bind($scope: ng.IScope, key: string, opts?: { - defaultValue?: any; - storeName?: string; - }): any; - unbind($scope: ng.IScope, key: string, storeName?: string): void; - } -} - diff --git a/angularLocalStorage/index.d.ts b/angularLocalStorage/index.d.ts new file mode 100644 index 0000000000..84ecc42e5e --- /dev/null +++ b/angularLocalStorage/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for AngularLocalStorage 0.1.7 +// Project: https://github.com/agrublev/angularLocalStorage +// Definitions by: Horiuchi_H +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.localStorage { + interface ILocalStorageService { + set(key: string, value: any): any; + get(key: string): any; + remove(key: string): boolean; + clearAll(): void; + + bind($scope: ng.IScope, key: string, opts?: { + defaultValue?: any; + storeName?: string; + }): any; + unbind($scope: ng.IScope, key: string, storeName?: string): void; + } +} + diff --git a/angularLocalStorage/tsconfig.json b/angularLocalStorage/tsconfig.json new file mode 100644 index 0000000000..6384fa3f7e --- /dev/null +++ b/angularLocalStorage/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angularLocalStorage-tests.ts" + ] +} \ No newline at end of file diff --git a/angularfire/angularfire-tests.ts b/angularfire/angularfire-tests.ts index c649301e37..38020c0f7c 100644 --- a/angularfire/angularfire-tests.ts +++ b/angularfire/angularfire-tests.ts @@ -1,5 +1,3 @@ -/// - var myapp = angular.module("myapp", ["firebase"]); interface AngularFireScope extends ng.IScope { diff --git a/angularfire/angularfire.d.ts b/angularfire/angularfire.d.ts deleted file mode 100644 index e60fcad361..0000000000 --- a/angularfire/angularfire.d.ts +++ /dev/null @@ -1,479 +0,0 @@ -// Type definitions for AngularFire 0.8.2 -// Project: http://angularfire.com -// Definitions by: Dénes Harmath -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -interface AngularFireService { - (firebase: Firebase, config?: any): AngularFire; -} - -/** - * @deprecated. Not possible with AngularFire 1.0+ - */ -interface AngularFire { - $asArray(): AngularFireArray; - $asObject(): AngularFireObject; - $ref(): Firebase; - $push(data: any): ng.IPromise; - $set(key: string, data: any): ng.IPromise; - $set(data: any): ng.IPromise; - $remove(key?: string): ng.IPromise; - $update(key: string, data: Object): ng.IPromise; - $update(data: any): ng.IPromise; - $transaction(updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise; - $transaction(key:string, updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise; -} - -/** - * Creates and maintains a synchronized object, with 2-way bindings between Angular and Firebase. - */ -interface AngularFireObject extends AngularFireSimpleObject { - $id: string; - $priority: number; - $value: any; - - /** - * Removes all keys from the FirebaseObject and also removes - * the remote data from the server. - * - * @returns a promise which will resolve after the op completes - */ - - $remove(): ng.IPromise; - /** - * Saves all data on the FirebaseObject back to Firebase. - * @returns a promise which will resolve after the save is completed. - */ - $save(): ng.IPromise; - - /** - * The loaded method is invoked after the initial batch of data arrives from the server. - * When this resolves, all data which existed prior to calling $asObject() is now cached - * locally in the object. - * - * As a shortcut is also possible to pass resolve/reject methods directly into this - * method just as they would be passed to .then() - * - * @param {Function} resolve - * @param {Function} reject - * @returns a promise which resolves after initial data is downloaded from Firebase - */ - $loaded(resolve?: (x: AngularFireObject) => ng.IHttpPromise<{}>, reject?: (err: any) => any): ng.IPromise; - - /** - * The loaded method is invoked after the initial batch of data arrives from the server. - * When this resolves, all data which existed prior to calling $asObject() is now cached - * locally in the object. - * - * As a shortcut is also possible to pass resolve/reject methods directly into this - * method just as they would be passed to .then() - * - * @param {Function} resolve - * @param {Function} reject - * @returns a promise which resolves after initial data is downloaded from Firebase - */ - $loaded(resolve?: (x: AngularFireObject) => ng.IPromise<{}>, reject?: (err: any) => any): ng.IPromise; - - /** - * The loaded method is invoked after the initial batch of data arrives from the server. - * When this resolves, all data which existed prior to calling $asObject() is now cached - * locally in the object. - * - * As a shortcut is also possible to pass resolve/reject methods directly into this - * method just as they would be passed to .then() - * - * @param {Function} resolve - * @param {Function} reject - * @returns a promise which resolves after initial data is downloaded from Firebase - */ - $loaded(resolve?: (x: AngularFireObject) => void, reject?: (err: any) => any): ng.IPromise; - - /** - * @returns {Firebase} the original Firebase instance used to create this object. - */ - $ref(): Firebase; - - /** - * Creates a 3-way data sync between this object, the Firebase server, and a - * scope variable. This means that any changes made to the scope variable are - * pushed to Firebase, and vice versa. - * - * If scope emits a $destroy event, the binding is automatically severed. Otherwise, - * it is possible to unbind the scope variable by using the `unbind` function - * passed into the resolve method. - * - * Can only be bound to one scope variable at a time. If a second is attempted, - * the promise will be rejected with an error. - * - * @param {object} scope - * @param {string} varName - * @returns a promise which resolves to an unbind method after data is set in scope - */ - $bindTo(scope: ng.IScope, varName: string): ng.IPromise; - - /** - * Listeners passed into this method are notified whenever a new change is received - * from the server. Each invocation is sent an object containing - * { type: 'value', key: 'my_firebase_id' } - * - * This method returns an unbind function that can be used to detach the listener. - * - * @param {Function} cb - * @param {Object} [context] - * @returns {Function} invoke to stop observing events - */ - $watch(callback: Function, context?: any): Function; - - /** - * Informs $firebase to stop sending events and clears memory being used - * by this object (delete's its local content). - */ - $destroy(): void; -} -interface AngularFireObjectService { - /** - * Creates a synchronized object with 2-way bindings between Angular and Firebase. - * - * @param {Firebase} ref - * @returns {FirebaseObject} - */ - (firebase: Firebase): AngularFireObject; - $extend(ChildClass: Object, methods?: Object): Object; -} - -/** - * Creates and maintains a synchronized list of data. This is a pseudo-read-only array. One should - * not call splice(), push(), pop(), et al directly on this array, but should instead use the - * $remove and $add methods. - * - * It is acceptable to .sort() this array, but it is important to use this in conjunction with - * $watch(), so that it will be re-sorted any time the server data changes. Examples of this are - * included in the $watch documentation. - */ -interface AngularFireArray extends Array { - /** - * Create a new record with a unique ID and add it to the end of the array. - * This should be used instead of Array.prototype.push, since those changes will not be - * synchronized with the server. - * - * Any value, including a primitive, can be added in this way. Note that when the record - * is created, the primitive value would be stored in $value (records are always objects - * by default). - * - * Returns a future which is resolved when the data has successfully saved to the server. - * The resolve callback will be passed a Firebase ref representing the new data element. - * - * @param data - * @returns a promise resolved after data is added - */ - $add(newData: any): ng.IPromise; - - /** - * Pass either an item in the array or the index of an item and it will be saved back - * to Firebase. While the array is read-only and its structure should not be changed, - * it is okay to modify properties on the objects it contains and then save those back - * individually. - * - * Returns a future which is resolved when the data has successfully saved to the server. - * The resolve callback will be passed a Firebase ref representing the saved element. - * If passed an invalid index or an object which is not a record in this array, - * the promise will be rejected. - * - * @param {int|object} indexOrItem - * @returns a promise resolved after data is saved - */ - $save(recordOrIndex: any): ng.IPromise; - - /** - * Pass either an existing item in this array or the index of that item and it will - * be removed both locally and in Firebase. This should be used in place of - * Array.prototype.splice for removing items out of the array, as calling splice - * will not update the value on the server. - * - * Returns a future which is resolved when the data has successfully removed from the - * server. The resolve callback will be passed a Firebase ref representing the deleted - * element. If passed an invalid index or an object which is not a record in this array, - * the promise will be rejected. - * - * @param {int|object} indexOrItem - * @returns a promise which resolves after data is removed - */ - $remove(recordOrIndex: any): ng.IPromise; - - /** - * Returns the record for a given Firebase key (record.$id). If the record is not found - * then returns null. - * - * @param {string} key - * @returns {Object|null} a record in this array - */ - $getRecord(key: string): AngularFireSimpleObject; - - /** - * Given an item in this array or the index of an item in the array, this returns the - * Firebase key (record.$id) for that record. If passed an invalid key or an item which - * does not exist in this array, it will return null. - * - * @param {int|object} indexOrItem - * @returns {null|string} - */ - $keyAt(recordOrIndex: any): string; - - /** - * The inverse of $keyAt, this method takes a Firebase key (record.$id) and returns the - * index in the array where that record is stored. If the record is not in the array, - * this method returns -1. - * - * @param {String} key - * @returns {int} -1 if not found - */ - $indexFor(key: string): number; - - /** - * The loaded method is invoked after the initial batch of data arrives from the server. - * When this resolves, all data which existed prior to calling $asArray() is now cached - * locally in the array. - * - * As a shortcut is also possible to pass resolve/reject methods directly into this - * method just as they would be passed to .then() - * - * @param {Function} [resolve] - * @param {Function} [reject] - * @returns a promise - */ - $loaded(resolve?: (x: AngularFireArray) => ng.IHttpPromise<{}>, reject?: (err: any) => any): ng.IPromise; - - /** - * The loaded method is invoked after the initial batch of data arrives from the server. - * When this resolves, all data which existed prior to calling $asArray() is now cached - * locally in the array. - * - * As a shortcut is also possible to pass resolve/reject methods directly into this - * method just as they would be passed to .then() - * - * @param {Function} [resolve] - * @param {Function} [reject] - * @returns a promise - */ - $loaded(resolve?: (x: AngularFireArray) => ng.IPromise<{}>, reject?: (err: any) => any): ng.IPromise; - - /** - * The loaded method is invoked after the initial batch of data arrives from the server. - * When this resolves, all data which existed prior to calling $asArray() is now cached - * locally in the array. - * - * As a shortcut is also possible to pass resolve/reject methods directly into this - * method just as they would be passed to .then() - * - * @param {Function} [resolve] - * @param {Function} [reject] - * @returns a promise - */ - $loaded(resolve?: (x: AngularFireArray) => void, reject?: (err: any) => any): ng.IPromise; - - /** - * @returns {Firebase} the original Firebase ref used to create this object. - */ - $ref(): Firebase; - - /** - * Listeners passed into this method are notified whenever a new change (add, updated, - * move, remove) is received from the server. Each invocation is sent an object - * containing { type: 'child_added|child_updated|child_moved|child_removed', - * key: 'key_of_item_affected'} - * - * Additionally, added and moved events receive a prevChild parameter, containing the - * key of the item before this one in the array. - * - * This method returns a function which can be invoked to stop observing events. - * - * @param {Function} cb - * @param {Object} [context] - * @returns {Function} used to stop observing - */ - $watch(cb: (event: string, key: string, prevChild: string) => void, context?: any): Function; - - /** - * Informs $firebase to stop sending events and clears memory being used - * by this array (delete's its local content). - */ - $destroy(): void; -} -interface AngularFireArrayService { - (firebase: Firebase): AngularFireArray; - $extend(ChildClass: Object, methods?: Object): Object; -} - -interface AngularFireSimpleObject { - $id: string; - $priority: number; - $value: any; - [key: string]: any; -} - - -interface AngularFireAuthService { - (firebase: Firebase): AngularFireAuth; -} - -interface AngularFireAuth { - /** - * Authenticates the Firebase reference with a custom authentication token. - * - * @param {string} authToken An authentication token or a Firebase Secret. A Firebase Secret - * should only be used for authenticating a server process and provides full read / write - * access to the entire Firebase. - * @param {Object} [options] An object containing optional client arguments, such as configuring - * session persistence. - * @return {Promise} A promise fulfilled with an object containing authentication data. - */ - $authWithCustomToken(authToken: string, options?: Object): ng.IPromise; - - /** - * Authenticates the Firebase reference anonymously. - * - * @param {Object} [options] An object containing optional client arguments, such as configuring - * session persistence. - * @return {Promise} A promise fulfilled with an object containing authentication data. - */ - $authAnonymously(options?: Object): ng.IPromise; - - /** - * Authenticates the Firebase reference with an email/password user. - * - * @param {Object} credentials An object containing email and password attributes corresponding - * to the user account. - * @param {Object} [options] An object containing optional client arguments, such as configuring - * session persistence. - * @return {Promise} A promise fulfilled with an object containing authentication data. - */ - $authWithPassword(credentials: FirebaseCredentials, options?: Object): ng.IPromise; - - /** - * Authenticates the Firebase reference with the OAuth popup flow. - * - * @param {string} provider The unique string identifying the OAuth provider to authenticate - * with, e.g. google. - * @param {Object} [options] An object containing optional client arguments, such as configuring - * session persistence. - * @return {Promise} A promise fulfilled with an object containing authentication data. - */ - $authWithOAuthPopup(provider: string, options?: Object): ng.IPromise; - - /** - * Authenticates the Firebase reference with the OAuth redirect flow. - * - * @param {string} provider The unique string identifying the OAuth provider to authenticate - * with, e.g. google. - * @param {Object} [options] An object containing optional client arguments, such as configuring - * session persistence. - * @return {Promise} A promise fulfilled with an object containing authentication data. - */ - $authWithOAuthRedirect(provider: string, options?: Object): ng.IPromise; - - /** - * Authenticates the Firebase reference with an OAuth token. - * - * @param {string} provider The unique string identifying the OAuth provider to authenticate - * with, e.g. google. - * @param {string|Object} credentials Either a string, such as an OAuth 2.0 access token, or an - * Object of key / value pairs, such as a set of OAuth 1.0a credentials. - * @param {Object} [options] An object containing optional client arguments, such as configuring - * session persistence. - * @return {Promise} A promise fulfilled with an object containing authentication data. - */ - $authWithOAuthToken(provider: string, credentials: Object|string, options?: Object): ng.IPromise; - - /** - * Synchronously retrieves the current authentication data. - * - * @return {Object} The client's authentication data. - */ - $getAuth(): FirebaseAuthData; - - /** - * Asynchronously fires the provided callback with the current authentication data every time - * the authentication data changes. It also fires as soon as the authentication data is - * retrieved from the server. - * - * @param {function} callback A callback that fires when the client's authenticate state - * changes. If authenticated, the callback will be passed an object containing authentication - * data according to the provider used to authenticate. Otherwise, it will be passed null. - * @param {string} [context] If provided, this object will be used as this when calling your - * callback. - * @return {function} A function which can be used to deregister the provided callback. - */ - $onAuth(callback: Function, context?: any): Function; - - /** - * Unauthenticates the Firebase reference. - */ - $unauth(): void; - - /** - * Utility method which can be used in a route's resolve() method to grab the current - * authentication data. - * - * @returns {Promise} A promise fulfilled with the client's current authentication - * state, which will be null if the client is not authenticated. - */ - $waitForAuth(): ng.IPromise; - - /** - * Utility method which can be used in a route's resolve() method to require that a route has - * a logged in client. - * - * @returns {Promise} A promise fulfilled with the client's current authentication - * state or rejected if the client is not authenticated. - */ - $requireAuth(): ng.IPromise; - - /** - * Creates a new email/password user. Note that this function only creates the user, if you - * wish to log in as the newly created user, call $authWithPassword() after the promise for - * this method has been resolved. - * - * @param {Object} credentials An object containing the email and password of the user to create. - * @return {Promise} A promise fulfilled with the user object, which contains the - * uid of the created user. - */ - $createUser(credentials: FirebaseCredentials): ng.IPromise; - - /** - * Removes an email/password user. - * - * @param {Object} credentials An object containing the email and password of the user to remove. - * @return {Promise<>} An empty promise fulfilled once the user is removed. - */ - $removeUser(credentials: FirebaseCredentials): ng.IPromise; - - /** - * Changes the email for an email/password user. - * - * @param {Object} credentials An object containing the old email, new email, and password of - * the user whose email is to change. - * @return {Promise<>} An empty promise fulfilled once the email change is complete. - */ - $changeEmail(credentials: FirebaseChangeEmailCredentials): ng.IPromise; - - /** - * Changes the password for an email/password user. - * - * @param {Object} credentials An object containing the email, old password, and new password of - * the user whose password is to change. - * @return {Promise<>} An empty promise fulfilled once the password change is complete. - */ - $changePassword(credentials: FirebaseChangePasswordCredentials): ng.IPromise; - - /** - * Sends a password reset email to an email/password user. - * - * @param {Object} credentials An object containing the email of the user to send a reset - * password email to. - * @return {Promise<>} An empty promise fulfilled once the reset password email is sent. - */ - $resetPassword(credentials: FirebaseResetPasswordCredentials): ng.IPromise; -} diff --git a/angularfire/index.d.ts b/angularfire/index.d.ts new file mode 100644 index 0000000000..11f806a9ec --- /dev/null +++ b/angularfire/index.d.ts @@ -0,0 +1,479 @@ +// Type definitions for AngularFire 0.8.2 +// Project: http://angularfire.com +// Definitions by: Dénes Harmath +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +interface AngularFireService { + (firebase: Firebase, config?: any): AngularFire; +} + +/** + * @deprecated. Not possible with AngularFire 1.0+ + */ +interface AngularFire { + $asArray(): AngularFireArray; + $asObject(): AngularFireObject; + $ref(): Firebase; + $push(data: any): ng.IPromise; + $set(key: string, data: any): ng.IPromise; + $set(data: any): ng.IPromise; + $remove(key?: string): ng.IPromise; + $update(key: string, data: Object): ng.IPromise; + $update(data: any): ng.IPromise; + $transaction(updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise; + $transaction(key:string, updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise; +} + +/** + * Creates and maintains a synchronized object, with 2-way bindings between Angular and Firebase. + */ +interface AngularFireObject extends AngularFireSimpleObject { + $id: string; + $priority: number; + $value: any; + + /** + * Removes all keys from the FirebaseObject and also removes + * the remote data from the server. + * + * @returns a promise which will resolve after the op completes + */ + + $remove(): ng.IPromise; + /** + * Saves all data on the FirebaseObject back to Firebase. + * @returns a promise which will resolve after the save is completed. + */ + $save(): ng.IPromise; + + /** + * The loaded method is invoked after the initial batch of data arrives from the server. + * When this resolves, all data which existed prior to calling $asObject() is now cached + * locally in the object. + * + * As a shortcut is also possible to pass resolve/reject methods directly into this + * method just as they would be passed to .then() + * + * @param {Function} resolve + * @param {Function} reject + * @returns a promise which resolves after initial data is downloaded from Firebase + */ + $loaded(resolve?: (x: AngularFireObject) => ng.IHttpPromise<{}>, reject?: (err: any) => any): ng.IPromise; + + /** + * The loaded method is invoked after the initial batch of data arrives from the server. + * When this resolves, all data which existed prior to calling $asObject() is now cached + * locally in the object. + * + * As a shortcut is also possible to pass resolve/reject methods directly into this + * method just as they would be passed to .then() + * + * @param {Function} resolve + * @param {Function} reject + * @returns a promise which resolves after initial data is downloaded from Firebase + */ + $loaded(resolve?: (x: AngularFireObject) => ng.IPromise<{}>, reject?: (err: any) => any): ng.IPromise; + + /** + * The loaded method is invoked after the initial batch of data arrives from the server. + * When this resolves, all data which existed prior to calling $asObject() is now cached + * locally in the object. + * + * As a shortcut is also possible to pass resolve/reject methods directly into this + * method just as they would be passed to .then() + * + * @param {Function} resolve + * @param {Function} reject + * @returns a promise which resolves after initial data is downloaded from Firebase + */ + $loaded(resolve?: (x: AngularFireObject) => void, reject?: (err: any) => any): ng.IPromise; + + /** + * @returns {Firebase} the original Firebase instance used to create this object. + */ + $ref(): Firebase; + + /** + * Creates a 3-way data sync between this object, the Firebase server, and a + * scope variable. This means that any changes made to the scope variable are + * pushed to Firebase, and vice versa. + * + * If scope emits a $destroy event, the binding is automatically severed. Otherwise, + * it is possible to unbind the scope variable by using the `unbind` function + * passed into the resolve method. + * + * Can only be bound to one scope variable at a time. If a second is attempted, + * the promise will be rejected with an error. + * + * @param {object} scope + * @param {string} varName + * @returns a promise which resolves to an unbind method after data is set in scope + */ + $bindTo(scope: ng.IScope, varName: string): ng.IPromise; + + /** + * Listeners passed into this method are notified whenever a new change is received + * from the server. Each invocation is sent an object containing + * { type: 'value', key: 'my_firebase_id' } + * + * This method returns an unbind function that can be used to detach the listener. + * + * @param {Function} cb + * @param {Object} [context] + * @returns {Function} invoke to stop observing events + */ + $watch(callback: Function, context?: any): Function; + + /** + * Informs $firebase to stop sending events and clears memory being used + * by this object (delete's its local content). + */ + $destroy(): void; +} +interface AngularFireObjectService { + /** + * Creates a synchronized object with 2-way bindings between Angular and Firebase. + * + * @param {Firebase} ref + * @returns {FirebaseObject} + */ + (firebase: Firebase): AngularFireObject; + $extend(ChildClass: Object, methods?: Object): Object; +} + +/** + * Creates and maintains a synchronized list of data. This is a pseudo-read-only array. One should + * not call splice(), push(), pop(), et al directly on this array, but should instead use the + * $remove and $add methods. + * + * It is acceptable to .sort() this array, but it is important to use this in conjunction with + * $watch(), so that it will be re-sorted any time the server data changes. Examples of this are + * included in the $watch documentation. + */ +interface AngularFireArray extends Array { + /** + * Create a new record with a unique ID and add it to the end of the array. + * This should be used instead of Array.prototype.push, since those changes will not be + * synchronized with the server. + * + * Any value, including a primitive, can be added in this way. Note that when the record + * is created, the primitive value would be stored in $value (records are always objects + * by default). + * + * Returns a future which is resolved when the data has successfully saved to the server. + * The resolve callback will be passed a Firebase ref representing the new data element. + * + * @param data + * @returns a promise resolved after data is added + */ + $add(newData: any): ng.IPromise; + + /** + * Pass either an item in the array or the index of an item and it will be saved back + * to Firebase. While the array is read-only and its structure should not be changed, + * it is okay to modify properties on the objects it contains and then save those back + * individually. + * + * Returns a future which is resolved when the data has successfully saved to the server. + * The resolve callback will be passed a Firebase ref representing the saved element. + * If passed an invalid index or an object which is not a record in this array, + * the promise will be rejected. + * + * @param {int|object} indexOrItem + * @returns a promise resolved after data is saved + */ + $save(recordOrIndex: any): ng.IPromise; + + /** + * Pass either an existing item in this array or the index of that item and it will + * be removed both locally and in Firebase. This should be used in place of + * Array.prototype.splice for removing items out of the array, as calling splice + * will not update the value on the server. + * + * Returns a future which is resolved when the data has successfully removed from the + * server. The resolve callback will be passed a Firebase ref representing the deleted + * element. If passed an invalid index or an object which is not a record in this array, + * the promise will be rejected. + * + * @param {int|object} indexOrItem + * @returns a promise which resolves after data is removed + */ + $remove(recordOrIndex: any): ng.IPromise; + + /** + * Returns the record for a given Firebase key (record.$id). If the record is not found + * then returns null. + * + * @param {string} key + * @returns {Object|null} a record in this array + */ + $getRecord(key: string): AngularFireSimpleObject; + + /** + * Given an item in this array or the index of an item in the array, this returns the + * Firebase key (record.$id) for that record. If passed an invalid key or an item which + * does not exist in this array, it will return null. + * + * @param {int|object} indexOrItem + * @returns {null|string} + */ + $keyAt(recordOrIndex: any): string; + + /** + * The inverse of $keyAt, this method takes a Firebase key (record.$id) and returns the + * index in the array where that record is stored. If the record is not in the array, + * this method returns -1. + * + * @param {String} key + * @returns {int} -1 if not found + */ + $indexFor(key: string): number; + + /** + * The loaded method is invoked after the initial batch of data arrives from the server. + * When this resolves, all data which existed prior to calling $asArray() is now cached + * locally in the array. + * + * As a shortcut is also possible to pass resolve/reject methods directly into this + * method just as they would be passed to .then() + * + * @param {Function} [resolve] + * @param {Function} [reject] + * @returns a promise + */ + $loaded(resolve?: (x: AngularFireArray) => ng.IHttpPromise<{}>, reject?: (err: any) => any): ng.IPromise; + + /** + * The loaded method is invoked after the initial batch of data arrives from the server. + * When this resolves, all data which existed prior to calling $asArray() is now cached + * locally in the array. + * + * As a shortcut is also possible to pass resolve/reject methods directly into this + * method just as they would be passed to .then() + * + * @param {Function} [resolve] + * @param {Function} [reject] + * @returns a promise + */ + $loaded(resolve?: (x: AngularFireArray) => ng.IPromise<{}>, reject?: (err: any) => any): ng.IPromise; + + /** + * The loaded method is invoked after the initial batch of data arrives from the server. + * When this resolves, all data which existed prior to calling $asArray() is now cached + * locally in the array. + * + * As a shortcut is also possible to pass resolve/reject methods directly into this + * method just as they would be passed to .then() + * + * @param {Function} [resolve] + * @param {Function} [reject] + * @returns a promise + */ + $loaded(resolve?: (x: AngularFireArray) => void, reject?: (err: any) => any): ng.IPromise; + + /** + * @returns {Firebase} the original Firebase ref used to create this object. + */ + $ref(): Firebase; + + /** + * Listeners passed into this method are notified whenever a new change (add, updated, + * move, remove) is received from the server. Each invocation is sent an object + * containing { type: 'child_added|child_updated|child_moved|child_removed', + * key: 'key_of_item_affected'} + * + * Additionally, added and moved events receive a prevChild parameter, containing the + * key of the item before this one in the array. + * + * This method returns a function which can be invoked to stop observing events. + * + * @param {Function} cb + * @param {Object} [context] + * @returns {Function} used to stop observing + */ + $watch(cb: (event: string, key: string, prevChild: string) => void, context?: any): Function; + + /** + * Informs $firebase to stop sending events and clears memory being used + * by this array (delete's its local content). + */ + $destroy(): void; +} +interface AngularFireArrayService { + (firebase: Firebase): AngularFireArray; + $extend(ChildClass: Object, methods?: Object): Object; +} + +interface AngularFireSimpleObject { + $id: string; + $priority: number; + $value: any; + [key: string]: any; +} + + +interface AngularFireAuthService { + (firebase: Firebase): AngularFireAuth; +} + +interface AngularFireAuth { + /** + * Authenticates the Firebase reference with a custom authentication token. + * + * @param {string} authToken An authentication token or a Firebase Secret. A Firebase Secret + * should only be used for authenticating a server process and provides full read / write + * access to the entire Firebase. + * @param {Object} [options] An object containing optional client arguments, such as configuring + * session persistence. + * @return {Promise} A promise fulfilled with an object containing authentication data. + */ + $authWithCustomToken(authToken: string, options?: Object): ng.IPromise; + + /** + * Authenticates the Firebase reference anonymously. + * + * @param {Object} [options] An object containing optional client arguments, such as configuring + * session persistence. + * @return {Promise} A promise fulfilled with an object containing authentication data. + */ + $authAnonymously(options?: Object): ng.IPromise; + + /** + * Authenticates the Firebase reference with an email/password user. + * + * @param {Object} credentials An object containing email and password attributes corresponding + * to the user account. + * @param {Object} [options] An object containing optional client arguments, such as configuring + * session persistence. + * @return {Promise} A promise fulfilled with an object containing authentication data. + */ + $authWithPassword(credentials: FirebaseCredentials, options?: Object): ng.IPromise; + + /** + * Authenticates the Firebase reference with the OAuth popup flow. + * + * @param {string} provider The unique string identifying the OAuth provider to authenticate + * with, e.g. google. + * @param {Object} [options] An object containing optional client arguments, such as configuring + * session persistence. + * @return {Promise} A promise fulfilled with an object containing authentication data. + */ + $authWithOAuthPopup(provider: string, options?: Object): ng.IPromise; + + /** + * Authenticates the Firebase reference with the OAuth redirect flow. + * + * @param {string} provider The unique string identifying the OAuth provider to authenticate + * with, e.g. google. + * @param {Object} [options] An object containing optional client arguments, such as configuring + * session persistence. + * @return {Promise} A promise fulfilled with an object containing authentication data. + */ + $authWithOAuthRedirect(provider: string, options?: Object): ng.IPromise; + + /** + * Authenticates the Firebase reference with an OAuth token. + * + * @param {string} provider The unique string identifying the OAuth provider to authenticate + * with, e.g. google. + * @param {string|Object} credentials Either a string, such as an OAuth 2.0 access token, or an + * Object of key / value pairs, such as a set of OAuth 1.0a credentials. + * @param {Object} [options] An object containing optional client arguments, such as configuring + * session persistence. + * @return {Promise} A promise fulfilled with an object containing authentication data. + */ + $authWithOAuthToken(provider: string, credentials: Object|string, options?: Object): ng.IPromise; + + /** + * Synchronously retrieves the current authentication data. + * + * @return {Object} The client's authentication data. + */ + $getAuth(): FirebaseAuthData; + + /** + * Asynchronously fires the provided callback with the current authentication data every time + * the authentication data changes. It also fires as soon as the authentication data is + * retrieved from the server. + * + * @param {function} callback A callback that fires when the client's authenticate state + * changes. If authenticated, the callback will be passed an object containing authentication + * data according to the provider used to authenticate. Otherwise, it will be passed null. + * @param {string} [context] If provided, this object will be used as this when calling your + * callback. + * @return {function} A function which can be used to deregister the provided callback. + */ + $onAuth(callback: Function, context?: any): Function; + + /** + * Unauthenticates the Firebase reference. + */ + $unauth(): void; + + /** + * Utility method which can be used in a route's resolve() method to grab the current + * authentication data. + * + * @returns {Promise} A promise fulfilled with the client's current authentication + * state, which will be null if the client is not authenticated. + */ + $waitForAuth(): ng.IPromise; + + /** + * Utility method which can be used in a route's resolve() method to require that a route has + * a logged in client. + * + * @returns {Promise} A promise fulfilled with the client's current authentication + * state or rejected if the client is not authenticated. + */ + $requireAuth(): ng.IPromise; + + /** + * Creates a new email/password user. Note that this function only creates the user, if you + * wish to log in as the newly created user, call $authWithPassword() after the promise for + * this method has been resolved. + * + * @param {Object} credentials An object containing the email and password of the user to create. + * @return {Promise} A promise fulfilled with the user object, which contains the + * uid of the created user. + */ + $createUser(credentials: FirebaseCredentials): ng.IPromise; + + /** + * Removes an email/password user. + * + * @param {Object} credentials An object containing the email and password of the user to remove. + * @return {Promise<>} An empty promise fulfilled once the user is removed. + */ + $removeUser(credentials: FirebaseCredentials): ng.IPromise; + + /** + * Changes the email for an email/password user. + * + * @param {Object} credentials An object containing the old email, new email, and password of + * the user whose email is to change. + * @return {Promise<>} An empty promise fulfilled once the email change is complete. + */ + $changeEmail(credentials: FirebaseChangeEmailCredentials): ng.IPromise; + + /** + * Changes the password for an email/password user. + * + * @param {Object} credentials An object containing the email, old password, and new password of + * the user whose password is to change. + * @return {Promise<>} An empty promise fulfilled once the password change is complete. + */ + $changePassword(credentials: FirebaseChangePasswordCredentials): ng.IPromise; + + /** + * Sends a password reset email to an email/password user. + * + * @param {Object} credentials An object containing the email of the user to send a reset + * password email to. + * @return {Promise<>} An empty promise fulfilled once the reset password email is sent. + */ + $resetPassword(credentials: FirebaseResetPasswordCredentials): ng.IPromise; +} diff --git a/angularfire/tsconfig.json b/angularfire/tsconfig.json new file mode 100644 index 0000000000..21e145d582 --- /dev/null +++ b/angularfire/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angularfire-tests.ts" + ] +} \ No newline at end of file diff --git a/angularjs-toaster/angularjs-toaster.d.ts b/angularjs-toaster/angularjs-toaster.d.ts deleted file mode 100644 index ee184620ae..0000000000 --- a/angularjs-toaster/angularjs-toaster.d.ts +++ /dev/null @@ -1,109 +0,0 @@ -// Type definitions for angularjs-toaster v0.4.13 -// Project: https://github.com/jirikavi/AngularJS-Toaster -// Definitions by: Ben Tesser -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace ngtoaster { - interface IToasterService { - pop(params:IPopParams): void - /** - * @param {string} type Type of toaster -- 'error', 'info', 'wait', 'success', and 'warning' - */ - pop(type?:string, title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number, showCloseButton?:boolean): void - error(params: IPopParams): void - error(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - info(params: IPopParams): void - info(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - wait(params: IPopParams): void - wait(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - success(params: IPopParams): void - success(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - warning(params: IPopParams): void - warning(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, - toasterId?:number): void - clear(): void - toast:IToast; - } - - interface IToasterEventRegistry { - setup(): void - subscribeToNewToastEvent(onNewToast:IToastEventListener): void - subscribeToClearToastsEvent(onClearToasts:IToastEventListener): void - unsubscribeToNewToastEvent(onNewToast:IToastEventListener): void - unsubscribeToClearToastsEvent(onClearToasts:IToastEventListener): void - } - - interface IPopParams extends IToast{ - toasterId?: number; - } - - interface IToastEventListener { - (event:Event, toasterId: number): void; - } - - interface IToast { - /** - * Acceptable types are: - * 'error', 'info', 'wait', 'success', and 'warning' - */ - type?: string; - title?: string; - body?: string; - timeout?: number; - bodyOutputType?: string; - clickHandler?: EventListener; - showCloseButton?: boolean; - } - - interface IToasterConfig { - /** - * limits max number of toasts - */ - limit?: number; - 'tap-to-dismiss'?: boolean; - 'close-button'?: boolean; - 'newest-on-top'?: boolean; - 'time-out'?: number; - 'icon-classes'?: IIconClasses; - /** - * Options include: - * '', 'trustedHtml', 'template', 'templateWithData' - */ - 'body-output-type'?: string; - 'body-template'?: string; - 'icon-class'?: string; - /** - * Options include: - * 'toast-top-full-width', 'toast-bottom-full-width', 'toast-center', - * 'toast-top-left', 'toast-top-center', 'toast-top-rigt', - * 'toast-bottom-left', 'toast-bottom-center', 'toast-bottom-rigt', - */ - 'position-class'?: string; - 'title-class'?: string; - 'message-class'?: string; - 'prevent-duplicates'?: boolean; - /** - * stop timeout on mouseover and restart timer on mouseout - */ - 'mouseover-timer-stop'?: boolean; - } - - interface IIconClasses { - error: string; - info: string; - wait: string; - success: string; - warning: string; - } -} - -declare module "ngtoaster" { - export = ngtoaster -} diff --git a/angularjs/README.md b/angularjs/README.md index 94dc303ae4..1b3affc92c 100644 --- a/angularjs/README.md +++ b/angularjs/README.md @@ -2,14 +2,14 @@ ## Referencing AngularJS definition files in your code -To do that, simply add `/// ` at the top of your code. +To do that, simply add `` at the top of your code. That will make available to your code all interfaces AngularJS' main module **ng** implements, as well as the **AUTO** module. If you are including other AngularJS' modules in your code, like **ngResource**, just like you needed to include the additional module implementation file in your code, _angular-resource.js_, you will also need to reference the definitions file related to that module. Your code would then have the following definitions files reference: - /// - /// + + Having these modules in separated files is actually good because they sometimes either augment or modify some of **ng**'s interfaces, and thus those differences should only be available to you when you really need them. Also, it forces you to explicit what you're going to be using. @@ -107,8 +107,8 @@ function Controller($scope: ICustomScope) { ### Working with $resource ```ts -/// -/// + + // We have the option to define arguments for a custom resource interface IArticleParameters { @@ -177,8 +177,8 @@ function MainController($resource: ng.resource.IResourceService) { ### Working with $resource in angular-1.0 definitions ```ts -/// -/// + + // Let's define a custom resource interface IArticleResourceClass extends ng.resource.IResourceClass { diff --git a/angularjs/angular-amd-tests.ts b/angularjs/angular-amd-tests.ts deleted file mode 100644 index 2ce75cc22d..0000000000 --- a/angularjs/angular-amd-tests.ts +++ /dev/null @@ -1,7 +0,0 @@ -/// - -import localName = require('angular'); -var mod: localName.IModule = localName.module('mod', []); - -// Remain compatible with the ambient version -var mod2: angular.IModule = mod; diff --git a/angularjs/angular-animate.d.ts b/angularjs/angular-animate.d.ts index 2f3cbc0f18..57eb619405 100644 --- a/angularjs/angular-animate.d.ts +++ b/angularjs/angular-animate.d.ts @@ -3,7 +3,6 @@ // Definitions by: Michel Salib , Adi Dahiya , Raphael Schweizer , Cody Schaaf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// declare module "angular-animate" { var _: string; diff --git a/angularjs/angular-component-router.d.ts b/angularjs/angular-component-router.d.ts index 2c56ef3a21..d1c2a7e373 100644 --- a/angularjs/angular-component-router.d.ts +++ b/angularjs/angular-component-router.d.ts @@ -3,7 +3,6 @@ // Definitions by: David Reher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// declare namespace angular { /** diff --git a/angularjs/angular-cookies.d.ts b/angularjs/angular-cookies.d.ts index e96ae7a671..1577ea6fef 100644 --- a/angularjs/angular-cookies.d.ts +++ b/angularjs/angular-cookies.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// declare module "angular-cookies" { var _: string; diff --git a/angularjs/angular-mocks-tests.ts b/angularjs/angular-mocks-tests.ts index 86bbe6c945..fd925016c2 100644 --- a/angularjs/angular-mocks-tests.ts +++ b/angularjs/angular-mocks-tests.ts @@ -1,4 +1,4 @@ -/// + /////////////////////////////////////// // IAngularStatic @@ -36,6 +36,7 @@ mock.module( function () { return 2; } ); mock.module({ module1: function () { return 1; } }); +mock.module.sharedInjector(); date = mock.TzDate(-7, '2013-1-1T15:00:00Z'); date = mock.TzDate(-8, 12345678); @@ -87,6 +88,15 @@ logCall = logService.warn; logs = logCall.logs; +/////////////////////////////////////// +// ControllerService mock +/////////////////////////////////////// +var $controller: ng.IControllerService; +$controller(class TestController {}, {}, {myBinding: 'works!'}); +$controller(function TestController() {}, {someLocal: 42}, {myBinding: 'works!'}); +$controller('TestController', {}, {myBinding: 'works!'}); + + /////////////////////////////////////// // IComponentControllerService /////////////////////////////////////// diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index 429c7b5269..3d8a6e8926 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -3,7 +3,6 @@ // Definitions by: Diego Vilar , Tony Curtis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// declare module "angular-mocks/ngMock" { var _: string; @@ -47,7 +46,10 @@ declare namespace angular { inject: IInjectStatic // see https://docs.angularjs.org/api/ngMock/function/angular.mock.module - module(...modules: any[]): any; + module: { + (...modules: any[]): any; + sharedInjector(): void; + } // see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate TzDate(offset: number, timestamp: number): Date; @@ -97,6 +99,18 @@ declare namespace angular { logs: string[]; } + /////////////////////////////////////////////////////////////////////////// + // ControllerService mock + // see https://docs.angularjs.org/api/ngMock/service/$controller + // This interface extends http://docs.angularjs.org/api/ng.$controller + /////////////////////////////////////////////////////////////////////////// + interface IControllerService { + // Although the documentation doesn't state this, locals are optional + (controllerConstructor: new (...args: any[]) => T, locals?: any, bindings?: any): T; + (controllerConstructor: Function, locals?: any, bindings?: any): T; + (controllerName: string, locals?: any, bindings?: any): T; + } + /////////////////////////////////////////////////////////////////////////// // ComponentControllerService // see https://docs.angularjs.org/api/ngMock/service/$componentController diff --git a/angularjs/angular-resource-tests.ts b/angularjs/angular-resource-tests.ts index 5a9963b14c..3aa202d0e8 100644 --- a/angularjs/angular-resource-tests.ts +++ b/angularjs/angular-resource-tests.ts @@ -1,4 +1,4 @@ -/// + import IHttpPromiseCallbackArg = angular.IHttpPromiseCallbackArg; @@ -98,9 +98,7 @@ resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { var promise : angular.IPromise; var arrayPromise : angular.IPromise; -var json: { - [index: string]: any; -}; +var json: IMyResource; promise = resource.$delete(); promise = resource.$delete({ key: 'value' }); diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index caae65ccb2..bf9c8030cd 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -3,7 +3,6 @@ // Definitions by: Diego Vilar , Michael Jess // Definitions: https://github.com/daptiv/DefinitelyTyped -/// declare module 'angular-resource' { var _: string; @@ -153,9 +152,7 @@ declare namespace angular.resource { /** the promise of the original server interaction that created this instance. **/ $promise : angular.IPromise; $resolved : boolean; - toJSON: () => { - [index: string]: any; - } + toJSON(): T; } /** diff --git a/angularjs/angular-route-tests.ts b/angularjs/angular-route-tests.ts index ab5fba0b62..0fefab51f7 100644 --- a/angularjs/angular-route-tests.ts +++ b/angularjs/angular-route-tests.ts @@ -1,5 +1,5 @@ -/// -/// + + /** * @license HTTP Auth Interceptor Module for AngularJS diff --git a/angularjs/angular-route.d.ts b/angularjs/angular-route.d.ts index 19dbf04896..569abc9df5 100644 --- a/angularjs/angular-route.d.ts +++ b/angularjs/angular-route.d.ts @@ -3,7 +3,6 @@ // Definitions by: Jonathan Park // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// declare module "angular-route" { var _: string; diff --git a/angularjs/angular-sanitize-tests.ts b/angularjs/angular-sanitize-tests.ts index d065392c79..94bb6615ec 100644 --- a/angularjs/angular-sanitize-tests.ts +++ b/angularjs/angular-sanitize-tests.ts @@ -1,4 +1,4 @@ -/// + var shouldBeString: string; diff --git a/angularjs/angular-sanitize.d.ts b/angularjs/angular-sanitize.d.ts index d87515adca..d677af7b2f 100644 --- a/angularjs/angular-sanitize.d.ts +++ b/angularjs/angular-sanitize.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// declare module "angular-sanitize" { var _: string; diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 0539ae62ac..1f7bd6d492 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -1,4 +1,3 @@ -/// // issue: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/369 // https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts deleted file mode 100644 index e86fd37052..0000000000 --- a/angularjs/angular.d.ts +++ /dev/null @@ -1,1932 +0,0 @@ -// Type definitions for Angular JS 1.5 -// Project: http://angularjs.org -// Definitions by: Diego Vilar -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -/// - -declare var angular: angular.IAngularStatic; - -// Support for painless dependency injection -interface Function { - $inject?: string[]; -} - -// Collapse angular into ng -import ng = angular; -// Support AMD require -declare module 'angular' { - export = angular; -} - -/////////////////////////////////////////////////////////////////////////////// -// ng module (angular.js) -/////////////////////////////////////////////////////////////////////////////// -declare namespace angular { - - // 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; - } - - interface IAngularBootstrapConfig { - strictDi?: boolean; - debugInfoEnabled?: boolean; - } - - /////////////////////////////////////////////////////////////////////////// - // AngularStatic - // see http://docs.angularjs.org/api - /////////////////////////////////////////////////////////////////////////// - interface IAngularStatic { - bind(context: any, fn: Function, ...args: any[]): Function; - - /** - * Use this function to manually start up angular application. - * - * @param element DOM element which is the root of angular application. - * @param modules An array of modules to load into the application. - * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a config block. - * @param config an object for defining configuration options for the application. The following keys are supported: - * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. - */ - bootstrap(element: string|Element|JQuery|Document, modules?: (string|Function|any[])[], config?: IAngularBootstrapConfig): auto.IInjectorService; - - /** - * 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; - - /** - * Wraps a raw DOM element or HTML string as a jQuery element. - * - * If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." - */ - 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?: T): T; - injector(modules?: any[], strictDi?: boolean): 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; - - /** - * Deeply extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.merge({}, object1, object2). - * - * Unlike extend(), merge() recursively descends into object properties of source objects, performing a deep copy. - * - * @param dst Destination object. - * @param src Source object(s). - */ - merge(dst: any, ...src: any[]): any; - - /** - * 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; - reloadWithDebugInfo(): void; - toJson(obj: any, pretty?: boolean): string; - uppercase(str: string): string; - version: { - full: string; - major: number; - minor: number; - dot: number; - codeName: string; - }; - - /** - * If window.name contains prefix NG_DEFER_BOOTSTRAP! when angular.bootstrap is called, the bootstrap process will be paused until angular.resumeBootstrap() is called. - * @param extraModules An optional array of modules that should be added to the original list of modules that the app was about to be bootstrapped with. - */ - resumeBootstrap?(extraModules?: string[]): ng.auto.IInjectorService; - } - - /////////////////////////////////////////////////////////////////////////// - // Module - // see http://docs.angularjs.org/api/angular.Module - /////////////////////////////////////////////////////////////////////////// - interface IModule { - /** - * Use this method to register a component. - * - * @param name The name of the component. - * @param options A definition object passed into the component. - */ - component(name: string, options: IComponentOptions): 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; - config(object: Object): 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; - /** - * Register a new directive with the compiler. - * - * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) - * @param directiveFactory An injectable directive factory function. - */ - directive(name: string, directiveFactory: IDirectiveFactory): IModule; - /** - * Register a new directive with the compiler. - * - * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) - * @param directiveFactory An injectable directive factory function. - */ - 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; - /** - * Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is a factory function that returns an instance instantiated by the injector from the service constructor function. - * - * @param name The name of the instance. - * @param serviceConstructor An injectable class (constructor function) that will be instantiated. - */ - service(name: string, serviceConstructor: Function): IModule; - /** - * Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is a factory function that returns an instance instantiated by the injector from the service constructor function. - * - * @param name The name of the instance. - * @param inlineAnnotatedConstructor An injectable class (constructor function) that will be instantiated. - */ - 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; - - /** - * 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, decoratorConstructor: Function): IModule; - decorator(name:string, inlineAnnotatedConstructor: any[]): 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; - - /** - * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with x- or data-) to its normalized, camelCase form. - * - * Also there is special case for Moz prefix starting with upper case letter. - * - * For further information check out the guide on @see https://docs.angularjs.org/guide/directive#matching-directives - */ - $normalize(name: string): string; - - /** - * 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; - - /** - * Adds and removes the appropriate CSS class values to the element based on the difference between - * the new and old CSS class values (specified as newClasses and oldClasses). - */ - $updateClass(newClasses: string, oldClasses: 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?: T) => 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; - $submitted: boolean; - $error: any; - $pending: any; - $addControl(control: INgModelController): void; - $removeControl(control: INgModelController): void; - $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController): void; - $setDirty(): void; - $setPristine(): void; - $commitViewValue(): void; - $rollbackViewValue(): void; - $setSubmitted(): void; - $setUntouched(): 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, trigger?: string): void; - $setPristine(): void; - $setDirty(): void; - $validate(): void; - $setTouched(): void; - $setUntouched(): void; - $rollbackViewValue(): void; - $commitViewValue(): 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; - $asyncValidators: IAsyncModelValidators; - - $pending: any; - $pristine: boolean; - $dirty: boolean; - $valid: boolean; - $invalid: boolean; - } - - //Allows tuning how model updates are done. - //https://docs.angularjs.org/api/ng/directive/ngModelOptions - interface INgModelOptions { - updateOn?: string; - debounce?: any; - allowInvalid?: boolean; - getterSetter?: boolean; - timezone?: string; - } - - interface IModelValidators { - /** - * viewValue is any because it can be an object that is called in the view like $viewValue.name:$viewValue.subName - */ - [index: string]: (modelValue: any, viewValue: any) => boolean; - } - - interface IAsyncModelValidators { - [index: string]: (modelValue: any, viewValue: any) => IPromise; - } - - interface IModelParser { - (value: any): any; - } - - interface IModelFormatter { - (value: any): any; - } - - interface IModelViewChangeListener { - (): void; - } - - /** - * $rootScope - $rootScopeProvider - service in module ng - * see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and https://docs.angularjs.org/api/ng/service/$rootScope - */ - interface IRootScopeService { - [index: string]: any; - - $apply(): any; - $apply(exp: string): any; - $apply(exp: (scope: IScope) => any): any; - - $applyAsync(): any; - $applyAsync(exp: string): any; - $applyAsync(exp: (scope: IScope) => any): any; - - /** - * Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners. - * - * The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled. - * - * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. - * - * @param name Event name to broadcast. - * @param args Optional one or more arguments which will be passed onto the event listeners. - */ - $broadcast(name: string, ...args: any[]): IAngularEvent; - $destroy(): void; - $digest(): void; - /** - * Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners. - * - * The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it. - * - * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. - * - * @param name Event name to emit. - * @param args Optional one or more arguments which will be passed onto the event listeners. - */ - $emit(name: string, ...args: any[]): IAngularEvent; - - $eval(): any; - $eval(expression: string, locals?: Object): any; - $eval(expression: (scope: IScope) => any, locals?: Object): any; - - $evalAsync(): void; - $evalAsync(expression: string): void; - $evalAsync(expression: (scope: IScope) => any): void; - - // Defaults to false by the implementation checking strategy - $new(isolate?: boolean, parent?: IScope): IScope; - - /** - * Listens on events of a given type. See $emit for discussion of event life cycle. - * - * The event listener function format is: function(event, args...). - * - * @param name Event name to listen on. - * @param listener Function to call when the event is emitted. - */ - $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): () => void; - - $watch(watchExpression: string, listener?: string, objectEquality?: boolean): () => void; - $watch(watchExpression: string, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): () => void; - $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): () => void; - $watch(watchExpression: (scope: IScope) => T, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): () => void; - - $watchCollection(watchExpression: string, listener: (newValue: T, oldValue: T, scope: IScope) => any): () => void; - $watchCollection(watchExpression: (scope: IScope) => T, listener: (newValue: T, oldValue: T, scope: IScope) => any): () => void; - - $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void; - $watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void; - - $parent: IScope; - $root: IRootScopeService; - $id: number; - - // Hidden members - $$isolateBindings: any; - $$phase: any; - } - - interface IScope extends IRootScopeService { } - - /** - * $scope for ngRepeat directive. - * see https://docs.angularjs.org/api/ng/directive/ngRepeat - */ - interface IRepeatScope extends IScope { - - /** - * iterator offset of the repeated element (0..length-1). - */ - $index: number; - - /** - * true if the repeated element is first in the iterator. - */ - $first: boolean; - - /** - * true if the repeated element is between the first and last in the iterator. - */ - $middle: boolean; - - /** - * true if the repeated element is last in the iterator. - */ - $last: boolean; - - /** - * true if the iterator position $index is even (otherwise false). - */ - $even: boolean; - - /** - * true if the iterator position $index is odd (otherwise false). - */ - $odd: boolean; - - } - - interface IAngularEvent { - /** - * the scope on which the event was $emit-ed or $broadcast-ed. - */ - targetScope: IScope; - /** - * the scope that is currently handling the event. Once the event propagates through the scope hierarchy, this property is set to null. - */ - currentScope: IScope; - /** - * name of the event. - */ - name: string; - /** - * calling stopPropagation function will cancel further event propagation (available only for events that were $emit-ed). - */ - stopPropagation?: Function; - /** - * calling preventDefault sets defaultPrevented flag to true. - */ - preventDefault: Function; - /** - * true if preventDefault was called. - */ - defaultPrevented: boolean; - } - - /////////////////////////////////////////////////////////////////////////// - // WindowService - // see http://docs.angularjs.org/api/ng.$window - /////////////////////////////////////////////////////////////////////////// - interface IWindowService extends Window { - [key: string]: any; - } - - /////////////////////////////////////////////////////////////////////////// - // TimeoutService - // see http://docs.angularjs.org/api/ng.$timeout - /////////////////////////////////////////////////////////////////////////// - interface ITimeoutService { - (delay?: number, invokeApply?: boolean): IPromise; - (fn: (...args: any[]) => T, delay?: number, invokeApply?: boolean, ...args: any[]): IPromise; - cancel(promise?: IPromise): boolean; - } - - /////////////////////////////////////////////////////////////////////////// - // IntervalService - // see http://docs.angularjs.org/api/ng.$interval - /////////////////////////////////////////////////////////////////////////// - interface IIntervalService { - (func: Function, delay: number, count?: number, invokeApply?: boolean, ...args: any[]): IPromise; - cancel(promise: IPromise): boolean; - } - - /** - * $filter - $filterProvider - service in module ng - * - * Filters are used for formatting data displayed to the user. - * - * see https://docs.angularjs.org/api/ng/service/$filter - */ - interface IFilterService { - (name: 'filter'): IFilterFilter; - (name: 'currency'): IFilterCurrency; - (name: 'number'): IFilterNumber; - (name: 'date'): IFilterDate; - (name: 'json'): IFilterJson; - (name: 'lowercase'): IFilterLowercase; - (name: 'uppercase'): IFilterUppercase; - (name: 'limitTo'): IFilterLimitTo; - (name: 'orderBy'): IFilterOrderBy; - /** - * Usage: - * $filter(name); - * - * @param name Name of the filter function to retrieve - */ - (name: string): T; - } - - interface IFilterFilter { - (array: T[], expression: string | IFilterFilterPatternObject | IFilterFilterPredicateFunc, comparator?: IFilterFilterComparatorFunc|boolean): T[]; - } - - interface IFilterFilterPatternObject { - [name: string]: any; - } - - interface IFilterFilterPredicateFunc { - (value: T, index: number, array: T[]): boolean; - } - - interface IFilterFilterComparatorFunc { - (actual: T, expected: T): boolean; - } - - interface IFilterCurrency { - /** - * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used. - * @param amount Input to filter. - * @param symbol Currency symbol or identifier to be displayed. - * @param fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale - * @return Formatted number - */ - (amount: number, symbol?: string, fractionSize?: number): string; - } - - interface IFilterNumber { - /** - * Formats a number as text. - * @param number Number to format. - * @param fractionSize Number of decimal places to round the number to. If this is not provided then the fraction size is computed from the current locale's number formatting pattern. In the case of the default locale, it will be 3. - * @return Number rounded to decimalPlaces and places a “,” after each third digit. - */ - (value: number|string, fractionSize?: number|string): string; - } - - interface IFilterDate { - /** - * Formats date to a string based on the requested format. - * - * @param date Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone. - * @param format Formatting rules (see Description). If not specified, mediumDate is used. - * @param timezone Timezone to be used for formatting. It understands UTC/GMT and the continental US time zone abbreviations, but for general use, use a time zone offset, for example, '+0430' (4 hours, 30 minutes east of the Greenwich meridian) If not specified, the timezone of the browser will be used. - * @return Formatted string or the input if input is not recognized as date/millis. - */ - (date: Date | number | string, format?: string, timezone?: string): string; - } - - interface IFilterJson { - /** - * Allows you to convert a JavaScript object into JSON string. - * @param object Any JavaScript object (including arrays and primitive types) to filter. - * @param spacing The number of spaces to use per indentation, defaults to 2. - * @return JSON string. - */ - (object: any, spacing?: number): string; - } - - interface IFilterLowercase { - /** - * Converts string to lowercase. - */ - (value: string): string; - } - - interface IFilterUppercase { - /** - * Converts string to uppercase. - */ - (value: string): string; - } - - interface IFilterLimitTo { - /** - * Creates a new array containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit. - * @param input Source array to be limited. - * @param limit The length of the returned array. If the limit number is positive, limit number of items from the beginning of the source array/string are copied. If the number is negative, limit number of items from the end of the source array are copied. The limit will be trimmed if it exceeds array.length. If limit is undefined, the input will be returned unchanged. - * @param begin Index at which to begin limitation. As a negative index, begin indicates an offset from the end of input. Defaults to 0. - * @return A new sub-array of length limit or less if input array had less than limit elements. - */ - (input: T[], limit: string|number, begin?: string|number): T[]; - /** - * Creates a new string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source string or number, as specified by the value and sign (positive or negative) of limit. If a number is used as input, it is converted to a string. - * @param input Source string or number to be limited. - * @param limit The length of the returned string. If the limit number is positive, limit number of items from the beginning of the source string are copied. If the number is negative, limit number of items from the end of the source string are copied. The limit will be trimmed if it exceeds input.length. If limit is undefined, the input will be returned unchanged. - * @param begin Index at which to begin limitation. As a negative index, begin indicates an offset from the end of input. Defaults to 0. - * @return A new substring of length limit or less if input had less than limit elements. - */ - (input: string|number, limit: string|number, begin?: string|number): string; - } - - interface IFilterOrderBy { - /** - * Orders a specified array by the expression predicate. It is ordered alphabetically for strings and numerically for numbers. Note: if you notice numbers are not being sorted as expected, make sure they are actually being saved as numbers and not strings. - * @param array The array to sort. - * @param expression A predicate to be used by the comparator to determine the order of elements. - * @param reverse Reverse the order of the array. - * @return Reverse the order of the array. - */ - (array: T[], expression: string|((value: T) => any)|(((value: T) => any)|string)[], reverse?: boolean): T[]; - } - - /** - * $filterProvider - $filter - provider in module ng - * - * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function. - * - * see https://docs.angularjs.org/api/ng/provider/$filterProvider - */ - interface IFilterProvider extends IServiceProvider { - /** - * register(name); - * - * @param name Name of the filter function, or an object map of filters where the keys are the filter names and the values are the filter factories. Note: Filter names must be valid angular Expressions identifiers, such as uppercase or orderBy. Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace your filters, then you can use capitalization (myappSubsectionFilterx) or underscores (myapp_subsection_filterx). - */ - register(name: string | {}): 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 extends IServiceProvider { - debugEnabled(): boolean; - debugEnabled(enabled: boolean): ILogProvider; - } - - // We define this as separate 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; - - literal: boolean; - constant: boolean; - - // 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; - } - - /** - * $location - $locationProvider - service in module ng - * see https://docs.angularjs.org/api/ng/service/$location - */ - interface ILocationService { - absUrl(): string; - hash(): string; - hash(newHash: string): ILocationService; - host(): string; - - /** - * Return path of current url - */ - path(): string; - - /** - * Change path when called with parameter and return $location. - * Note: Path should always begin with forward slash (/), this method will add the forward slash if it is missing. - * - * @param path New path - */ - path(path: string): ILocationService; - - port(): number; - protocol(): string; - replace(): ILocationService; - - /** - * Return search part (as object) of current url - */ - search(): any; - - /** - * Change search part when called with parameter and return $location. - * - * @param search When called with a single argument the method acts as a setter, setting the search component of $location to the specified value. - * - * If the argument is a hash object containing an array of values, these values will be encoded as duplicate search parameters in the url. - */ - search(search: any): ILocationService; - - /** - * Change search part when called with parameter and return $location. - * - * @param search New search params - * @param paramValue If search is a string or a Number, then paramValue will override only a single search property. If paramValue is null, the property specified via the first argument will be deleted. If paramValue is an array, it will override the property of the search component of $location specified via the first argument. If paramValue is true, the property specified via the first argument will be added with no value nor trailing equal sign. - */ - search(search: string, paramValue: string|number|string[]|boolean): ILocationService; - - state(): any; - state(state: 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; - html5Mode(mode: { enabled?: boolean; requireBase?: boolean; rewriteLinks?: 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 {} - - interface IQResolveReject { - (): void; - (value: T): void; - } - /** - * $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 { - new (resolver: (resolve: IQResolveReject) => any): IPromise; - new (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; - (resolver: (resolve: IQResolveReject) => any): IPromise; - (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): 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 of values, each value corresponding to the promise at the same index in the promises array. 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 of promises. - */ - all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise, T7 | IPromise, T8 | IPromise, T9 | IPromise, T10 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; - all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise, T7 | IPromise, T8 | IPromise, T9 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; - all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise, T7 | IPromise, T8 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6, T7, T8]>; - all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise, T7 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6, T7]>; - all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6]>; - all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise]): IPromise<[T1, T2, T3, T4, T5]>; - all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise ]): IPromise<[T1, T2, T3, T4]>; - all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise]): IPromise<[T1, T2, T3]>; - all(values: [T1 | IPromise, T2 | IPromise]): IPromise<[T1, T2]>; - 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 a hash of values, each value corresponding to the promise at the same key in the promises hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. - * - * @param promises A hash of promises. - */ - all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any; }>; - all(promises: { [id: string]: IPromise; }): IPromise; - /** - * 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 - */ - resolve(value: IPromise|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. - */ - resolve(): 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|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. - */ - when(): IPromise; - } - - interface IPromise { - /** - * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. - * The successCallBack may return IPromise for when a $q.reject() needs to be returned - * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method. - */ - then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; - - /** - * Shorthand for promise.then(null, errorCallback) - */ - catch(onRejected: (reason: any) => IPromise|TResult): IPromise; - - /** - * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information. - * - * Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible. - */ - finally(finallyCallback: () => any): IPromise; - } - - interface IDeferred { - resolve(value?: T|IPromise): void; - reject(reason?: any): void; - notify(state?: any): void; - promise: IPromise; - } - - /////////////////////////////////////////////////////////////////////////// - // AnchorScrollService - // see http://docs.angularjs.org/api/ng.$anchorScroll - /////////////////////////////////////////////////////////////////////////// - interface IAnchorScrollService { - (): void; - (hash: string): void; - yOffset: any; - } - - interface IAnchorScrollProvider extends IServiceProvider { - disableAutoScrolling(): void; - } - - /** - * $cacheFactory - service in module ng - * - * Factory that constructs Cache objects and gives access to them. - * - * see https://docs.angularjs.org/api/ng/service/$cacheFactory - */ - interface ICacheFactoryService { - /** - * Factory that constructs Cache objects and gives access to them. - * - * @param cacheId Name or id of the newly created cache. - * @param optionsMap Options object that specifies the cache behavior. Properties: - * - * capacity — turns the cache into LRU cache. - */ - (cacheId: string, optionsMap?: { capacity?: number; }): ICacheObject; - - /** - * Get information about all the caches that have been created. - * @returns key-value map of cacheId to the result of calling cache#info - */ - info(): any; - - /** - * Get access to a cache object by the cacheId used when it was created. - * - * @param cacheId Name or id of a cache to access. - */ - get(cacheId: string): ICacheObject; - } - - /** - * $cacheFactory.Cache - type in module ng - * - * A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data. - * - * see https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache - */ - interface ICacheObject { - /** - * Retrieve information regarding a particular Cache. - */ - info(): { - /** - * the id of the cache instance - */ - id: string; - - /** - * the number of entries kept in the cache instance - */ - size: number; - - //...: any additional properties from the options object when creating the cache. - }; - - /** - * Inserts a named entry into the Cache object to be retrieved later, and incrementing the size of the cache if the key was not already present in the cache. If behaving like an LRU cache, it will also remove stale entries from the set. - * - * It will not insert undefined values into the cache. - * - * @param key the key under which the cached data is stored. - * @param value the value to store alongside the key. If it is undefined, the key will not be stored. - */ - put(key: string, value?: T): T; - - /** - * Retrieves named data stored in the Cache object. - * - * @param key the key of the data to be retrieved - */ - get(key: string): T; - - /** - * Removes an entry from the Cache object. - * - * @param key the key of the entry to be removed - */ - remove(key: string): void; - - /** - * Clears the cache object of any entries. - */ - removeAll(): void; - - /** - * Destroys the Cache object entirely, removing it from the $cacheFactory set. - */ - 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; - directive(directivesMap: Object, directiveFactory: Function): ICompileProvider; - directive(name: string, inlineAnnotatedFunction: any[]): ICompileProvider; - directive(directivesMap: Object, inlineAnnotatedFunction: any[]): ICompileProvider; - - // Undocumented, but it is there... - directive(directivesMap: any): ICompileProvider; - - component(name: string, options: IComponentOptions): ICompileProvider; - - aHrefSanitizationWhitelist(): RegExp; - aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; - - imgSrcSanitizationWhitelist(): RegExp; - imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; - - debugInfoEnabled(enabled?: boolean): any; - } - - 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: new (...args: any[]) => T, locals?: any, later?: boolean, ident?: string): T; - (controllerConstructor: Function, locals?: any, later?: boolean, ident?: string): T; - (controllerName: string, locals?: any, later?: boolean, ident?: string): T; - } - - interface IControllerProvider extends IServiceProvider { - register(name: string, controllerConstructor: Function): void; - register(name: string, dependencyAnnotatedConstructor: any[]): void; - allowGlobals(): void; - } - - /** - * xhrFactory - * Replace or decorate this service to create your own custom XMLHttpRequest objects. - * see https://docs.angularjs.org/api/ng/service/$xhrFactory - */ - interface IXhrFactory { - (method: string, url: string): T; - } - - /** - * 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; - - /** - * Shortcut method to perform PATCH request. - * - * @param url Relative or absolute URL specifying the destination of the request - * @param data Request content - * @param config Optional configuration object - */ - patch(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: IHttpProviderDefaults; - - /** - * Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes. - */ - pendingRequests: IRequestConfig[]; - } - - /** - * 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 extends IHttpProviderDefaults { - /** - * {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; - - /** - * {string|Object} - * Data to be sent as the request message data. - */ - data?: any; - - /** - * Timeout in milliseconds, or promise that should abort the request when resolved. - */ - timeout?: number|IPromise; - - /** - * See [XMLHttpRequest.responseType]https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype - */ - 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 IHttpHeadersGetter { - (): { [name: string]: string; }; - (headerName: string): string; - } - - interface IHttpPromiseCallback { - (data: T, status: number, headers: IHttpHeadersGetter, config: IRequestConfig): void; - } - - interface IHttpPromiseCallbackArg { - data?: T; - status?: number; - headers?: IHttpHeadersGetter; - config?: IRequestConfig; - statusText?: string; - } - - interface IHttpPromise extends IPromise> { - /** - * The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. - * If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. - * @deprecated - */ - success?(callback: IHttpPromiseCallback): IHttpPromise; - /** - * The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. - * If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. - * @deprecated - */ - error?(callback: IHttpPromiseCallback): IHttpPromise; - } - - // See the jsdoc for transformData() at https://github.com/angular/angular.js/blob/master/src/ng/http.js#L228 - interface IHttpRequestTransformer { - (data: any, headersGetter: IHttpHeadersGetter): any; - } - - // The definition of fields are the same as IHttpPromiseCallbackArg - interface IHttpResponseTransformer { - (data: any, headersGetter: IHttpHeadersGetter, status: number): any; - } - - type HttpHeaderType = {[requestType: string]:string|((config:IRequestConfig) => string)}; - - interface IHttpRequestConfigHeaders { - [requestType: string]: any; - common?: any; - get?: any; - post?: any; - put?: any; - patch?: any; - } - - /** - * Object that controls the defaults for $http provider. Not all fields of IRequestShortcutConfig can be configured - * via defaults and the docs do not say which. The following is based on the inspection of the source code. - * https://docs.angularjs.org/api/ng/service/$http#defaults - * https://docs.angularjs.org/api/ng/service/$http#usage - * https://docs.angularjs.org/api/ng/provider/$httpProvider The properties section - */ - interface IHttpProviderDefaults { - /** - * {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; - - /** - * 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. - * @see {@link https://docs.angularjs.org/api/ng/service/$http#transforming-requests-and-responses} - */ - transformRequest?: IHttpRequestTransformer |IHttpRequestTransformer[]; - - /** - * 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?: IHttpResponseTransformer | IHttpResponseTransformer[]; - - /** - * 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. - * The key of the map is the request verb in lower case. The "common" key applies to all requests. - * @see {@link https://docs.angularjs.org/api/ng/service/$http#setting-http-headers} - */ - headers?: IHttpRequestConfigHeaders; - - /** Name of HTTP header to populate with the XSRF token. */ - xsrfHeaderName?: string; - - /** Name of cookie containing the XSRF token. */ - xsrfCookieName?: string; - - /** - * 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; - - /** - * A function used to the prepare string representation of request parameters (specified as an object). If - * specified as string, it is interpreted as a function registered with the $injector. Defaults to - * $httpParamSerializer. - */ - paramSerializer?: string | ((obj: any) => string); - } - - interface IHttpInterceptor { - request?: (config: IRequestConfig) => IRequestConfig|IPromise; - requestError?: (rejection: any) => any; - response?: (response: IHttpPromiseCallbackArg) => IPromise>|IHttpPromiseCallbackArg; - responseError?: (rejection: any) => any; - } - - interface IHttpInterceptorFactory { - (...args: any[]): IHttpInterceptor; - } - - interface IHttpProvider extends IServiceProvider { - defaults: IHttpProviderDefaults; - - /** - * Register service factories (names or implementations) for interceptors which are called before and after - * each request. - */ - interceptors: (string|IHttpInterceptorFactory|(string|IHttpInterceptorFactory)[])[]; - useApplyAsync(): boolean; - useApplyAsync(value: boolean): IHttpProvider; - - /** - * - * @param {boolean=} value If true, `$http` will return a normal promise without the `success` and `error` methods. - * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. - * otherwise, returns the current configured value. - */ - useLegacyPromiseExtensions(value:boolean) : boolean | IHttpProvider; - } - - /////////////////////////////////////////////////////////////////////////// - // 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, trustedContext?: string, allOrNothing?: 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; - resourceUrlBlacklist(): any[]; - resourceUrlWhitelist(): any[]; - } - - /** - * $templateRequest service - * see http://docs.angularjs.org/api/ng/service/$templateRequest - */ - interface ITemplateRequestService { - /** - * Downloads a template using $http and, upon success, stores the - * contents inside of $templateCache. - * - * If the HTTP request fails or the response data of the HTTP request is - * empty then a $compile error will be thrown (unless - * {ignoreRequestError} is set to true). - * - * @param tpl The template URL. - * @param ignoreRequestError Whether or not to ignore the exception - * when the request fails or the template is - * empty. - * - * @return A promise whose value is the template content. - */ - (tpl: string, ignoreRequestError?: boolean): IPromise; - /** - * total amount of pending template requests being downloaded. - * @type {number} - */ - totalPendingRequests: number; - } - - /////////////////////////////////////////////////////////////////////////// - // Component - // see http://angularjs.blogspot.com.br/2015/11/angularjs-15-beta2-and-14-releases.html - // and http://toddmotto.com/exploring-the-angular-1-5-component-method/ - /////////////////////////////////////////////////////////////////////////// - /** - * Runtime representation a type that a Component or other object is instances of. - * - * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by - * the `MyCustomComponent` constructor function. - */ - interface Type extends Function { - } - - /** - * `RouteDefinition` defines a route within a {@link RouteConfig} decorator. - * - * Supported keys: - * - `path` or `aux` (requires exactly one of these) - * - `component`, `loader`, `redirectTo` (requires exactly one of these) - * - `name` or `as` (optional) (requires exactly one of these) - * - `data` (optional) - * - * See also {@link Route}, {@link AsyncRoute}, {@link AuxRoute}, and {@link Redirect}. - */ - interface RouteDefinition { - path?: string; - aux?: string; - component?: Type | ComponentDefinition | string; - loader?: Function; - redirectTo?: any[]; - as?: string; - name?: string; - data?: any; - useAsDefault?: boolean; - } - - /** - * Represents either a component type (`type` is `component`) or a loader function - * (`type` is `loader`). - * - * See also {@link RouteDefinition}. - */ - interface ComponentDefinition { - type: string; - loader?: Function; - component?: Type; - } - - /** - * Component definition object (a simplified directive definition object) - */ - interface IComponentOptions { - /** - * Controller constructor function that should be associated with newly created scope or the name of a registered - * controller if passed as a string. Empty function by default. - * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection) - */ - controller?: string | Function | (string | Function)[]; - /** - * An identifier name for a reference to the controller. If present, the controller will be published to scope under - * the controllerAs name. If not present, this will default to be the same as the component name. - * @default "$ctrl" - */ - controllerAs?: string; - /** - * html template as a string or a function that returns an html template as a string which should be used as the - * contents of this component. Empty string by default. - * If template is a function, then it is injected with the following locals: - * $element - Current element - * $attrs - Current attributes object for the element - * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection) - */ - template?: string | Function | (string | Function)[]; - /** - * path or function that returns a path to an html template that should be used as the contents of this component. - * If templateUrl is a function, then it is injected with the following locals: - * $element - Current element - * $attrs - Current attributes object for the element - * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection) - */ - templateUrl?: string | Function | (string | Function)[]; - /** - * Define DOM attribute binding to component properties. Component properties are always bound to the component - * controller and not to the scope. - */ - bindings?: {[binding: string]: string}; - /** - * Whether transclusion is enabled. Enabled by default. - */ - transclude?: boolean | string | {[slot: string]: string}; - require?: string | string[] | {[controller: string]: string}; - } - - interface IComponentTemplateFn { - ( $element?: IAugmentedJQuery, $attrs?: IAttributes ): string; - } - - /////////////////////////////////////////////////////////////////////////// - // 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: {}, - transclude: ITranscludeFunction - ): void; - } - - interface IDirectivePrePost { - pre?: IDirectiveLinkFn; - post?: IDirectiveLinkFn; - } - - interface IDirectiveCompileFn { - ( - templateElement: IAugmentedJQuery, - templateAttributes: IAttributes, - /** - * @deprecated - * Note: The transclude function that is passed to the compile function is deprecated, - * as it e.g. does not know about the right outer scope. Please use the transclude function - * that is passed to the link function instead. - */ - transclude: ITranscludeFunction - ): IDirectivePrePost; - } - - interface IDirective { - compile?: IDirectiveCompileFn; - controller?: any; - controllerAs?: string; - /** - * @deprecated - * Deprecation warning: although bindings for non-ES6 class controllers are currently bound to this before - * the controller constructor is called, this use is now deprecated. Please place initialization code that - * relies upon bindings inside a $onInit method on the controller, instead. - */ - bindToController?: boolean | Object; - link?: IDirectiveLinkFn | IDirectivePrePost; - multiElement?: boolean; - name?: string; - priority?: number; - /** - * @deprecated - */ - replace?: boolean; - require?: string | string[] | {[controller: string]: string}; - restrict?: string; - scope?: boolean | Object; - template?: string | Function; - templateNamespace?: string; - templateUrl?: string | Function; - terminal?: boolean; - transclude?: boolean | string | {[slot: string]: string}; - } - - /** - * 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(): any; - controller(name: string): any; - injector(): any; - scope(): IScope; - - /** - * Overload for custom scope interfaces - */ - scope(): T; - isolateScope(): IScope; - - inheritedData(key: string, value: any): JQuery; - inheritedData(obj: { [key: string]: any; }): JQuery; - inheritedData(key?: string): any; - } - - /////////////////////////////////////////////////////////////////////////// - // AUTO module (angular.js) - /////////////////////////////////////////////////////////////////////////// - export module auto { - - /////////////////////////////////////////////////////////////////////// - // InjectorService - // see http://docs.angularjs.org/api/AUTO.$injector - /////////////////////////////////////////////////////////////////////// - interface IInjectorService { - annotate(fn: Function, strictDi?: boolean): string[]; - annotate(inlineAnnotatedFunction: any[]): string[]; - get(name: string, caller?: string): T; - has(name: string): boolean; - instantiate(typeConstructor: Function, locals?: any): T; - invoke(inlineAnnotatedFunction: any[]): any; - invoke(func: Function, context?: any, locals?: any): any; - strictDi: boolean; - } - - /////////////////////////////////////////////////////////////////////// - // 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): IServiceProvider; - factory(name: string, inlineAnnotatedFunction: any[]): IServiceProvider; - provider(name: string, provider: IServiceProvider): IServiceProvider; - provider(name: string, serviceProviderConstructor: Function): IServiceProvider; - service(name: string, constructor: Function): IServiceProvider; - service(name: string, inlineAnnotatedFunction: any[]): IServiceProvider; - value(name: string, value: any): IServiceProvider; - } - - } - - /** - * $http params serializer that converts objects to strings - * see https://docs.angularjs.org/api/ng/service/$httpParamSerializer - */ - interface IHttpParamSerializer { - (obj: Object): string; - } -} diff --git a/angularjs/index.d.ts b/angularjs/index.d.ts new file mode 100644 index 0000000000..1d2f37e281 --- /dev/null +++ b/angularjs/index.d.ts @@ -0,0 +1,1934 @@ +// Type definitions for Angular JS 1.5 +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/// + +declare var angular: angular.IAngularStatic; + +// Support for painless dependency injection +interface Function { + $inject?: string[]; +} + +export as namespace angular; +export as namespace ng; + +// Support AMD require +export = angular; + +import ng = angular; + +/////////////////////////////////////////////////////////////////////////////// +// ng module (angular.js) +/////////////////////////////////////////////////////////////////////////////// +declare namespace angular { + + // 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; + } + + interface IAngularBootstrapConfig { + strictDi?: boolean; + debugInfoEnabled?: boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // see http://docs.angularjs.org/api + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + bind(context: any, fn: Function, ...args: any[]): Function; + + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a config block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: string|Element|JQuery|Document, modules?: (string|Function|any[])[], config?: IAngularBootstrapConfig): auto.IInjectorService; + + /** + * 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; + + /** + * Wraps a raw DOM element or HTML string as a jQuery element. + * + * If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." + */ + 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?: T): T; + injector(modules?: any[], strictDi?: boolean): 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; + + /** + * Deeply extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.merge({}, object1, object2). + * + * Unlike extend(), merge() recursively descends into object properties of source objects, performing a deep copy. + * + * @param dst Destination object. + * @param src Source object(s). + */ + merge(dst: any, ...src: any[]): any; + + /** + * 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; + reloadWithDebugInfo(): void; + toJson(obj: any, pretty?: boolean): string; + uppercase(str: string): string; + version: { + full: string; + major: number; + minor: number; + dot: number; + codeName: string; + }; + + /** + * If window.name contains prefix NG_DEFER_BOOTSTRAP! when angular.bootstrap is called, the bootstrap process will be paused until angular.resumeBootstrap() is called. + * @param extraModules An optional array of modules that should be added to the original list of modules that the app was about to be bootstrapped with. + */ + resumeBootstrap?(extraModules?: string[]): ng.auto.IInjectorService; + } + + /////////////////////////////////////////////////////////////////////////// + // Module + // see http://docs.angularjs.org/api/angular.Module + /////////////////////////////////////////////////////////////////////////// + interface IModule { + /** + * Use this method to register a component. + * + * @param name The name of the component. + * @param options A definition object passed into the component. + */ + component(name: string, options: IComponentOptions): 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; + config(object: Object): 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: T): 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; + /** + * Register a new directive with the compiler. + * + * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) + * @param directiveFactory An injectable directive factory function. + */ + directive(name: string, directiveFactory: IDirectiveFactory): IModule; + /** + * Register a new directive with the compiler. + * + * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) + * @param directiveFactory An injectable directive factory function. + */ + 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; + /** + * Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is a factory function that returns an instance instantiated by the injector from the service constructor function. + * + * @param name The name of the instance. + * @param serviceConstructor An injectable class (constructor function) that will be instantiated. + */ + service(name: string, serviceConstructor: Function): IModule; + /** + * Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is a factory function that returns an instance instantiated by the injector from the service constructor function. + * + * @param name The name of the instance. + * @param inlineAnnotatedConstructor An injectable class (constructor function) that will be instantiated. + */ + 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: T): IModule; + value(object: Object): IModule; + + /** + * 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, decoratorConstructor: Function): IModule; + decorator(name:string, inlineAnnotatedConstructor: any[]): 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; + + /** + * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with x- or data-) to its normalized, camelCase form. + * + * Also there is special case for Moz prefix starting with upper case letter. + * + * For further information check out the guide on @see https://docs.angularjs.org/guide/directive#matching-directives + */ + $normalize(name: string): string; + + /** + * 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; + + /** + * Adds and removes the appropriate CSS class values to the element based on the difference between + * the new and old CSS class values (specified as newClasses and oldClasses). + */ + $updateClass(newClasses: string, oldClasses: 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?: T) => 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; + $submitted: boolean; + $error: any; + $pending: any; + $addControl(control: INgModelController): void; + $removeControl(control: INgModelController): void; + $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController): void; + $setDirty(): void; + $setPristine(): void; + $commitViewValue(): void; + $rollbackViewValue(): void; + $setSubmitted(): void; + $setUntouched(): 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, trigger?: string): void; + $setPristine(): void; + $setDirty(): void; + $validate(): void; + $setTouched(): void; + $setUntouched(): void; + $rollbackViewValue(): void; + $commitViewValue(): 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; + $asyncValidators: IAsyncModelValidators; + + $pending: any; + $pristine: boolean; + $dirty: boolean; + $valid: boolean; + $invalid: boolean; + } + + //Allows tuning how model updates are done. + //https://docs.angularjs.org/api/ng/directive/ngModelOptions + interface INgModelOptions { + updateOn?: string; + debounce?: any; + allowInvalid?: boolean; + getterSetter?: boolean; + timezone?: string; + } + + interface IModelValidators { + /** + * viewValue is any because it can be an object that is called in the view like $viewValue.name:$viewValue.subName + */ + [index: string]: (modelValue: any, viewValue: any) => boolean; + } + + interface IAsyncModelValidators { + [index: string]: (modelValue: any, viewValue: any) => IPromise; + } + + interface IModelParser { + (value: any): any; + } + + interface IModelFormatter { + (value: any): any; + } + + interface IModelViewChangeListener { + (): void; + } + + /** + * $rootScope - $rootScopeProvider - service in module ng + * see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and https://docs.angularjs.org/api/ng/service/$rootScope + */ + interface IRootScopeService { + [index: string]: any; + + $apply(): any; + $apply(exp: string): any; + $apply(exp: (scope: IScope) => any): any; + + $applyAsync(): any; + $applyAsync(exp: string): any; + $applyAsync(exp: (scope: IScope) => any): any; + + /** + * Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners. + * + * The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled. + * + * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. + * + * @param name Event name to broadcast. + * @param args Optional one or more arguments which will be passed onto the event listeners. + */ + $broadcast(name: string, ...args: any[]): IAngularEvent; + $destroy(): void; + $digest(): void; + /** + * Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners. + * + * The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it. + * + * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. + * + * @param name Event name to emit. + * @param args Optional one or more arguments which will be passed onto the event listeners. + */ + $emit(name: string, ...args: any[]): IAngularEvent; + + $eval(): any; + $eval(expression: string, locals?: Object): any; + $eval(expression: (scope: IScope) => any, locals?: Object): any; + + $evalAsync(): void; + $evalAsync(expression: string): void; + $evalAsync(expression: (scope: IScope) => any): void; + + // Defaults to false by the implementation checking strategy + $new(isolate?: boolean, parent?: IScope): IScope; + + /** + * Listens on events of a given type. See $emit for discussion of event life cycle. + * + * The event listener function format is: function(event, args...). + * + * @param name Event name to listen on. + * @param listener Function to call when the event is emitted. + */ + $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): () => void; + + $watch(watchExpression: string, listener?: string, objectEquality?: boolean): () => void; + $watch(watchExpression: string, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): () => void; + $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): () => void; + $watch(watchExpression: (scope: IScope) => T, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): () => void; + + $watchCollection(watchExpression: string, listener: (newValue: T, oldValue: T, scope: IScope) => any): () => void; + $watchCollection(watchExpression: (scope: IScope) => T, listener: (newValue: T, oldValue: T, scope: IScope) => any): () => void; + + $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void; + $watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void; + + $parent: IScope; + $root: IRootScopeService; + $id: number; + + // Hidden members + $$isolateBindings: any; + $$phase: any; + } + + interface IScope extends IRootScopeService { } + + /** + * $scope for ngRepeat directive. + * see https://docs.angularjs.org/api/ng/directive/ngRepeat + */ + interface IRepeatScope extends IScope { + + /** + * iterator offset of the repeated element (0..length-1). + */ + $index: number; + + /** + * true if the repeated element is first in the iterator. + */ + $first: boolean; + + /** + * true if the repeated element is between the first and last in the iterator. + */ + $middle: boolean; + + /** + * true if the repeated element is last in the iterator. + */ + $last: boolean; + + /** + * true if the iterator position $index is even (otherwise false). + */ + $even: boolean; + + /** + * true if the iterator position $index is odd (otherwise false). + */ + $odd: boolean; + + } + + interface IAngularEvent { + /** + * the scope on which the event was $emit-ed or $broadcast-ed. + */ + targetScope: IScope; + /** + * the scope that is currently handling the event. Once the event propagates through the scope hierarchy, this property is set to null. + */ + currentScope: IScope; + /** + * name of the event. + */ + name: string; + /** + * calling stopPropagation function will cancel further event propagation (available only for events that were $emit-ed). + */ + stopPropagation?: Function; + /** + * calling preventDefault sets defaultPrevented flag to true. + */ + preventDefault(): void; + /** + * true if preventDefault was called. + */ + defaultPrevented: boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // WindowService + // see http://docs.angularjs.org/api/ng.$window + /////////////////////////////////////////////////////////////////////////// + interface IWindowService extends Window { + [key: string]: any; + } + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ng.$timeout + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + (delay?: number, invokeApply?: boolean): IPromise; + (fn: (...args: any[]) => T, delay?: number, invokeApply?: boolean, ...args: any[]): IPromise; + cancel(promise?: IPromise): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // IntervalService + // see http://docs.angularjs.org/api/ng.$interval + /////////////////////////////////////////////////////////////////////////// + interface IIntervalService { + (func: Function, delay: number, count?: number, invokeApply?: boolean, ...args: any[]): IPromise; + cancel(promise: IPromise): boolean; + } + + /** + * $filter - $filterProvider - service in module ng + * + * Filters are used for formatting data displayed to the user. + * + * see https://docs.angularjs.org/api/ng/service/$filter + */ + interface IFilterService { + (name: 'filter'): IFilterFilter; + (name: 'currency'): IFilterCurrency; + (name: 'number'): IFilterNumber; + (name: 'date'): IFilterDate; + (name: 'json'): IFilterJson; + (name: 'lowercase'): IFilterLowercase; + (name: 'uppercase'): IFilterUppercase; + (name: 'limitTo'): IFilterLimitTo; + (name: 'orderBy'): IFilterOrderBy; + /** + * Usage: + * $filter(name); + * + * @param name Name of the filter function to retrieve + */ + (name: string): T; + } + + interface IFilterFilter { + (array: T[], expression: string | IFilterFilterPatternObject | IFilterFilterPredicateFunc, comparator?: IFilterFilterComparatorFunc|boolean): T[]; + } + + interface IFilterFilterPatternObject { + [name: string]: any; + } + + interface IFilterFilterPredicateFunc { + (value: T, index: number, array: T[]): boolean; + } + + interface IFilterFilterComparatorFunc { + (actual: T, expected: T): boolean; + } + + interface IFilterCurrency { + /** + * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used. + * @param amount Input to filter. + * @param symbol Currency symbol or identifier to be displayed. + * @param fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale + * @return Formatted number + */ + (amount: number, symbol?: string, fractionSize?: number): string; + } + + interface IFilterNumber { + /** + * Formats a number as text. + * @param number Number to format. + * @param fractionSize Number of decimal places to round the number to. If this is not provided then the fraction size is computed from the current locale's number formatting pattern. In the case of the default locale, it will be 3. + * @return Number rounded to decimalPlaces and places a “,” after each third digit. + */ + (value: number|string, fractionSize?: number|string): string; + } + + interface IFilterDate { + /** + * Formats date to a string based on the requested format. + * + * @param date Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone. + * @param format Formatting rules (see Description). If not specified, mediumDate is used. + * @param timezone Timezone to be used for formatting. It understands UTC/GMT and the continental US time zone abbreviations, but for general use, use a time zone offset, for example, '+0430' (4 hours, 30 minutes east of the Greenwich meridian) If not specified, the timezone of the browser will be used. + * @return Formatted string or the input if input is not recognized as date/millis. + */ + (date: Date | number | string, format?: string, timezone?: string): string; + } + + interface IFilterJson { + /** + * Allows you to convert a JavaScript object into JSON string. + * @param object Any JavaScript object (including arrays and primitive types) to filter. + * @param spacing The number of spaces to use per indentation, defaults to 2. + * @return JSON string. + */ + (object: any, spacing?: number): string; + } + + interface IFilterLowercase { + /** + * Converts string to lowercase. + */ + (value: string): string; + } + + interface IFilterUppercase { + /** + * Converts string to uppercase. + */ + (value: string): string; + } + + interface IFilterLimitTo { + /** + * Creates a new array containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit. + * @param input Source array to be limited. + * @param limit The length of the returned array. If the limit number is positive, limit number of items from the beginning of the source array/string are copied. If the number is negative, limit number of items from the end of the source array are copied. The limit will be trimmed if it exceeds array.length. If limit is undefined, the input will be returned unchanged. + * @param begin Index at which to begin limitation. As a negative index, begin indicates an offset from the end of input. Defaults to 0. + * @return A new sub-array of length limit or less if input array had less than limit elements. + */ + (input: T[], limit: string|number, begin?: string|number): T[]; + /** + * Creates a new string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source string or number, as specified by the value and sign (positive or negative) of limit. If a number is used as input, it is converted to a string. + * @param input Source string or number to be limited. + * @param limit The length of the returned string. If the limit number is positive, limit number of items from the beginning of the source string are copied. If the number is negative, limit number of items from the end of the source string are copied. The limit will be trimmed if it exceeds input.length. If limit is undefined, the input will be returned unchanged. + * @param begin Index at which to begin limitation. As a negative index, begin indicates an offset from the end of input. Defaults to 0. + * @return A new substring of length limit or less if input had less than limit elements. + */ + (input: string|number, limit: string|number, begin?: string|number): string; + } + + interface IFilterOrderBy { + /** + * Orders a specified array by the expression predicate. It is ordered alphabetically for strings and numerically for numbers. Note: if you notice numbers are not being sorted as expected, make sure they are actually being saved as numbers and not strings. + * @param array The array to sort. + * @param expression A predicate to be used by the comparator to determine the order of elements. + * @param reverse Reverse the order of the array. + * @return Reverse the order of the array. + */ + (array: T[], expression: string|((value: T) => any)|(((value: T) => any)|string)[], reverse?: boolean): T[]; + } + + /** + * $filterProvider - $filter - provider in module ng + * + * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function. + * + * see https://docs.angularjs.org/api/ng/provider/$filterProvider + */ + interface IFilterProvider extends IServiceProvider { + /** + * register(name); + * + * @param name Name of the filter function, or an object map of filters where the keys are the filter names and the values are the filter factories. Note: Filter names must be valid angular Expressions identifiers, such as uppercase or orderBy. Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace your filters, then you can use capitalization (myappSubsectionFilterx) or underscores (myapp_subsection_filterx). + */ + register(name: string | {}): 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 extends IServiceProvider { + debugEnabled(): boolean; + debugEnabled(enabled: boolean): ILogProvider; + } + + // We define this as separate 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; + + literal: boolean; + constant: boolean; + + // 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; + } + + /** + * $location - $locationProvider - service in module ng + * see https://docs.angularjs.org/api/ng/service/$location + */ + interface ILocationService { + absUrl(): string; + hash(): string; + hash(newHash: string): ILocationService; + host(): string; + + /** + * Return path of current url + */ + path(): string; + + /** + * Change path when called with parameter and return $location. + * Note: Path should always begin with forward slash (/), this method will add the forward slash if it is missing. + * + * @param path New path + */ + path(path: string): ILocationService; + + port(): number; + protocol(): string; + replace(): ILocationService; + + /** + * Return search part (as object) of current url + */ + search(): any; + + /** + * Change search part when called with parameter and return $location. + * + * @param search When called with a single argument the method acts as a setter, setting the search component of $location to the specified value. + * + * If the argument is a hash object containing an array of values, these values will be encoded as duplicate search parameters in the url. + */ + search(search: any): ILocationService; + + /** + * Change search part when called with parameter and return $location. + * + * @param search New search params + * @param paramValue If search is a string or a Number, then paramValue will override only a single search property. If paramValue is null, the property specified via the first argument will be deleted. If paramValue is an array, it will override the property of the search component of $location specified via the first argument. If paramValue is true, the property specified via the first argument will be added with no value nor trailing equal sign. + */ + search(search: string, paramValue: string|number|string[]|boolean): ILocationService; + + state(): any; + state(state: 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; + html5Mode(mode: { enabled?: boolean; requireBase?: boolean; rewriteLinks?: 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 {} + + interface IQResolveReject { + (): void; + (value: T): void; + } + /** + * $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 { + new (resolver: (resolve: IQResolveReject) => any): IPromise; + new (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; + (resolver: (resolve: IQResolveReject) => any): IPromise; + (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): 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 of values, each value corresponding to the promise at the same index in the promises array. 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 of promises. + */ + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise, T7 | IPromise, T8 | IPromise, T9 | IPromise, T10 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise, T7 | IPromise, T8 | IPromise, T9 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise, T7 | IPromise, T8 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise, T7 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6, T7]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise]): IPromise<[T1, T2, T3, T4, T5]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise ]): IPromise<[T1, T2, T3, T4]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise]): IPromise<[T1, T2, T3]>; + all(values: [T1 | IPromise, T2 | IPromise]): IPromise<[T1, T2]>; + 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 a hash of values, each value corresponding to the promise at the same key in the promises hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises A hash of promises. + */ + all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any; }>; + all(promises: { [id: string]: IPromise; }): IPromise; + /** + * 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 + */ + resolve(value: IPromise|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. + */ + resolve(): 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|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. + */ + when(): IPromise; + } + + interface IPromise { + /** + * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. + * The successCallBack may return IPromise for when a $q.reject() needs to be returned + * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method. + */ + then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + + /** + * Shorthand for promise.then(null, errorCallback) + */ + catch(onRejected: (reason: any) => IPromise|TResult): IPromise; + + /** + * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information. + * + * Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible. + */ + finally(finallyCallback: () => any): IPromise; + } + + interface IDeferred { + resolve(value?: T|IPromise): void; + reject(reason?: any): void; + notify(state?: any): void; + promise: IPromise; + } + + /////////////////////////////////////////////////////////////////////////// + // AnchorScrollService + // see http://docs.angularjs.org/api/ng.$anchorScroll + /////////////////////////////////////////////////////////////////////////// + interface IAnchorScrollService { + (): void; + (hash: string): void; + yOffset: any; + } + + interface IAnchorScrollProvider extends IServiceProvider { + disableAutoScrolling(): void; + } + + /** + * $cacheFactory - service in module ng + * + * Factory that constructs Cache objects and gives access to them. + * + * see https://docs.angularjs.org/api/ng/service/$cacheFactory + */ + interface ICacheFactoryService { + /** + * Factory that constructs Cache objects and gives access to them. + * + * @param cacheId Name or id of the newly created cache. + * @param optionsMap Options object that specifies the cache behavior. Properties: + * + * capacity — turns the cache into LRU cache. + */ + (cacheId: string, optionsMap?: { capacity?: number; }): ICacheObject; + + /** + * Get information about all the caches that have been created. + * @returns key-value map of cacheId to the result of calling cache#info + */ + info(): any; + + /** + * Get access to a cache object by the cacheId used when it was created. + * + * @param cacheId Name or id of a cache to access. + */ + get(cacheId: string): ICacheObject; + } + + /** + * $cacheFactory.Cache - type in module ng + * + * A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data. + * + * see https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache + */ + interface ICacheObject { + /** + * Retrieve information regarding a particular Cache. + */ + info(): { + /** + * the id of the cache instance + */ + id: string; + + /** + * the number of entries kept in the cache instance + */ + size: number; + + //...: any additional properties from the options object when creating the cache. + }; + + /** + * Inserts a named entry into the Cache object to be retrieved later, and incrementing the size of the cache if the key was not already present in the cache. If behaving like an LRU cache, it will also remove stale entries from the set. + * + * It will not insert undefined values into the cache. + * + * @param key the key under which the cached data is stored. + * @param value the value to store alongside the key. If it is undefined, the key will not be stored. + */ + put(key: string, value?: T): T; + + /** + * Retrieves named data stored in the Cache object. + * + * @param key the key of the data to be retrieved + */ + get(key: string): T; + + /** + * Removes an entry from the Cache object. + * + * @param key the key of the entry to be removed + */ + remove(key: string): void; + + /** + * Clears the cache object of any entries. + */ + removeAll(): void; + + /** + * Destroys the Cache object entirely, removing it from the $cacheFactory set. + */ + 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; + directive(directivesMap: Object, directiveFactory: Function): ICompileProvider; + directive(name: string, inlineAnnotatedFunction: any[]): ICompileProvider; + directive(directivesMap: Object, inlineAnnotatedFunction: any[]): ICompileProvider; + + // Undocumented, but it is there... + directive(directivesMap: any): ICompileProvider; + + component(name: string, options: IComponentOptions): ICompileProvider; + + aHrefSanitizationWhitelist(): RegExp; + aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; + + imgSrcSanitizationWhitelist(): RegExp; + imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; + + debugInfoEnabled(enabled?: boolean): any; + } + + 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: new (...args: any[]) => T, locals?: any, later?: boolean, ident?: string): T; + (controllerConstructor: Function, locals?: any, later?: boolean, ident?: string): T; + (controllerName: string, locals?: any, later?: boolean, ident?: string): T; + } + + interface IControllerProvider extends IServiceProvider { + register(name: string, controllerConstructor: Function): void; + register(name: string, dependencyAnnotatedConstructor: any[]): void; + allowGlobals(): void; + } + + /** + * xhrFactory + * Replace or decorate this service to create your own custom XMLHttpRequest objects. + * see https://docs.angularjs.org/api/ng/service/$xhrFactory + */ + interface IXhrFactory { + (method: string, url: string): T; + } + + /** + * 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; + + /** + * Shortcut method to perform PATCH request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + patch(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: IHttpProviderDefaults; + + /** + * Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes. + */ + pendingRequests: IRequestConfig[]; + } + + /** + * 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 extends IHttpProviderDefaults { + /** + * {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; + + /** + * {string|Object} + * Data to be sent as the request message data. + */ + data?: any; + + /** + * Timeout in milliseconds, or promise that should abort the request when resolved. + */ + timeout?: number|IPromise; + + /** + * See [XMLHttpRequest.responseType]https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype + */ + 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 IHttpHeadersGetter { + (): { [name: string]: string; }; + (headerName: string): string; + } + + interface IHttpPromiseCallback { + (data: T, status: number, headers: IHttpHeadersGetter, config: IRequestConfig): void; + } + + interface IHttpPromiseCallbackArg { + data?: T; + status?: number; + headers?: IHttpHeadersGetter; + config?: IRequestConfig; + statusText?: string; + } + + interface IHttpPromise extends IPromise> { + /** + * The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. + * If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. + * @deprecated + */ + success?(callback: IHttpPromiseCallback): IHttpPromise; + /** + * The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. + * If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. + * @deprecated + */ + error?(callback: IHttpPromiseCallback): IHttpPromise; + } + + // See the jsdoc for transformData() at https://github.com/angular/angular.js/blob/master/src/ng/http.js#L228 + interface IHttpRequestTransformer { + (data: any, headersGetter: IHttpHeadersGetter): any; + } + + // The definition of fields are the same as IHttpPromiseCallbackArg + interface IHttpResponseTransformer { + (data: any, headersGetter: IHttpHeadersGetter, status: number): any; + } + + type HttpHeaderType = {[requestType: string]:string|((config:IRequestConfig) => string)}; + + interface IHttpRequestConfigHeaders { + [requestType: string]: any; + common?: any; + get?: any; + post?: any; + put?: any; + patch?: any; + } + + /** + * Object that controls the defaults for $http provider. Not all fields of IRequestShortcutConfig can be configured + * via defaults and the docs do not say which. The following is based on the inspection of the source code. + * https://docs.angularjs.org/api/ng/service/$http#defaults + * https://docs.angularjs.org/api/ng/service/$http#usage + * https://docs.angularjs.org/api/ng/provider/$httpProvider The properties section + */ + interface IHttpProviderDefaults { + /** + * {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; + + /** + * 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. + * @see {@link https://docs.angularjs.org/api/ng/service/$http#transforming-requests-and-responses} + */ + transformRequest?: IHttpRequestTransformer |IHttpRequestTransformer[]; + + /** + * 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?: IHttpResponseTransformer | IHttpResponseTransformer[]; + + /** + * 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. + * The key of the map is the request verb in lower case. The "common" key applies to all requests. + * @see {@link https://docs.angularjs.org/api/ng/service/$http#setting-http-headers} + */ + headers?: IHttpRequestConfigHeaders; + + /** Name of HTTP header to populate with the XSRF token. */ + xsrfHeaderName?: string; + + /** Name of cookie containing the XSRF token. */ + xsrfCookieName?: string; + + /** + * 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; + + /** + * A function used to the prepare string representation of request parameters (specified as an object). If + * specified as string, it is interpreted as a function registered with the $injector. Defaults to + * $httpParamSerializer. + */ + paramSerializer?: string | ((obj: any) => string); + } + + interface IHttpInterceptor { + request?: (config: IRequestConfig) => IRequestConfig|IPromise; + requestError?: (rejection: any) => any; + response?: (response: IHttpPromiseCallbackArg) => IPromise>|IHttpPromiseCallbackArg; + responseError?: (rejection: any) => any; + } + + interface IHttpInterceptorFactory { + (...args: any[]): IHttpInterceptor; + } + + interface IHttpProvider extends IServiceProvider { + defaults: IHttpProviderDefaults; + + /** + * Register service factories (names or implementations) for interceptors which are called before and after + * each request. + */ + interceptors: (string|IHttpInterceptorFactory|(string|IHttpInterceptorFactory)[])[]; + useApplyAsync(): boolean; + useApplyAsync(value: boolean): IHttpProvider; + + /** + * + * @param {boolean=} value If true, `$http` will return a normal promise without the `success` and `error` methods. + * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. + * otherwise, returns the current configured value. + */ + useLegacyPromiseExtensions(value:boolean) : boolean | IHttpProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // 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, trustedContext?: string, allOrNothing?: 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; + resourceUrlBlacklist(): any[]; + resourceUrlWhitelist(): any[]; + } + + /** + * $templateRequest service + * see http://docs.angularjs.org/api/ng/service/$templateRequest + */ + interface ITemplateRequestService { + /** + * Downloads a template using $http and, upon success, stores the + * contents inside of $templateCache. + * + * If the HTTP request fails or the response data of the HTTP request is + * empty then a $compile error will be thrown (unless + * {ignoreRequestError} is set to true). + * + * @param tpl The template URL. + * @param ignoreRequestError Whether or not to ignore the exception + * when the request fails or the template is + * empty. + * + * @return A promise whose value is the template content. + */ + (tpl: string, ignoreRequestError?: boolean): IPromise; + /** + * total amount of pending template requests being downloaded. + * @type {number} + */ + totalPendingRequests: number; + } + + /////////////////////////////////////////////////////////////////////////// + // Component + // see http://angularjs.blogspot.com.br/2015/11/angularjs-15-beta2-and-14-releases.html + // and http://toddmotto.com/exploring-the-angular-1-5-component-method/ + /////////////////////////////////////////////////////////////////////////// + /** + * Runtime representation a type that a Component or other object is instances of. + * + * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by + * the `MyCustomComponent` constructor function. + */ + interface Type extends Function { + } + + /** + * `RouteDefinition` defines a route within a {@link RouteConfig} decorator. + * + * Supported keys: + * - `path` or `aux` (requires exactly one of these) + * - `component`, `loader`, `redirectTo` (requires exactly one of these) + * - `name` or `as` (optional) (requires exactly one of these) + * - `data` (optional) + * + * See also {@link Route}, {@link AsyncRoute}, {@link AuxRoute}, and {@link Redirect}. + */ + interface RouteDefinition { + path?: string; + aux?: string; + component?: Type | ComponentDefinition | string; + loader?: Function; + redirectTo?: any[]; + as?: string; + name?: string; + data?: any; + useAsDefault?: boolean; + } + + /** + * Represents either a component type (`type` is `component`) or a loader function + * (`type` is `loader`). + * + * See also {@link RouteDefinition}. + */ + interface ComponentDefinition { + type: string; + loader?: Function; + component?: Type; + } + + /** + * Component definition object (a simplified directive definition object) + */ + interface IComponentOptions { + /** + * Controller constructor function that should be associated with newly created scope or the name of a registered + * controller if passed as a string. Empty function by default. + * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection) + */ + controller?: string | Function | (string | Function)[]; + /** + * An identifier name for a reference to the controller. If present, the controller will be published to scope under + * the controllerAs name. If not present, this will default to be the same as the component name. + * @default "$ctrl" + */ + controllerAs?: string; + /** + * html template as a string or a function that returns an html template as a string which should be used as the + * contents of this component. Empty string by default. + * If template is a function, then it is injected with the following locals: + * $element - Current element + * $attrs - Current attributes object for the element + * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection) + */ + template?: string | Function | (string | Function)[]; + /** + * path or function that returns a path to an html template that should be used as the contents of this component. + * If templateUrl is a function, then it is injected with the following locals: + * $element - Current element + * $attrs - Current attributes object for the element + * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection) + */ + templateUrl?: string | Function | (string | Function)[]; + /** + * Define DOM attribute binding to component properties. Component properties are always bound to the component + * controller and not to the scope. + */ + bindings?: {[binding: string]: string}; + /** + * Whether transclusion is enabled. Enabled by default. + */ + transclude?: boolean | string | {[slot: string]: string}; + require?: string | string[] | {[controller: string]: string}; + } + + interface IComponentTemplateFn { + ( $element?: IAugmentedJQuery, $attrs?: IAttributes ): string; + } + + /////////////////////////////////////////////////////////////////////////// + // 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: {}, + transclude: ITranscludeFunction + ): void; + } + + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + interface IDirectiveCompileFn { + ( + templateElement: IAugmentedJQuery, + templateAttributes: IAttributes, + /** + * @deprecated + * Note: The transclude function that is passed to the compile function is deprecated, + * as it e.g. does not know about the right outer scope. Please use the transclude function + * that is passed to the link function instead. + */ + transclude: ITranscludeFunction + ): IDirectivePrePost; + } + + interface IDirective { + compile?: IDirectiveCompileFn; + controller?: any; + controllerAs?: string; + /** + * @deprecated + * Deprecation warning: although bindings for non-ES6 class controllers are currently bound to this before + * the controller constructor is called, this use is now deprecated. Please place initialization code that + * relies upon bindings inside a $onInit method on the controller, instead. + */ + bindToController?: boolean | Object; + link?: IDirectiveLinkFn | IDirectivePrePost; + multiElement?: boolean; + name?: string; + priority?: number; + /** + * @deprecated + */ + replace?: boolean; + require?: string | string[] | {[controller: string]: string}; + restrict?: string; + scope?: boolean | Object; + template?: string | Function; + templateNamespace?: string; + templateUrl?: string | Function; + terminal?: boolean; + transclude?: boolean | string | {[slot: string]: string}; + } + + /** + * 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(): any; + controller(name: string): any; + injector(): any; + scope(): IScope; + + /** + * Overload for custom scope interfaces + */ + scope(): T; + isolateScope(): IScope; + + inheritedData(key: string, value: any): JQuery; + inheritedData(obj: { [key: string]: any; }): JQuery; + inheritedData(key?: string): any; + } + + /////////////////////////////////////////////////////////////////////////// + // AUTO module (angular.js) + /////////////////////////////////////////////////////////////////////////// + export module auto { + + /////////////////////////////////////////////////////////////////////// + // InjectorService + // see http://docs.angularjs.org/api/AUTO.$injector + /////////////////////////////////////////////////////////////////////// + interface IInjectorService { + annotate(fn: Function, strictDi?: boolean): string[]; + annotate(inlineAnnotatedFunction: any[]): string[]; + get(name: string, caller?: string): T; + has(name: string): boolean; + instantiate(typeConstructor: Function, locals?: any): T; + invoke(inlineAnnotatedFunction: any[]): any; + invoke(func: Function, context?: any, locals?: any): any; + strictDi: boolean; + } + + /////////////////////////////////////////////////////////////////////// + // 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): IServiceProvider; + factory(name: string, inlineAnnotatedFunction: any[]): IServiceProvider; + provider(name: string, provider: IServiceProvider): IServiceProvider; + provider(name: string, serviceProviderConstructor: Function): IServiceProvider; + service(name: string, constructor: Function): IServiceProvider; + service(name: string, inlineAnnotatedFunction: any[]): IServiceProvider; + value(name: string, value: any): IServiceProvider; + } + + } + + /** + * $http params serializer that converts objects to strings + * see https://docs.angularjs.org/api/ng/service/$httpParamSerializer + */ + interface IHttpParamSerializer { + (obj: Object): string; + } +} diff --git a/angularjs/legacy/angular-1.0-tests.ts b/angularjs/legacy/angular-1.0-tests.ts index 33138c0c2f..b0e7ed692c 100644 --- a/angularjs/legacy/angular-1.0-tests.ts +++ b/angularjs/legacy/angular-1.0-tests.ts @@ -1,4 +1,4 @@ -/// + // issue: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/369 https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js diff --git a/angularjs/legacy/angular-1.0-tests.ts.tscparams b/angularjs/legacy/angular-1.0-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/angularjs/legacy/angular-1.0-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/angularjs/legacy/angular-1.0.d.ts b/angularjs/legacy/angular-1.0.d.ts index 6e8420b9d2..8c3fbca20a 100644 --- a/angularjs/legacy/angular-1.0.d.ts +++ b/angularjs/legacy/angular-1.0.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare var angular: ng.IAngularStatic; diff --git a/angularjs/legacy/angular-1.2-tests.ts b/angularjs/legacy/angular-1.2-tests.ts index 71e96d0804..d618fa8d25 100644 --- a/angularjs/legacy/angular-1.2-tests.ts +++ b/angularjs/legacy/angular-1.2-tests.ts @@ -1,4 +1,4 @@ -/// + // issue: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/369 // https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js diff --git a/angularjs/legacy/angular-1.2.d.ts b/angularjs/legacy/angular-1.2.d.ts index fe018ba989..2c4fd8d014 100644 --- a/angularjs/legacy/angular-1.2.d.ts +++ b/angularjs/legacy/angular-1.2.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare var angular: ng.IAngularStatic; diff --git a/angularjs/legacy/angular-1.4.d.ts b/angularjs/legacy/angular-1.4.d.ts index 22c504712e..da16c30920 100644 --- a/angularjs/legacy/angular-1.4.d.ts +++ b/angularjs/legacy/angular-1.4.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare var angular: angular.IAngularStatic; diff --git a/angularjs/legacy/angular-animate-1.2.d.ts b/angularjs/legacy/angular-animate-1.2.d.ts index f4928bd0ca..0a74608c27 100644 --- a/angularjs/legacy/angular-animate-1.2.d.ts +++ b/angularjs/legacy/angular-animate-1.2.d.ts @@ -3,7 +3,7 @@ // Definitions by: Michel Salib , Adi Dahiya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + /////////////////////////////////////////////////////////////////////////////// // ngAnimate module (angular-animate.js) diff --git a/angularjs/legacy/angular-animate-1.3.d.ts b/angularjs/legacy/angular-animate-1.3.d.ts index c689203ff3..6f103bc83c 100644 --- a/angularjs/legacy/angular-animate-1.3.d.ts +++ b/angularjs/legacy/angular-animate-1.3.d.ts @@ -3,7 +3,7 @@ // Definitions by: Michel Salib , Adi Dahiya , Raphael Schweizer , Cody Schaaf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + declare module "angular-animate" { var _: string; diff --git a/angularjs/legacy/angular-cookies-1.0.d.ts b/angularjs/legacy/angular-cookies-1.0.d.ts index 0b53de186b..78c8bd4229 100644 --- a/angularjs/legacy/angular-cookies-1.0.d.ts +++ b/angularjs/legacy/angular-cookies-1.0.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + /////////////////////////////////////////////////////////////////////////////// // ngCookies module (angular-cookies.js) diff --git a/angularjs/legacy/angular-cookies-1.2.d.ts b/angularjs/legacy/angular-cookies-1.2.d.ts index aaf08327e2..662bf11662 100644 --- a/angularjs/legacy/angular-cookies-1.2.d.ts +++ b/angularjs/legacy/angular-cookies-1.2.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + /////////////////////////////////////////////////////////////////////////////// // ngCookies module (angular-cookies.js) diff --git a/angularjs/legacy/angular-mocks-1.0.d.ts b/angularjs/legacy/angular-mocks-1.0.d.ts index 340f58e3c6..7ffa97f0ee 100644 --- a/angularjs/legacy/angular-mocks-1.0.d.ts +++ b/angularjs/legacy/angular-mocks-1.0.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + /////////////////////////////////////////////////////////////////////////////// // functions attached to global object (window) diff --git a/angularjs/legacy/angular-mocks-1.2-tests.ts b/angularjs/legacy/angular-mocks-1.2-tests.ts index 6f359a67c4..34e29addc0 100644 --- a/angularjs/legacy/angular-mocks-1.2-tests.ts +++ b/angularjs/legacy/angular-mocks-1.2-tests.ts @@ -1,4 +1,4 @@ -/// + /////////////////////////////////////// // IAngularStatic diff --git a/angularjs/legacy/angular-mocks-1.2.d.ts b/angularjs/legacy/angular-mocks-1.2.d.ts index 2a1ce25196..3b4f7e0405 100644 --- a/angularjs/legacy/angular-mocks-1.2.d.ts +++ b/angularjs/legacy/angular-mocks-1.2.d.ts @@ -3,7 +3,7 @@ // Definitions by: Diego Vilar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + /////////////////////////////////////////////////////////////////////////////// // functions attached to global object (window) diff --git a/angularjs/legacy/angular-resource-1.0.d.ts b/angularjs/legacy/angular-resource-1.0.d.ts index 07f5f7e0ff..88ea0adcd8 100644 --- a/angularjs/legacy/angular-resource-1.0.d.ts +++ b/angularjs/legacy/angular-resource-1.0.d.ts @@ -3,7 +3,7 @@ // Definitions by: Diego Vilar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + /////////////////////////////////////////////////////////////////////////////// diff --git a/angularjs/legacy/angular-resource-1.2-tests.ts b/angularjs/legacy/angular-resource-1.2-tests.ts index ca970f5c40..f79b4752d3 100644 --- a/angularjs/legacy/angular-resource-1.2-tests.ts +++ b/angularjs/legacy/angular-resource-1.2-tests.ts @@ -1,4 +1,4 @@ -/// + interface IMyResource extends ng.resource.IResource { }; interface IMyResourceClass extends ng.resource.IResourceClass { }; diff --git a/angularjs/legacy/angular-resource-1.2.d.ts b/angularjs/legacy/angular-resource-1.2.d.ts index b0ccb5e7e6..5270037426 100644 --- a/angularjs/legacy/angular-resource-1.2.d.ts +++ b/angularjs/legacy/angular-resource-1.2.d.ts @@ -3,7 +3,7 @@ // Definitions by: Diego Vilar , Michael Jess // Definitions: https://github.com/daptiv/DefinitelyTyped -/// + /////////////////////////////////////////////////////////////////////////////// diff --git a/angularjs/legacy/angular-resource-1.3.d.ts b/angularjs/legacy/angular-resource-1.3.d.ts index 798bc0a581..7390570991 100644 --- a/angularjs/legacy/angular-resource-1.3.d.ts +++ b/angularjs/legacy/angular-resource-1.3.d.ts @@ -3,7 +3,7 @@ // Definitions by: Diego Vilar , Michael Jess // Definitions: https://github.com/daptiv/DefinitelyTyped -/// + declare module 'angular-resource' { var _: string; diff --git a/angularjs/legacy/angular-route-1.2-tests.ts b/angularjs/legacy/angular-route-1.2-tests.ts index 0b82110ef2..d076c148c2 100644 --- a/angularjs/legacy/angular-route-1.2-tests.ts +++ b/angularjs/legacy/angular-route-1.2-tests.ts @@ -1,4 +1,4 @@ -/// + /** * @license HTTP Auth Interceptor Module for AngularJS diff --git a/angularjs/legacy/angular-route-1.2.d.ts b/angularjs/legacy/angular-route-1.2.d.ts index 9c1dd4aa25..29b57a39b4 100644 --- a/angularjs/legacy/angular-route-1.2.d.ts +++ b/angularjs/legacy/angular-route-1.2.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jonathan Park // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + /////////////////////////////////////////////////////////////////////////////// diff --git a/angularjs/legacy/angular-sanitize-1.0.d.ts b/angularjs/legacy/angular-sanitize-1.0.d.ts index 510a7bc82b..e883621105 100644 --- a/angularjs/legacy/angular-sanitize-1.0.d.ts +++ b/angularjs/legacy/angular-sanitize-1.0.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + /////////////////////////////////////////////////////////////////////////////// // ngSanitize module (angular-sanitize.js) diff --git a/angularjs/legacy/angular-sanitize-1.2-tests.ts b/angularjs/legacy/angular-sanitize-1.2-tests.ts index 853bbf3495..94bb6615ec 100644 --- a/angularjs/legacy/angular-sanitize-1.2-tests.ts +++ b/angularjs/legacy/angular-sanitize-1.2-tests.ts @@ -1,4 +1,4 @@ -/// + var shouldBeString: string; diff --git a/angularjs/legacy/angular-sanitize-1.2.d.ts b/angularjs/legacy/angular-sanitize-1.2.d.ts index cbd559688a..88c3eec39e 100644 --- a/angularjs/legacy/angular-sanitize-1.2.d.ts +++ b/angularjs/legacy/angular-sanitize-1.2.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + /////////////////////////////////////////////////////////////////////////////// // ngSanitize module (angular-sanitize.js) diff --git a/angularjs/legacy/angular-scenario-1.0.d.ts.tscparams b/angularjs/legacy/angular-scenario-1.0.d.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/angularjs/legacy/angular-scenario-1.0.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/angularjs/legacy/angular-scenario-1.2.d.ts b/angularjs/legacy/angular-scenario-1.2.d.ts index 75490855bf..5dfa36fc5f 100644 --- a/angularjs/legacy/angular-scenario-1.2.d.ts +++ b/angularjs/legacy/angular-scenario-1.2.d.ts @@ -3,7 +3,7 @@ // Definitions by: RomanoLindano // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace ng { export interface IAngularStatic { diff --git a/angularjs/tsconfig.json b/angularjs/tsconfig.json new file mode 100644 index 0000000000..8653344dce --- /dev/null +++ b/angularjs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "files": [ + "index.d.ts", + "angular-mocks-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/angulartics/angulartics-tests.ts b/angulartics/angulartics-tests.ts index f5a7190bd6..36ad8f46cf 100644 --- a/angulartics/angulartics-tests.ts +++ b/angulartics/angulartics-tests.ts @@ -1,5 +1,5 @@ -/// -/// + +/// namespace Analytics { angular.module("angulartics.app", ["angulartics"]) diff --git a/angulartics/angulartics.d.ts b/angulartics/angulartics.d.ts deleted file mode 100644 index 8714e1a903..0000000000 --- a/angulartics/angulartics.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Type definitions for Angulartics v0.20.2 -// Project: http://luisfarzati.github.io/angulartics/ -// Definitions by: Steven Fan -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -declare namespace angulartics { - - interface IAngularticsStatic { - waitForVendorApi(objectName:string, delay:number, containsField?:any, registerFn?:any, onTimeout?:boolean): void; - } - - interface IAnalyticsService { - eventTrack(eventName: string, properties?: any): any; - pageTrack(path:string, location?:angular.ILocationService): any; - setAlias(alias: string): any; - setUsername(username: string): any; - setUserProperties(properties: any): any; - setSuperProperties(properties: any): any; - } - - interface IAnalyticsServiceProvider extends angular.IServiceProvider { - virtualPageviews(value: boolean): void; - excludeRoutes(value: string[]): void; - firstPageview(value: boolean): void; - withBase(value: boolean): void; - withAutoBase(value: boolean): void; - developerMode(value: boolean): void; - - registerPageTrack(callback:(path:string, location?:angular.ILocationService) => any): void; - registerEventTrack(callback: (eventName: string, properties?: any) => any): void; - registerSetAlias(callback: (alias: string) => any): void - registerSetUsername(callback: (username: string) => any): void - registerSetUserProperties(callback: (userProperties: any) => any): void - registerSetSuperProperties(callback: (superProperties: any) => any): void - - settings: { - pageTracking: { - autoTrackingVirtualPages: boolean, - autoTrackingFirstPage: boolean, - basePath: string, - autoBasePath: boolean - }, - developerMode: boolean - } - } -} - -declare var angulartics:angulartics.IAngularticsStatic; diff --git a/angulartics/index.d.ts b/angulartics/index.d.ts new file mode 100644 index 0000000000..28976019f1 --- /dev/null +++ b/angulartics/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for Angulartics v0.20.2 +// Project: http://luisfarzati.github.io/angulartics/ +// Definitions by: Steven Fan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +declare namespace angulartics { + + interface IAngularticsStatic { + waitForVendorApi(objectName:string, delay:number, containsField?:any, registerFn?:any, onTimeout?:boolean): void; + } + + interface IAnalyticsService { + eventTrack(eventName: string, properties?: any): any; + pageTrack(path:string, location?:angular.ILocationService): any; + setAlias(alias: string): any; + setUsername(username: string): any; + setUserProperties(properties: any): any; + setSuperProperties(properties: any): any; + } + + interface IAnalyticsServiceProvider extends angular.IServiceProvider { + virtualPageviews(value: boolean): void; + excludeRoutes(value: string[]): void; + firstPageview(value: boolean): void; + withBase(value: boolean): void; + withAutoBase(value: boolean): void; + developerMode(value: boolean): void; + + registerPageTrack(callback:(path:string, location?:angular.ILocationService) => any): void; + registerEventTrack(callback: (eventName: string, properties?: any) => any): void; + registerSetAlias(callback: (alias: string) => any): void + registerSetUsername(callback: (username: string) => any): void + registerSetUserProperties(callback: (userProperties: any) => any): void + registerSetSuperProperties(callback: (superProperties: any) => any): void + + settings: { + pageTracking: { + autoTrackingVirtualPages: boolean, + autoTrackingFirstPage: boolean, + basePath: string, + autoBasePath: boolean + }, + developerMode: boolean + } + } +} + +declare var angulartics:angulartics.IAngularticsStatic; diff --git a/angulartics/tsconfig.json b/angulartics/tsconfig.json new file mode 100644 index 0000000000..48e13b9a7a --- /dev/null +++ b/angulartics/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angulartics-tests.ts" + ] +} \ No newline at end of file diff --git a/animation-frame/animation-frame-tests.ts b/animation-frame/animation-frame-tests.ts index f7b1648303..2e0486f6ab 100644 --- a/animation-frame/animation-frame-tests.ts +++ b/animation-frame/animation-frame-tests.ts @@ -1,4 +1,3 @@ -/// namespace AnimationFrameTests { var animation = new AnimationFrame(); function frame() { diff --git a/animation-frame/animation-frame.d.ts b/animation-frame/index.d.ts similarity index 100% rename from animation-frame/animation-frame.d.ts rename to animation-frame/index.d.ts diff --git a/animation-frame/tsconfig.json b/animation-frame/tsconfig.json new file mode 100644 index 0000000000..0ca71ed844 --- /dev/null +++ b/animation-frame/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "animation-frame-tests.ts" + ] +} \ No newline at end of file diff --git a/ansi-styles/ansi-styles-tests.ts b/ansi-styles/ansi-styles-tests.ts index dc3187ef5b..235f98dce1 100644 --- a/ansi-styles/ansi-styles-tests.ts +++ b/ansi-styles/ansi-styles-tests.ts @@ -1,4 +1,3 @@ -/// import ansi = require('ansi-styles'); diff --git a/ansi-styles/ansi-styles.d.ts b/ansi-styles/ansi-styles.d.ts deleted file mode 100644 index e5c01c6a5a..0000000000 --- a/ansi-styles/ansi-styles.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -// Type definitions for ansi-styles 2.0.1 -// Project: https://github.com/sindresorhus/ansi-styles -// Definitions by: bryn austin bellomy -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -declare module "ansi-styles" -{ - export interface EscapeCodePair { - open: string; - close: string; - } - - export var reset: EscapeCodePair; - - export var bold: EscapeCodePair; - export var dim: EscapeCodePair; - export var italic: EscapeCodePair; - export var underline: EscapeCodePair; - export var inverse: EscapeCodePair; - export var hidden: EscapeCodePair; - export var strikethrough: EscapeCodePair; - - export var black: EscapeCodePair; - export var red: EscapeCodePair; - export var green: EscapeCodePair; - export var yellow: EscapeCodePair; - export var blue: EscapeCodePair; - export var magenta: EscapeCodePair; - export var cyan: EscapeCodePair; - export var white: EscapeCodePair; - export var gray: EscapeCodePair; - - export var bgBlack: EscapeCodePair; - export var bgRed: EscapeCodePair; - export var bgGreen: EscapeCodePair; - export var bgYellow: EscapeCodePair; - export var bgBlue: EscapeCodePair; - export var bgMagenta: EscapeCodePair; - export var bgCyan: EscapeCodePair; - export var bgWhite: EscapeCodePair; -} \ No newline at end of file diff --git a/ansi-styles/index.d.ts b/ansi-styles/index.d.ts new file mode 100644 index 0000000000..4522ece77a --- /dev/null +++ b/ansi-styles/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for ansi-styles 2.0.1 +// Project: https://github.com/sindresorhus/ansi-styles +// Definitions by: bryn austin bellomy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + +export interface EscapeCodePair { + open: string; + close: string; +} + +export declare var reset: EscapeCodePair; + +export declare var bold: EscapeCodePair; +export declare var dim: EscapeCodePair; +export declare var italic: EscapeCodePair; +export declare var underline: EscapeCodePair; +export declare var inverse: EscapeCodePair; +export declare var hidden: EscapeCodePair; +export declare var strikethrough: EscapeCodePair; + +export declare var black: EscapeCodePair; +export declare var red: EscapeCodePair; +export declare var green: EscapeCodePair; +export declare var yellow: EscapeCodePair; +export declare var blue: EscapeCodePair; +export declare var magenta: EscapeCodePair; +export declare var cyan: EscapeCodePair; +export declare var white: EscapeCodePair; +export declare var gray: EscapeCodePair; + +export declare var bgBlack: EscapeCodePair; +export declare var bgRed: EscapeCodePair; +export declare var bgGreen: EscapeCodePair; +export declare var bgYellow: EscapeCodePair; +export declare var bgBlue: EscapeCodePair; +export declare var bgMagenta: EscapeCodePair; +export declare var bgCyan: EscapeCodePair; +export declare var bgWhite: EscapeCodePair; diff --git a/ansi-styles/tsconfig.json b/ansi-styles/tsconfig.json new file mode 100644 index 0000000000..a633f70d76 --- /dev/null +++ b/ansi-styles/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "ansi-styles-tests.ts" + ] +} \ No newline at end of file diff --git a/ansicolors/ansicolors.d.ts b/ansicolors/ansicolors.d.ts deleted file mode 100644 index 2bbfcafc6e..0000000000 --- a/ansicolors/ansicolors.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Type definitions for ansicolors -// Project: https://github.com/thlorenz/ansicolors -// Definitions by: rogierschouten -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "ansicolors" { - var colors: {[index: string]: (s: string) => string;}; - export = colors; -} diff --git a/ansicolors/index.d.ts b/ansicolors/index.d.ts new file mode 100644 index 0000000000..6750283895 --- /dev/null +++ b/ansicolors/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for ansicolors +// Project: https://github.com/thlorenz/ansicolors +// Definitions by: rogierschouten +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare var colors: { [index: string]: (s: string) => string; }; +export = colors; diff --git a/ansicolors/tsconfig.json b/ansicolors/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/ansicolors/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/antd/antd-tests.tsx b/antd/antd-tests.tsx index 6655862723..142ca6ccdd 100644 --- a/antd/antd-tests.tsx +++ b/antd/antd-tests.tsx @@ -1,6 +1,4 @@ -/// -/// -import React = __React +/// /*import { Affix, Button, diff --git a/antd/antd.d.ts b/antd/antd.d.ts deleted file mode 100644 index 62288af91b..0000000000 --- a/antd/antd.d.ts +++ /dev/null @@ -1,2085 +0,0 @@ -// Type definitions for Antd v0.12.10 -// Project: http://ant.design -// Definitions by: bang88 , Bruce Mitchener -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -/// -declare namespace Antd { - - import React = __React - - // Affix - interface AffixProps { - /** - * 达到指定偏移量后触发 - */ - offset?: number - } - /** - * # Affix - * 将页面元素钉在可视范围。 - * ## 何时使用 - * 当内容区域比较长,需要滚动页面时,这部分内容对应的操作或者导航需要在滚动范围内始终展现。常用于侧边菜单和按钮组合。 - * 页面可视范围过小时,慎用此功能以免遮挡页面内容。 - */ - export class Affix extends React.Component { - render(): JSX.Element - } - - - // Alert - interface AlertProps { - /** - * 必选参数,指定警告提示的样式,有四种选择`success`、`info`、`warn`、`error` - */ - type: string, - /**可选参数,默认不显示关闭按钮 */ - closable?: boolean, - /**可选参数,自定义关闭按钮 */ - closeText?: React.ReactNode, - /**必选参数,警告提示内容 */ - message: React.ReactNode, - /**可选参数,警告提示的辅助性文字介绍 */ - description?: React.ReactNode, - /**可选参数,关闭时触发的回调函数 */ - onClose?: Function, - /**可选参数,是否显示辅助图标 */ - showIcon?: boolean - } - - - /** - * # Alert - * 警告提示,展现需要关注的信息。 - - * ## 何时使用 - - * - 当某个页面需要向用户显示警告的信息时。 - * - 非浮层的静态展现形式,始终展现,不会自动消失,用户可以点击关闭。 - * */ - export class Alert extends React.Component { - render(): JSX.Element - } - - - // Badge - /** - * #Badge - * - * 图标右上角的圆形徽标数字。 - - * ## 何时使用 - - * 一般出现在通知图标或头像的右上角,用于显示需要处理的消息条数,通过醒目视觉形式吸引用户处理。 - * - */ - export class Badge extends React.Component { - render(): JSX.Element - } - interface BadgeProps { - /** 展示的数字,大于 overflowCount 时显示为 `${overflowCount}+`,为 0 时隐藏*/ - count: number, - /** 展示封顶的数字值*/ - overflowCount?: number, - /** 不展示数字,只有一个小红点*/ - dot?: boolean - } - - - // Button - interface ButtonProps { - /** 设置按钮类型,可选值为 `primary` `ghost` 或者不设 */ - type?: ButtonType | string, - /** 设置按钮形状,可选值为 `circle` `circle-outline` 或者不设*/ - shape?: string, - /** 设置按钮大小,可选值为 `small` `large` 或者不设*/ - size?: string, - /** 设置 `button` 原生的 `type` 值,可选值请参考 HTML标准*/ - htmlType?: string, - /** `click` 事件的 handler*/ - onClick?: Function, - /** 设置按钮载入状态*/ - loading?: boolean, - /** 样式名*/ - className?: string, - } - - - enum ButtonType { - primary, - ghost, - dashed - } - - interface ButtonGroupProps { - /** 设置按钮大小,可选值为 `small` `large` 或者不设*/ - size?: string - - } - - /** - 可以将多个 `Button` 放入 `Button.Group` 的容器中。 - - 通过设置 `size` 为 `large` `small` 分别把按钮组合设为大、小尺寸。若不设置 `size`,则尺寸为中。*/ - class ButtonGroup extends React.Component { - render(): JSX.Element - } - - /** - * #Button - 按钮用于开始一个即时操作。 - - ## 何时使用 - - 标记了一个(或封装一组)操作命令,响应用户点击行为,触发相应的业务逻辑。*/ - export class Button extends React.Component { - static Group: typeof ButtonGroup - render(): JSX.Element - } - - - - // Breadcrumb - - interface BreadcrumbItemProps { - /** 链接,如不传则不可点击 */ - href?: string - } - export class BreadcrumbItem extends React.Component { - render(): JSX.Element - } - - interface BreadcrumbProps { - /** router 的路由栈信息 */ - routes?: Array, - /** 路由的参数*/ - params?: Object, - /** 分隔符自定义*/ - separator?: string | React.ReactNode - } - /** - * #Breadcrumb - 显示当前页面在系统层级结构中的位置,并能向上返回。 - - ## 何时使用 - - - 当系统拥有超过两级以上的层级结构时; - - 当需要告知用户“你在哪里”时; - - 当需要向上导航的功能时。*/ - export class Breadcrumb extends React.Component { - static Item: typeof BreadcrumbItem - render(): JSX.Element - } - - - // Calendar - interface CalendarProps { - /** 自定义渲染月单元格*/ - monthCellRender?: Function, - /** 自定义渲染日期单元格*/ - dateCellRender?: Function, - /** 是否全屏显示*/ - fullscreen?: boolean, - /** 国际化配置*/ - locale?: Object, - prefixCls?: string, - className?: string, - style?: Object, - /** 日期面板变化回调*/ - onPanelChange?: Function, - /** 展示日期*/ - value?: Date, - /** 默认展示日期*/ - defaultValue?: Date, - /** 初始模式,`month/year`*/ - mode?: string - } - /** - * #Calendar - 按照日历形式展示数据的容器。 - - ## 何时使用 - - 当数据是日期或按照日期划分时,例如日程、课表、价格日历等,农历等。目前支持年/月切换。 - */ - export class Calendar extends React.Component { - render(): JSX.Element - } - - - // Carousel - interface CarouselProps { - /** 动画效果函数,可取 scrollx, fade*/ - effect?: string, - /** 是否显示面板指示点*/ - dots?: boolean, - /** 垂直显示*/ - vertical?: boolean, - /** 是否自动切换*/ - autoplay?: boolean, - /** 动画效果*/ - easing?: string, - /** 切换面板的回调*/ - beforeChange?: Function, - /** 切换面板的回调*/ - afterChange?: Function - } - /** - * #Carousel - 旋转木马,一组轮播的区域。 - - ## 何时使用 - - - 当有一组平级的内容。 - - 当内容空间不足时,可以用走马灯的形式进行收纳,进行轮播展现。 - - 常用于一组图片或卡片轮播。 - */ - export class Carousel extends React.Component { - render(): JSX.Element - } - - - - // Cascader - interface CascaderProps { - /** 可选项数据源*/ - options: Object, - /** 默认的选中项*/ - defaultValue?: Array, - /** 指定选中项*/ - value?: Array, - /** 选择完成后的回调*/ - onChange?: Function, - /** 选择后展示的渲染函数*/ - displayRender?: Function, - /** 自定义样式*/ - style?: Object, - /** 自定义类名*/ - className?: string, - /** 自定义浮层类名*/ - popupClassName?: string, - /** 浮层预设位置:`bottomLeft` `bottomRight` `topLeft` `topRight` */ - popupPlacement?: string, - /** 输入框占位文本*/ - placeholder?: string, - /** 输入框大小,可选 `large` `default` `small` */ - size?: string, - /** 禁用*/ - disabled?: boolean, - /** 是否支持清除*/ - allowClear?: boolean - - } - /** - * #Cascader - 级联选择框。 - - - ## 何时使用 - - - 需要从一组相关联的数据集合进行选择,例如省市区,公司层级,事物分类等。 - - 从一个较大的数据集合中进行选择时,用多级分类进行分隔,方便选择。 - - 比起 Select 组件,可以在同一个浮层中完成选择,有较好的体验。*/ - export class Cascader extends React.Component { - render(): JSX.Element - } - - - - - // Checkbox - interface CheckboxProps { - /** 指定当前是否选中*/ - checked?: boolean, - /** 初始是否选中*/ - defaultChecked?: boolean, - /** 变化时回调函数*/ - onChange?: Function - } - - interface CheckboxGroupProps { - /** 默认选中的选项*/ - defaultValue?: Array, - /** 指定选中的选项*/ - value?: Array, - /** 指定可选项*/ - options?: Array, - /** 变化时回调函数*/ - onChange?: Function - } - /** Checkbox 组*/ - class CheckboxGroup extends React.Component { - render(): JSX.Element - } - /** - * #Checkbox - 多选框。 - - ## 何时使用 - - - 在一组可选项中进行多项选择时; - - 单独使用可以表示两种状态之间的切换,和 `switch` 类似。区别在于切换 `switch` 会直接触发状态改变,而 `checkbox` 一般用于状态标记,需要和提交操作配合。 - */ - export class Checkbox extends React.Component { - static Group: typeof CheckboxGroup - render(): JSX.Element - } - - - - // Collapse - - interface CollapseProps { - /** 当前激活 tab 面板的 key*/ - activeKey?: Array | string, - /** 初始化选中面板的key */ - defaultActiveKey?: Array, - /** 切换面板的回调*/ - onChange?: Function - - } - class CollapsePanel extends React.Component<{ - /** 对应 activeKey */ - key: string, - /** 面板头内容*/ - header: React.ReactNode | string - }, {}> { - render(): JSX.Element - } - /** - * #Collapse - 可以折叠/展开的内容区域。 - - ## 何时使用 - - - 对复杂区域进行分组和隐藏,保持页面的整洁。 - - `手风琴` 是一种特殊的折叠面板,只允许单个内容区域展开。*/ - export class Collapse extends React.Component { - static Panel: typeof CollapsePanel - render(): JSX.Element - } - - - - // DatePicker - interface DatePickerProps { - - value?: string | Date, - defaultValue?: string | Date, - /** 展示的日期格式,配置参考 [GregorianCalendarFormat](https://github.com/yiminghe/gregorian-calendar-format)*/ - format?: string, - /** 不可选择的日期*/ - disabledDate?: Function, - /** 时间发生变化的回调,发生在用户选择时间时*/ - onChange?: Function, - /** 禁用*/ - disabled?: boolean, - style?: Object, - /** 格外的弹出日历样式*/ - popupStyle?: Object, - /** 输入框大小,`large` 高度为 32px,`small` 为 22px,默认是 28px*/ - size?: string, - /** 国际化配置*/ - locale?: Object, - /** 增加时间选择功能*/ - showTime?: boolean, - /** 点击确定按钮的回调*/ - onOk?: Function, - /** 定义浮层的容器,默认为 body 上新建 div*/ - getCalendarContainer?: Function - - } - interface RangePickProps extends DatePickerProps { - - } - class RangePicker extends React.Component { - render(): JSX.Element - } - class MonthPicker extends React.Component { - render(): JSX.Element - } - /** - * #DatePicker - 输入或选择日期的控件。 - - ## 何时使用 - - 当用户需要输入一个日期,可以点击标准输入框,弹出日期面板进行选择。*/ - export class DatePicker extends React.Component, {}> { - static RangePicker: typeof RangePicker - static MonthPicker: typeof MonthPicker - render(): JSX.Element - } - - - - - // Dropdown - - interface DropdownProps { - /** 触发下拉的行为 ['click'] or ['hover']*/ - trigger?: Array, - /** 菜单节点*/ - overlay: React.ReactNode - - } - - class DropdownButton extends React.Component<{ - /** 按钮类型*/ - type?: string, - /** 点击左侧按钮的回调*/ - onClick?: Function, - /** 触发下拉的行为*/ - trigger?: string, - /** 菜单节点*/ - overlay: React.ReactNode - }, {}> { - render(): JSX.Element - } - /** - * #Dropdown - 向下弹出的列表。 - - ## 何时使用 - - 当页面上的操作命令过多时,用此组件可以收纳操作元素。点击或移入触点,会出现一个下拉菜单。可在列表中进行选择,并执行相应的命令。 - */ - export class Dropdown extends React.Component { - static Button: typeof DropdownButton - render(): JSX.Element - } - - - - // Form - - interface FormItemProps { - prefixCls?: string, - /** label 标签的文本*/ - label?: React.ReactNode, - /** label 标签布局,通 `` 组件,设置 `span` `offset` 值,如 `{span: 3, offset: 12}`*/ - labelCol?: Object, - /** 提示信息,如不设置,则会根据校验规则自动生成 */ - help?: React.ReactNode | boolean, - /** 额外的提示信息,和 help 类似,当需要错误信息和提示文案同时出现时,可以使用这个。*/ - extra?: string, - /** 是否必填,如不设置,则会根据校验规则自动生成 */ - validateStatus?: string, - /** 配合 validateStatus 属性使用,是否展示校验状态图标 */ - hasFeedback?: boolean, - /** 需要为输入控件设置布局样式时,使用该属性,用法同 labelCol*/ - wrapperCol?: Object, - className?: string, - required?: boolean, - id?: string - } - /** - 表单一定会包含表单域,表单域可以是输入控件,标准表单域,标签,下拉菜单,文本域等。 - - 这里我们分别封装了表单域 `` 和输入控件 ``。*/ - export class FormItem extends React.Component { - render(): JSX.Element - } - interface FormComponentProps { - form: CreateFormOptions - } - export class FormComponent extends React.Component { - render(): JSX.Element - } - - // function create - type CreateFormOptions = { - /** 获取一组输入控件的值,如不传入参数,则获取全部组件的值*/ - getFieldsValue(): (fieldNames?: Array) => any - /** 获取一个输入控件的值*/ - getFieldValue(): (fieldName: string) => any - /** 设置一组输入控件的值*/ - setFieldsValue(): (obj: Object) => void - /** 设置一组输入控件的值*/ - setFields(): (obj: Object) => void - /** 校验并获取一组输入域的值与 Error*/ - validateFields(): (fieldNames?: Array, options?: Object, callback?: (erros: any, values: any) => void) => any - /** 与 `validateFields` 相似,但校验完后,如果校验不通过的菜单域不在可见范围内,则自动滚动进可见范围 */ - validateFieldsAndScroll(): (fieldNames?: Array, options?: Object, callback?: (erros: any, values: any) => void) => any - /** 获取某个输入控件的 Error */ - getFieldError(): (name: string) => Object - /** 判断一个输入控件是否在校验状态*/ - isFieldValidating(): (name: string) => Object - /**重置一组输入控件的值与状态,如不传入参数,则重置所有组件*/ - resetFields(): (names?: Array) => void - - getFieldsValue(): (id: string, options: { - /** 子节点的值的属性,如 Checkbox 的是 'checked'*/ - valuePropName?: string, - /** 子节点的初始值,类型、可选值均由子节点决定*/ - initialValue?: any, - /** 收集子节点的值的时机*/ - trigger?: string, - /** 校验子节点值的时机*/ - validateTrigger?: string, - /** 校验规则,参见 [async-validator](https://github.com/yiminghe/async-validator) */ - rules?: Array, - /** 必填输入控件唯一标志*/ - id?: string - }) => Array - - - } - - interface ComponentDecorator { - (component: T): T; - } - interface FormProps { - prefixCls?: string, - /** 水平排列布局*/ - horizontal?: boolean, - /** 行内排列布局*/ - inline?: boolean, - /** 经 `Form.create()` 包装过的组件会自带 `this.props.form` 属性,直接传给 Form 即可*/ - form?: Object, - /** 数据验证成功后回调事件*/ - onSubmit?: (e: React.FormEvent) => void, - } - /** - * #Form - 具有数据收集、校验和提交功能的表单,包含复选框、单选框、输入框、下拉选择框等元素。 - - ## 表单 - - 我们为 `form` 提供了以下两种排列方式: - - - 水平排列:可以实现 `label` 标签和表单控件的水平排列; - - 行内排列:使其表现为 `inline-block` 级别的控件。 - */ - export class Form extends React.Component { - static Item: typeof FormItem - static create(options?: { - /** - * 当 `Form.Item` 子节点的值发生改变时触发,可以把对应的值转存到 Redux store - */ - onFieldsChange?: (props: Object, fields: Array) => void, - /** 把 props 转为对应的值,可用于把 Redux store 中的值读出 */ - mapPropsToFields?: (props: Object) => void - }): ComponentDecorator - render(): JSX.Element - } - - - - - - // Icon - interface IconProps { - /** 图标类型*/ - type: string - } - /** - * #Icon - 有含义的矢量图形,每一个图标打倒一个敌人。 - - ## 图标的命名规范 - - 我们为每个图标赋予了语义化的命名,命名规则如下: - - - 实心和描线图标保持同名,用 `-o` 来区分,比如 `question-circle`(实心) 和 `question-circle-o`(描线); - - - 命名顺序:`[icon名]-[形状可选]-[描线与否]-[方向可选]`。 - - ## 如何使用 - - 使用 `` 标签声明组件,指定图标对应的 type 属性,示例代码如下: - - ```html - - ``` - - 最终会渲染为: - - ```html - - ```*/ - export class Icon extends React.Component { - render(): JSX.Element - } - - - - - // Input - interface InputProps { - /** 【必须】声明 input 类型,同原生 input 标签的 type 属性*/ - type?: string, - id: string | number, - /** 控件大小,默认值为 default 。注:标准表单内的输入框大小限制为 large。 {'large','default','small'}*/ - size?: string, - /** 是否禁用状态,默认为 false*/ - disabled?: boolean, - value?: any, - /** 设置初始默认值*/ - defaultValue?: any, - className?: string, - /** 带标签的 input,设置前置标签*/ - addonBefore?: React.ReactNode, - /** 带标签的 input,设置后置标签*/ - addonAfter?: React.ReactNode, - prefixCls?: string, - placeholder?: string - } - export class Input extends React.Component { - render(): JSX.Element - } - - - - - // InputNumber - interface InputNumberProps { - /** 最小值*/ - min: number, - /** 最大值*/ - max: number, - /** 当前值*/ - value?: number, - /** 每次改变步数*/ - step?: number, - /** 初始值*/ - defaultValue?: number, - /** 变化回调*/ - onChange?: Function, - /** 禁用*/ - disabled?: boolean, - /** 输入框大小*/ - size?: string - - } - /** - * #InputNumber - 通过鼠标或键盘,输入范围内的数值。 - - ## 何时使用 - - 当需要获取标准数值时。*/ - export class InputNumber extends React.Component { - render(): JSX.Element - } - - - // Layout - // Row - interface RowProps { - type?: string, - align?: string, - justify?: string, - className?: string - } - export class Row extends React.Component { - render(): JSX.Element - } - - // Col - interface ColProps { - span?: string, - order?: string, - offset?: string, - push?: string, - pull?: string, - className?: string - } - /** - 在多数业务情况下,Ant Design需要在设计区域内解决大量信息收纳的问题,因此在12栅格系统的基础上,我们将整个设计建议区域按照24等分的原则进行划分。 - - 划分之后的信息区块我们称之为“盒子”。建议横向排列的盒子数量最多四个,最少一个。“盒子”在整个屏幕上占比见上图。设计部分基于盒子的单位定制盒子内部的排版规则,以保证视觉层面的舒适感。 - - ## 概述 - - 布局的栅格化系统,我们是基于行(row)和列(col)来定义信息区块的外部框架,以保证页面的每个区域能够稳健地排布起来。下面简单介绍一下它的工作原理: - - * 通过`row`在水平方向建立一组`column`(简写col) - * 你的内容应当放置于`col`内,并且,只有`col`可以作为`row`的直接元素 - * 栅格系统中的列是指1到24的值来表示其跨越的范围。例如,三个等宽的列可以使用`.col-8`来创建 - * 如果一个`row`中的`col`总和超过24,那么多余的`col`会作为一个整体另起一行排列 - - ## Flex 布局 - - 我们的栅格化系统支持 Flex 布局,允许子元素在父节点内的水平对齐方式 - 居左、居中、居右、等宽排列、分散排列。子元素与子元素之间,支持顶部对齐、垂直居中对齐、底部对齐的方式。同时,支持使用 order 来定义元素的排列顺序。 - - Flex 布局是基于 24 栅格来定义每一个“盒子”的宽度,但排版则不拘泥于栅格。*/ - export class Col extends React.Component { - render(): JSX.Element - } - - - - - // Menu - interface MenuItemProps { - /** - * (是否禁用) - * - * @type {boolean} - */ - disabled?: boolean, - key: string - } - export class MenuItem extends React.Component { - render(): JSX.Element - } - - interface MenuSubMenuProps { - /** - * (子菜单项值) - * - * @type {(string | React.ReactNode)} - */ - title: string | React.ReactNode, - /** - * (子菜单的菜单项) - * - * @type {(MenuItem | MenuSubMenu)} - */ - children?: JSX.Element[] - } - export class MenuSubMenu extends React.Component { - render(): JSX.Element - } - - interface MenuItemGroupProps { - /** - * (分组标题) - * - * @type {(string | React.ReactNode)} - */ - title: string | React.ReactNode, - /** - * (分组的菜单项) - * - * @type {MenuItem} - */ - children?: JSX.Element[] - } - export class MenuItemGroup extends React.Component { - render(): JSX.Element - } - - - // enum - enum MenuTheme { - light, - dark - } - enum MenuMode { - vertical, - horizontal, - inline - } - interface MenuProps { - /** 主题颜色*/ - theme?: MenuTheme | string, - /** 菜单类型 enum: `vertical` `horizontal` `inline`*/ - mode?: MenuMode | string, - /** 当前选中的菜单项 key 数组*/ - selectedKeys?: Array, - /** 初始选中的菜单项 key 数组*/ - defaultSelectedKeys?: Array, - /** 当前展开的菜单项 key 数组*/ - openKeys?: Array, - /** 初始展开的菜单项 key 数组*/ - defaultOpenKeys?: Array, - /** - * 被选中时调用 - * - * @type {(item: any, key: string, selectedKeys: Array) => void} - */ - onSelect?: (item: any, key: string, selectedKeys: Array) => void, - /** 取消选中时调用*/ - onDeselect?: (item: any, key: string, selectedKeys: Array) => void, - /** 点击 menuitem 调用此函数*/ - onClick?: (item: any, key: string) => void, - /** 根节点样式*/ - style?: Object - } - /** - # Menu - 为页面和功能提供导航的菜单列表。 - - ## 何时使用 - - 导航菜单是一个网站的灵魂,用户依赖导航在各个页面中进行跳转。一般分为顶部导航和侧边导航,顶部导航提供全局性的类目和功能,侧边导航提供多级结构来收纳和排列网站架构。 - - 更多布局和导航的范例可以参考:[常用布局](/spec/layout)。*/ - export class Menu extends React.Component { - static Item: typeof MenuItem - static SubMenu: typeof MenuSubMenu - static ItemGroup: typeof MenuItemGroup - static Divider: typeof React.Component - render(): JSX.Element - } - - - - // Message - type MessageFunc = ( - /** 提示内容*/ - content: string, - /** 自动关闭的延时*/ - duration?: number - ) => void - /** - * #Message - 全局展示操作反馈信息。 - - ## 何时使用 - - - 可提供成功、警告和错误等反馈信息。 - - 顶部居中显示并自动消失,是一种不打断用户操作的轻量级提示方式。*/ - export const message: { - - success: MessageFunc - error: MessageFunc - info: MessageFunc - loading: MessageFunc - config: (options: { - /** - * 消息距离顶部的位置 - * - * @type {number} - */ - top: number - }) => void - destroy: () => void - } - - // Modal - type ModalFunc = (options: { - visible?: boolean, - title?: React.ReactNode | string, - onOk?: Function, - onCancel?: Function, - width?: string | number, - iconClassName?: string, - okText?: string, - cancelText?: string - }) => void - - interface ModalProps { - /** 对话框是否可见*/ - visible?: boolean, - /** 确定按钮 loading*/ - confirmLoading?: boolean, - /** 标题*/ - title?: React.ReactNode | string, - /** 是否显示右上角的关闭按钮*/ - closable?: boolean, - /** 点击确定回调*/ - onOk?: Function, - /** 点击遮罩层或右上角叉或取消按钮的回调*/ - onCancel?: Function, - /** 宽度*/ - width?: string | number, - /** 底部内容*/ - footer?: React.ReactNode | string, - /** 确认按钮文字*/ - okText?: string, - /** 取消按钮文字*/ - cancelText?: string, - /** 点击蒙层是否允许关闭*/ - maskClosable?: boolean - } - - /** - # Modal - 模态对话框。 - - ## 何时使用 - - 需要用户处理事务,又不希望跳转页面以致打断工作流程时,可以使用 `Modal` 在当前页面正中打开一个浮层,承载相应的操作。 - - 另外当需要一个简洁的确认框询问用户时,可以使用精心封装好的 `ant.Modal.confirm()` 等方法。*/ - export class Modal extends React.Component { - static info: ModalFunc - static success: ModalFunc - static error: ModalFunc - static confirm: ModalFunc - render(): JSX.Element - } - - - - - // Notification - type NotificationFunc = ( - config: { - /** 通知提醒标题,必选 */ - message: React.ReactNode | string, - /** 通知提醒内容,必选*/ - description: React.ReactNode | string, - /** 自定义关闭按钮*/ - btn?: React.ReactNode | string, - /** 当前通知唯一标志*/ - key?: string, - /** 点击默认关闭按钮时触发的回调函数*/ - onClose?: Function, - /** 默认 4.5 秒后自动关闭,配置为 null 则不自动关闭*/ - duration?: number - }) => void - /** - * #notification - 全局展示通知提醒信息。 - - ## 何时使用 - - 在系统右上角显示通知提醒信息。经常用于以下情况: - - - 较为复杂的通知内容。 - - 带有交互的通知,给出用户下一步的行动点。 - - 系统主动推送。*/ - export const notification: { - success: NotificationFunc - error: NotificationFunc - info: NotificationFunc - warn: NotificationFunc - close: (key: string) => void - destroy: () => void - config: (options: { - /** 消息距离顶部的位置*/ - top: number - }) => void - - } - - - - - // Pagination - interface PaginationProps { - /** 当前页数*/ - current?: number, - /** 默认的当前页数*/ - defaultCurrent?: number, - /** 数据总数*/ - total: number, - /** 初始的每页条数*/ - defaultPageSize?: number, - /** 每页条数*/ - pageSize?: number, - /** 页码改变的回调,参数是改变后的页码*/ - onChange?: Function, - /** 是否可以改变 pageSize */ - showSizeChanger?: boolean, - /** 指定每页可以显示多少条*/ - pageSizeOptions?: Array - /** pageSize 变化的回调 */ - onShowSizeChange?: Function, - /** 是否可以快速跳转至某页*/ - showQuickJumper?: boolean, - /** 当为「small」时,是小尺寸分页 */ - size?: string, - /** 当添加该属性时,显示为简单分页*/ - simple?: Object, - /** 用于显示总共有多少条数据*/ - showTotal?: Function - } - /** - * #Pagination - 采用分页的形式分隔长列表,每次只加载一个页面。 - - ## 何时使用 - - - 当加载/渲染所有数据将花费很多时间时; - - 可切换页码浏览数据。*/ - export class Pagination extends React.Component { - render(): JSX.Element - } - - - - - // Popconfirm - enum Placement { - top, left, right, bottom - } - interface PopconfirmProps { - /** - * 气泡框位置,可选 `top/left/right/bottom` - * - * @type {(Placement | string)} - */ - placement?: Placement | string, - /** 确认框的描述*/ - title?: string, - /** 点击确认的回调*/ - onConfirm?: Function, - onCancel?: Function, - /** 显示隐藏的回调*/ - onVisibleChange?: (visible: boolean) => void, - /** 确认按钮文字*/ - okText?: string, - /** 取消按钮文字*/ - cancelText?: string - } - /** - * #Popconfirm - 点击元素,弹出气泡式的确认框。 - - ## 何时使用 - - 目标元素的操作需要用户进一步的确认时,在目标元素附近弹出浮层提示,询问用户。 - - 和 `confirm` 弹出的全屏居中模态对话框相比,交互形式更轻量。 - */ - export class Popconfirm extends React.Component { - render(): JSX.Element - } - - - - - // Popover - enum Trigger { - hover, focus, click - } - enum PopoverPlacement { - top, - left, right, bottom, - topLeft, topRight, bottomLeft, bottomRight, - leftTop, leftBottom, rightTop, rightBottom - } - interface PopoverProps { - /** 触发行为,可选 `hover/focus/click` */ - trigger?: Trigger | string, - /** 气泡框位置,可选 `top/left/right/bottom` `topLeft/topRight/bottomLeft/bottomRight` `leftTop/leftBottom/rightTop/rightBottom`*/ - placement?: PopoverPlacement | string, - /** 卡片标题*/ - title?: React.ReactNode | string, - /** 卡片内容*/ - overlay?: React.ReactNode | string, - prefixCls?: string, - /** 用于手动控制浮层显隐*/ - visible?: boolean, - /** 显示隐藏改变的回调*/ - onVisibleChange?: Function - } - /** - * #Popover - 点击/鼠标移入元素,弹出气泡式的卡片浮层。 - - ## 何时使用 - - 当目标元素有进一步的描述和相关操作时,可以收纳到卡片中,根据用户的操作行为进行展现。 - - 和 `Tooltip` 的区别是,用户可以对浮层上的元素进行操作,因此它可以承载更复杂的内容,比如链接或按钮等。 - */ - export class Popover extends React.Component { - render(): JSX.Element - } - - - - - // Progress - enum ProgressStatus { - normal, - exception, - active - } - - interface LineProps { - /** 百分比*/ - percent: number, - /** 内容的模板函数*/ - format?: (percent: any) => void, - /** 状态,可选:normal、exception、active*/ - status?: ProgressStatus | string, - /** 进度条线的宽度,单位是px*/ - strokeWidth?: number, - /** 是否显示进度数值和状态图标*/ - showInfo?: boolean - } - export class Line extends React.Component { - render(): JSX.Element - } - - interface CircleProps { - /** 百分比*/ - percent: number, - /** 内容的模板函数*/ - format?: (percent: any) => void, - /** 状态,可选:normal、exception*/ - status?: ProgressStatus | string, - /** 进度条线的宽度,单位是进度条画布宽度的百分比*/ - strokeWidth?: number, - /** 必填,进度条画布宽度,单位px。这里没有提供height属性设置,Line型高度就是strokeWidth,Circle型高度等于width*/ - width?: number - } - export class Circle extends React.Component { - render(): JSX.Element - } - /** - * #Progress - 展示操作的当前进度。 - - ## 何时使用 - - 在操作需要较长时间才能完成时,为用户显示该操作的当前进度和状态。 - - * 当一个操作会打断当前界面,或者需要在后台运行,且耗时可能超过2秒时; - * 当需要显示一个操作完成的百分比时。*/ - export const Progress: { - Line: typeof Line, - Circle: typeof Circle - } - - - // QueueAnim - interface QueueAnimProps { - /** 动画内置参数 `left` `right` `top` `bottom` `scale` `scaleBig` `scaleX` `scaleY`*/ - type?: string | Array, - /** 配置动画参数 如 `{opacity:[1, 0],translateY:[0, -30]}` 具体参考 [velocity](http://julian.com/research/velocity) 的写法*/ - animConfig?: Object | Array, - /** 整个动画的延时,以毫秒为单位*/ - delay?: number | Array, - /** 每个动画的时间,以毫秒为单位*/ - duration?: number | Array, - /** 每个动画的间隔时间,以毫秒为单位*/ - interval?: number | Array, - /** 出场时是否倒放,从最后一个 dom 开始往上播放 */ - leaveReverse?: boolean, - /** 动画的缓动函数,[查看详细](http://julian.com/research/velocity/#easing)*/ - ease?: string | Array, - /** 进出场动画进行中的类名*/ - animatingClassName?: Array, - /** QueueAnim 替换的标签名*/ - component?: string - } - /** - * #QueueAnim - 通过简单的配置对一组元素添加串行的进场动画效果。 - - ## 何时使用 - - - 从内容A到内容B的转变过程时能有效的吸引用户注意力,突出视觉中心,提高整体视觉效果。 - - - 小的信息元素排布或块状较多的情况下,根据一定的路径层次依次进场,区分维度层级,来凸显量级,使页面转场更加流畅和舒适,提高整体视觉效果和产品的质感。 - - - 特别适合首页和需要视觉展示效果的宣传页,以及单页应用的切换页面动效。 - */ - export class QueueAnim extends React.Component { - render(): JSX.Element - } - - - - - // Radio - enum RadioGroupSize { - large, - default, - small - } - interface RadioGroupProps { - /** 选项变化时的回调函数*/ - onChange?: (e: Event) => void, - /** 用于设置当前选中的值*/ - value?: string, - /** 默认选中的值*/ - defaultValue?: string, - /** 大小,只对按钮样式生效*/ - size?: RadioGroupSize | string - } - export class RadioGroup extends React.Component { - render(): JSX.Element - } - - - interface RadioProps { - /** 指定当前是否选中*/ - checked?: boolean, - /** 初始是否选中*/ - defaultChecked?: boolean, - /** 根据 value 进行比较,判断是否选中 */ - value?: any - } - /** - * #Radio - 单选框。 - - ## 何时使用 - - - 用于在多个备选项中选中单个状态。 - - 和 Select 的区别是,Radio 所有选项默认可见,方便用户在比较中选择,因此选项不宜过多。 - */ - export class Radio extends React.Component { - static Group: typeof RadioGroup - static Button: typeof Button - render(): JSX.Element - } - - - - // Select - interface SelectOptionProps { - /** 是否禁用*/ - disabled?: boolean, - /** 如果 react 需要你设置此项,此项值与 value 的值相同,然后可以省略 value 设置*/ - key?: string, - /** 默认根据此属性值进行筛选*/ - value: string - } - export class SelectOption extends React.Component { - render(): JSX.Element - } - - interface SelectOptGroupProps { - /** 组名*/ - label: string | React.ReactNode, - key?: string - } - export class SelectOptGroup extends React.Component { - render(): JSX.Element - } - - interface SelectProps { - /** 指定当前选中的条目*/ - value?: string | Array, - /** 指定默认选中的条目*/ - defaultValue?: string | Array, - /** 支持多选*/ - multiple?: boolean, - /** 支持清除, 单选模式有效*/ - allowClear?: boolean, - /** 是否根据输入项进行筛选,可为一个函数,返回满足要求的 option 即可*/ - filterOption?: boolean | Function, - /** 可以把随意输入的条目作为 tag,输入项不需要与下拉选项匹配*/ - tags?: boolean, - /** 被选中时调用,参数为选中项的 value 值 */ - onSelect?: (value: any, option: any) => void, - /** 取消选中时调用,参数为选中项的 option value 值,仅在 multiple 或 tags 模式下生效*/ - onDeselect?: (value: any, option: any) => void, - /** 选中option,或input的value变化(combobox 模式下)时,调用此函数*/ - onChange?: (value: any, label: any) => void, - /** 文本框值变化时回调*/ - onSearch?: (value: string) => void, - /** 选择框默认文字*/ - placeholder?: string, - /** 搜索框默认文字*/ - searchPlaceholder?: string, - /** 当下拉列表为空时显示的内容*/ - notFoundContent?: string, - /** 下拉菜单和选择器同宽*/ - dropdownMatchSelectWidth?: boolean, - /** 搜索时过滤对应的 option 属性,如设置为 children 表示对内嵌内容进行搜索*/ - optionFilterProp?: string, - /** 输入框自动提示模式*/ - combobox?: SVGSymbolElement, - /** 选择框大小,可选 `large` `small` */ - size?: string, - /** 在下拉中显示搜索框*/ - showSearch?: boolean, - /** 是否禁用*/ - disabled?: boolean, - style?: Object - } - /** - * #Select - 类似 Select2 的选择器。 - - ## 何时使用 - - 弹出一个下拉菜单给用户选择操作,用于代替原生的选择器,或者需要一个更优雅的多选器时。*/ - export class Select extends React.Component { - static Option: typeof SelectOption - static OptGroup: typeof SelectOptGroup - render(): JSX.Element - } - - - - // Slider - interface SliderProps { - /** 最小值*/ - min?: number, - /** 最大值*/ - max?: number, - /** 步长,取值必须大于 0,并且可被 (max - min) 整除。当 `marks` 不为空对象时,可以设置 `step` 为 `null`,此时 Slider 的可选值仅有 marks 标出来的部分。*/ - step?: number, - /** 分段标记,key 的类型必须为 `Number` 且取值在闭区间 [min, max] 内*/ - marks?: { key: number, value: any }, - /** 设置当前取值。当 `range` 为 `false` 时,使用 `Number`,否则用 `[Number, Number]`*/ - value?: number | Array, - /** 设置当前取值。当 `range` 为 `false` 时,使用 `Number`,否则用 `[Number, Number]`*/ - defaultValue?: number | Array, - /** `marks` 不为空对象时有效,值为 true 时表示值为包含关系,false 表示并列*/ - included?: boolean, - /** 值为 `true` 时,滑块为禁用状态*/ - disabled?: boolean, - /** 当 `range` 为 `true` 时,该属性可以设置是否允许两个滑块交换位置。*/ - allowCross?: boolean, - /** 当 Slider 的值发生改变时,会触发 onChange 事件,并把改变后的值作为参数传入。*/ - onChange?: Function, - /** 与 `onmouseup` 触发时机一致,把当前值作为参数传入。*/ - onAfterChange?: Function, - /** Slider 会把当前值传给 `tipFormatter`,并在 Tooltip 中显示 `tipFormatter` 的返回值,若为 null,则隐藏 Tooltip。*/ - tipFormatter?: Function | any, - range?: boolean - } - /** - * #Slider - 滑动型输入器,展示当前值和可选范围。 - - ## 何时使用 - - 当用户需要在数值区间/自定义区间内进行选择时,可为连续或离散值。*/ - export class Slider extends React.Component { - render(): JSX.Element - } - - - - - // Spin - interface SpinProps { - /** spin组件中点的大小,可选值为 small default large*/ - size?: string, - /** 用于内嵌其他组件的模式,可以关闭 loading 效果*/ - spining?: boolean - } - /** - * #Spin - 用于页面和区块的加载中状态。 - - ## 何时使用 - - 页面局部处于等待异步数据或正在渲染过程时,合适的加载动效会有效缓解用户的焦虑。 - */ - export class Spin extends React.Component { - render(): JSX.Element - } - - - - - // Steps - enum StepStatus { - wait, process, finish - } - interface StepProps { - /** 可选参数,指定状态。当不配置该属性时,会使用父Steps元素的current来自动指定状态。*/ - status?: StepStatus | string, - /** 必要参数,标题。*/ - title: string | React.ReactNode, - /** 可选参数,步骤的详情描述。*/ - description?: string | React.ReactNode, - /** 可选参数,步骤的Icon。如果不指定,则使用默认的样式。*/ - icon?: string | React.ReactNode - } - export class Step extends React.Component { - render(): JSX.Element - } - - interface StepsProps { - /** 可选参数,指定当前处理正在执行状态的步骤,从0开始记数。在子Step元素中,可以通过status属性覆盖状态。*/ - current?: number, - /** 可选参数,指定大小(目前只支持普通和迷你两种大小)。 small, default */ - size?: string, - /** 可选参数,指定步骤条方向(目前支持水平和竖直两种方向,默认水平方向)。*/ - direction?: string, - /** 可选参数,指定步骤的详细描述文字的最大宽度。*/ - maxDescriptionWidth?: number - - } - /** - * #Steps - 引导用户按照流程完成任务的导航条。 - - ## 何时使用 - - 当任务复杂或者存在先后关系时,将其分解成一系列步骤,从而简化任务。*/ - export class Steps extends React.Component { - static Step: typeof Step - render(): JSX.Element - } - - - - // Switch - interface SwitchProps { - /** 指定当前是否选中*/ - checked?: boolean, - /** 初始是否选中*/ - defaultChecked?: boolean, - /** 变化时回调函数*/ - onChange?: (checked: boolean) => void, - /** 选中时的内容*/ - checkedChildren?: React.ReactNode, - /** 非选中时的内容*/ - unCheckedChildren?: React.ReactNode, - /** 开关大小*/ - size?: string - } - /** - * #Switch - 开关选择器。 - - ## 何时使用 - - - 需要表示开关状态/两种状态之间的切换时; - - 和 `checkbox `的区别是,切换 `switch` 会直接触发状态改变,而 `checkbox` 一般用于状态标记,需要和提交操作配合。 - */ - export class Switch extends React.Component { - render(): JSX.Element - } - - - - - // Table - enum RowSelectionType { - checkbox, - radio - } - type SelectedRowKeys = Array - interface RowSelection { - type?: RowSelectionType | string, - selectedRowKeys?: SelectedRowKeys, - onChange?: (selectedRowKeys: SelectedRowKeys, selectedRows: any) => void, - getCheckboxProps?: (record: any) => void, - onSelect?: (record: any, selected: any, selectedRows: any) => void, - onSelectAll?: (rselectedecord: any, selectedRows: any, changeRows: any) => void - } - interface Columns { - /** React 需要的 key,建议设置*/ - key?: string, - /** 列头显示文字*/ - title?: string | React.ReactNode, - /** 列数据在数据项中对应的 key*/ - dataIndex?: string, - /** 生成复杂数据的渲染函数,参数分别为当前列的值,当前列数据,列索引,@return里面可以设置表格[行/列合并](#demo-colspan-rowspan)*/ - render?: (text?: any, record?: any, index?: number) => React.ReactNode, - /** 表头的筛选菜单项*/ - filters?: Array, - /** 本地模式下,确定筛选的运行函数*/ - onFilter?: Function, - /** 是否多选*/ - filterMultiple?: boolean, - /** 排序函数,本地排序使用一个函数,需要服务端排序可设为 true */ - sorter?: boolean | Function, - /** 表头列合并,设置为 0 时,不渲染*/ - colSpan?: number, - /** 列宽度*/ - width?: string | number, - /** 列的 className*/ - className?: string - } - interface TableProps { - /** 列表项是否可选择*/ - rowSelection?: RowSelection, - /** 分页器*/ - pagination?: Object, - /** 正常或迷你类型 : `default` or `small` */ - size?: string, - /** 数据数组*/ - dataSource: Array, - /** 表格列的配置描述*/ - columns: Columns, - /** 表格行 key 的取值*/ - rowKey?: (record: any, index: number) => string, - /** 额外的展开行*/ - expandedRowRender?: Function, - /** 默认展开的行*/ - defaultExpandedRowKeys?: Array, - /** 分页、排序、筛选变化时触发*/ - onChange?: (pagination: Object, filters: any, sorter: any) => void, - /** 页面是否加载中*/ - loading?: boolean, - /** 默认文案设置,目前包括排序、过滤、空数据文案: `{ filterConfirm: '确定', filterReset: '重置', emptyText: '暂无数据' }` */ - locale?: Object, - /** 展示树形数据时,每层缩进的宽度,以 px 为单位*/ - indentSize?: number, - /** 处理行点击事件*/ - onRowClick?: (record: any, index: number) => void, - /** 是否固定表头*/ - useFixedHeader?: boolean, - /** 是否展示外边框和列边框*/ - bordered?: boolean, - /** 是否显示表头*/ - showHeader?: boolean, - /** 表格底部自定义渲染函数*/ - footer?: (currentPageData: Object) => void - - } - /** - * #Table - 展示行列数据。 - - ## 何时使用 - - - 当有大量结构化的数据需要展现时; - - 当需要对数据进行排序、搜索、分页、自定义操作等复杂行为时。*/ - export class Table extends React.Component { - render(): JSX.Element - } - - - - // Tabs - interface TabPaneProps { - /** 选项卡头显示文字*/ - tab: React.ReactNode | string - } - export class TabPane extends React.Component { - render(): JSX.Element - } - - enum TabsType { - line, card, 'editable-card' - } - enum TabsPosition { - top, - right, - bottom, - left - } - interface TabsProps { - /** 当前激活 tab 面板的 key */ - activeKey?: string, - /** 初始化选中面板的 key,如果没有设置 activeKey*/ - defaultActiveKey?: string, - /** 切换面板的回调*/ - onChange?: Function, - /** tab 被点击的回调 */ - onTabClick?: Function, - /** tab bar 上额外的元素 */ - tabBarExtraContent?: React.ReactNode, - /** 页签的基本样式,可选 `line`、`card` `editable-card` 类型*/ - type?: TabsType | string, - /** 页签位置,可选值有 `top` `right` `bottom` `left`*/ - tabPosition?: TabsPosition | string, - /** 新增和删除页签的回调,在 `type="editable-card"` 时有效*/ - onEdit?: (targetKey: string, action: any) => void - } - /** - * #Tabs - 选项卡切换组件。 - - ## 何时使用 - - 提供平级的区域将大块内容进行收纳和展现,保持界面整洁。 - - Ant Design 依次提供了三级选项卡,分别用于不同的场景。 - - - 卡片式的页签,提供可关闭的样式,常用于容器顶部。 - - 标准线条式页签,用于容器内部的主功能切换,这是最常用的 Tabs。 - - [RadioButton](/components/radio/#demo-radiobutton) 可作为更次级的页签来使用。*/ - export class Tabs extends React.Component { - static TabPane: typeof TabPane - render(): JSX.Element - } - - - - - // Tag - interface TagProps { - /** 标签是否可以关闭*/ - closable?: boolean, - /** 关闭时的回调*/ - onClose?: Function, - /** 动画关闭后的回调*/ - afterClose?: Function, - /** 标签的色彩*/ - color?: string - } - /** - * #Tag - 进行标记和分类的小标签。 - - ## 何时使用 - - - 用于标记事物的属性和维度。 - - 进行分类。*/ - export class Tag extends React.Component { - render(): JSX.Element - } - - - - - - - // TimePicker - interface TimePickerProps { - /** 默认时间*/ - value?: string | Date, - /** 初始默认时间*/ - defaultValue?: string | Date, - /** 展示的时间格式 : "HH:mm:ss"、"HH:mm"、"mm:ss" */ - format?: string, - /** 时间发生变化的回调*/ - onChange?: (Date: Date) => void, - /** 禁用全部操作*/ - disabled?: boolean, - /** 没有值的时候显示的内容*/ - placeholder?: string, - /** 国际化配置*/ - locale?: Object, - /** 隐藏禁止选择的选项*/ - hideDisabledOptions?: boolean, - /** 禁止选择部分小时选项*/ - disabledHours?: Function, - /** 禁止选择部分分钟选项*/ - disabledMinutes?: Function, - /** 禁止选择部分秒选项*/ - disabledSeconds?: Function - - } - /** - * #TimePicker - 输入或选择时间的控件。 - - 何时使用 - -------- - - 当用户需要输入一个时间,可以点击标准输入框,弹出时间面板进行选择。 - */ - export class TimePicker extends React.Component { - render(): JSX.Element - } - - - - - // Timeline - interface TimeLineItemProps { - /** 指定圆圈颜色。*/ - color?: string - } - export class TimeLineItem extends React.Component { - render(): JSX.Element - } - - interface TimelineProps { - /** 指定最后一个幽灵节点是否存在或内容*/ - pending?: boolean | React.ReactNode - } - /** - * #Timeline - 垂直展示的时间流信息。 - - ## 何时使用 - - - 当有一系列信息需要从上至下按时间排列时; - - 需要有一条时间轴进行视觉上的串联时;*/ - export class Timeline extends React.Component { - static Item: typeof TimeLineItem - render(): JSX.Element - } - - - - // Tooltip - - interface TooltipProps { - /** 气泡框位置,可选 `top` `left` `right` `bottom` `topLeft` `topRight` `bottomLeft` `bottomRight` `leftTop` `leftBottom` `rightTop` `rightBottom`*/ - placement?: PopoverPlacement | string, - /** 提示文字*/ - title?: string | React.ReactNode - } - /** - * #Tooltip - 简单的文字提示气泡框。 - - ## 何时使用 - - 鼠标移入则显示提示,移出消失,气泡浮层不承载复杂文本和操作。 - - 可用来代替系统默认的 `title` 提示,提供一个`按钮/文字/操作`的文案解释。*/ - export class Tooltip extends React.Component { - render(): JSX.Element - } - - - - - - // Transfer - interface TransferProps { - /** 数据源*/ - dataSource: Array, - /** 每行数据渲染函数*/ - render?: (record: Object) => any, - /** 显示在右侧框数据的key集合*/ - targetKeys: Array, - /** 变化时回调函数*/ - onChange?: (targetKeys: any, direction: string, moveKeys: any) => void, - /** 两个穿梭框的自定义样式*/ - listStyle?: Object, - /** 自定义类*/ - className?: string, - /** 标题集合,顺序从左至右*/ - titles?: Array, - /** 操作文案集合,顺序从上至下*/ - operations?: Array, - /** 是否显示搜索框*/ - showSearch?: boolean, - /** 搜索框的默认值*/ - searchPlaceholder?: string, - /** 当列表为空时显示的内容*/ - notFoundContent?: React.ReactNode | string - /** 底部渲染函数*/ - footer?: (props: any) => any - } - /** - * #Transfer - 双栏穿梭选择框。 - - ## 何时使用 - - 用直观的方式在两栏中移动元素,完成选择行为。 - */ - export class Transfer extends React.Component { - render(): JSX.Element - } - - - - - - // Tree - interface TreeNodeProps { - disabled?: boolean, - disableCheckbox?: boolean, - title?: string | React.ReactNode, - key?: string, - isLeaf?: boolean - } - export class TreeNode extends React.Component { - render(): JSX.Element - } - - interface TreeProps { - showLine?: boolean, - className?: string, - /** 是否支持多选*/ - multiple?: boolean, - /** 是否支持选中*/ - checkable?: boolean, - /** 默认展开所有树节点*/ - defaultExpandAll?: boolean, - /** 默认展开指定的树节点*/ - defaultExpandedKeys?: Array, - /** (受控)展开指定的树节点*/ - expandedKeys?: Array, - /** (受控)选中复选框的树节点*/ - checkedKeys?: Array, - /** 默认选中复选框的树节点*/ - defaultCheckedKeys?: Array, - /** (受控)设置选中的树节点*/ - selectedKeys?: Array, - /** 默认选中的树节点*/ - defaultSelectedKeys?: Array, - /** 展开/收起节点时触发 */ - onExpand?: (node: any, expanded: any, expandedKeys: any) => void, - /** 点击复选框触发*/ - onCheck?: (checkedKeys: any, e: { checked: boolean, checkedNodes: any, node: any, event: Event }) => void, - /** 点击树节点触发*/ - onSelect?: (selectedKeys: any, e: { selected: boolean, selectedNodes: any, node: any, event: Event }) => void, - /** filter some treeNodes as you need. it should return true */ - filterTreeNode?: (node: any) => boolean, - /** 异步加载数据*/ - loadData?: (node: any) => void, - /** 响应右键点击*/ - onRightClick?: (options: { event: Event, node: any }) => void, - /** 设置节点可拖拽(IE>8)*/ - draggable?: boolean, - /** 开始拖拽时调用*/ - onDragStart?: (options: { event: Event, node: any }) => void, - /** dragenter 触发时调用*/ - onDragEnter?: (options: { event: Event, node: any, expandedKeys: any }) => void, - /** dragover 触发时调用 */ - onDragOver?: (options: { event: Event, node: any }) => void, - /** dragleave 触发时调用*/ - onDragLeave?: (options: { event: Event, node: any }) => void, - /** drop 触发时调用*/ - onDrop?: (options: { event: Event, node: any, dragNode: any, dragNodesKeys: any }) => void, - } - /** - * #Tree - * 文件夹、组织架构、生物分类、国家地区等等,世间万物的大多数结构都是树形结构。使用`树控件`可以完整展现其中的层级关系,并具有展开收起选择等交互功能。 - */ - export class Tree extends React.Component { - static TreeNode: typeof TreeNode - render(): JSX.Element - } - - - - - - // TreeSelect - interface TreeSelectTreeNodeProps { - disabled?: boolean, - /** 此项必须设置(其值在整个树范围内唯一)*/ - key: string, - /** 默认根据此属性值进行筛选*/ - value?: string, - /** 树节点显示的内容*/ - title?: React.ReactNode | string, - /** 是否是叶子节点*/ - isLeaf?: boolean - } - export class TreeSelectTreeNode extends React.Component { - render(): JSX.Element - } - - type TreeData = Array<{ value: any, label: string, children: TreeData }> - interface TreeSelectProps { - style?: Object, - /** 指定当前选中的条目*/ - value?: string | Array, - /** 指定默认选中的条目*/ - defaultValue?: string | Array, - /** 支持多选*/ - multiple?: boolean, - /** 可以把随意输入的条目作为 tag,输入项不需要与下拉选项匹配*/ - tags?: boolean, - /** 被选中时调用,参数为选中项的 value 值*/ - onSelect?: (value: any) => void, - /** 选中option,或input的value变化(combobox 模式下)时,调用此函数*/ - onChange?: (value: any, label: any) => void, - /** 显示清除按钮*/ - allowClear?: boolean, - /** 文本框值变化时回调*/ - onSearch?: (value: any) => void, - /** 选择框默认文字*/ - placeholder?: string, - /** 搜索框默认文字*/ - searchPlaceholder?: string, - /** 下拉菜单的样式*/ - dropdownStyle?: Object, - /** 下拉菜单和选择器同宽*/ - dropdownMatchSelectWidth?: boolean, - /** 输入框自动提示模式*/ - combobox?: boolean, - /** 选择框大小,可选 `large` `small`*/ - size?: string, - /** 在下拉中显示搜索框*/ - showSearch?: boolean, - /** 是否禁用*/ - disabled?: boolean, - /** 默认展开所有树节点*/ - treeDefaultExpandAll?: boolean, - /** 显示checkbox*/ - treeCheckable?: boolean, - /** 是否根据输入项进行筛选,返回值true*/ - filterTreeNode?: (treeNode: any) => boolean, - /** 输入项过滤对应的 treeNode 属性*/ - treeNodeFilterProp?: string, - /** 作为显示的prop设置*/ - treeNodeLabelProp?: string, - /** treeNodes数据,如果设置则不需要手动构造TreeNode节点(如果value在整个树范围内不唯一,需要设置`key`其值为整个树范围内的唯一id*/ - treeData?: TreeData, - /** 异步加载数据*/ - loadData?: (node: any) => void - } - /** - * #TreeSelect - 树型选择控件。 - - ## 何时使用 - - 类似 Select 的选择控件,可选择的数据结构是一个树形结构时,可以使用 TreeSelect,例如公司层级、学科系统、分类目录等等。 - */ - export class TreeSelect extends React.Component { - static TreeNode: typeof TreeSelectTreeNode - render(): JSX.Element - } - - - - - - - // Upload - interface UploadProps { - /** 可选参数, 上传的文件 */ - name?: string, - /** 必选参数, 上传的地址 */ - action: string, - /** 可选参数, 上传所需参数 */ - data?: Object, - /** 可选参数, 设置上传的请求头部,IE10 以上有效*/ - headers?: Object, - /** 可选参数, 是否展示 uploadList, 默认开启 */ - showUploadList?: boolean, - /** 可选参数, 是否支持多选文件,`ie10+` 支持。开启后按住 ctrl 可选择多个文件。*/ - multiple?: boolean, - /** 可选参数, 接受上传的文件类型, 详见 input accept Attribute */ - accept?: string, - /** 可选参数, 上传文件之前的钩子,参数为上传的文件,若返回 `false` 或者 Promise 则停止上传。**注意:该方法不支持老 IE**。*/ - beforeUpload?: Function, - /** 可选参数, 上传文件改变时的状态,详见 onChange */ - onChange?: (info: Object) => void, - /** 上传列表的内建样式,支持两种基本样式 `text` or `picture` */ - listType?: string, - /** 自定义类名*/ - className?: string - - } - /** - * #Upload - 文件选择上传和拖拽上传控件。 - - ## 何时使用 - - 上传是将信息(网页、文字、图片、视频等)通过网页或者上传工具发布到远程服务器上的过程。 - - - 当需要上传一个或一些文件时。 - - 当需要展现上传的进度时。 - - 当需要使用拖拽交互时。*/ - export class Upload extends React.Component { - render(): JSX.Element - } - - - - - - -} - - -// export all antd -declare module 'antd' { - export = Antd -} -// single export point -declare module 'antd/lib/Affix' { - export default Antd.Affix -} -declare module 'antd/lib/Button' { - export default Antd.Button -} -declare module 'antd/lib/Alert' { - export default Antd.Alert -} -declare module 'antd/lib/Badge' { - export default Antd.Badge -} -declare module 'antd/lib/Breadcrumb' { - export default Antd.Breadcrumb -} -declare module 'antd/lib/Calendar' { - export default Antd.Calendar -} -declare module 'antd/lib/Carousel' { - export default Antd.Carousel -} -declare module 'antd/lib/Cascader' { - export default Antd.Cascader -} -declare module 'antd/lib/Checkbox' { - export default Antd.Checkbox -} -declare module 'antd/lib/Collapse' { - export default Antd.Collapse -} -declare module 'antd/lib/DatePicker' { - export default Antd.DatePicker -} -declare module 'antd/lib/Dropdown' { - export default Antd.Dropdown -} -declare module 'antd/lib/Icon' { - export default Antd.Icon -} -declare module 'antd/lib/Form' { - export default Antd.Form -} -declare module 'antd/lib/Input' { - export default Antd.Input -} -declare module 'antd/lib/InputNumber' { - export default Antd.InputNumber -} -declare module 'antd/lib/Row' { - export default Antd.Row -} -declare module 'antd/lib/Col' { - export default Antd.Col -} -declare module 'antd/lib/Menu' { - export default Antd.Menu -} -declare module 'antd/lib/message' { - export default Antd.message -} -declare module 'antd/lib/Modal' { - export default Antd.Modal -} -declare module 'antd/lib/notification' { - export default Antd.notification -} -declare module 'antd/lib/Pagination' { - export default Antd.Pagination -} -declare module 'antd/lib/Popconfirm' { - export default Antd.Popconfirm -} -declare module 'antd/lib/Popover' { - export default Antd.Popover -} -declare module 'antd/lib/Progress' { - export default Antd.Progress -} -declare module 'antd/lib/QueueAnim' { - export default Antd.QueueAnim -} -declare module 'antd/lib/Radio' { - export default Antd.Radio -} -declare module 'antd/lib/Select' { - export default Antd.Select -} -declare module 'antd/lib/Slider' { - export default Antd.Slider -} -declare module 'antd/lib/Spin' { - export default Antd.Spin -} -declare module 'antd/lib/Steps' { - export default Antd.Steps -} -declare module 'antd/lib/Switch' { - export default Antd.Switch -} -declare module 'antd/lib/Table' { - export default Antd.Table -} -declare module 'antd/lib/Tabs' { - export default Antd.Tabs -} -declare module 'antd/lib/Tag' { - export default Antd.Tag -} -declare module 'antd/lib/TimePicker' { - export default Antd.TimePicker -} -declare module 'antd/lib/Timeline' { - export default Antd.Timeline -} -declare module 'antd/lib/Tooltip' { - export default Antd.Tooltip -} -declare module 'antd/lib/Transfer' { - export default Antd.Transfer -} -declare module 'antd/lib/Tree' { - export default Antd.Tree -} -declare module 'antd/lib/TreeSelect' { - export default Antd.TreeSelect -} -declare module 'antd/lib/Upload' { - export default Antd.Upload -} diff --git a/antd/index.d.ts b/antd/index.d.ts new file mode 100644 index 0000000000..0f14303a19 --- /dev/null +++ b/antd/index.d.ts @@ -0,0 +1,2082 @@ +// Type definitions for Antd v0.12.10 +// Project: http://ant.design +// Definitions by: bang88 , Bruce Mitchener +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace Antd { + // Affix + interface AffixProps { + /** + * 达到指定偏移量后触发 + */ + offset?: number + } + /** + * # Affix + * 将页面元素钉在可视范围。 + * ## 何时使用 + * 当内容区域比较长,需要滚动页面时,这部分内容对应的操作或者导航需要在滚动范围内始终展现。常用于侧边菜单和按钮组合。 + * 页面可视范围过小时,慎用此功能以免遮挡页面内容。 + */ + export class Affix extends React.Component { + render(): JSX.Element + } + + + // Alert + interface AlertProps { + /** + * 必选参数,指定警告提示的样式,有四种选择`success`、`info`、`warn`、`error` + */ + type: string, + /**可选参数,默认不显示关闭按钮 */ + closable?: boolean, + /**可选参数,自定义关闭按钮 */ + closeText?: React.ReactNode, + /**必选参数,警告提示内容 */ + message: React.ReactNode, + /**可选参数,警告提示的辅助性文字介绍 */ + description?: React.ReactNode, + /**可选参数,关闭时触发的回调函数 */ + onClose?: Function, + /**可选参数,是否显示辅助图标 */ + showIcon?: boolean + } + + + /** + * # Alert + * 警告提示,展现需要关注的信息。 + + * ## 何时使用 + + * - 当某个页面需要向用户显示警告的信息时。 + * - 非浮层的静态展现形式,始终展现,不会自动消失,用户可以点击关闭。 + * */ + export class Alert extends React.Component { + render(): JSX.Element + } + + + // Badge + /** + * #Badge + * + * 图标右上角的圆形徽标数字。 + + * ## 何时使用 + + * 一般出现在通知图标或头像的右上角,用于显示需要处理的消息条数,通过醒目视觉形式吸引用户处理。 + * + */ + export class Badge extends React.Component { + render(): JSX.Element + } + interface BadgeProps { + /** 展示的数字,大于 overflowCount 时显示为 `${overflowCount}+`,为 0 时隐藏*/ + count: number, + /** 展示封顶的数字值*/ + overflowCount?: number, + /** 不展示数字,只有一个小红点*/ + dot?: boolean + } + + + // Button + interface ButtonProps { + /** 设置按钮类型,可选值为 `primary` `ghost` 或者不设 */ + type?: ButtonType | string, + /** 设置按钮形状,可选值为 `circle` `circle-outline` 或者不设*/ + shape?: string, + /** 设置按钮大小,可选值为 `small` `large` 或者不设*/ + size?: string, + /** 设置 `button` 原生的 `type` 值,可选值请参考 HTML标准*/ + htmlType?: string, + /** `click` 事件的 handler*/ + onClick?: Function, + /** 设置按钮载入状态*/ + loading?: boolean, + /** 样式名*/ + className?: string, + } + + + enum ButtonType { + primary, + ghost, + dashed + } + + interface ButtonGroupProps { + /** 设置按钮大小,可选值为 `small` `large` 或者不设*/ + size?: string + + } + + /** + 可以将多个 `Button` 放入 `Button.Group` 的容器中。 + + 通过设置 `size` 为 `large` `small` 分别把按钮组合设为大、小尺寸。若不设置 `size`,则尺寸为中。*/ + class ButtonGroup extends React.Component { + render(): JSX.Element + } + + /** + * #Button + 按钮用于开始一个即时操作。 + + ## 何时使用 + + 标记了一个(或封装一组)操作命令,响应用户点击行为,触发相应的业务逻辑。*/ + export class Button extends React.Component { + static Group: typeof ButtonGroup + render(): JSX.Element + } + + + + // Breadcrumb + + interface BreadcrumbItemProps { + /** 链接,如不传则不可点击 */ + href?: string + } + export class BreadcrumbItem extends React.Component { + render(): JSX.Element + } + + interface BreadcrumbProps { + /** router 的路由栈信息 */ + routes?: Array, + /** 路由的参数*/ + params?: Object, + /** 分隔符自定义*/ + separator?: string | React.ReactNode + } + /** + * #Breadcrumb + 显示当前页面在系统层级结构中的位置,并能向上返回。 + + ## 何时使用 + + - 当系统拥有超过两级以上的层级结构时; + - 当需要告知用户“你在哪里”时; + - 当需要向上导航的功能时。*/ + export class Breadcrumb extends React.Component { + static Item: typeof BreadcrumbItem + render(): JSX.Element + } + + + // Calendar + interface CalendarProps { + /** 自定义渲染月单元格*/ + monthCellRender?: Function, + /** 自定义渲染日期单元格*/ + dateCellRender?: Function, + /** 是否全屏显示*/ + fullscreen?: boolean, + /** 国际化配置*/ + locale?: Object, + prefixCls?: string, + className?: string, + style?: Object, + /** 日期面板变化回调*/ + onPanelChange?: Function, + /** 展示日期*/ + value?: Date, + /** 默认展示日期*/ + defaultValue?: Date, + /** 初始模式,`month/year`*/ + mode?: string + } + /** + * #Calendar + 按照日历形式展示数据的容器。 + + ## 何时使用 + + 当数据是日期或按照日期划分时,例如日程、课表、价格日历等,农历等。目前支持年/月切换。 + */ + export class Calendar extends React.Component { + render(): JSX.Element + } + + + // Carousel + interface CarouselProps { + /** 动画效果函数,可取 scrollx, fade*/ + effect?: string, + /** 是否显示面板指示点*/ + dots?: boolean, + /** 垂直显示*/ + vertical?: boolean, + /** 是否自动切换*/ + autoplay?: boolean, + /** 动画效果*/ + easing?: string, + /** 切换面板的回调*/ + beforeChange?: Function, + /** 切换面板的回调*/ + afterChange?: Function + } + /** + * #Carousel + 旋转木马,一组轮播的区域。 + + ## 何时使用 + + - 当有一组平级的内容。 + - 当内容空间不足时,可以用走马灯的形式进行收纳,进行轮播展现。 + - 常用于一组图片或卡片轮播。 + */ + export class Carousel extends React.Component { + render(): JSX.Element + } + + + + // Cascader + interface CascaderProps { + /** 可选项数据源*/ + options: Object, + /** 默认的选中项*/ + defaultValue?: Array, + /** 指定选中项*/ + value?: Array, + /** 选择完成后的回调*/ + onChange?: Function, + /** 选择后展示的渲染函数*/ + displayRender?: Function, + /** 自定义样式*/ + style?: Object, + /** 自定义类名*/ + className?: string, + /** 自定义浮层类名*/ + popupClassName?: string, + /** 浮层预设位置:`bottomLeft` `bottomRight` `topLeft` `topRight` */ + popupPlacement?: string, + /** 输入框占位文本*/ + placeholder?: string, + /** 输入框大小,可选 `large` `default` `small` */ + size?: string, + /** 禁用*/ + disabled?: boolean, + /** 是否支持清除*/ + allowClear?: boolean + + } + /** + * #Cascader + 级联选择框。 + + + ## 何时使用 + + - 需要从一组相关联的数据集合进行选择,例如省市区,公司层级,事物分类等。 + - 从一个较大的数据集合中进行选择时,用多级分类进行分隔,方便选择。 + - 比起 Select 组件,可以在同一个浮层中完成选择,有较好的体验。*/ + export class Cascader extends React.Component { + render(): JSX.Element + } + + + + + // Checkbox + interface CheckboxProps { + /** 指定当前是否选中*/ + checked?: boolean, + /** 初始是否选中*/ + defaultChecked?: boolean, + /** 变化时回调函数*/ + onChange?: Function + } + + interface CheckboxGroupProps { + /** 默认选中的选项*/ + defaultValue?: Array, + /** 指定选中的选项*/ + value?: Array, + /** 指定可选项*/ + options?: Array, + /** 变化时回调函数*/ + onChange?: Function + } + /** Checkbox 组*/ + class CheckboxGroup extends React.Component { + render(): JSX.Element + } + /** + * #Checkbox + 多选框。 + + ## 何时使用 + + - 在一组可选项中进行多项选择时; + - 单独使用可以表示两种状态之间的切换,和 `switch` 类似。区别在于切换 `switch` 会直接触发状态改变,而 `checkbox` 一般用于状态标记,需要和提交操作配合。 + */ + export class Checkbox extends React.Component { + static Group: typeof CheckboxGroup + render(): JSX.Element + } + + + + // Collapse + + interface CollapseProps { + /** 当前激活 tab 面板的 key*/ + activeKey?: Array | string, + /** 初始化选中面板的key */ + defaultActiveKey?: Array, + /** 切换面板的回调*/ + onChange?: Function + + } + class CollapsePanel extends React.Component<{ + /** 对应 activeKey */ + key: string, + /** 面板头内容*/ + header: React.ReactNode | string + }, {}> { + render(): JSX.Element + } + /** + * #Collapse + 可以折叠/展开的内容区域。 + + ## 何时使用 + + - 对复杂区域进行分组和隐藏,保持页面的整洁。 + - `手风琴` 是一种特殊的折叠面板,只允许单个内容区域展开。*/ + export class Collapse extends React.Component { + static Panel: typeof CollapsePanel + render(): JSX.Element + } + + + + // DatePicker + interface DatePickerProps { + + value?: string | Date, + defaultValue?: string | Date, + /** 展示的日期格式,配置参考 [GregorianCalendarFormat](https://github.com/yiminghe/gregorian-calendar-format)*/ + format?: string, + /** 不可选择的日期*/ + disabledDate?: Function, + /** 时间发生变化的回调,发生在用户选择时间时*/ + onChange?: Function, + /** 禁用*/ + disabled?: boolean, + style?: Object, + /** 格外的弹出日历样式*/ + popupStyle?: Object, + /** 输入框大小,`large` 高度为 32px,`small` 为 22px,默认是 28px*/ + size?: string, + /** 国际化配置*/ + locale?: Object, + /** 增加时间选择功能*/ + showTime?: boolean, + /** 点击确定按钮的回调*/ + onOk?: Function, + /** 定义浮层的容器,默认为 body 上新建 div*/ + getCalendarContainer?: Function + + } + interface RangePickProps extends DatePickerProps { + + } + class RangePicker extends React.Component { + render(): JSX.Element + } + class MonthPicker extends React.Component { + render(): JSX.Element + } + /** + * #DatePicker + 输入或选择日期的控件。 + + ## 何时使用 + + 当用户需要输入一个日期,可以点击标准输入框,弹出日期面板进行选择。*/ + export class DatePicker extends React.Component, {}> { + static RangePicker: typeof RangePicker + static MonthPicker: typeof MonthPicker + render(): JSX.Element + } + + + + + // Dropdown + + interface DropdownProps { + /** 触发下拉的行为 ['click'] or ['hover']*/ + trigger?: Array, + /** 菜单节点*/ + overlay: React.ReactNode + + } + + class DropdownButton extends React.Component<{ + /** 按钮类型*/ + type?: string, + /** 点击左侧按钮的回调*/ + onClick?: Function, + /** 触发下拉的行为*/ + trigger?: string, + /** 菜单节点*/ + overlay: React.ReactNode + }, {}> { + render(): JSX.Element + } + /** + * #Dropdown + 向下弹出的列表。 + + ## 何时使用 + + 当页面上的操作命令过多时,用此组件可以收纳操作元素。点击或移入触点,会出现一个下拉菜单。可在列表中进行选择,并执行相应的命令。 + */ + export class Dropdown extends React.Component { + static Button: typeof DropdownButton + render(): JSX.Element + } + + + + // Form + + interface FormItemProps { + prefixCls?: string, + /** label 标签的文本*/ + label?: React.ReactNode, + /** label 标签布局,通 `` 组件,设置 `span` `offset` 值,如 `{span: 3, offset: 12}`*/ + labelCol?: Object, + /** 提示信息,如不设置,则会根据校验规则自动生成 */ + help?: React.ReactNode | boolean, + /** 额外的提示信息,和 help 类似,当需要错误信息和提示文案同时出现时,可以使用这个。*/ + extra?: string, + /** 是否必填,如不设置,则会根据校验规则自动生成 */ + validateStatus?: string, + /** 配合 validateStatus 属性使用,是否展示校验状态图标 */ + hasFeedback?: boolean, + /** 需要为输入控件设置布局样式时,使用该属性,用法同 labelCol*/ + wrapperCol?: Object, + className?: string, + required?: boolean, + id?: string + } + /** + 表单一定会包含表单域,表单域可以是输入控件,标准表单域,标签,下拉菜单,文本域等。 + + 这里我们分别封装了表单域 `` 和输入控件 ``。*/ + export class FormItem extends React.Component { + render(): JSX.Element + } + interface FormComponentProps { + form: CreateFormOptions + } + export class FormComponent extends React.Component { + render(): JSX.Element + } + + // function create + type CreateFormOptions = { + /** 获取一组输入控件的值,如不传入参数,则获取全部组件的值*/ + getFieldsValue(): (fieldNames?: Array) => any + /** 获取一个输入控件的值*/ + getFieldValue(): (fieldName: string) => any + /** 设置一组输入控件的值*/ + setFieldsValue(): (obj: Object) => void + /** 设置一组输入控件的值*/ + setFields(): (obj: Object) => void + /** 校验并获取一组输入域的值与 Error*/ + validateFields(): (fieldNames?: Array, options?: Object, callback?: (erros: any, values: any) => void) => any + /** 与 `validateFields` 相似,但校验完后,如果校验不通过的菜单域不在可见范围内,则自动滚动进可见范围 */ + validateFieldsAndScroll(): (fieldNames?: Array, options?: Object, callback?: (erros: any, values: any) => void) => any + /** 获取某个输入控件的 Error */ + getFieldError(): (name: string) => Object + /** 判断一个输入控件是否在校验状态*/ + isFieldValidating(): (name: string) => Object + /**重置一组输入控件的值与状态,如不传入参数,则重置所有组件*/ + resetFields(): (names?: Array) => void + + getFieldsValue(): (id: string, options: { + /** 子节点的值的属性,如 Checkbox 的是 'checked'*/ + valuePropName?: string, + /** 子节点的初始值,类型、可选值均由子节点决定*/ + initialValue?: any, + /** 收集子节点的值的时机*/ + trigger?: string, + /** 校验子节点值的时机*/ + validateTrigger?: string, + /** 校验规则,参见 [async-validator](https://github.com/yiminghe/async-validator) */ + rules?: Array, + /** 必填输入控件唯一标志*/ + id?: string + }) => Array + + + } + + interface ComponentDecorator { + (component: T): T; + } + interface FormProps { + prefixCls?: string, + /** 水平排列布局*/ + horizontal?: boolean, + /** 行内排列布局*/ + inline?: boolean, + /** 经 `Form.create()` 包装过的组件会自带 `this.props.form` 属性,直接传给 Form 即可*/ + form?: Object, + /** 数据验证成功后回调事件*/ + onSubmit?: (e: React.FormEvent) => void, + } + /** + * #Form + 具有数据收集、校验和提交功能的表单,包含复选框、单选框、输入框、下拉选择框等元素。 + + ## 表单 + + 我们为 `form` 提供了以下两种排列方式: + + - 水平排列:可以实现 `label` 标签和表单控件的水平排列; + - 行内排列:使其表现为 `inline-block` 级别的控件。 + */ + export class Form extends React.Component { + static Item: typeof FormItem + static create(options?: { + /** + * 当 `Form.Item` 子节点的值发生改变时触发,可以把对应的值转存到 Redux store + */ + onFieldsChange?: (props: Object, fields: Array) => void, + /** 把 props 转为对应的值,可用于把 Redux store 中的值读出 */ + mapPropsToFields?: (props: Object) => void + }): ComponentDecorator + render(): JSX.Element + } + + + + + + // Icon + interface IconProps { + /** 图标类型*/ + type: string + } + /** + * #Icon + 有含义的矢量图形,每一个图标打倒一个敌人。 + + ## 图标的命名规范 + + 我们为每个图标赋予了语义化的命名,命名规则如下: + + - 实心和描线图标保持同名,用 `-o` 来区分,比如 `question-circle`(实心) 和 `question-circle-o`(描线); + + - 命名顺序:`[icon名]-[形状可选]-[描线与否]-[方向可选]`。 + + ## 如何使用 + + 使用 `` 标签声明组件,指定图标对应的 type 属性,示例代码如下: + + ```html + + ``` + + 最终会渲染为: + + ```html + + ```*/ + export class Icon extends React.Component { + render(): JSX.Element + } + + + + + // Input + interface InputProps { + /** 【必须】声明 input 类型,同原生 input 标签的 type 属性*/ + type?: string, + id: string | number, + /** 控件大小,默认值为 default 。注:标准表单内的输入框大小限制为 large。 {'large','default','small'}*/ + size?: string, + /** 是否禁用状态,默认为 false*/ + disabled?: boolean, + value?: any, + /** 设置初始默认值*/ + defaultValue?: any, + className?: string, + /** 带标签的 input,设置前置标签*/ + addonBefore?: React.ReactNode, + /** 带标签的 input,设置后置标签*/ + addonAfter?: React.ReactNode, + prefixCls?: string, + placeholder?: string + } + export class Input extends React.Component { + render(): JSX.Element + } + + + + + // InputNumber + interface InputNumberProps { + /** 最小值*/ + min: number, + /** 最大值*/ + max: number, + /** 当前值*/ + value?: number, + /** 每次改变步数*/ + step?: number, + /** 初始值*/ + defaultValue?: number, + /** 变化回调*/ + onChange?: Function, + /** 禁用*/ + disabled?: boolean, + /** 输入框大小*/ + size?: string + + } + /** + * #InputNumber + 通过鼠标或键盘,输入范围内的数值。 + + ## 何时使用 + + 当需要获取标准数值时。*/ + export class InputNumber extends React.Component { + render(): JSX.Element + } + + + // Layout + // Row + interface RowProps { + type?: string, + align?: string, + justify?: string, + className?: string + } + export class Row extends React.Component { + render(): JSX.Element + } + + // Col + interface ColProps { + span?: string, + order?: string, + offset?: string, + push?: string, + pull?: string, + className?: string + } + /** + 在多数业务情况下,Ant Design需要在设计区域内解决大量信息收纳的问题,因此在12栅格系统的基础上,我们将整个设计建议区域按照24等分的原则进行划分。 + + 划分之后的信息区块我们称之为“盒子”。建议横向排列的盒子数量最多四个,最少一个。“盒子”在整个屏幕上占比见上图。设计部分基于盒子的单位定制盒子内部的排版规则,以保证视觉层面的舒适感。 + + ## 概述 + + 布局的栅格化系统,我们是基于行(row)和列(col)来定义信息区块的外部框架,以保证页面的每个区域能够稳健地排布起来。下面简单介绍一下它的工作原理: + + * 通过`row`在水平方向建立一组`column`(简写col) + * 你的内容应当放置于`col`内,并且,只有`col`可以作为`row`的直接元素 + * 栅格系统中的列是指1到24的值来表示其跨越的范围。例如,三个等宽的列可以使用`.col-8`来创建 + * 如果一个`row`中的`col`总和超过24,那么多余的`col`会作为一个整体另起一行排列 + + ## Flex 布局 + + 我们的栅格化系统支持 Flex 布局,允许子元素在父节点内的水平对齐方式 - 居左、居中、居右、等宽排列、分散排列。子元素与子元素之间,支持顶部对齐、垂直居中对齐、底部对齐的方式。同时,支持使用 order 来定义元素的排列顺序。 + + Flex 布局是基于 24 栅格来定义每一个“盒子”的宽度,但排版则不拘泥于栅格。*/ + export class Col extends React.Component { + render(): JSX.Element + } + + + + + // Menu + interface MenuItemProps { + /** + * (是否禁用) + * + * @type {boolean} + */ + disabled?: boolean, + key: string + } + export class MenuItem extends React.Component { + render(): JSX.Element + } + + interface MenuSubMenuProps { + /** + * (子菜单项值) + * + * @type {(string | React.ReactNode)} + */ + title: string | React.ReactNode, + /** + * (子菜单的菜单项) + * + * @type {(MenuItem | MenuSubMenu)} + */ + children?: JSX.Element[] + } + export class MenuSubMenu extends React.Component { + render(): JSX.Element + } + + interface MenuItemGroupProps { + /** + * (分组标题) + * + * @type {(string | React.ReactNode)} + */ + title: string | React.ReactNode, + /** + * (分组的菜单项) + * + * @type {MenuItem} + */ + children?: JSX.Element[] + } + export class MenuItemGroup extends React.Component { + render(): JSX.Element + } + + + // enum + enum MenuTheme { + light, + dark + } + enum MenuMode { + vertical, + horizontal, + inline + } + interface MenuProps { + /** 主题颜色*/ + theme?: MenuTheme | string, + /** 菜单类型 enum: `vertical` `horizontal` `inline`*/ + mode?: MenuMode | string, + /** 当前选中的菜单项 key 数组*/ + selectedKeys?: Array, + /** 初始选中的菜单项 key 数组*/ + defaultSelectedKeys?: Array, + /** 当前展开的菜单项 key 数组*/ + openKeys?: Array, + /** 初始展开的菜单项 key 数组*/ + defaultOpenKeys?: Array, + /** + * 被选中时调用 + * + * @type {(item: any, key: string, selectedKeys: Array) => void} + */ + onSelect?: (item: any, key: string, selectedKeys: Array) => void, + /** 取消选中时调用*/ + onDeselect?: (item: any, key: string, selectedKeys: Array) => void, + /** 点击 menuitem 调用此函数*/ + onClick?: (item: any, key: string) => void, + /** 根节点样式*/ + style?: Object + } + /** + # Menu + 为页面和功能提供导航的菜单列表。 + + ## 何时使用 + + 导航菜单是一个网站的灵魂,用户依赖导航在各个页面中进行跳转。一般分为顶部导航和侧边导航,顶部导航提供全局性的类目和功能,侧边导航提供多级结构来收纳和排列网站架构。 + + 更多布局和导航的范例可以参考:[常用布局](/spec/layout)。*/ + export class Menu extends React.Component { + static Item: typeof MenuItem + static SubMenu: typeof MenuSubMenu + static ItemGroup: typeof MenuItemGroup + static Divider: typeof React.Component + render(): JSX.Element + } + + + + // Message + type MessageFunc = ( + /** 提示内容*/ + content: string, + /** 自动关闭的延时*/ + duration?: number + ) => void + /** + * #Message + 全局展示操作反馈信息。 + + ## 何时使用 + + - 可提供成功、警告和错误等反馈信息。 + - 顶部居中显示并自动消失,是一种不打断用户操作的轻量级提示方式。*/ + export const message: { + + success: MessageFunc + error: MessageFunc + info: MessageFunc + loading: MessageFunc + config: (options: { + /** + * 消息距离顶部的位置 + * + * @type {number} + */ + top: number + }) => void + destroy: () => void + } + + // Modal + type ModalFunc = (options: { + visible?: boolean, + title?: React.ReactNode | string, + onOk?: Function, + onCancel?: Function, + width?: string | number, + iconClassName?: string, + okText?: string, + cancelText?: string + }) => void + + interface ModalProps { + /** 对话框是否可见*/ + visible?: boolean, + /** 确定按钮 loading*/ + confirmLoading?: boolean, + /** 标题*/ + title?: React.ReactNode | string, + /** 是否显示右上角的关闭按钮*/ + closable?: boolean, + /** 点击确定回调*/ + onOk?: Function, + /** 点击遮罩层或右上角叉或取消按钮的回调*/ + onCancel?: Function, + /** 宽度*/ + width?: string | number, + /** 底部内容*/ + footer?: React.ReactNode | string, + /** 确认按钮文字*/ + okText?: string, + /** 取消按钮文字*/ + cancelText?: string, + /** 点击蒙层是否允许关闭*/ + maskClosable?: boolean + } + + /** + # Modal + 模态对话框。 + + ## 何时使用 + + 需要用户处理事务,又不希望跳转页面以致打断工作流程时,可以使用 `Modal` 在当前页面正中打开一个浮层,承载相应的操作。 + + 另外当需要一个简洁的确认框询问用户时,可以使用精心封装好的 `ant.Modal.confirm()` 等方法。*/ + export class Modal extends React.Component { + static info: ModalFunc + static success: ModalFunc + static error: ModalFunc + static confirm: ModalFunc + render(): JSX.Element + } + + + + + // Notification + type NotificationFunc = ( + config: { + /** 通知提醒标题,必选 */ + message: React.ReactNode | string, + /** 通知提醒内容,必选*/ + description: React.ReactNode | string, + /** 自定义关闭按钮*/ + btn?: React.ReactNode | string, + /** 当前通知唯一标志*/ + key?: string, + /** 点击默认关闭按钮时触发的回调函数*/ + onClose?: Function, + /** 默认 4.5 秒后自动关闭,配置为 null 则不自动关闭*/ + duration?: number + }) => void + /** + * #notification + 全局展示通知提醒信息。 + + ## 何时使用 + + 在系统右上角显示通知提醒信息。经常用于以下情况: + + - 较为复杂的通知内容。 + - 带有交互的通知,给出用户下一步的行动点。 + - 系统主动推送。*/ + export const notification: { + success: NotificationFunc + error: NotificationFunc + info: NotificationFunc + warn: NotificationFunc + close: (key: string) => void + destroy: () => void + config: (options: { + /** 消息距离顶部的位置*/ + top: number + }) => void + + } + + + + + // Pagination + interface PaginationProps { + /** 当前页数*/ + current?: number, + /** 默认的当前页数*/ + defaultCurrent?: number, + /** 数据总数*/ + total: number, + /** 初始的每页条数*/ + defaultPageSize?: number, + /** 每页条数*/ + pageSize?: number, + /** 页码改变的回调,参数是改变后的页码*/ + onChange?: Function, + /** 是否可以改变 pageSize */ + showSizeChanger?: boolean, + /** 指定每页可以显示多少条*/ + pageSizeOptions?: Array + /** pageSize 变化的回调 */ + onShowSizeChange?: Function, + /** 是否可以快速跳转至某页*/ + showQuickJumper?: boolean, + /** 当为「small」时,是小尺寸分页 */ + size?: string, + /** 当添加该属性时,显示为简单分页*/ + simple?: Object, + /** 用于显示总共有多少条数据*/ + showTotal?: Function + } + /** + * #Pagination + 采用分页的形式分隔长列表,每次只加载一个页面。 + + ## 何时使用 + + - 当加载/渲染所有数据将花费很多时间时; + - 可切换页码浏览数据。*/ + export class Pagination extends React.Component { + render(): JSX.Element + } + + + + + // Popconfirm + enum Placement { + top, left, right, bottom + } + interface PopconfirmProps { + /** + * 气泡框位置,可选 `top/left/right/bottom` + * + * @type {(Placement | string)} + */ + placement?: Placement | string, + /** 确认框的描述*/ + title?: string, + /** 点击确认的回调*/ + onConfirm?: Function, + onCancel?: Function, + /** 显示隐藏的回调*/ + onVisibleChange?: (visible: boolean) => void, + /** 确认按钮文字*/ + okText?: string, + /** 取消按钮文字*/ + cancelText?: string + } + /** + * #Popconfirm + 点击元素,弹出气泡式的确认框。 + + ## 何时使用 + + 目标元素的操作需要用户进一步的确认时,在目标元素附近弹出浮层提示,询问用户。 + + 和 `confirm` 弹出的全屏居中模态对话框相比,交互形式更轻量。 + */ + export class Popconfirm extends React.Component { + render(): JSX.Element + } + + + + + // Popover + enum Trigger { + hover, focus, click + } + enum PopoverPlacement { + top, + left, right, bottom, + topLeft, topRight, bottomLeft, bottomRight, + leftTop, leftBottom, rightTop, rightBottom + } + interface PopoverProps { + /** 触发行为,可选 `hover/focus/click` */ + trigger?: Trigger | string, + /** 气泡框位置,可选 `top/left/right/bottom` `topLeft/topRight/bottomLeft/bottomRight` `leftTop/leftBottom/rightTop/rightBottom`*/ + placement?: PopoverPlacement | string, + /** 卡片标题*/ + title?: React.ReactNode | string, + /** 卡片内容*/ + overlay?: React.ReactNode | string, + prefixCls?: string, + /** 用于手动控制浮层显隐*/ + visible?: boolean, + /** 显示隐藏改变的回调*/ + onVisibleChange?: Function + } + /** + * #Popover + 点击/鼠标移入元素,弹出气泡式的卡片浮层。 + + ## 何时使用 + + 当目标元素有进一步的描述和相关操作时,可以收纳到卡片中,根据用户的操作行为进行展现。 + + 和 `Tooltip` 的区别是,用户可以对浮层上的元素进行操作,因此它可以承载更复杂的内容,比如链接或按钮等。 + */ + export class Popover extends React.Component { + render(): JSX.Element + } + + + + + // Progress + enum ProgressStatus { + normal, + exception, + active + } + + interface LineProps { + /** 百分比*/ + percent: number, + /** 内容的模板函数*/ + format?: (percent: any) => void, + /** 状态,可选:normal、exception、active*/ + status?: ProgressStatus | string, + /** 进度条线的宽度,单位是px*/ + strokeWidth?: number, + /** 是否显示进度数值和状态图标*/ + showInfo?: boolean + } + export class Line extends React.Component { + render(): JSX.Element + } + + interface CircleProps { + /** 百分比*/ + percent: number, + /** 内容的模板函数*/ + format?: (percent: any) => void, + /** 状态,可选:normal、exception*/ + status?: ProgressStatus | string, + /** 进度条线的宽度,单位是进度条画布宽度的百分比*/ + strokeWidth?: number, + /** 必填,进度条画布宽度,单位px。这里没有提供height属性设置,Line型高度就是strokeWidth,Circle型高度等于width*/ + width?: number + } + export class Circle extends React.Component { + render(): JSX.Element + } + /** + * #Progress + 展示操作的当前进度。 + + ## 何时使用 + + 在操作需要较长时间才能完成时,为用户显示该操作的当前进度和状态。 + + * 当一个操作会打断当前界面,或者需要在后台运行,且耗时可能超过2秒时; + * 当需要显示一个操作完成的百分比时。*/ + export const Progress: { + Line: typeof Line, + Circle: typeof Circle + } + + + // QueueAnim + interface QueueAnimProps { + /** 动画内置参数 `left` `right` `top` `bottom` `scale` `scaleBig` `scaleX` `scaleY`*/ + type?: string | Array, + /** 配置动画参数 如 `{opacity:[1, 0],translateY:[0, -30]}` 具体参考 [velocity](http://julian.com/research/velocity) 的写法*/ + animConfig?: Object | Array, + /** 整个动画的延时,以毫秒为单位*/ + delay?: number | Array, + /** 每个动画的时间,以毫秒为单位*/ + duration?: number | Array, + /** 每个动画的间隔时间,以毫秒为单位*/ + interval?: number | Array, + /** 出场时是否倒放,从最后一个 dom 开始往上播放 */ + leaveReverse?: boolean, + /** 动画的缓动函数,[查看详细](http://julian.com/research/velocity/#easing)*/ + ease?: string | Array, + /** 进出场动画进行中的类名*/ + animatingClassName?: Array, + /** QueueAnim 替换的标签名*/ + component?: string + } + /** + * #QueueAnim + 通过简单的配置对一组元素添加串行的进场动画效果。 + + ## 何时使用 + + - 从内容A到内容B的转变过程时能有效的吸引用户注意力,突出视觉中心,提高整体视觉效果。 + + - 小的信息元素排布或块状较多的情况下,根据一定的路径层次依次进场,区分维度层级,来凸显量级,使页面转场更加流畅和舒适,提高整体视觉效果和产品的质感。 + + - 特别适合首页和需要视觉展示效果的宣传页,以及单页应用的切换页面动效。 + */ + export class QueueAnim extends React.Component { + render(): JSX.Element + } + + + + + // Radio + enum RadioGroupSize { + large, + default, + small + } + interface RadioGroupProps { + /** 选项变化时的回调函数*/ + onChange?: (e: Event) => void, + /** 用于设置当前选中的值*/ + value?: string, + /** 默认选中的值*/ + defaultValue?: string, + /** 大小,只对按钮样式生效*/ + size?: RadioGroupSize | string + } + export class RadioGroup extends React.Component { + render(): JSX.Element + } + + + interface RadioProps { + /** 指定当前是否选中*/ + checked?: boolean, + /** 初始是否选中*/ + defaultChecked?: boolean, + /** 根据 value 进行比较,判断是否选中 */ + value?: any + } + /** + * #Radio + 单选框。 + + ## 何时使用 + + - 用于在多个备选项中选中单个状态。 + - 和 Select 的区别是,Radio 所有选项默认可见,方便用户在比较中选择,因此选项不宜过多。 + */ + export class Radio extends React.Component { + static Group: typeof RadioGroup + static Button: typeof Button + render(): JSX.Element + } + + + + // Select + interface SelectOptionProps { + /** 是否禁用*/ + disabled?: boolean, + /** 如果 react 需要你设置此项,此项值与 value 的值相同,然后可以省略 value 设置*/ + key?: string, + /** 默认根据此属性值进行筛选*/ + value: string + } + export class SelectOption extends React.Component { + render(): JSX.Element + } + + interface SelectOptGroupProps { + /** 组名*/ + label: string | React.ReactNode, + key?: string + } + export class SelectOptGroup extends React.Component { + render(): JSX.Element + } + + interface SelectProps { + /** 指定当前选中的条目*/ + value?: string | Array, + /** 指定默认选中的条目*/ + defaultValue?: string | Array, + /** 支持多选*/ + multiple?: boolean, + /** 支持清除, 单选模式有效*/ + allowClear?: boolean, + /** 是否根据输入项进行筛选,可为一个函数,返回满足要求的 option 即可*/ + filterOption?: boolean | Function, + /** 可以把随意输入的条目作为 tag,输入项不需要与下拉选项匹配*/ + tags?: boolean, + /** 被选中时调用,参数为选中项的 value 值 */ + onSelect?: (value: any, option: any) => void, + /** 取消选中时调用,参数为选中项的 option value 值,仅在 multiple 或 tags 模式下生效*/ + onDeselect?: (value: any, option: any) => void, + /** 选中option,或input的value变化(combobox 模式下)时,调用此函数*/ + onChange?: (value: any, label: any) => void, + /** 文本框值变化时回调*/ + onSearch?: (value: string) => void, + /** 选择框默认文字*/ + placeholder?: string, + /** 搜索框默认文字*/ + searchPlaceholder?: string, + /** 当下拉列表为空时显示的内容*/ + notFoundContent?: string, + /** 下拉菜单和选择器同宽*/ + dropdownMatchSelectWidth?: boolean, + /** 搜索时过滤对应的 option 属性,如设置为 children 表示对内嵌内容进行搜索*/ + optionFilterProp?: string, + /** 输入框自动提示模式*/ + combobox?: SVGSymbolElement, + /** 选择框大小,可选 `large` `small` */ + size?: string, + /** 在下拉中显示搜索框*/ + showSearch?: boolean, + /** 是否禁用*/ + disabled?: boolean, + style?: Object + } + /** + * #Select + 类似 Select2 的选择器。 + + ## 何时使用 + + 弹出一个下拉菜单给用户选择操作,用于代替原生的选择器,或者需要一个更优雅的多选器时。*/ + export class Select extends React.Component { + static Option: typeof SelectOption + static OptGroup: typeof SelectOptGroup + render(): JSX.Element + } + + + + // Slider + interface SliderProps { + /** 最小值*/ + min?: number, + /** 最大值*/ + max?: number, + /** 步长,取值必须大于 0,并且可被 (max - min) 整除。当 `marks` 不为空对象时,可以设置 `step` 为 `null`,此时 Slider 的可选值仅有 marks 标出来的部分。*/ + step?: number, + /** 分段标记,key 的类型必须为 `Number` 且取值在闭区间 [min, max] 内*/ + marks?: { key: number, value: any }, + /** 设置当前取值。当 `range` 为 `false` 时,使用 `Number`,否则用 `[Number, Number]`*/ + value?: number | Array, + /** 设置当前取值。当 `range` 为 `false` 时,使用 `Number`,否则用 `[Number, Number]`*/ + defaultValue?: number | Array, + /** `marks` 不为空对象时有效,值为 true 时表示值为包含关系,false 表示并列*/ + included?: boolean, + /** 值为 `true` 时,滑块为禁用状态*/ + disabled?: boolean, + /** 当 `range` 为 `true` 时,该属性可以设置是否允许两个滑块交换位置。*/ + allowCross?: boolean, + /** 当 Slider 的值发生改变时,会触发 onChange 事件,并把改变后的值作为参数传入。*/ + onChange?: Function, + /** 与 `onmouseup` 触发时机一致,把当前值作为参数传入。*/ + onAfterChange?: Function, + /** Slider 会把当前值传给 `tipFormatter`,并在 Tooltip 中显示 `tipFormatter` 的返回值,若为 null,则隐藏 Tooltip。*/ + tipFormatter?: Function | any, + range?: boolean + } + /** + * #Slider + 滑动型输入器,展示当前值和可选范围。 + + ## 何时使用 + + 当用户需要在数值区间/自定义区间内进行选择时,可为连续或离散值。*/ + export class Slider extends React.Component { + render(): JSX.Element + } + + + + + // Spin + interface SpinProps { + /** spin组件中点的大小,可选值为 small default large*/ + size?: string, + /** 用于内嵌其他组件的模式,可以关闭 loading 效果*/ + spining?: boolean + } + /** + * #Spin + 用于页面和区块的加载中状态。 + + ## 何时使用 + + 页面局部处于等待异步数据或正在渲染过程时,合适的加载动效会有效缓解用户的焦虑。 + */ + export class Spin extends React.Component { + render(): JSX.Element + } + + + + + // Steps + enum StepStatus { + wait, process, finish + } + interface StepProps { + /** 可选参数,指定状态。当不配置该属性时,会使用父Steps元素的current来自动指定状态。*/ + status?: StepStatus | string, + /** 必要参数,标题。*/ + title: string | React.ReactNode, + /** 可选参数,步骤的详情描述。*/ + description?: string | React.ReactNode, + /** 可选参数,步骤的Icon。如果不指定,则使用默认的样式。*/ + icon?: string | React.ReactNode + } + export class Step extends React.Component { + render(): JSX.Element + } + + interface StepsProps { + /** 可选参数,指定当前处理正在执行状态的步骤,从0开始记数。在子Step元素中,可以通过status属性覆盖状态。*/ + current?: number, + /** 可选参数,指定大小(目前只支持普通和迷你两种大小)。 small, default */ + size?: string, + /** 可选参数,指定步骤条方向(目前支持水平和竖直两种方向,默认水平方向)。*/ + direction?: string, + /** 可选参数,指定步骤的详细描述文字的最大宽度。*/ + maxDescriptionWidth?: number + + } + /** + * #Steps + 引导用户按照流程完成任务的导航条。 + + ## 何时使用 + + 当任务复杂或者存在先后关系时,将其分解成一系列步骤,从而简化任务。*/ + export class Steps extends React.Component { + static Step: typeof Step + render(): JSX.Element + } + + + + // Switch + interface SwitchProps { + /** 指定当前是否选中*/ + checked?: boolean, + /** 初始是否选中*/ + defaultChecked?: boolean, + /** 变化时回调函数*/ + onChange?: (checked: boolean) => void, + /** 选中时的内容*/ + checkedChildren?: React.ReactNode, + /** 非选中时的内容*/ + unCheckedChildren?: React.ReactNode, + /** 开关大小*/ + size?: string + } + /** + * #Switch + 开关选择器。 + + ## 何时使用 + + - 需要表示开关状态/两种状态之间的切换时; + - 和 `checkbox `的区别是,切换 `switch` 会直接触发状态改变,而 `checkbox` 一般用于状态标记,需要和提交操作配合。 + */ + export class Switch extends React.Component { + render(): JSX.Element + } + + + + + // Table + enum RowSelectionType { + checkbox, + radio + } + type SelectedRowKeys = Array + interface RowSelection { + type?: RowSelectionType | string, + selectedRowKeys?: SelectedRowKeys, + onChange?: (selectedRowKeys: SelectedRowKeys, selectedRows: any) => void, + getCheckboxProps?: (record: any) => void, + onSelect?: (record: any, selected: any, selectedRows: any) => void, + onSelectAll?: (rselectedecord: any, selectedRows: any, changeRows: any) => void + } + interface Columns { + /** React 需要的 key,建议设置*/ + key?: string, + /** 列头显示文字*/ + title?: string | React.ReactNode, + /** 列数据在数据项中对应的 key*/ + dataIndex?: string, + /** 生成复杂数据的渲染函数,参数分别为当前列的值,当前列数据,列索引,@return里面可以设置表格[行/列合并](#demo-colspan-rowspan)*/ + render?: (text?: any, record?: any, index?: number) => React.ReactNode, + /** 表头的筛选菜单项*/ + filters?: Array, + /** 本地模式下,确定筛选的运行函数*/ + onFilter?: Function, + /** 是否多选*/ + filterMultiple?: boolean, + /** 排序函数,本地排序使用一个函数,需要服务端排序可设为 true */ + sorter?: boolean | Function, + /** 表头列合并,设置为 0 时,不渲染*/ + colSpan?: number, + /** 列宽度*/ + width?: string | number, + /** 列的 className*/ + className?: string + } + interface TableProps { + /** 列表项是否可选择*/ + rowSelection?: RowSelection, + /** 分页器*/ + pagination?: Object, + /** 正常或迷你类型 : `default` or `small` */ + size?: string, + /** 数据数组*/ + dataSource: Array, + /** 表格列的配置描述*/ + columns: Columns, + /** 表格行 key 的取值*/ + rowKey?: (record: any, index: number) => string, + /** 额外的展开行*/ + expandedRowRender?: Function, + /** 默认展开的行*/ + defaultExpandedRowKeys?: Array, + /** 分页、排序、筛选变化时触发*/ + onChange?: (pagination: Object, filters: any, sorter: any) => void, + /** 页面是否加载中*/ + loading?: boolean, + /** 默认文案设置,目前包括排序、过滤、空数据文案: `{ filterConfirm: '确定', filterReset: '重置', emptyText: '暂无数据' }` */ + locale?: Object, + /** 展示树形数据时,每层缩进的宽度,以 px 为单位*/ + indentSize?: number, + /** 处理行点击事件*/ + onRowClick?: (record: any, index: number) => void, + /** 是否固定表头*/ + useFixedHeader?: boolean, + /** 是否展示外边框和列边框*/ + bordered?: boolean, + /** 是否显示表头*/ + showHeader?: boolean, + /** 表格底部自定义渲染函数*/ + footer?: (currentPageData: Object) => void + + } + /** + * #Table + 展示行列数据。 + + ## 何时使用 + + - 当有大量结构化的数据需要展现时; + - 当需要对数据进行排序、搜索、分页、自定义操作等复杂行为时。*/ + export class Table extends React.Component { + render(): JSX.Element + } + + + + // Tabs + interface TabPaneProps { + /** 选项卡头显示文字*/ + tab: React.ReactNode | string + } + export class TabPane extends React.Component { + render(): JSX.Element + } + + enum TabsType { + line, card, 'editable-card' + } + enum TabsPosition { + top, + right, + bottom, + left + } + interface TabsProps { + /** 当前激活 tab 面板的 key */ + activeKey?: string, + /** 初始化选中面板的 key,如果没有设置 activeKey*/ + defaultActiveKey?: string, + /** 切换面板的回调*/ + onChange?: Function, + /** tab 被点击的回调 */ + onTabClick?: Function, + /** tab bar 上额外的元素 */ + tabBarExtraContent?: React.ReactNode, + /** 页签的基本样式,可选 `line`、`card` `editable-card` 类型*/ + type?: TabsType | string, + /** 页签位置,可选值有 `top` `right` `bottom` `left`*/ + tabPosition?: TabsPosition | string, + /** 新增和删除页签的回调,在 `type="editable-card"` 时有效*/ + onEdit?: (targetKey: string, action: any) => void + } + /** + * #Tabs + 选项卡切换组件。 + + ## 何时使用 + + 提供平级的区域将大块内容进行收纳和展现,保持界面整洁。 + + Ant Design 依次提供了三级选项卡,分别用于不同的场景。 + + - 卡片式的页签,提供可关闭的样式,常用于容器顶部。 + - 标准线条式页签,用于容器内部的主功能切换,这是最常用的 Tabs。 + - [RadioButton](/components/radio/#demo-radiobutton) 可作为更次级的页签来使用。*/ + export class Tabs extends React.Component { + static TabPane: typeof TabPane + render(): JSX.Element + } + + + + + // Tag + interface TagProps { + /** 标签是否可以关闭*/ + closable?: boolean, + /** 关闭时的回调*/ + onClose?: Function, + /** 动画关闭后的回调*/ + afterClose?: Function, + /** 标签的色彩*/ + color?: string + } + /** + * #Tag + 进行标记和分类的小标签。 + + ## 何时使用 + + - 用于标记事物的属性和维度。 + - 进行分类。*/ + export class Tag extends React.Component { + render(): JSX.Element + } + + + + + + + // TimePicker + interface TimePickerProps { + /** 默认时间*/ + value?: string | Date, + /** 初始默认时间*/ + defaultValue?: string | Date, + /** 展示的时间格式 : "HH:mm:ss"、"HH:mm"、"mm:ss" */ + format?: string, + /** 时间发生变化的回调*/ + onChange?: (Date: Date) => void, + /** 禁用全部操作*/ + disabled?: boolean, + /** 没有值的时候显示的内容*/ + placeholder?: string, + /** 国际化配置*/ + locale?: Object, + /** 隐藏禁止选择的选项*/ + hideDisabledOptions?: boolean, + /** 禁止选择部分小时选项*/ + disabledHours?: Function, + /** 禁止选择部分分钟选项*/ + disabledMinutes?: Function, + /** 禁止选择部分秒选项*/ + disabledSeconds?: Function + + } + /** + * #TimePicker + 输入或选择时间的控件。 + + 何时使用 + -------- + + 当用户需要输入一个时间,可以点击标准输入框,弹出时间面板进行选择。 + */ + export class TimePicker extends React.Component { + render(): JSX.Element + } + + + + + // Timeline + interface TimeLineItemProps { + /** 指定圆圈颜色。*/ + color?: string + } + export class TimeLineItem extends React.Component { + render(): JSX.Element + } + + interface TimelineProps { + /** 指定最后一个幽灵节点是否存在或内容*/ + pending?: boolean | React.ReactNode + } + /** + * #Timeline + 垂直展示的时间流信息。 + + ## 何时使用 + + - 当有一系列信息需要从上至下按时间排列时; + - 需要有一条时间轴进行视觉上的串联时;*/ + export class Timeline extends React.Component { + static Item: typeof TimeLineItem + render(): JSX.Element + } + + + + // Tooltip + + interface TooltipProps { + /** 气泡框位置,可选 `top` `left` `right` `bottom` `topLeft` `topRight` `bottomLeft` `bottomRight` `leftTop` `leftBottom` `rightTop` `rightBottom`*/ + placement?: PopoverPlacement | string, + /** 提示文字*/ + title?: string | React.ReactNode + } + /** + * #Tooltip + 简单的文字提示气泡框。 + + ## 何时使用 + + 鼠标移入则显示提示,移出消失,气泡浮层不承载复杂文本和操作。 + + 可用来代替系统默认的 `title` 提示,提供一个`按钮/文字/操作`的文案解释。*/ + export class Tooltip extends React.Component { + render(): JSX.Element + } + + + + + + // Transfer + interface TransferProps { + /** 数据源*/ + dataSource: Array, + /** 每行数据渲染函数*/ + render?: (record: Object) => any, + /** 显示在右侧框数据的key集合*/ + targetKeys: Array, + /** 变化时回调函数*/ + onChange?: (targetKeys: any, direction: string, moveKeys: any) => void, + /** 两个穿梭框的自定义样式*/ + listStyle?: Object, + /** 自定义类*/ + className?: string, + /** 标题集合,顺序从左至右*/ + titles?: Array, + /** 操作文案集合,顺序从上至下*/ + operations?: Array, + /** 是否显示搜索框*/ + showSearch?: boolean, + /** 搜索框的默认值*/ + searchPlaceholder?: string, + /** 当列表为空时显示的内容*/ + notFoundContent?: React.ReactNode | string + /** 底部渲染函数*/ + footer?: (props: any) => any + } + /** + * #Transfer + 双栏穿梭选择框。 + + ## 何时使用 + + 用直观的方式在两栏中移动元素,完成选择行为。 + */ + export class Transfer extends React.Component { + render(): JSX.Element + } + + + + + + // Tree + interface TreeNodeProps { + disabled?: boolean, + disableCheckbox?: boolean, + title?: string | React.ReactNode, + key?: string, + isLeaf?: boolean + } + export class TreeNode extends React.Component { + render(): JSX.Element + } + + interface TreeProps { + showLine?: boolean, + className?: string, + /** 是否支持多选*/ + multiple?: boolean, + /** 是否支持选中*/ + checkable?: boolean, + /** 默认展开所有树节点*/ + defaultExpandAll?: boolean, + /** 默认展开指定的树节点*/ + defaultExpandedKeys?: Array, + /** (受控)展开指定的树节点*/ + expandedKeys?: Array, + /** (受控)选中复选框的树节点*/ + checkedKeys?: Array, + /** 默认选中复选框的树节点*/ + defaultCheckedKeys?: Array, + /** (受控)设置选中的树节点*/ + selectedKeys?: Array, + /** 默认选中的树节点*/ + defaultSelectedKeys?: Array, + /** 展开/收起节点时触发 */ + onExpand?: (node: any, expanded: any, expandedKeys: any) => void, + /** 点击复选框触发*/ + onCheck?: (checkedKeys: any, e: { checked: boolean, checkedNodes: any, node: any, event: Event }) => void, + /** 点击树节点触发*/ + onSelect?: (selectedKeys: any, e: { selected: boolean, selectedNodes: any, node: any, event: Event }) => void, + /** filter some treeNodes as you need. it should return true */ + filterTreeNode?: (node: any) => boolean, + /** 异步加载数据*/ + loadData?: (node: any) => void, + /** 响应右键点击*/ + onRightClick?: (options: { event: Event, node: any }) => void, + /** 设置节点可拖拽(IE>8)*/ + draggable?: boolean, + /** 开始拖拽时调用*/ + onDragStart?: (options: { event: Event, node: any }) => void, + /** dragenter 触发时调用*/ + onDragEnter?: (options: { event: Event, node: any, expandedKeys: any }) => void, + /** dragover 触发时调用 */ + onDragOver?: (options: { event: Event, node: any }) => void, + /** dragleave 触发时调用*/ + onDragLeave?: (options: { event: Event, node: any }) => void, + /** drop 触发时调用*/ + onDrop?: (options: { event: Event, node: any, dragNode: any, dragNodesKeys: any }) => void, + } + /** + * #Tree + * 文件夹、组织架构、生物分类、国家地区等等,世间万物的大多数结构都是树形结构。使用`树控件`可以完整展现其中的层级关系,并具有展开收起选择等交互功能。 + */ + export class Tree extends React.Component { + static TreeNode: typeof TreeNode + render(): JSX.Element + } + + + + + + // TreeSelect + interface TreeSelectTreeNodeProps { + disabled?: boolean, + /** 此项必须设置(其值在整个树范围内唯一)*/ + key: string, + /** 默认根据此属性值进行筛选*/ + value?: string, + /** 树节点显示的内容*/ + title?: React.ReactNode | string, + /** 是否是叶子节点*/ + isLeaf?: boolean + } + export class TreeSelectTreeNode extends React.Component { + render(): JSX.Element + } + + type TreeData = Array<{ value: any, label: string, children: TreeData }> + interface TreeSelectProps { + style?: Object, + /** 指定当前选中的条目*/ + value?: string | Array, + /** 指定默认选中的条目*/ + defaultValue?: string | Array, + /** 支持多选*/ + multiple?: boolean, + /** 可以把随意输入的条目作为 tag,输入项不需要与下拉选项匹配*/ + tags?: boolean, + /** 被选中时调用,参数为选中项的 value 值*/ + onSelect?: (value: any) => void, + /** 选中option,或input的value变化(combobox 模式下)时,调用此函数*/ + onChange?: (value: any, label: any) => void, + /** 显示清除按钮*/ + allowClear?: boolean, + /** 文本框值变化时回调*/ + onSearch?: (value: any) => void, + /** 选择框默认文字*/ + placeholder?: string, + /** 搜索框默认文字*/ + searchPlaceholder?: string, + /** 下拉菜单的样式*/ + dropdownStyle?: Object, + /** 下拉菜单和选择器同宽*/ + dropdownMatchSelectWidth?: boolean, + /** 输入框自动提示模式*/ + combobox?: boolean, + /** 选择框大小,可选 `large` `small`*/ + size?: string, + /** 在下拉中显示搜索框*/ + showSearch?: boolean, + /** 是否禁用*/ + disabled?: boolean, + /** 默认展开所有树节点*/ + treeDefaultExpandAll?: boolean, + /** 显示checkbox*/ + treeCheckable?: boolean, + /** 是否根据输入项进行筛选,返回值true*/ + filterTreeNode?: (treeNode: any) => boolean, + /** 输入项过滤对应的 treeNode 属性*/ + treeNodeFilterProp?: string, + /** 作为显示的prop设置*/ + treeNodeLabelProp?: string, + /** treeNodes数据,如果设置则不需要手动构造TreeNode节点(如果value在整个树范围内不唯一,需要设置`key`其值为整个树范围内的唯一id*/ + treeData?: TreeData, + /** 异步加载数据*/ + loadData?: (node: any) => void + } + /** + * #TreeSelect + 树型选择控件。 + + ## 何时使用 + + 类似 Select 的选择控件,可选择的数据结构是一个树形结构时,可以使用 TreeSelect,例如公司层级、学科系统、分类目录等等。 + */ + export class TreeSelect extends React.Component { + static TreeNode: typeof TreeSelectTreeNode + render(): JSX.Element + } + + + + + + + // Upload + interface UploadProps { + /** 可选参数, 上传的文件 */ + name?: string, + /** 必选参数, 上传的地址 */ + action: string, + /** 可选参数, 上传所需参数 */ + data?: Object, + /** 可选参数, 设置上传的请求头部,IE10 以上有效*/ + headers?: Object, + /** 可选参数, 是否展示 uploadList, 默认开启 */ + showUploadList?: boolean, + /** 可选参数, 是否支持多选文件,`ie10+` 支持。开启后按住 ctrl 可选择多个文件。*/ + multiple?: boolean, + /** 可选参数, 接受上传的文件类型, 详见 input accept Attribute */ + accept?: string, + /** 可选参数, 上传文件之前的钩子,参数为上传的文件,若返回 `false` 或者 Promise 则停止上传。**注意:该方法不支持老 IE**。*/ + beforeUpload?: Function, + /** 可选参数, 上传文件改变时的状态,详见 onChange */ + onChange?: (info: Object) => void, + /** 上传列表的内建样式,支持两种基本样式 `text` or `picture` */ + listType?: string, + /** 自定义类名*/ + className?: string + + } + /** + * #Upload + 文件选择上传和拖拽上传控件。 + + ## 何时使用 + + 上传是将信息(网页、文字、图片、视频等)通过网页或者上传工具发布到远程服务器上的过程。 + + - 当需要上传一个或一些文件时。 + - 当需要展现上传的进度时。 + - 当需要使用拖拽交互时。*/ + export class Upload extends React.Component { + render(): JSX.Element + } + + + + + + +} + + +// export all antd +declare module 'antd' { + export = Antd +} +// single export point +declare module 'antd/lib/Affix' { + export default Antd.Affix +} +declare module 'antd/lib/Button' { + export default Antd.Button +} +declare module 'antd/lib/Alert' { + export default Antd.Alert +} +declare module 'antd/lib/Badge' { + export default Antd.Badge +} +declare module 'antd/lib/Breadcrumb' { + export default Antd.Breadcrumb +} +declare module 'antd/lib/Calendar' { + export default Antd.Calendar +} +declare module 'antd/lib/Carousel' { + export default Antd.Carousel +} +declare module 'antd/lib/Cascader' { + export default Antd.Cascader +} +declare module 'antd/lib/Checkbox' { + export default Antd.Checkbox +} +declare module 'antd/lib/Collapse' { + export default Antd.Collapse +} +declare module 'antd/lib/DatePicker' { + export default Antd.DatePicker +} +declare module 'antd/lib/Dropdown' { + export default Antd.Dropdown +} +declare module 'antd/lib/Icon' { + export default Antd.Icon +} +declare module 'antd/lib/Form' { + export default Antd.Form +} +declare module 'antd/lib/Input' { + export default Antd.Input +} +declare module 'antd/lib/InputNumber' { + export default Antd.InputNumber +} +declare module 'antd/lib/Row' { + export default Antd.Row +} +declare module 'antd/lib/Col' { + export default Antd.Col +} +declare module 'antd/lib/Menu' { + export default Antd.Menu +} +declare module 'antd/lib/message' { + export default Antd.message +} +declare module 'antd/lib/Modal' { + export default Antd.Modal +} +declare module 'antd/lib/notification' { + export default Antd.notification +} +declare module 'antd/lib/Pagination' { + export default Antd.Pagination +} +declare module 'antd/lib/Popconfirm' { + export default Antd.Popconfirm +} +declare module 'antd/lib/Popover' { + export default Antd.Popover +} +declare module 'antd/lib/Progress' { + export default Antd.Progress +} +declare module 'antd/lib/QueueAnim' { + export default Antd.QueueAnim +} +declare module 'antd/lib/Radio' { + export default Antd.Radio +} +declare module 'antd/lib/Select' { + export default Antd.Select +} +declare module 'antd/lib/Slider' { + export default Antd.Slider +} +declare module 'antd/lib/Spin' { + export default Antd.Spin +} +declare module 'antd/lib/Steps' { + export default Antd.Steps +} +declare module 'antd/lib/Switch' { + export default Antd.Switch +} +declare module 'antd/lib/Table' { + export default Antd.Table +} +declare module 'antd/lib/Tabs' { + export default Antd.Tabs +} +declare module 'antd/lib/Tag' { + export default Antd.Tag +} +declare module 'antd/lib/TimePicker' { + export default Antd.TimePicker +} +declare module 'antd/lib/Timeline' { + export default Antd.Timeline +} +declare module 'antd/lib/Tooltip' { + export default Antd.Tooltip +} +declare module 'antd/lib/Transfer' { + export default Antd.Transfer +} +declare module 'antd/lib/Tree' { + export default Antd.Tree +} +declare module 'antd/lib/TreeSelect' { + export default Antd.TreeSelect +} +declare module 'antd/lib/Upload' { + export default Antd.Upload +} diff --git a/antd/tsconfig.json b/antd/tsconfig.json new file mode 100644 index 0000000000..197d812c22 --- /dev/null +++ b/antd/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "antd-tests.tsx" + ] +} \ No newline at end of file diff --git a/any-db-transaction/any-db-transaction-tests.ts b/any-db-transaction/any-db-transaction-tests.ts index 8e38fe5a3c..8e96f43883 100644 --- a/any-db-transaction/any-db-transaction-tests.ts +++ b/any-db-transaction/any-db-transaction-tests.ts @@ -1,7 +1,3 @@ - -/// -/// - "use strict"; import anyDB = require("any-db"); diff --git a/any-db-transaction/any-db-transaction.d.ts b/any-db-transaction/any-db-transaction.d.ts deleted file mode 100644 index 675f18e9cc..0000000000 --- a/any-db-transaction/any-db-transaction.d.ts +++ /dev/null @@ -1,94 +0,0 @@ -// Type definitions for any-db-transaction 2.2.1 -// Project: https://github.com/grncdr/node-any-db-transaction -// Definitions by: Rogier Schouten -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare module "any-db-transaction" { - import anyDB = require("any-db"); - - namespace begin { - /** - * Transaction objects are are simple wrappers around a Connection that also implement the Queryable API, - * but guarantee that all queries take place within a single database transaction or not at all. Note that - * begin also understands how to acquire (and release) a connection from a ConnectionPool as well, so you - * can simply pass a pool to it: var tx = begin(pool) - * - * By default, any queries that error during a transaction will cause an automatic rollback. If a query has - * no callback, the transaction will also handle (and re-emit) 'error' events for the Query instance. - * This enables handling errors for an entire transaction in a single place. - * - * Transactions may also be nested by passing a Transaction to begin and these nested transactions can - * safely error and rollback without rolling back their parent transaction - * - * Transaction events: - * 'query', query - emitted immediately after .query is called on a connection via tx.query. The argument is a query object. - * 'commit:start' - Emitted when .commit() is called. - * 'commit:complete' - Emitted after the transaction has committed. - * 'rollback:start' - Emitted when .rollback() is called. - * 'rollback:complete' - Emitted after the transaction has rolled back. - * 'close' - Emitted after rollback or commit completes. - * 'error', err - Emitted under three conditions: - * There was an error acquiring a connection. - * Any query performed in this transaction emits an error that would otherwise go unhandled. - * Any of query, begin, commit, or rollback are called after the connection has already been committed or rolled back. - * Note that the 'error' event may be emitted multiple times! depending on the callback you are registering, you way want to wrap it using [once][]. - */ - interface Transaction extends anyDB.Queryable { - - /** - * Issue a COMMIT (or RELEASE ... in the case of nested transactions) statement to the database. - * If a continuation is provided it will be called (possibly with an error) after the COMMIT - * statement completes. The transaction object itself will be unusable after calling commit(). - */ - commit(callback?: (error: Error) => void): void; - - /** - * The same as Transaction.commit but issues a ROLLBACK. Again, the transaction will be unusable after calling this method. - */ - rollback(callback?: (error: Error) => void): void; - } - - interface TransactionOptions { - /** - * Adapter name e.g. 'mysql' - */ - adapter?: anyDB.Adapter; - /** - * SQL statement for beginning a transaction, default 'BEGIN' - */ - begin?: string; - /** - * SQL statement for committing a transaction, default 'COMMIT' - */ - commit?: string; - /** - * SQL statement for rolling back a transaction, default 'ROLLBACK' - */ - rollback?: string; - /** - * Callback for transaction - */ - callback?: (error: Error, transaction: Transaction) => void; - /** - * Rollback automatically on error, default true - */ - autoRollback?: boolean; - } - } - - /** - * Start a transaction - */ - function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - function begin(q: anyDB.Queryable, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - function begin(q: anyDB.Queryable, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - - export = begin; -} - - - diff --git a/any-db-transaction/index.d.ts b/any-db-transaction/index.d.ts new file mode 100644 index 0000000000..8428e7640f --- /dev/null +++ b/any-db-transaction/index.d.ts @@ -0,0 +1,88 @@ +// Type definitions for any-db-transaction 2.2.1 +// Project: https://github.com/grncdr/node-any-db-transaction +// Definitions by: Rogier Schouten +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import anyDB = require("any-db"); + +declare namespace begin { + /** + * Transaction objects are are simple wrappers around a Connection that also implement the Queryable API, + * but guarantee that all queries take place within a single database transaction or not at all. Note that + * begin also understands how to acquire (and release) a connection from a ConnectionPool as well, so you + * can simply pass a pool to it: var tx = begin(pool) + * + * By default, any queries that error during a transaction will cause an automatic rollback. If a query has + * no callback, the transaction will also handle (and re-emit) 'error' events for the Query instance. + * This enables handling errors for an entire transaction in a single place. + * + * Transactions may also be nested by passing a Transaction to begin and these nested transactions can + * safely error and rollback without rolling back their parent transaction + * + * Transaction events: + * 'query', query - emitted immediately after .query is called on a connection via tx.query. The argument is a query object. + * 'commit:start' - Emitted when .commit() is called. + * 'commit:complete' - Emitted after the transaction has committed. + * 'rollback:start' - Emitted when .rollback() is called. + * 'rollback:complete' - Emitted after the transaction has rolled back. + * 'close' - Emitted after rollback or commit completes. + * 'error', err - Emitted under three conditions: + * There was an error acquiring a connection. + * Any query performed in this transaction emits an error that would otherwise go unhandled. + * Any of query, begin, commit, or rollback are called after the connection has already been committed or rolled back. + * Note that the 'error' event may be emitted multiple times! depending on the callback you are registering, you way want to wrap it using [once][]. + */ + interface Transaction extends anyDB.Queryable { + + /** + * Issue a COMMIT (or RELEASE ... in the case of nested transactions) statement to the database. + * If a continuation is provided it will be called (possibly with an error) after the COMMIT + * statement completes. The transaction object itself will be unusable after calling commit(). + */ + commit(callback?: (error: Error) => void): void; + + /** + * The same as Transaction.commit but issues a ROLLBACK. Again, the transaction will be unusable after calling this method. + */ + rollback(callback?: (error: Error) => void): void; + } + + interface TransactionOptions { + /** + * Adapter name e.g. 'mysql' + */ + adapter?: anyDB.Adapter; + /** + * SQL statement for beginning a transaction, default 'BEGIN' + */ + begin?: string; + /** + * SQL statement for committing a transaction, default 'COMMIT' + */ + commit?: string; + /** + * SQL statement for rolling back a transaction, default 'ROLLBACK' + */ + rollback?: string; + /** + * Callback for transaction + */ + callback?: (error: Error, transaction: Transaction) => void; + /** + * Rollback automatically on error, default true + */ + autoRollback?: boolean; + } +} + +/** + * Start a transaction + */ +declare function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; +declare function begin(q: anyDB.Queryable, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; +declare function begin(q: anyDB.Queryable, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; +declare function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; + +export = begin; diff --git a/any-db-transaction/tsconfig.json b/any-db-transaction/tsconfig.json new file mode 100644 index 0000000000..312f073285 --- /dev/null +++ b/any-db-transaction/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "any-db-transaction-tests.ts" + ] +} \ No newline at end of file diff --git a/any-db/any-db-tests.ts b/any-db/any-db-tests.ts index 41744c452c..ca173cc4d2 100644 --- a/any-db/any-db-tests.ts +++ b/any-db/any-db-tests.ts @@ -1,5 +1,4 @@ -/// "use strict"; diff --git a/any-db/any-db.d.ts b/any-db/any-db.d.ts deleted file mode 100644 index 8a64b6f323..0000000000 --- a/any-db/any-db.d.ts +++ /dev/null @@ -1,303 +0,0 @@ -// Type definitions for any-db 2.1.0 -// Project: https://github.com/grncdr/node-any-db -// Definitions by: Rogier Schouten -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "any-db" { - import events = require("events"); - import stream = require("stream"); - - export interface ConnectOpts { - adapter: string; - } - - export interface Adapter { - name: string; - /** - * Create a new connection object. In common usage, config will be created by parse-db-url and passed to the adapter by any-db. - * If a continuation is given, it must be called, either with an error or the established connection. - */ - createConnection(opts: ConnectOpts, callback?: (error: Error, result: Connection) => void): Connection; - - /** - * Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code, - * it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract - * by synchronously returning a Query stream - */ - createQuery(text: string, params?: any[], callback?: (error: Error, result: ResultSet) => void): Query; - createQuery(query: Query): Query; - } - /** - * Other properties are driver specific - */ - export interface Field { - name: string; - } - - /** - * ResultSet objects are just plain data that collect results of a query when a continuation - * is provided to Queryable.query. The lastInsertId is optional, and currently supported by - * sqlite3 and mysql but not postgres, because it is not supported by Postgres itself. - */ - export interface ResultSet { - /** - * Affected rows. Note e.g. for INSERT queries the rows property is not filled even - * though rowCount is non-zero. - */ - rowCount: number; - /** - * Result rows - */ - rows: any[]; - /** - * Result field descriptions - */ - fields: Field[]; - - /** - * Not supported by all drivers. - */ - fieldCount?: number; - /** - * Not supported by all drivers. - */ - lastInsertId?: any; - /** - * Not supported by all drivers. - */ - affectedRows?: number; - /** - * Not supported by all drivers. - */ - changedRows?: number; - } - - /** - * Query objects are returned by the Queryable.query method, available on connections, - * pools, and transactions. Queries are instances of Readable, and as such can be piped - * through transforms and support backpressure for more efficient memory-usage on very - * large results sets. (Note: at this time the sqlite3 driver does not support backpressure) - * - * Internally, Query instances are created by a database Adapter and may have more methods, - * properties, and events than are described here. Consult the documentation for your - * specific adapter to find out about any extensions. - * - * Events: - * - * Error event - * The 'error' event is emitted at most once per query. Note that this event will be - * emitted for errors even if a callback was provided, the callback will - * simply be subscribed to the 'error' event. - * One argument is passed to event listeners: - * error - the error object. - * - * Fields event - * A 'fields' event is emmitted before any 'data' events. - * One argument is passed to event listeners: - * fields - an array of [Field][ResultSet] objects. - * - * The following events are part of the stream.Readable interface which is implemented by Query: - * - * Data event - * A 'data' event is emitted for each row in the query result set. - * One argument is passed to event listeners: - * row contains the contents of a single row in the query result - * - * Close event - * A 'close' event is emitted when the query completes. - * No arguments are passed to event listeners. - * - * End event - * An 'end' event is emitted after all query results have been consumed. - * No arguments are passed to event listeners. - */ - export interface Query extends stream.Readable { - /** - * The SQL query as a string. If you are using MySQL this will contain - * interpolated values after the query has been enqueued by a connection. - */ - text: string; - - /** - * The array of parameter values. - */ - values: any[]; - - /** - * The callback (if any) that was provided to Queryable.query. Note that - * Query objects must not use a closed over reference to their callback, - * as other any-db libraries may rely on modifying the callback property - * of a Query they did not create. - */ - callback: (error: Error, results: ResultSet) => void; - } - - /** - * Events: - * The 'query' event is emitted immediately before a query is executed. One argument is passed to event handlers: - * - query: a Query object - */ - export interface Queryable extends events.EventEmitter { - /** - * The Adapter instance that will be used by this Queryable for creating Query instances and/or connections. - */ - adapter: Adapter; - - /** - * Execute a SQL statement using bound parameters (if they are provided) and return a Query object - * that is a Readable stream of the resulting rows. If a Continuation is provided the rows - * returned by the database will be aggregated into a [ResultSet][] which will be passed to the - * continuation after the query has completed. - * The second form is not needed for normal use, but must be implemented by adapters to work correctly - * with ConnectionPool and Transaction. See Adapter.createQuery for more details. - */ - query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query - - /** - * The second form is not needed for normal use, but must be implemented by adapters to work correctly - * with ConnectionPool and Transaction. See Adapter.createQuery for more details. - */ - // query(query: Query): Query; - } - - /** - * Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire, - * both of which delegate to the createConnection implementation of the specified adapter. - * While all Connection objects implement the Queryable interface, the implementations in - * each adapter may add additional methods or emit additional events. If you need to access a - * feature of your database that is not described here (such as Postgres' server-side prepared - * statements), consult the documentation for your adapter. - * - * Events: - * Error event - * The 'error' event is emitted when there is a connection-level error. - * No arguments are passed to event listeners. - * - * Open event - * The 'open' event is emitted when the connection has been established and is ready to query. - * No arguments are passed to event listeners. - * - * Close event - * The 'close' event is emitted when the connection has been closed. - * No arguments are passed to event listeners. - */ - export interface Connection extends Queryable { - /** - * Close the database connection. If a continuation is provided it - * will be called after the connection has closed. - */ - end(callback?: (error: Error) => void): void; - } - - export interface ConnectionStatic { - new(): Connection; - - name: string; - createConnection(): void; - createPool(): void; - } - - /** - * ConnectionPool events - * 'acquire' - emitted whenever pool.acquire is called - * 'release' - emitted whenever pool.release is called - * 'query', query - emitted immediately after .query is called on a - * connection via pool.query. The argument is a Query object. - * 'close' - emitted when the connection pool has closed all of it - * connections after a call to close(). - */ - export interface ConnectionPool extends Queryable { - /** - * Implements Queryable.query by automatically acquiring a connection - * and releasing it when the query completes. - */ - query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query; - - /** - * Remove a connection from the pool. If you use this method you must - * return the connection back to the pool using ConnectionPool.release - */ - acquire(callback: (error: Error, result: Connection) => void): void; - - /** - * Return a connection to the pool. This should only be called with connections - * you've manually acquired. You must not continue to use the connection after releasing it. - */ - release(connection: Connection): void; - - /** - * Stop giving out new connections, and close all existing database connections as they - * are returned to the pool. - */ - close(callback?: (error: Error) => void): void; - } - - /** - * A PoolConfig is generally a plain object with any of the following properties (they are all optional): - */ - export interface PoolConfig { - /** - * min (default 0) The minimum number of connections to keep open in the pool. - */ - min?: number; - /** - * max (default 10) The maximum number of connections to keep open in the pool. - * When this limit is reached further requests for connections will queue waiting - * for an existing connection to be released back into the pool. - */ - max?: number; - /** - * (default 30000) The maximum amount of time a connection can sit idle in the pool before being reaped - */ - idleTimeout?: number; - /** - * (default 1000) How frequently the pool should check for connections that are old enough to be reaped. - */ - reapInterval?: number; - /** - * (default true) When this is true, the pool will reap connections that - * have been idle for more than idleTimeout milliseconds. - */ - refreshIdle?: boolean; - /** - * Called immediately after a connection is first established. Use this to do one-time setup of new connections. - * The supplied Connection will not be added to the pool until you pass it to the done continuation. - */ - onConnect?: (connection: Connection, ready: (error: Error, result: Connection) => void) => void; - /** - * Called each time a connection is returned to the pool. Use this to restore a connection to - * it's original state (e.g. rollback transactions, set the database session vars). If reset - * fails to call the done continuation the connection will be lost in limbo. - */ - reset?: (connection: Connection, done: (error: Error) => void) => void; - /** - * (default function (err) { return true }) - Called when an error is encountered - * by pool.query or emitted by an idle connection. If shouldDestroyConnection(error) - * is truthy the connection will be destroyed, otherwise it will be reset. - */ - shouldDestroyConnection?: (error: Error) => boolean; - } - - /** - * Create a database connection. - * @param url String of the form adapter://user:password@host/database - * @param callback - * @returns Connection object. - */ - export function createConnection(url: string, callback?: (error: Error, connection: Connection) => void): Connection; - - /** - * Create a database connection. - * @param opts Object with adapter name and any properties that the given adapter requires - * @param callback - * @returns Connection object. - */ - export function createConnection(opts: ConnectOpts, callback?: (error: Error, connection: Connection) => void): Connection; - - - export function createPool(url: string, config: PoolConfig): ConnectionPool; - export function createPool(opts: ConnectOpts, config: PoolConfig): ConnectionPool; - -} diff --git a/any-db/index.d.ts b/any-db/index.d.ts new file mode 100644 index 0000000000..47265e1f53 --- /dev/null +++ b/any-db/index.d.ts @@ -0,0 +1,301 @@ +// Type definitions for any-db 2.1.0 +// Project: https://github.com/grncdr/node-any-db +// Definitions by: Rogier Schouten +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import events = require("events"); +import stream = require("stream"); + +export interface ConnectOpts { + adapter: string; +} + +export interface Adapter { + name: string; + /** + * Create a new connection object. In common usage, config will be created by parse-db-url and passed to the adapter by any-db. + * If a continuation is given, it must be called, either with an error or the established connection. + */ + createConnection(opts: ConnectOpts, callback?: (error: Error, result: Connection) => void): Connection; + + /** + * Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code, + * it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract + * by synchronously returning a Query stream + */ + createQuery(text: string, params?: any[], callback?: (error: Error, result: ResultSet) => void): Query; + createQuery(query: Query): Query; +} +/** + * Other properties are driver specific + */ +export interface Field { + name: string; +} + +/** + * ResultSet objects are just plain data that collect results of a query when a continuation + * is provided to Queryable.query. The lastInsertId is optional, and currently supported by + * sqlite3 and mysql but not postgres, because it is not supported by Postgres itself. + */ +export interface ResultSet { + /** + * Affected rows. Note e.g. for INSERT queries the rows property is not filled even + * though rowCount is non-zero. + */ + rowCount: number; + /** + * Result rows + */ + rows: any[]; + /** + * Result field descriptions + */ + fields: Field[]; + + /** + * Not supported by all drivers. + */ + fieldCount?: number; + /** + * Not supported by all drivers. + */ + lastInsertId?: any; + /** + * Not supported by all drivers. + */ + affectedRows?: number; + /** + * Not supported by all drivers. + */ + changedRows?: number; +} + +/** + * Query objects are returned by the Queryable.query method, available on connections, + * pools, and transactions. Queries are instances of Readable, and as such can be piped + * through transforms and support backpressure for more efficient memory-usage on very + * large results sets. (Note: at this time the sqlite3 driver does not support backpressure) + * + * Internally, Query instances are created by a database Adapter and may have more methods, + * properties, and events than are described here. Consult the documentation for your + * specific adapter to find out about any extensions. + * + * Events: + * + * Error event + * The 'error' event is emitted at most once per query. Note that this event will be + * emitted for errors even if a callback was provided, the callback will + * simply be subscribed to the 'error' event. + * One argument is passed to event listeners: + * error - the error object. + * + * Fields event + * A 'fields' event is emmitted before any 'data' events. + * One argument is passed to event listeners: + * fields - an array of [Field][ResultSet] objects. + * + * The following events are part of the stream.Readable interface which is implemented by Query: + * + * Data event + * A 'data' event is emitted for each row in the query result set. + * One argument is passed to event listeners: + * row contains the contents of a single row in the query result + * + * Close event + * A 'close' event is emitted when the query completes. + * No arguments are passed to event listeners. + * + * End event + * An 'end' event is emitted after all query results have been consumed. + * No arguments are passed to event listeners. + */ +export interface Query extends stream.Readable { + /** + * The SQL query as a string. If you are using MySQL this will contain + * interpolated values after the query has been enqueued by a connection. + */ + text: string; + + /** + * The array of parameter values. + */ + values: any[]; + + /** + * The callback (if any) that was provided to Queryable.query. Note that + * Query objects must not use a closed over reference to their callback, + * as other any-db libraries may rely on modifying the callback property + * of a Query they did not create. + */ + callback: (error: Error, results: ResultSet) => void; +} + +/** + * Events: + * The 'query' event is emitted immediately before a query is executed. One argument is passed to event handlers: + * - query: a Query object + */ +export interface Queryable extends events.EventEmitter { + /** + * The Adapter instance that will be used by this Queryable for creating Query instances and/or connections. + */ + adapter: Adapter; + + /** + * Execute a SQL statement using bound parameters (if they are provided) and return a Query object + * that is a Readable stream of the resulting rows. If a Continuation is provided the rows + * returned by the database will be aggregated into a [ResultSet][] which will be passed to the + * continuation after the query has completed. + * The second form is not needed for normal use, but must be implemented by adapters to work correctly + * with ConnectionPool and Transaction. See Adapter.createQuery for more details. + */ + query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query + + /** + * The second form is not needed for normal use, but must be implemented by adapters to work correctly + * with ConnectionPool and Transaction. See Adapter.createQuery for more details. + */ + // query(query: Query): Query; +} + +/** + * Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire, + * both of which delegate to the createConnection implementation of the specified adapter. + * While all Connection objects implement the Queryable interface, the implementations in + * each adapter may add additional methods or emit additional events. If you need to access a + * feature of your database that is not described here (such as Postgres' server-side prepared + * statements), consult the documentation for your adapter. + * + * Events: + * Error event + * The 'error' event is emitted when there is a connection-level error. + * No arguments are passed to event listeners. + * + * Open event + * The 'open' event is emitted when the connection has been established and is ready to query. + * No arguments are passed to event listeners. + * + * Close event + * The 'close' event is emitted when the connection has been closed. + * No arguments are passed to event listeners. + */ +export interface Connection extends Queryable { + /** + * Close the database connection. If a continuation is provided it + * will be called after the connection has closed. + */ + end(callback?: (error: Error) => void): void; +} + +export interface ConnectionStatic { + new (): Connection; + + name: string; + createConnection(): void; + createPool(): void; +} + +/** + * ConnectionPool events + * 'acquire' - emitted whenever pool.acquire is called + * 'release' - emitted whenever pool.release is called + * 'query', query - emitted immediately after .query is called on a + * connection via pool.query. The argument is a Query object. + * 'close' - emitted when the connection pool has closed all of it + * connections after a call to close(). + */ +export interface ConnectionPool extends Queryable { + /** + * Implements Queryable.query by automatically acquiring a connection + * and releasing it when the query completes. + */ + query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query; + + /** + * Remove a connection from the pool. If you use this method you must + * return the connection back to the pool using ConnectionPool.release + */ + acquire(callback: (error: Error, result: Connection) => void): void; + + /** + * Return a connection to the pool. This should only be called with connections + * you've manually acquired. You must not continue to use the connection after releasing it. + */ + release(connection: Connection): void; + + /** + * Stop giving out new connections, and close all existing database connections as they + * are returned to the pool. + */ + close(callback?: (error: Error) => void): void; +} + +/** + * A PoolConfig is generally a plain object with any of the following properties (they are all optional): + */ +export interface PoolConfig { + /** + * min (default 0) The minimum number of connections to keep open in the pool. + */ + min?: number; + /** + * max (default 10) The maximum number of connections to keep open in the pool. + * When this limit is reached further requests for connections will queue waiting + * for an existing connection to be released back into the pool. + */ + max?: number; + /** + * (default 30000) The maximum amount of time a connection can sit idle in the pool before being reaped + */ + idleTimeout?: number; + /** + * (default 1000) How frequently the pool should check for connections that are old enough to be reaped. + */ + reapInterval?: number; + /** + * (default true) When this is true, the pool will reap connections that + * have been idle for more than idleTimeout milliseconds. + */ + refreshIdle?: boolean; + /** + * Called immediately after a connection is first established. Use this to do one-time setup of new connections. + * The supplied Connection will not be added to the pool until you pass it to the done continuation. + */ + onConnect?: (connection: Connection, ready: (error: Error, result: Connection) => void) => void; + /** + * Called each time a connection is returned to the pool. Use this to restore a connection to + * it's original state (e.g. rollback transactions, set the database session vars). If reset + * fails to call the done continuation the connection will be lost in limbo. + */ + reset?: (connection: Connection, done: (error: Error) => void) => void; + /** + * (default function (err) { return true }) - Called when an error is encountered + * by pool.query or emitted by an idle connection. If shouldDestroyConnection(error) + * is truthy the connection will be destroyed, otherwise it will be reset. + */ + shouldDestroyConnection?: (error: Error) => boolean; +} + +/** + * Create a database connection. + * @param url String of the form adapter://user:password@host/database + * @param callback + * @returns Connection object. + */ +export declare function createConnection(url: string, callback?: (error: Error, connection: Connection) => void): Connection; + +/** + * Create a database connection. + * @param opts Object with adapter name and any properties that the given adapter requires + * @param callback + * @returns Connection object. + */ +export declare function createConnection(opts: ConnectOpts, callback?: (error: Error, connection: Connection) => void): Connection; + + +export declare function createPool(url: string, config: PoolConfig): ConnectionPool; +export declare function createPool(opts: ConnectOpts, config: PoolConfig): ConnectionPool; diff --git a/any-db/tsconfig.json b/any-db/tsconfig.json new file mode 100644 index 0000000000..80cbf86eb6 --- /dev/null +++ b/any-db/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "any-db-tests.ts" + ] +} \ No newline at end of file diff --git a/anydb-sql-migrations/anydb-sql-migrations-tests.ts b/anydb-sql-migrations/anydb-sql-migrations-tests.ts index f9c3da03a2..ed79ace368 100644 --- a/anydb-sql-migrations/anydb-sql-migrations-tests.ts +++ b/anydb-sql-migrations/anydb-sql-migrations-tests.ts @@ -1,5 +1,3 @@ -/// -/// import anydbsql = require('anydb-sql'); import { Table, Column } from 'anydb-sql' import migrator = require('anydb-sql-migrations'); diff --git a/anydb-sql-migrations/anydb-sql-migrations.d.ts b/anydb-sql-migrations/anydb-sql-migrations.d.ts deleted file mode 100644 index 9ab421c3ac..0000000000 --- a/anydb-sql-migrations/anydb-sql-migrations.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Type definitions for anydb-sql-migrations -// Project: https://github.com/spion/anydb-sql-migrations -// Definitions by: Gorgi Kosev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare module "anydb-sql-migrations" { - import Promise = require('bluebird'); - import { Column, Table, Transaction, AnydbSql } from 'anydb-sql'; - export interface Migration { - version: string; - } - export interface MigrationsTable extends Table { - version: Column; - } - export interface MigFn { - (tx: Transaction): Promise; - } - export interface MigrationTask { - up: MigFn; - down: MigFn; - name: string; - } - export function create(db: AnydbSql, tasks: any): { - run: () => Promise; - migrateTo: (target?: string) => Promise; - check: (f: (m: { - type: string; - items: MigrationTask[]; - }) => any) => Promise; - }; -} \ No newline at end of file diff --git a/anydb-sql-migrations/index.d.ts b/anydb-sql-migrations/index.d.ts new file mode 100644 index 0000000000..a72271ebb5 --- /dev/null +++ b/anydb-sql-migrations/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for anydb-sql-migrations +// Project: https://github.com/spion/anydb-sql-migrations +// Definitions by: Gorgi Kosev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import Promise = require('bluebird'); +import { Column, Table, Transaction, AnydbSql } from 'anydb-sql'; +export interface Migration { + version: string; +} +export interface MigrationsTable extends Table { + version: Column; +} +export interface MigFn { + (tx: Transaction): Promise; +} +export interface MigrationTask { + up: MigFn; + down: MigFn; + name: string; +} +export declare function create(db: AnydbSql, tasks: any): { + run: () => Promise; + migrateTo: (target?: string) => Promise; + check: (f: (m: { + type: string; + items: MigrationTask[]; + }) => any) => Promise; +}; diff --git a/anydb-sql-migrations/tsconfig.json b/anydb-sql-migrations/tsconfig.json new file mode 100644 index 0000000000..6f219e28f4 --- /dev/null +++ b/anydb-sql-migrations/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "anydb-sql-migrations-tests.ts" + ] +} \ No newline at end of file diff --git a/anydb-sql/anydb-sql-tests.ts b/anydb-sql/anydb-sql-tests.ts index 9e0264f7bb..745431d857 100644 --- a/anydb-sql/anydb-sql-tests.ts +++ b/anydb-sql/anydb-sql-tests.ts @@ -1,4 +1,4 @@ -/// + import anydbsql = require('anydb-sql'); import { Table, Column } from 'anydb-sql' diff --git a/anydb-sql/anydb-sql.d.ts b/anydb-sql/anydb-sql.d.ts deleted file mode 100644 index 6b5f0b2cd6..0000000000 --- a/anydb-sql/anydb-sql.d.ts +++ /dev/null @@ -1,190 +0,0 @@ -// Type definitions for anydb-sql -// Project: https://github.com/doxout/anydb-sql -// Definitions by: Gorgi Kosev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "anydb-sql" { - interface AnyDBPool extends anydbSQL.DatabaseConnection { - query:(text:string, values:any[], callback:(err:Error, result:any)=>void)=>void - begin:()=>anydbSQL.Transaction - close:(err:Error)=>void - } - - interface Dictionary { [key:string]:T; } - - namespace anydbSQL { - export interface OrderByValueNode {} - export interface ColumnDefinition { - primaryKey?:boolean; - dataType?:string; - references?: {table:string; column: string} - notNull?:boolean - } - - export interface TableDefinition { - name:string - columns:Dictionary - has?:Dictionary<{from:string; many?:boolean}> - } - - - export interface QueryLike { - query:string; - values: any[] - text:string - } - export interface DatabaseConnection { - queryAsync(query:string, ...params:any[]):Promise<{rowCount:number;rows:T[]}> - queryAsync(query:QueryLike):Promise<{rowCount:number;rows:T[]}> - } - - export interface Transaction extends DatabaseConnection { - rollback():void - commitAsync():Promise - } - - export interface SubQuery { - select(node:Column):SubQuery - where(...nodes:any[]):SubQuery - from(table:TableNode):SubQuery - group(...nodes:any[]):SubQuery - order(criteria:OrderByValueNode):SubQuery - notExists(subQuery:SubQuery):SubQuery - } - - interface Executable { - get():Promise - getWithin(tx:DatabaseConnection):Promise - exec():Promise - all():Promise - execWithin(tx:DatabaseConnection):Promise - allWithin(tx:DatabaseConnection):Promise - toQuery():QueryLike; - } - - interface Queryable { - where(...nodes:any[]):Query - delete():ModifyingQuery - select(...nodes:any[]):Query - selectDeep(table: Table): Query - selectDeep(...nodesOrTables:any[]):Query - } - - export interface Query extends Executable, Queryable { - from(table:TableNode):Query - update(o:Dictionary):ModifyingQuery - update(o:{}):ModifyingQuery - group(...nodes:any[]):Query - order(...criteria:OrderByValueNode[]):Query - limit(l:number):Query - offset(o:number):Query - } - - export interface ModifyingQuery extends Executable { - returning(...nodes:any[]):Query - where(...nodes:any[]):ModifyingQuery - } - - export interface TableNode { - join(table:TableNode):JoinTableNode - leftJoin(table:TableNode):JoinTableNode - } - - export interface JoinTableNode extends TableNode { - on(filter:BinaryNode):TableNode - on(filter:string):TableNode - } - - interface CreateQuery extends Executable { - ifNotExists():Executable - } - interface DropQuery extends Executable { - ifExists():Executable - } - export interface Table extends TableNode, Queryable { - create():CreateQuery - drop():DropQuery - as(name:string):Table - update(o:any):ModifyingQuery - insert(row:T):ModifyingQuery - insert(rows:T[]):ModifyingQuery - select():Query - select(...nodes:any[]):Query - from(table:TableNode):Query - star():Column - subQuery():SubQuery - eventEmitter:{emit:(type:string, ...args:any[])=>void - on:(eventName:string, handler:Function)=>void} - columns:Column[] - sql: SQL; - alter():AlterQuery - } - export interface AlterQuery extends Executable { - addColumn(column:Column): AlterQuery; - addColumn(name: string, options:string): AlterQuery; - dropColumn(column: Column): AlterQuery; - renameColumn(column: Column, newColumn: Column):AlterQuery; - renameColumn(column: Column, newName: string):AlterQuery; - renameColumn(name: string, newName: string):AlterQuery; - rename(newName: string): AlterQuery - } - - export interface SQL { - functions: { - LOWER(c:Column):Column - } - } - - export interface BinaryNode { - and(node:BinaryNode):BinaryNode - or(node:BinaryNode):BinaryNode - } - - export interface Column { - in(arr:T[]):BinaryNode - in(subQuery:SubQuery):BinaryNode - notIn(arr:T[]):BinaryNode - equals(node:any):BinaryNode - notEquals(node:any):BinaryNode - gte(node:any):BinaryNode - lte(node:any):BinaryNode - gt(node:any):BinaryNode - lt(node:any):BinaryNode - like(str:string):BinaryNode - multiply:{ - (node:Column):Column - (n:number):Column - } - isNull():BinaryNode - isNotNull():BinaryNode - sum():Column - count():Column - count(name:string):Column - distinct():Column - as(name:string):Column - ascending:OrderByValueNode - descending:OrderByValueNode - asc:OrderByValueNode - desc:OrderByValueNode - } - - export interface AnydbSql extends DatabaseConnection { - define(map:TableDefinition):Table; - transaction(fn:(tx:Transaction)=>Promise):Promise - allOf(...tables:Table[]):any - models:Dictionary> - functions:{LOWER:(name:Column)=>Column - RTRIM:(name:Column)=>Column} - makeFunction(name:string):Function - begin():Transaction - open():void; - close():void; - getPool():AnyDBPool; - dialect():string; - } - } - - function anydbSQL(config:Object):anydbSQL.AnydbSql; - - export = anydbSQL; -} diff --git a/anydb-sql/index.d.ts b/anydb-sql/index.d.ts new file mode 100644 index 0000000000..367ade6ff9 --- /dev/null +++ b/anydb-sql/index.d.ts @@ -0,0 +1,193 @@ +// Type definitions for anydb-sql +// Project: https://github.com/doxout/anydb-sql +// Definitions by: Gorgi Kosev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +interface AnyDBPool extends anydbSQL.DatabaseConnection { + query: (text: string, values: any[], callback: (err: Error, result: any) => void) => void + begin: () => anydbSQL.Transaction + close: (err: Error) => void +} + +interface Dictionary { [key: string]: T; } + +declare namespace anydbSQL { + export interface OrderByValueNode { } + export interface ColumnDefinition { + primaryKey?: boolean; + dataType?: string; + references?: { table: string; column: string } + notNull?: boolean + } + + export interface TableDefinition { + name: string + columns: Dictionary + has?: Dictionary<{ from: string; many?: boolean }> + } + + + export interface QueryLike { + query: string; + values: any[] + text: string + } + export interface DatabaseConnection { + queryAsync(query: string, ...params: any[]): Promise<{ rowCount: number; rows: T[] }> + queryAsync(query: QueryLike): Promise<{ rowCount: number; rows: T[] }> + } + + export interface Transaction extends DatabaseConnection { + rollback(): void + commitAsync(): Promise + } + + export interface SubQuery { + select(node: Column): SubQuery + where(...nodes: any[]): SubQuery + from(table: TableNode): SubQuery + group(...nodes: any[]): SubQuery + order(criteria: OrderByValueNode): SubQuery + notExists(subQuery: SubQuery): SubQuery + } + + interface Executable { + get(): Promise + getWithin(tx: DatabaseConnection): Promise + exec(): Promise + all(): Promise + execWithin(tx: DatabaseConnection): Promise + allWithin(tx: DatabaseConnection): Promise + toQuery(): QueryLike; + } + + interface Queryable { + where(...nodes: any[]): Query + delete(): ModifyingQuery + select(...nodes: any[]): Query + selectDeep(table: Table): Query + selectDeep(...nodesOrTables: any[]): Query + } + + export interface Query extends Executable, Queryable { + from(table: TableNode): Query + update(o: Dictionary): ModifyingQuery + update(o: {}): ModifyingQuery + group(...nodes: any[]): Query + order(...criteria: OrderByValueNode[]): Query + limit(l: number): Query + offset(o: number): Query + } + + export interface ModifyingQuery extends Executable { + returning(...nodes: any[]): Query + where(...nodes: any[]): ModifyingQuery + } + + export interface TableNode { + join(table: TableNode): JoinTableNode + leftJoin(table: TableNode): JoinTableNode + } + + export interface JoinTableNode extends TableNode { + on(filter: BinaryNode): TableNode + on(filter: string): TableNode + } + + interface CreateQuery extends Executable { + ifNotExists(): Executable + } + interface DropQuery extends Executable { + ifExists(): Executable + } + export interface Table extends TableNode, Queryable { + create(): CreateQuery + drop(): DropQuery + as(name: string): Table + update(o: any): ModifyingQuery + insert(row: T): ModifyingQuery + insert(rows: T[]): ModifyingQuery + select(): Query + select(...nodes: any[]): Query + from(table: TableNode): Query + star(): Column + subQuery(): SubQuery + eventEmitter: { + emit: (type: string, ...args: any[]) => void + on: (eventName: string, handler: Function) => void + } + columns: Column[] + sql: SQL; + alter(): AlterQuery + } + export interface AlterQuery extends Executable { + addColumn(column: Column): AlterQuery; + addColumn(name: string, options: string): AlterQuery; + dropColumn(column: Column): AlterQuery; + renameColumn(column: Column, newColumn: Column): AlterQuery; + renameColumn(column: Column, newName: string): AlterQuery; + renameColumn(name: string, newName: string): AlterQuery; + rename(newName: string): AlterQuery + } + + export interface SQL { + functions: { + LOWER(c: Column): Column + } + } + + export interface BinaryNode { + and(node: BinaryNode): BinaryNode + or(node: BinaryNode): BinaryNode + } + + export interface Column { + in(arr: T[]): BinaryNode + in(subQuery: SubQuery): BinaryNode + notIn(arr: T[]): BinaryNode + equals(node: any): BinaryNode + notEquals(node: any): BinaryNode + gte(node: any): BinaryNode + lte(node: any): BinaryNode + gt(node: any): BinaryNode + lt(node: any): BinaryNode + like(str: string): BinaryNode + multiply: { + (node: Column): Column + (n: number): Column + } + isNull(): BinaryNode + isNotNull(): BinaryNode + sum(): Column + count(): Column + count(name: string): Column + distinct(): Column + as(name: string): Column + ascending: OrderByValueNode + descending: OrderByValueNode + asc: OrderByValueNode + desc: OrderByValueNode + } + + export interface AnydbSql extends DatabaseConnection { + define(map: TableDefinition): Table; + transaction(fn: (tx: Transaction) => Promise): Promise + allOf(...tables: Table[]): any + models: Dictionary> + functions: { + LOWER: (name: Column) => Column + RTRIM: (name: Column) => Column + } + makeFunction(name: string): Function + begin(): Transaction + open(): void; + close(): void; + getPool(): AnyDBPool; + dialect(): string; + } +} + +declare function anydbSQL(config: Object): anydbSQL.AnydbSql; + +export = anydbSQL; diff --git a/anydb-sql/tsconfig.json b/anydb-sql/tsconfig.json new file mode 100644 index 0000000000..7d21e01799 --- /dev/null +++ b/anydb-sql/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "anydb-sql-tests.ts" + ] +} \ No newline at end of file diff --git a/api-error-handler/api-error-handler-tests.ts b/api-error-handler/api-error-handler-tests.ts index fc92cf9a70..3bc39c4a7b 100644 --- a/api-error-handler/api-error-handler-tests.ts +++ b/api-error-handler/api-error-handler-tests.ts @@ -1,4 +1,3 @@ -/// import * as errorHandler from 'api-error-handler'; import * as express from 'express'; diff --git a/api-error-handler/api-error-handler.d.ts b/api-error-handler/api-error-handler.d.ts deleted file mode 100644 index 96fbb16b29..0000000000 --- a/api-error-handler/api-error-handler.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Type definitions for api-error-handler v1.0.0 -// Project: https://github.com/expressjs/api-error-handler -// Definitions by: Tanguy Krotoff -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'api-error-handler' { - import * as express from 'express'; - - namespace apiErrorHandler { - - // Body response: the JSON returned by api-error-handler - // See https://github.com/expressjs/api-error-handler/blob/1.0.0/index.js - interface Response { - status: number; - stack?: string; - message: string; - - // Client errors - code?: any; - name?: string; - type?: any; - } - } - - function apiErrorHandler(options?: any): express.ErrorRequestHandler; - - export = apiErrorHandler; -} diff --git a/api-error-handler/index.d.ts b/api-error-handler/index.d.ts new file mode 100644 index 0000000000..e9337cc448 --- /dev/null +++ b/api-error-handler/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for api-error-handler v1.0.0 +// Project: https://github.com/expressjs/api-error-handler +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + + +import * as express from 'express'; + +declare namespace apiErrorHandler { + + // Body response: the JSON returned by api-error-handler + // See https://github.com/expressjs/api-error-handler/blob/1.0.0/index.js + interface Response { + status: number; + stack?: string; + message: string; + + // Client errors + code?: any; + name?: string; + type?: any; + } +} + +declare function apiErrorHandler(options?: any): express.ErrorRequestHandler; + +export = apiErrorHandler; diff --git a/api-error-handler/tsconfig.json b/api-error-handler/tsconfig.json new file mode 100644 index 0000000000..331888b947 --- /dev/null +++ b/api-error-handler/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "api-error-handler-tests.ts" + ] +} \ No newline at end of file diff --git a/apn/apn-tests.ts b/apn/apn-tests.ts index b47259d76b..ea4bb34ae3 100644 --- a/apn/apn-tests.ts +++ b/apn/apn-tests.ts @@ -1,4 +1,3 @@ -/// import apn = require("apn"); //Hand made TypeScript tests diff --git a/apn/apn.d.ts b/apn/apn.d.ts deleted file mode 100644 index cf11b13c0e..0000000000 --- a/apn/apn.d.ts +++ /dev/null @@ -1,364 +0,0 @@ -// Type definitions for node-apn -// Project: https://github.com/argon/node-apn -// Definitions by: Zenorbi -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -declare module "apn" { - import events = require("events"); - import net = require("net"); - export interface ConnectionOptions { - /** - * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) - */ - cert?:string|Buffer; - /** - * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) - */ - key?:string|Buffer; - /** - * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). - */ - ca?:(string|Buffer)[]; - /** - * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will always be used instead of certificate and key above. - */ - pfx?:string|Buffer; - /** - * The passphrase for the connection key, if required - */ - passphrase?:string; - /** - * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) - */ - production?:boolean; - /** - * Enable when you are using a VoIP certificate to enable paylods up to 4096 bytes. - */ - voip?:boolean; - /** - * Gateway port (Defaults to: `2195`) - */ - port?:number; - /** - * Reject Unauthorized property to be passed through to tls.connect() (Defaults to `true`) - */ - rejectUnauthorized?:boolean; - /** - * Number of notifications to cache for error purposes (See "Handling Errors" below, (Defaults to: `1000`) - */ - cacheLength?:number; - /** - * Whether the cache should grow in response to messages being lost after errors. (Will still emit a 'cacheTooSmall' event) (Defaults to: `true`) - */ - autoAdjustCache?:boolean; - /** - * The maximum number of connections to create for sending messages. (Defaults to: `1`) - */ - maxConnections?:number; - /** - * The duration of time the module should wait, in milliseconds, when trying to establish a connection to Apple before failing. 0 = Disabled. {Defaults to: `10000`} - */ - connectTimeout?:number; - /** - * The duration the socket should stay alive with no activity in milliseconds. 0 = Disabled. (Defaults to: `3600000` - 1h) - */ - connectionTimeout?:number; - /** - * The maximum number of connection failures that will be tolerated before `apn` will "terminate". (Defaults to: 10) - */ - connectionRetryLimit?:number; - /** - * Whether to buffer notifications and resend them after failure. (Defaults to: `true`) - */ - buffersNotifications?:number; - /** - * Whether to aggresively empty the notification buffer while connected - if set to true node-apn may enter a tight loop under heavy load while delivering notifications. (Defaults to: `false`) - */ - fastMode?:boolean; - } - export class Connection extends events.EventEmitter { - constructor(options:ConnectionOptions); - /** - * This is the business end of the module. Create a `Notification` object and pass it in, along with a single recipient or an array of them and node-apn will take care of the rest, delivering the notification to each recipient. - * - * A "recipient" is either a `Device` object, a `String`, or a `Buffer` containing the device token. `Device` objects are used internally and will be created if necessary. Where applicable, all events will return a `Device` regardless of the type passed to this method. - */ - pushNotification(notification:Notification, recipient:Device|string|Buffer|(Device|string|Buffer)[]):void; - /** - * Used to manually adjust the "cacheLength" property in the options. This is ideal if you choose to use the `cacheTooSmall` event to tweak your environment. It is safe for increasing and reducing cache size. - */ - setCacheLength(newLength:number):void; - /** - * Indicate to node-apn that when the queue of pending notifications is fully drained that it should close all open connections. This will mean that if there are no other pending resources (open sockets, running timers, etc.) the application will terminate. If notifications are pushed after the connection has completely shutdown a new connection will be established and, if applicable, `shutdown` will need to be called again. - */ - shutdown():void; - /** - * Emitted when an error occurs during initialisation of the module, usually due to a problem with the keys and certificates. - */ - on(event: "error", listener: (error:Error) => void):this; - /** - * Emitted when the connection socket experiences an error. This may be useful for debugging but no action should be necessary. - */ - on(event: "socketError", listener: (error:Error) => void):this; - /** - * Emitted when a notification has been sent to Apple - not a guarantee that it has been accepted by Apple, an error relating to it may occur later on. A notification may also be "transmitted" several times if a preceding notification caused an error requiring retransmission. - */ - on(event: "transmitted", listener: (notification:Notification, decive:Device) => void):this; - /** - * Emitted when all pending notifications have been transmitted to Apple and the pending queue is empty. This may be called more than once if a notification error occurs and notifications must be re-sent. - */ - on(event: "completed", listener: () => void):this; - /** - * Emitted when Apple returns a notification as invalid but the notification has already been expunged from the cache - usually due to high throughput and indicates that notifications will be getting lost. The parameter is an estimate of how many notifications have been lost. You should experiment with increasing the cache size or enabling ```autoAdjustCache``` if you see this frequently. - * - * **Note**: With ```autoAdjustCache``` enabled this event will still be emitted when an adjustment is triggered. - */ - on(event: "cacheTooSmall", listener: (sizeDifference:number) => void):this; - /** - * Emitted when a connection to Apple is successfully established. The parameter indicates the number of open connections. No action is required as the connection is managed internally. - */ - on(event: "connected", listener: (openSockets:net.Socket[]) => void):this; - /** - * Emitted when the connection to Apple has been closed, this could be for numerous reasons, for example an error has occurred or the connection has timed out. The parameter is the same as for `connected` and again, no action is required. - */ - on(event: "disconnected", listener: (openSockets:net.Socket[]) => void):this; - /** - * Emitted when the connectionTimeout option has been specified and no activity has occurred on a socket for a specified duration. The socket will be closed immediately after this event and a `disconnected` event will also be emitted. - */ - on(event: "timeout", listener: () => void):this; - /** - * Emitted when a message has been received from Apple stating that a notification was invalid or if an internal error occurred before that notification could be pushed to Apple. If the notification is still in the cache it will be passed as the second argument, otherwise null. Where possible the associated `Device` object will be passed as a third parameter, however in cases where the token supplied to the module cannot be parsed into a `Buffer` the supplied value will be returned. - - * Error codes smaller than 512 correspond to those returned by Apple as per their [docs][errors]. Other errors are applicable to `node-apn` itself. Definitions can be found in `lib/errors.js`. - */ - on(event: "transmissionError", listener: (errorCode:number, notification:Notification, device:Device|Buffer) => void):this; - on(event: string, listener: Function):this; - } - export interface NotificationAlertOptions { - title?:string; - body:string; - "title-loc-key"?:string; - "title-loc-args"?:string[]; - "action-loc-key"?:string; - "loc-key"?:string; - "loc-args"?:string[]; - "launch-image"?:string; - } - export class Notification { - /** - * The maximum number of retries which should be performed when sending a notification if an error occurs. A value of 0 will only allow one attempt at sending (0 retries). Set to -1 to disable (default). - */ - public retryLimit:number; - /** - * The UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately. - */ - public expiry:number; - /** - * From Apple's Documentation, Provide one of the following values: - * - * - 10 - The push message is sent immediately. (Default) - * > The push notification must trigger an alert, sound, or badge on the device. It is an error use this priority for a push that contains only the content-available key. - * - 5 - The push message is sent at a time that conserves power on the device receiving it. - */ - public priority:number; - /** - * The encoding to use when transmitting the notification to APNS, defaults to `utf8`. `utf16le` is also possible but as each character is represented by a minimum of 2 bytes, will at least halve the possible payload size. If in doubt leave as default. - */ - public encoding:string; - /** - * This object represents the root JSON object that you can add custom information for your application to. The properties below will only be added to the payload (under `aps`) when the notification is prepared for sending. - */ - public payload:any; - /** - * The value to specify for `payload.aps.badge` - */ - public badge:number; - /** - * The value to specify for `payload.aps.sound` - */ - public sound:string; - /** - * The value to specify for `payload.aps.alert` can be either a `String` or an `Object` as outlined by the payload documentation. - */ - public alert:string|NotificationAlertOptions; - /** - * Setting this to true will specify "content-available" in the payload when it is compiled. - */ - public newsstandAvailable:boolean; - /** - * Setting this to true will specify "content-available" in the payload when it is compiled. - */ - public contentAvailable:boolean; - /** - * The value to specify for the `mdm` field where applicable. - */ - public mdm:string|Object; - /** - * The value to specify for `payload.aps['url-args']`. This used for Safari Push NOtifications and should be an array of values in accordance with the Web Payload Documentation. - */ - public urlArgs:string[]; - /** - * When this parameter is set and `notification#trim()` is called it will attempt to truncate the string at the nearest space. - */ - public truncateAtWordEnd:boolean; - /** - * You can optionally pass in an object representing the payload, or configure properties on the returned object. - */ - constructor(payload?:any); - /** - * Set the `aps.alert` text body. This will use the most space-efficient means. - */ - setAlertText(alertText:string):Notification; - /** - * Set the `title` property of the `aps.alert` object - used with Safari Push Notifications - */ - setAlertTitle(alertTitle:string):Notification; - /** - * Set the `action` property of the `aps.alert` object - used with Safari Push Notifications - */ - setAlertAction(alertAction:string):Notification; - /** - * Set the `action-loc-key` property of the `aps.alert` object. - */ - setActionLocKey(key:string):Notification; - /** - * Set the `loc-key` property of the `aps.alert` object. - */ - setLocKey(key:string):Notification; - /** - * Set the `loc-args` property of the `aps.alert` object. - */ - setLocArgs(args:string[]):Notification; - /** - * Set the `launch-image` property of the `aps.alert` object. - */ - setLaunchImage(image:string):Notification; - /** - * Set the `mdm` property on the payload. - */ - setMDM(mdm:string|Object):Notification; - /** - * Set the `content-available` property of the `aps` object. - */ - setNewsstandAvailable(available:boolean):Notification; - /** - * Set the `content-available` property of the `aps` object. - */ - setContentAvailable(available:boolean):Notification; - /** - * Set the `url-args` property of the `aps` object. - */ - setUrlArgs(urlArgs:string[]):Notification; - /** - * Attempt to automatically trim the notification alert text body to meet the payload size limit of 2048 bytes. - */ - trim():number; - } - export class Device { - public token:Buffer; - /** - * `deviceToken` can be a `Buffer` or a `String` containing a "hex" representation of the token. Throws an error if the deviceToken supplied is invalid. - */ - constructor(deviceToken:string|Buffer); - } - - export interface FeedbackOptions { - /** - * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) - */ - cert?:string|Buffer; - /** - * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) - */ - key?:string|Buffer; - /** - * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). - */ - ca?:(string|Buffer)[]; - /** - * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will be used instead of certificate and key above. - */ - pfx?:string|Buffer; - /** - * The passphrase for the connection key, if required - */ - passphrase?:string; - /** - * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) - */ - production?:boolean; - /** - * Feedback server port (Defaults to: `2196`) - */ - port?:number; - /** - * Sets the behaviour for triggering the `feedback` event. When `true` the event will be triggered once per connection with an array of timestamp and device token tuples. Otherwise a `feedback` event will be emitted once per token received. (Defaults to: true) - */ - batchFeedback?:boolean; - /** - * The maximum number of tokens to pass when emitting the event - a value of 0 will cause all tokens to be passed after connection is reset. After this number of tokens are received the `feedback` event will be emitted. (Only applies when `batchFeedback` is enabled) - */ - batchSize?:number; - /** - * How often to automatically poll the feedback service. Set to `0` to disable. (Defaults to: `3600`) - */ - interval?:number; - } - export interface FeedbackData { - time:number; - device:Device; - } - /** - * Connection to the Apple Push Notification Feedback Service and if `interval` isn't disabled automatically begins polling the service. Many of the options are the same as `apn.Connection()` - */ - export class Feedback { - constructor(options:FeedbackOptions); - /** - * Trigger a query of the feedback service. If `interval` is non-zero then this method will be called automatically. - */ - start():void; - /** - * You can cancel the interval by calling `feedback.cancel()`. If you do not wish to have the service automatically queried then set `interval` to 0 and use `feedback.start()` to manually invoke it one time. - */ - cancel():void; - /** - * Emitted when an error occurs initialising the module. Usually caused by failing to load the certificates. - */ - on(event: "error", listener: (error:Error) => void):Feedback; - /** - * Emitted when an error occurs receiving or processing the feedback and in the case of a socket error occurring. These errors are usually informational and node-apn will automatically recover. - */ - on(event: "feedbackError", listener: (error:Error) => void):Feedback; - /** - * Emitted when data has been received from the feedback service, typically once per connection. `feedbackData` is an array of objects, each containing the `time` returned by the server (epoch time) and the `device` a `Buffer` containing the device token. - */ - on(event: "feedback", listener: (feedbackData:FeedbackData[]) => void):Feedback; - on(event: string, listener: Function):Feedback; - } - - export enum Errors { - "noErrorsEncountered"= 0, - "processingError"= 1, - "missingDeviceToken"= 2, - "missingTopic"= 3, - "missingPayload"= 4, - "invalidTokenSize"= 5, - "invalidTopicSize"= 6, - "invalidPayloadSize"= 7, - "invalidToken"= 8, - "apnsShutdown"= 10, - "none"= 255, - "retryLimitExceeded"= 512, - "moduleInitialisationFailed"= 513, - "connectionRetryLimitExceeded"= 514, // When a connection is unable to be established. Usually because of a network / SSL error this will be emitted - "connectionTerminated"= 515 - } - - //Lowercase aliases - export {Connection as connection}; - export {Device as device}; - export {Errors as error}; - export {Feedback as feedback}; - export {Notification as notification}; -} diff --git a/apn/index.d.ts b/apn/index.d.ts new file mode 100644 index 0000000000..7a36c396b4 --- /dev/null +++ b/apn/index.d.ts @@ -0,0 +1,363 @@ +// Type definitions for node-apn +// Project: https://github.com/argon/node-apn +// Definitions by: Zenorbi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import events = require("events"); +import net = require("net"); +export interface ConnectionOptions { + /** + * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) + */ + cert?: string | Buffer; + /** + * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) + */ + key?: string | Buffer; + /** + * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). + */ + ca?: (string | Buffer)[]; + /** + * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will always be used instead of certificate and key above. + */ + pfx?: string | Buffer; + /** + * The passphrase for the connection key, if required + */ + passphrase?: string; + /** + * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) + */ + production?: boolean; + /** + * Enable when you are using a VoIP certificate to enable paylods up to 4096 bytes. + */ + voip?: boolean; + /** + * Gateway port (Defaults to: `2195`) + */ + port?: number; + /** + * Reject Unauthorized property to be passed through to tls.connect() (Defaults to `true`) + */ + rejectUnauthorized?: boolean; + /** + * Number of notifications to cache for error purposes (See "Handling Errors" below, (Defaults to: `1000`) + */ + cacheLength?: number; + /** + * Whether the cache should grow in response to messages being lost after errors. (Will still emit a 'cacheTooSmall' event) (Defaults to: `true`) + */ + autoAdjustCache?: boolean; + /** + * The maximum number of connections to create for sending messages. (Defaults to: `1`) + */ + maxConnections?: number; + /** + * The duration of time the module should wait, in milliseconds, when trying to establish a connection to Apple before failing. 0 = Disabled. {Defaults to: `10000`} + */ + connectTimeout?: number; + /** + * The duration the socket should stay alive with no activity in milliseconds. 0 = Disabled. (Defaults to: `3600000` - 1h) + */ + connectionTimeout?: number; + /** + * The maximum number of connection failures that will be tolerated before `apn` will "terminate". (Defaults to: 10) + */ + connectionRetryLimit?: number; + /** + * Whether to buffer notifications and resend them after failure. (Defaults to: `true`) + */ + buffersNotifications?: number; + /** + * Whether to aggresively empty the notification buffer while connected - if set to true node-apn may enter a tight loop under heavy load while delivering notifications. (Defaults to: `false`) + */ + fastMode?: boolean; +} +export declare class Connection extends events.EventEmitter { + constructor(options: ConnectionOptions); + /** + * This is the business end of the module. Create a `Notification` object and pass it in, along with a single recipient or an array of them and node-apn will take care of the rest, delivering the notification to each recipient. + * + * A "recipient" is either a `Device` object, a `String`, or a `Buffer` containing the device token. `Device` objects are used internally and will be created if necessary. Where applicable, all events will return a `Device` regardless of the type passed to this method. + */ + pushNotification(notification: Notification, recipient: Device | string | Buffer | (Device | string | Buffer)[]): void; + /** + * Used to manually adjust the "cacheLength" property in the options. This is ideal if you choose to use the `cacheTooSmall` event to tweak your environment. It is safe for increasing and reducing cache size. + */ + setCacheLength(newLength: number): void; + /** + * Indicate to node-apn that when the queue of pending notifications is fully drained that it should close all open connections. This will mean that if there are no other pending resources (open sockets, running timers, etc.) the application will terminate. If notifications are pushed after the connection has completely shutdown a new connection will be established and, if applicable, `shutdown` will need to be called again. + */ + shutdown(): void; + /** + * Emitted when an error occurs during initialisation of the module, usually due to a problem with the keys and certificates. + */ + on(event: "error", listener: (error: Error) => void): this; + /** + * Emitted when the connection socket experiences an error. This may be useful for debugging but no action should be necessary. + */ + on(event: "socketError", listener: (error: Error) => void): this; + /** + * Emitted when a notification has been sent to Apple - not a guarantee that it has been accepted by Apple, an error relating to it may occur later on. A notification may also be "transmitted" several times if a preceding notification caused an error requiring retransmission. + */ + on(event: "transmitted", listener: (notification: Notification, decive: Device) => void): this; + /** + * Emitted when all pending notifications have been transmitted to Apple and the pending queue is empty. This may be called more than once if a notification error occurs and notifications must be re-sent. + */ + on(event: "completed", listener: () => void): this; + /** + * Emitted when Apple returns a notification as invalid but the notification has already been expunged from the cache - usually due to high throughput and indicates that notifications will be getting lost. The parameter is an estimate of how many notifications have been lost. You should experiment with increasing the cache size or enabling ```autoAdjustCache``` if you see this frequently. + * + * **Note**: With ```autoAdjustCache``` enabled this event will still be emitted when an adjustment is triggered. + */ + on(event: "cacheTooSmall", listener: (sizeDifference: number) => void): this; + /** + * Emitted when a connection to Apple is successfully established. The parameter indicates the number of open connections. No action is required as the connection is managed internally. + */ + on(event: "connected", listener: (openSockets: net.Socket[]) => void): this; + /** + * Emitted when the connection to Apple has been closed, this could be for numerous reasons, for example an error has occurred or the connection has timed out. The parameter is the same as for `connected` and again, no action is required. + */ + on(event: "disconnected", listener: (openSockets: net.Socket[]) => void): this; + /** + * Emitted when the connectionTimeout option has been specified and no activity has occurred on a socket for a specified duration. The socket will be closed immediately after this event and a `disconnected` event will also be emitted. + */ + on(event: "timeout", listener: () => void): this; + /** + * Emitted when a message has been received from Apple stating that a notification was invalid or if an internal error occurred before that notification could be pushed to Apple. If the notification is still in the cache it will be passed as the second argument, otherwise null. Where possible the associated `Device` object will be passed as a third parameter, however in cases where the token supplied to the module cannot be parsed into a `Buffer` the supplied value will be returned. + + * Error codes smaller than 512 correspond to those returned by Apple as per their [docs][errors]. Other errors are applicable to `node-apn` itself. Definitions can be found in `lib/errors.js`. + */ + on(event: "transmissionError", listener: (errorCode: number, notification: Notification, device: Device | Buffer) => void): this; + on(event: string, listener: Function): this; +} +export interface NotificationAlertOptions { + title?: string; + body: string; + "title-loc-key"?: string; + "title-loc-args"?: string[]; + "action-loc-key"?: string; + "loc-key"?: string; + "loc-args"?: string[]; + "launch-image"?: string; +} +export declare class Notification { + /** + * The maximum number of retries which should be performed when sending a notification if an error occurs. A value of 0 will only allow one attempt at sending (0 retries). Set to -1 to disable (default). + */ + public retryLimit: number; + /** + * The UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately. + */ + public expiry: number; + /** + * From Apple's Documentation, Provide one of the following values: + * + * - 10 - The push message is sent immediately. (Default) + * > The push notification must trigger an alert, sound, or badge on the device. It is an error use this priority for a push that contains only the content-available key. + * - 5 - The push message is sent at a time that conserves power on the device receiving it. + */ + public priority: number; + /** + * The encoding to use when transmitting the notification to APNS, defaults to `utf8`. `utf16le` is also possible but as each character is represented by a minimum of 2 bytes, will at least halve the possible payload size. If in doubt leave as default. + */ + public encoding: string; + /** + * This object represents the root JSON object that you can add custom information for your application to. The properties below will only be added to the payload (under `aps`) when the notification is prepared for sending. + */ + public payload: any; + /** + * The value to specify for `payload.aps.badge` + */ + public badge: number; + /** + * The value to specify for `payload.aps.sound` + */ + public sound: string; + /** + * The value to specify for `payload.aps.alert` can be either a `String` or an `Object` as outlined by the payload documentation. + */ + public alert: string | NotificationAlertOptions; + /** + * Setting this to true will specify "content-available" in the payload when it is compiled. + */ + public newsstandAvailable: boolean; + /** + * Setting this to true will specify "content-available" in the payload when it is compiled. + */ + public contentAvailable: boolean; + /** + * The value to specify for the `mdm` field where applicable. + */ + public mdm: string | Object; + /** + * The value to specify for `payload.aps['url-args']`. This used for Safari Push NOtifications and should be an array of values in accordance with the Web Payload Documentation. + */ + public urlArgs: string[]; + /** + * When this parameter is set and `notification#trim()` is called it will attempt to truncate the string at the nearest space. + */ + public truncateAtWordEnd: boolean; + /** + * You can optionally pass in an object representing the payload, or configure properties on the returned object. + */ + constructor(payload?: any); + /** + * Set the `aps.alert` text body. This will use the most space-efficient means. + */ + setAlertText(alertText: string): Notification; + /** + * Set the `title` property of the `aps.alert` object - used with Safari Push Notifications + */ + setAlertTitle(alertTitle: string): Notification; + /** + * Set the `action` property of the `aps.alert` object - used with Safari Push Notifications + */ + setAlertAction(alertAction: string): Notification; + /** + * Set the `action-loc-key` property of the `aps.alert` object. + */ + setActionLocKey(key: string): Notification; + /** + * Set the `loc-key` property of the `aps.alert` object. + */ + setLocKey(key: string): Notification; + /** + * Set the `loc-args` property of the `aps.alert` object. + */ + setLocArgs(args: string[]): Notification; + /** + * Set the `launch-image` property of the `aps.alert` object. + */ + setLaunchImage(image: string): Notification; + /** + * Set the `mdm` property on the payload. + */ + setMDM(mdm: string | Object): Notification; + /** + * Set the `content-available` property of the `aps` object. + */ + setNewsstandAvailable(available: boolean): Notification; + /** + * Set the `content-available` property of the `aps` object. + */ + setContentAvailable(available: boolean): Notification; + /** + * Set the `url-args` property of the `aps` object. + */ + setUrlArgs(urlArgs: string[]): Notification; + /** + * Attempt to automatically trim the notification alert text body to meet the payload size limit of 2048 bytes. + */ + trim(): number; +} +export declare class Device { + public token: Buffer; + /** + * `deviceToken` can be a `Buffer` or a `String` containing a "hex" representation of the token. Throws an error if the deviceToken supplied is invalid. + */ + constructor(deviceToken: string | Buffer); +} + +export interface FeedbackOptions { + /** + * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) + */ + cert?: string | Buffer; + /** + * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) + */ + key?: string | Buffer; + /** + * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). + */ + ca?: (string | Buffer)[]; + /** + * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will be used instead of certificate and key above. + */ + pfx?: string | Buffer; + /** + * The passphrase for the connection key, if required + */ + passphrase?: string; + /** + * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) + */ + production?: boolean; + /** + * Feedback server port (Defaults to: `2196`) + */ + port?: number; + /** + * Sets the behaviour for triggering the `feedback` event. When `true` the event will be triggered once per connection with an array of timestamp and device token tuples. Otherwise a `feedback` event will be emitted once per token received. (Defaults to: true) + */ + batchFeedback?: boolean; + /** + * The maximum number of tokens to pass when emitting the event - a value of 0 will cause all tokens to be passed after connection is reset. After this number of tokens are received the `feedback` event will be emitted. (Only applies when `batchFeedback` is enabled) + */ + batchSize?: number; + /** + * How often to automatically poll the feedback service. Set to `0` to disable. (Defaults to: `3600`) + */ + interval?: number; +} +export interface FeedbackData { + time: number; + device: Device; +} +/** + * Connection to the Apple Push Notification Feedback Service and if `interval` isn't disabled automatically begins polling the service. Many of the options are the same as `apn.Connection()` + */ +export declare class Feedback { + constructor(options: FeedbackOptions); + /** + * Trigger a query of the feedback service. If `interval` is non-zero then this method will be called automatically. + */ + start(): void; + /** + * You can cancel the interval by calling `feedback.cancel()`. If you do not wish to have the service automatically queried then set `interval` to 0 and use `feedback.start()` to manually invoke it one time. + */ + cancel(): void; + /** + * Emitted when an error occurs initialising the module. Usually caused by failing to load the certificates. + */ + on(event: "error", listener: (error: Error) => void): Feedback; + /** + * Emitted when an error occurs receiving or processing the feedback and in the case of a socket error occurring. These errors are usually informational and node-apn will automatically recover. + */ + on(event: "feedbackError", listener: (error: Error) => void): Feedback; + /** + * Emitted when data has been received from the feedback service, typically once per connection. `feedbackData` is an array of objects, each containing the `time` returned by the server (epoch time) and the `device` a `Buffer` containing the device token. + */ + on(event: "feedback", listener: (feedbackData: FeedbackData[]) => void): Feedback; + on(event: string, listener: Function): Feedback; +} + +export declare enum Errors { + "noErrorsEncountered" = 0, + "processingError" = 1, + "missingDeviceToken" = 2, + "missingTopic" = 3, + "missingPayload" = 4, + "invalidTokenSize" = 5, + "invalidTopicSize" = 6, + "invalidPayloadSize" = 7, + "invalidToken" = 8, + "apnsShutdown" = 10, + "none" = 255, + "retryLimitExceeded" = 512, + "moduleInitialisationFailed" = 513, + "connectionRetryLimitExceeded" = 514, // When a connection is unable to be established. Usually because of a network / SSL error this will be emitted + "connectionTerminated" = 515 +} + +//Lowercase aliases +export {Connection as connection}; +export {Device as device}; +export {Errors as error}; +export {Feedback as feedback}; +export {Notification as notification}; diff --git a/apn/tsconfig.json b/apn/tsconfig.json new file mode 100644 index 0000000000..b71212927a --- /dev/null +++ b/apn/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "apn-tests.ts" + ] +} \ No newline at end of file diff --git a/appframework/appframework-tests.ts b/appframework/appframework-tests.ts index 16cfe9802f..4e5932334a 100644 --- a/appframework/appframework-tests.ts +++ b/appframework/appframework-tests.ts @@ -1,4 +1,4 @@ -/// + af(($: appFrameworkStatic) => {}); diff --git a/appframework/appframework.d.ts b/appframework/index.d.ts similarity index 100% rename from appframework/appframework.d.ts rename to appframework/index.d.ts diff --git a/appframework/tsconfig.json b/appframework/tsconfig.json new file mode 100644 index 0000000000..c3c50199f7 --- /dev/null +++ b/appframework/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "appframework-tests.ts" + ] +} \ No newline at end of file diff --git a/appletvjs/README.md b/appletvjs/README.md index 161282ed69..5d5b7f43ed 100644 --- a/appletvjs/README.md +++ b/appletvjs/README.md @@ -2,7 +2,7 @@ ## Referencing AppleTVJS definition files in your code -To do that, simply add `/// ` at the top of your code. +To do that, simply add `` at the top of your code. This will allow you to have intellisense in your AppleTVJS typescript code. diff --git a/appletvjs/appletvjs-tests.ts b/appletvjs/appletvjs-tests.ts index 8bdda9c633..55f720e26d 100644 --- a/appletvjs/appletvjs-tests.ts +++ b/appletvjs/appletvjs-tests.ts @@ -1,4 +1,4 @@ -/// + //test the global app events and functions function test_AppEvents() { diff --git a/appletvjs/appletvjs.d.ts b/appletvjs/index.d.ts similarity index 100% rename from appletvjs/appletvjs.d.ts rename to appletvjs/index.d.ts diff --git a/appletvjs/tsconfig.json b/appletvjs/tsconfig.json new file mode 100644 index 0000000000..3371d6b973 --- /dev/null +++ b/appletvjs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "appletvjs-tests.ts" + ] +} \ No newline at end of file diff --git a/applicationinsights/applicationinsights-tests.ts b/applicationinsights/applicationinsights-tests.ts index eb9d5e7019..00c303eff4 100644 --- a/applicationinsights/applicationinsights-tests.ts +++ b/applicationinsights/applicationinsights-tests.ts @@ -1,4 +1,3 @@ -/// import * as appInsights from "applicationinsights"; // basic use diff --git a/applicationinsights/applicationinsights.d.ts b/applicationinsights/index.d.ts similarity index 100% rename from applicationinsights/applicationinsights.d.ts rename to applicationinsights/index.d.ts diff --git a/applicationinsights/tsconfig.json b/applicationinsights/tsconfig.json new file mode 100644 index 0000000000..7769102d83 --- /dev/null +++ b/applicationinsights/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "applicationinsights-tests.ts" + ] +} \ No newline at end of file diff --git a/arbiter/Arbiter-tests.ts b/arbiter/Arbiter-tests.ts index fbdbe5b94a..ce7659e76f 100644 --- a/arbiter/Arbiter-tests.ts +++ b/arbiter/Arbiter-tests.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // May 22 2013 -/// + diff --git a/arbiter/Arbiter.d.ts b/arbiter/index.d.ts similarity index 100% rename from arbiter/Arbiter.d.ts rename to arbiter/index.d.ts diff --git a/arbiter/tsconfig.json b/arbiter/tsconfig.json new file mode 100644 index 0000000000..8e4258a8f9 --- /dev/null +++ b/arbiter/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "arbiter-tests.ts" + ] +} \ No newline at end of file diff --git a/arcgis-js-api/arcgis-js-api-tests.ts b/arcgis-js-api/arcgis-js-api-tests.ts index bf13a1a0a3..33b7d44960 100644 --- a/arcgis-js-api/arcgis-js-api-tests.ts +++ b/arcgis-js-api/arcgis-js-api-tests.ts @@ -1,4 +1,4 @@ -/// + import esri = require("esri"); import Map = require("esri/map"); diff --git a/arcgis-js-api/arcgis-js-api.d.ts b/arcgis-js-api/index.d.ts similarity index 100% rename from arcgis-js-api/arcgis-js-api.d.ts rename to arcgis-js-api/index.d.ts diff --git a/arcgis-js-api/tsconfig.json b/arcgis-js-api/tsconfig.json new file mode 100644 index 0000000000..b7534290e0 --- /dev/null +++ b/arcgis-js-api/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "arcgis-js-api-tests.ts" + ] +} \ No newline at end of file diff --git a/archiver/archiver-tests.ts b/archiver/archiver-tests.ts index dcd71ca905..3bef66a44c 100644 --- a/archiver/archiver-tests.ts +++ b/archiver/archiver-tests.ts @@ -1,5 +1,5 @@ -/// -/// + +/// import Archiver = require('archiver'); import FS = require('fs'); diff --git a/archiver/archiver.d.ts b/archiver/archiver.d.ts deleted file mode 100644 index d5133555a4..0000000000 --- a/archiver/archiver.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -// Type definitions for archiver v0.15.0 -// Project: https://github.com/archiverjs/node-archiver -// Definitions by: Esri -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/* =================== USAGE =================== - - import Archiver = require('archiver); - var archiver = Archiver.create('zip'); - archiver.pipe(FS.createWriteStream('xxx')); - archiver.append(FS.createReadStream('xxx')); - archiver.finalize(); - - =============================================== */ - -/// -declare module "archiver" { - import * as FS from 'fs'; - import * as STREAM from 'stream'; - - interface nameInterface { - name?: string; - } - - interface Archiver extends STREAM.Transform { - pipe(writeStream: FS.WriteStream): void; - append(readStream: FS.ReadStream, name: nameInterface): void; - finalize(): void; - } - - interface Options { - - } - - function archiver(format: string, options?: Options): Archiver; - - namespace archiver { - function create(format: string, options?: Options): Archiver; - } - - export = archiver; -} diff --git a/archiver/index.d.ts b/archiver/index.d.ts new file mode 100644 index 0000000000..74a3351b99 --- /dev/null +++ b/archiver/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for archiver v0.15.0 +// Project: https://github.com/archiverjs/node-archiver +// Definitions by: Esri +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* =================== USAGE =================== + + import Archiver = require('archiver); + var archiver = Archiver.create('zip'); + archiver.pipe(FS.createWriteStream('xxx')); + archiver.append(FS.createReadStream('xxx')); + archiver.finalize(); + + =============================================== */ + +/// + +import * as FS from 'fs'; +import * as STREAM from 'stream'; + +interface nameInterface { + name?: string; +} + +interface Archiver extends STREAM.Transform { + pipe(writeStream: FS.WriteStream): void; + append(readStream: FS.ReadStream, name: nameInterface): void; + finalize(): void; +} + +interface Options { + +} + +declare function archiver(format: string, options?: Options): Archiver; + +declare namespace archiver { + function create(format: string, options?: Options): Archiver; +} + +export = archiver; diff --git a/archiver/tsconfig.json b/archiver/tsconfig.json new file mode 100644 index 0000000000..f04152848c --- /dev/null +++ b/archiver/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "archiver-tests.ts" + ] +} \ No newline at end of file diff --git a/archy/archy-tests.ts b/archy/archy-tests.ts index b2f62384ff..dba85bafea 100644 --- a/archy/archy-tests.ts +++ b/archy/archy-tests.ts @@ -1,4 +1,3 @@ -/// import archy = require("archy"); diff --git a/archy/archy.d.ts b/archy/archy.d.ts deleted file mode 100644 index f4e13ef8a9..0000000000 --- a/archy/archy.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Type definitions for archy -// Project: https://github.com/substack/node-archy -// Definitions by: vvakame -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "archy" { - function archy(obj: archy.Data, prefix?: string, opts?: archy.Options): string; - function archy(obj: string, prefix?: string, opts?: archy.Options): string; - - namespace archy { - interface Data { - label: string; - nodes?: (Data | string)[]; - } - interface Options { - unicode?: boolean; - } - } - - export = archy; -} diff --git a/archy/index.d.ts b/archy/index.d.ts new file mode 100644 index 0000000000..82b101236c --- /dev/null +++ b/archy/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for archy +// Project: https://github.com/substack/node-archy +// Definitions by: vvakame +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare function archy(obj: archy.Data, prefix?: string, opts?: archy.Options): string; +declare function archy(obj: string, prefix?: string, opts?: archy.Options): string; + +declare namespace archy { + interface Data { + label: string; + nodes?: (Data | string)[]; + } + interface Options { + unicode?: boolean; + } +} + +export = archy; diff --git a/archy/tsconfig.json b/archy/tsconfig.json new file mode 100644 index 0000000000..672e65a0ac --- /dev/null +++ b/archy/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "archy-tests.ts" + ] +} \ No newline at end of file diff --git a/argparse/argparse-tests.ts b/argparse/argparse-tests.ts index bf565c5f54..cec1ece95b 100644 --- a/argparse/argparse-tests.ts +++ b/argparse/argparse-tests.ts @@ -1,4 +1,4 @@ -/// + // near copy of each of the tests from https://github.com/nodeca/argparse/tree/master/examples import {ArgumentParser, RawDescriptionHelpFormatter} from 'argparse'; diff --git a/argparse/argparse.d.ts b/argparse/argparse.d.ts deleted file mode 100644 index 886fef8cc9..0000000000 --- a/argparse/argparse.d.ts +++ /dev/null @@ -1,90 +0,0 @@ -// Type definitions for argparse v1.0.3 -// Project: https://github.com/nodeca/argparse -// Definitions by: Andrew Schurman -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "argparse" { - export class ArgumentParser extends ArgumentGroup { - constructor(options? : ArgumentParserOptions); - - addSubparsers(options? : SubparserOptions) : SubParser; - parseArgs(args? : string[], ns? : Namespace|Object) : any; - printUsage() : void; - printHelp() : void; - formatUsage() : string; - formatHelp() : string; - parseKnownArgs(args? : string[], ns? : Namespace|Object) : any[]; - convertArgLineToArg(argLine : string) : string[]; - exit(status : number, message : string) : void; - error(err : string|Error) : void; - } - - interface Namespace {} - - class SubParser { - addParser(name : string, options? : SubArgumentParserOptions) : ArgumentParser; - } - - class ArgumentGroup { - addArgument(args : string[], options? : ArgumentOptions) : void; - addArgumentGroup(options? : ArgumentGroupOptions) : ArgumentGroup; - addMutuallyExclusiveGroup(options? : {required : boolean}) : ArgumentGroup; - setDefaults(options? : {}) : void; - getDefault(dest : string) : any; - } - - interface SubparserOptions { - title? : string; - description? : string; - prog? : string; - parserClass? : {new() : any}; - action? : string; - dest? : string; - help? : string; - metavar? : string; - } - - interface SubArgumentParserOptions extends ArgumentParserOptions { - aliases? : string[]; - help? : string; - } - - interface ArgumentParserOptions { - description? : string; - epilog? : string; - addHelp? : boolean; - argumentDefault? : any; - parents? : ArgumentParser[]; - prefixChars? : string; - formatterClass? : {new() : HelpFormatter|ArgumentDefaultsHelpFormatter|RawDescriptionHelpFormatter|RawTextHelpFormatter}; - prog? : string; - usage? : string; - version? : string; - } - - interface ArgumentGroupOptions { - prefixChars? : string; - argumentDefault? : any; - title? : string; - description? : string; - } - - export class HelpFormatter {} - export class ArgumentDefaultsHelpFormatter {} - export class RawDescriptionHelpFormatter {} - export class RawTextHelpFormatter {} - - interface ArgumentOptions { - action? : string; - optionStrings? : string[]; - dest? : string; - nargs? : string|number; - constant? : any; - defaultValue? : any; - type? : string|Function; - choices? : string|string[]; - required? : boolean; - help? : string; - metavar? : string; - } -} diff --git a/argparse/index.d.ts b/argparse/index.d.ts new file mode 100644 index 0000000000..845d5d8fd3 --- /dev/null +++ b/argparse/index.d.ts @@ -0,0 +1,89 @@ +// Type definitions for argparse v1.0.3 +// Project: https://github.com/nodeca/argparse +// Definitions by: Andrew Schurman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +export declare class ArgumentParser extends ArgumentGroup { + constructor(options?: ArgumentParserOptions); + + addSubparsers(options?: SubparserOptions): SubParser; + parseArgs(args?: string[], ns?: Namespace | Object): any; + printUsage(): void; + printHelp(): void; + formatUsage(): string; + formatHelp(): string; + parseKnownArgs(args?: string[], ns?: Namespace | Object): any[]; + convertArgLineToArg(argLine: string): string[]; + exit(status: number, message: string): void; + error(err: string | Error): void; +} + +interface Namespace { } + +declare class SubParser { + addParser(name: string, options?: SubArgumentParserOptions): ArgumentParser; +} + +declare class ArgumentGroup { + addArgument(args: string[], options?: ArgumentOptions): void; + addArgumentGroup(options?: ArgumentGroupOptions): ArgumentGroup; + addMutuallyExclusiveGroup(options?: { required: boolean }): ArgumentGroup; + setDefaults(options?: {}): void; + getDefault(dest: string): any; +} + +interface SubparserOptions { + title?: string; + description?: string; + prog?: string; + parserClass?: { new (): any }; + action?: string; + dest?: string; + help?: string; + metavar?: string; +} + +interface SubArgumentParserOptions extends ArgumentParserOptions { + aliases?: string[]; + help?: string; +} + +interface ArgumentParserOptions { + description?: string; + epilog?: string; + addHelp?: boolean; + argumentDefault?: any; + parents?: ArgumentParser[]; + prefixChars?: string; + formatterClass?: { new (): HelpFormatter | ArgumentDefaultsHelpFormatter | RawDescriptionHelpFormatter | RawTextHelpFormatter }; + prog?: string; + usage?: string; + version?: string; +} + +interface ArgumentGroupOptions { + prefixChars?: string; + argumentDefault?: any; + title?: string; + description?: string; +} + +export declare class HelpFormatter { } +export declare class ArgumentDefaultsHelpFormatter { } +export declare class RawDescriptionHelpFormatter { } +export declare class RawTextHelpFormatter { } + +interface ArgumentOptions { + action?: string; + optionStrings?: string[]; + dest?: string; + nargs?: string | number; + constant?: any; + defaultValue?: any; + type?: string | Function; + choices?: string | string[]; + required?: boolean; + help?: string; + metavar?: string; +} diff --git a/argparse/tsconfig.json b/argparse/tsconfig.json new file mode 100644 index 0000000000..ea8bcd979a --- /dev/null +++ b/argparse/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "argparse-tests.ts" + ] +} \ No newline at end of file diff --git a/asana/asana-tests.ts b/asana/asana-tests.ts index c1531ec9dd..3bef3e2c07 100644 --- a/asana/asana-tests.ts +++ b/asana/asana-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// import * as asana from 'asana'; import * as util from 'util'; diff --git a/asana/asana.d.ts b/asana/asana.d.ts deleted file mode 100644 index 61cb54d26f..0000000000 --- a/asana/asana.d.ts +++ /dev/null @@ -1,2476 +0,0 @@ -// Type definitions for node-asana 0.14.0 -// Project: https://github.com/Asana/node-asana -// Definitions by: Qubo -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare module "asana" { - import * as Promise from 'bluebird'; - - namespace asana { - var Client: ClientStatic; - - interface ClientStatic { - /** - * Constructs a Client with instances of all the resources using the dispatcher. - * It also keeps a reference to the dispatcher so that way the end user can have - * access to it. - * @class - * @classdesc A wrapper for the Asana API which is authenticated for one user - * @param {Dispatcher} dispatcher The request dispatcher to use - * @param {Object} options Options to configure the client - * @param {String} [clientId] ID of the client, required for Oauth - * @param {String} [clientSecret] Secret key, for some Oauth flows - * @param {String} [redirectUri] Default redirect URI for this client - * @param {String} [asanaBaseUrl] Base URL for Asana, for debugging - */ - (dispatcher: Dispatcher, options?: ClientOptions): asana.Client; - /** - * Creates a new client. - * @param {Object} options Options for specifying the client, see constructor. - */ - create(options?: ClientOptions): Client; - } - - /** Options to configure the client */ - interface ClientOptions extends DispatcherOptions { - clientId?: string|number; - clientSecret?: string; - redirectUri?: string; - asanaBaseUrl?: string; - } - - interface Client { - /** - * Ensures the client is authorized to make requests. Kicks off the - * configured Oauth flow, if any. - * - * @returns {Promise} A promise that resolves to this client when - * authorization is complete. - */ - authorize(): Promise; - - /** - * Configure the Client to use a user's API Key and then authenticate - * through HTTP Basic Authentication. This should only be done for testing, - * as requests using Oauth can provide more security, higher rate limits, and - * more features. - * @param {String} apiKey The Asana Api Key of the user - * @return {Client} this - * @param apiKey - * @return - */ - useBasicAuth(apiKey: string): this; - - /** - * Configure the client to authenticate using a Personal Access Token. - * @param {String} accessToken The Personal Access Token to use for - * authenticating requests. - * @return {Client} this - * @param accessToken - * @return - */ - useAccessToken(accessToken: string): this; - - /** - * Configure the client to authenticate via Oauth. Credentials can be - * supplied, or they can be obtained by running an Oauth flow. - * @param {Object} options Options for Oauth. Includes any options for - * the selected flow. - * @option {Function} [flowType] Type of OauthFlow to use to obtain user - * authorization. Defaults to autodetect based on environment. - * @option {Object} [credentials] Credentials to use; no flow required to - * obtain authorization. This object should at a minimum contain an - * `access_token` string field. - * @return {Client} this - * @param options - * @return - */ - useOauth(options?: auth.OauthAuthenticatorOptions): this; - - /** - * The internal dispatcher. This is mostly used by the resources but provided - * for custom requests to the API or API features that have not yet been added - * to the client. - * @type {Dispatcher} - */ - dispatcher: Dispatcher; - /** - * An instance of the Attachments resource. - * @type {Attachments} - */ - attachments: resources.Attachments; - /** - * An instance of the Events resource. - * @type {Events} - */ - events: resources.Events; - /** - * An instance of the Projects resource. - * @type {Projects} - */ - projects: resources.Projects; - /** - * An instance of the Stories resource. - * @type {Stories} - */ - stories: resources.Stories; - /** - * An instance of the Tags resource. - * @type {Tags} - */ - tags: resources.Tags; - /** - * An instance of the Tasks resource. - * @type {Tasks} - */ - tasks: resources.Tasks; - /** - * An instance of the Teams resource. - * @type {Teams} - */ - teams: resources.Teams; - /** - * An instance of the Users resource. - * @type {Users} - */ - users: resources.Users; - /** - * An instance of the Workspaces resource. - * @type {Workspaces} - */ - workspaces: resources.Workspaces; - /** - * Store off Oauth info. - */ - app: auth.App; - } - - var Dispatcher: DispatcherStatic; - - interface DispatcherStatic { - /** - * Creates a dispatcher which will act as a basic wrapper for making HTTP - * requests to the API, and handle authentication. - * @class - * @classdesc A HTTP wrapper for the Asana API - * @param {Object} options for default behavior of the Dispatcher - * @option {Authenticator} [authenticator] Object to use for authentication. - * Can also be set later with `setAuthenticator`. - * @option {String} [retryOnRateLimit] Automatically handle `RateLimitEnforced` - * errors by sleeping and retrying after the waiting period. - * @option {Function} [handleUnauthorized] Automatically handle - * `NoAuthorization` with the callback. If the callback returns `true` - * (or a promise resolving to `true), will retry the request. - * @option {String} [asanaBaseUrl] Base URL for Asana, for debugging - * @option {Number} [requestTimeout] Timeout (in milliseconds) to wait for the - * request to finish. - */ - new (options?: DispatcherOptions): Dispatcher; - - /** - * Default handler for requests that are considered unauthorized. - * Requests that the authenticator try to refresh its credentials if - * possible. - * @return {Promise} True iff refresh was successful, false if not. - * @return - */ - maybeReauthorize(): Promise; - - /** - * The relative API path for the current version of the Asana API. - * @type {String} - */ - API_PATH : string; - } - - interface DispatcherOptions { - authenticator?: auth.Authenticator; - retryOnRateLimit?: boolean; - handleUnauthorized?: () => boolean|Promise; - requestTimeout?: string; - } - - interface Dispatcher { - /** - * Creates an Asana API Url by concatenating the ROOT_URL with path provided. - * @param {String} path The path - * @return {String} The url - * @param path - * @return - */ - url(path: string): string; - - /** - * Configure the authentication mechanism to use. - * @returns {Dispatcher} this - * @param authenticator - * @return - */ - setAuthenticator(authenticator: auth.Authenticator): this; - - /** - * Ensure the dispatcher is authorized to make requests. Call this before - * making any API requests. - * - * @returns {Promise} Resolves when the dispatcher is authorized, rejected if - * there was a problem authorizing. - * @return - */ - authorize(): Promise; - - /** - * Dispatches a request to the Asana API. The request parameters are passed to - * the request module. - * @param {Object} params The params for request - * @param {Object} [dispatchOptions] Options for handling request/response - * @return {Promise} The response for the request - * @param params - * @param dispatchOptions? - * @return - */ - dispatch(params: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a GET request to the Asana API. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `dispatch`. - * @return {Promise} The response for the request - * @param path - * @param query? - * @param dispatchOptions? - * @return - */ - get(path: string, query?: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a POST request to the Asana API. - * @param {String} path The path of the API - * @param {Object} data The data to be sent - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `dispatch`. - * @return {Promise} The response for the request - * @param path - * @param data - * @param dispatchOptions? - * @return - */ - post(path: string, data: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a PUT request to the Asana API. - * @param {String} path The path of the API - * @param {Object} data The data to be sent - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `dispatch`. - * @return {Promise} The response for the request - * @param path - * @param data - * @param dispatchOptions? - * @return - */ - put(path: string, data: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a DELETE request to the Asana API. - * @param {String} path The path of the API - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `dispatch`. - * @return {Promise} The response for the request - * @param path - * @param dispatchOptions? - * @return - */ - delete(path: string, dispatchOptions?: any): Promise; - - /** - * The base URL for Asana - * @type {String} - */ - asanaBaseUrl : string; - - /** - * Whether requests should be automatically retried if rate limited. - * @type {Boolean} - */ - retryOnRateLimit : boolean; - - /** - * Handler for unauthorized requests which may seek reauthorization. - * Default behavior is available if configured with an Oauth authenticator - * that has a refresh token, and will refresh the current access token. - * @type {Function} - */ - handleUnauthorized : () => boolean|Promise; - - /** - * The amount of time in milliseconds to wait for a request to finish. - * @type {Number} - */ - requestTimeout : number; - } - - namespace auth { - var BasicAuthenticator: BasicAuthenticatorStatic; - - interface BasicAuthenticatorStatic { - /** - * @param apiKey - */ - new (apiKey: string): BasicAuthenticator; - } - - interface BasicAuthenticator extends Authenticator { - /** - * @param {Object} request The request to modify, for the `request` library. - * @return {Object} The `request` parameter, modified to include authentication - * information using the stored credentials. - * @param request - * @return - */ - authenticateRequest(request: BasicAuthenticatorRequest): BasicAuthenticatorRequest; - } - - interface BasicAuthenticatorRequest { - auth : { - username : string; - password : string; - } - } - - var OauthAuthenticator: OauthAuthenticatorStatic; - - interface OauthAuthenticatorStatic { - /** - * Creates an authenticator that uses Oauth for authentication. - * - * @param {Object} options Configure the authenticator; must specify one - * of `flow` or `credentials`. - * @option {App} app The app being authenticated for. - * @option {OauthFlow} [flow] The flow to use to get credentials - * when needed. - * @option {String|Object} [credentials] Initial credentials to use. This can - * be either the object returned from an access token request (which - * contains the token and some other metadata) or just the `access_token` - * field. - * @constructor - */ - new (options: OauthAuthenticatorOptions): OauthAuthenticator; - } - - interface OauthAuthenticatorOptions { - flowType?: auth.FlowType; - credentials?: Credentials|string; - } - - interface Credentials { - access_token?: string; - refresh_token?: string; - } - - interface OauthAuthenticator extends Authenticator { - /** - * @param {Object} request The request to modify, for the `request` library. - * @return {Object} The `request` parameter, modified to include authentication - * information using the stored credentials. - * @param request - * @return - */ - authenticateRequest(request: OauthAuthenticatorRequest): OauthAuthenticatorRequest; - } - - interface OauthAuthenticatorRequest { - /** - * When browserify-d, the `auth` component of the `request` library - * doesn't work so well, so we just manually set the bearer token instead. - */ - headers : { - Authorization : string; - } - } - - /** - * A layer to abstract the differences between using different types of - * authentication (Oauth vs. Basic). The Authenticator is responsible for - * establishing credentials and applying them to outgoing requests. - * @constructor - */ - interface Authenticator { - /** - * Establishes credentials. - * - * @return {Promise} Resolves when initial credentials have been - * completed and `authenticateRequest` calls can expect to succeed. - * @return - */ - establishCredentials(): Promise; - - /** - * Attempts to refresh credentials, if possible, given the current credentials. - * - * @return {Promise} Resolves to `true` if credentials have been successfully - * established and `authenticateRequests` can expect to succeed, else - * resolves to `false`. - * @return - */ - refreshCredentials(): Promise; - } - - var App: AppStatic; - - interface AppStatic { - /** - * An abstraction around an App used with Asana. - * - * @options {Object} Options to construct the app - * @option {String} clientId The ID of the app - * @option {String} [clientSecret] The secret key, if available here - * @option {String} [redirectUri] The default redirect URI - * @option {String} [scope] Scope to use, supports `default` and `scim` - * @option {String} [asanaBaseUrl] Base URL to use for Asana, for debugging - * @constructor - */ - new (options: AppOptions): App; - } - - interface AppOptions extends AsanaAuthorizeUrlOptions { - clientId?: string|number; - clientSecret?: string; - scope?: string; - } - - interface App { - /** - * @param {Object} options Overrides to the app's defaults - * @option {String} asanaBaseUrl - * @option {String} redirectUri - * @returns {String} The URL used to authorize a user for the app. - * @param options - * @return - */ - asanaAuthorizeUrl(options?: AsanaAuthorizeUrlOptions): string; - - /** - * @param {Object} options Overrides to the app's defaults - * @option {String} asanaBaseUrl - * @option {String} redirectUri - * @returns {String} The URL used to acquire an access token. - * @param options - * @return - */ - asanaTokenUrl(options?: AsanaAuthorizeUrlOptions): string; - - /** - * @param {String} code An authorization code obtained via `asanaAuthorizeUrl`. - * @param {Object} options Overrides to the app's defaults - * @option {String} asanaBaseUrl - * @option {String} redirectUri - * @return {Promise} The token, which will include the `access_token` - * used for API access, as well as a `refresh_token` which can be stored - * to get a new access token without going through the flow again. - * @param code - * @param options - * @return - */ - accessTokenFromCode(code: string, options?: AsanaAuthorizeUrlOptions): Promise; - - /** - * @param {String} refreshToken A refresh token obtained via Oauth. - * @param {Object} options Overrides to the app's defaults - * @option {String} asanaBaseUrl - * @option {String} redirectUri - * @return {Promise} The token, which will include the `access_token` - * used for API access. - * @param refreshToken - * @param options - * @return - */ - accessTokenFromRefreshToken(refreshToken: string, options: AsanaAuthorizeUrlOptions): Promise; - - scope : string; - - asanaBaseUrl : string; - } - - interface AsanaAuthorizeUrlOptions { - redirectUri?: string; - asanaBaseUrl?: string; - } - - var OauthError: OauthErrorStatic; - - interface OauthErrorStatic { - /** - * @param options {Object} A data blob parsed from a query string or JSON - * response from the Asana API - * @option {String} error The string code identifying the error. - * @option {String} [error_uri] A link to help and information about the error. - * @option {String} [error_description] A description of the error. - * @constructor - */ - new (options: OauthErrorOptions): OauthError; - } - - interface OauthErrorOptions { - error?: string; - error_uri?: string; - error_description?: string; - } - - interface OauthError extends Error { - } - - /** - * Auto-detects the type of Oauth flow to use that's appropriate to the - * environment. - * - * @returns {Function|null} The type of Oauth flow to use, or null if no - * appropriate type could be determined. - * @param env - * @return - */ - function autoDetect(env: any): Function; - - var RedirectFlow: RedirectFlowStatic; - - interface RedirectFlowStatic extends FlowType { - /** - * An Oauth flow that runs in the browser and requests user authorization by - * redirecting to an authorization page on Asana, and redirecting back with - * the credentials. - * @param {Object} options See `BaseBrowserFlow` for options. - * @constructor - */ - new (options: any): RedirectFlow; - } - - interface RedirectFlow extends BaseBrowserFlow { - } - - var PopupFlow: PopupFlowStatic; - - interface PopupFlowStatic extends FlowType { - /** - * An Oauth flow that runs in the browser and requests user authorization by - * popping up a window and prompting the user. - * @param {Object} options See `BaseBrowserFlow` for options. - * @constructor - */ - new (options: any): PopupFlow; - } - - interface PopupFlow extends BaseBrowserFlow { - /** - * @param popupWidth - * @param popupHeight - */ - _popupParams(popupWidth: number, popupHeight: number): void; - - runReceiver(): void; - } - - var NativeFlow: NativeFlowStatic; - - interface NativeFlowStatic extends FlowType { - /** - * An Oauth flow that can be run from the console or an app that does - * not have the ability to open and manage a browser on its own. - * @param {Object} options - * @option {App} app App to authenticate for - * @option {String function(String)} [instructions] Function returning the - * instructions to output to the user. Passed the authorize url. - * @option {String function()} [prompt] String to output immediately before - * waiting for a line from stdin. - * @constructor - */ - new (options: any): NativeFlow; - } - - interface NativeFlow extends Flow { - /** - * Run the Oauth flow, prompting the user to go to the authorization URL - * and enter the code it displays when finished. - * - * @return {Promise} The access token object, which will include - * `access_token` and `refresh_token`. - */ - run(): void; - - /** - * @param {String} code An authorization code obtained via `asanaAuthorizeUrl`. - * @return {Promise} The token, which will include the `access_token` - * used for API access, as well as a `refresh_token` which can be stored - * to get a new access token without going through the flow again. - * @param code - */ - accessToken(code: string): void; - - /** - * @return {Promise} The access token, which will include a refresh token - * that can be stored in the future to create a client without going - * through the Oauth flow. - * @param url - * @return - */ - promptForCode(url: string): any; - } - - var ChromeExtensionFlow: ChromeExtensionFlowStatic; - - interface ChromeExtensionFlowStatic extends FlowType { - /** - * An Oauth flow that runs in a Chrome browser extension and requests user - * authorization by opening a temporary tab to prompt the user. - * @param {Object} options See `BaseBrowserFlow` for options, plus the below: - * @options {String} [receiverPath] Full path and filename from the base - * directory of the extension to the receiver page. This is an HTML file - * that has been made web-accessible, and that calls the receiver method - * `Asana.auth.ChromeExtensionFlow.runReceiver();`. - * @constructor - */ - new (options: any): ChromeExtensionFlow; - } - - interface ChromeExtensionFlow extends BaseBrowserFlow { - /** - * Runs the receiver code to send the Oauth result to the requesting tab. - */ - runReceiver(): void; - } - - var BaseBrowserFlow: BaseBrowserFlowStatic; - - interface BaseBrowserFlowStatic extends FlowType { - /** - * A base class for any flow that runs in the browser. All subclasses use the - * "implicit grant" flow to authenticate via the browser. - * @param {Object} options - * @option {App} app The app this flow is for - * @option {String} [redirectUri] The URL that Asana should redirect to once - * user authorization is complete. Defaults to the URL configured in - * the app, and if none then the current page URL. - * @constructor - */ - new (options: any): BaseBrowserFlow; - } - - interface BaseBrowserFlow extends Flow { - /** - * @param {String} authUrl The URL the user should be navigated to in order - * to authorize the app. - * @param {String} state The unique state generated for this auth request. - * @return {Promise} Resolved when authorization has successfully started, - * i.e. the user has been navigated to a page requesting authorization. - * @param authUrl - * @param state - * @return - */ - startAuthorization(authUrl: string, state: string): any; - - /** - * @return {Promise} Credentials returned from Oauth. - * @param state - */ - finishAuthorization(state: string): void; - - /** - * @return {String} The URL to redirect to that will receive the - * @return - */ - receiverUrl(): string; - - /** - * @return {String} The URL to redirect to that will receive the - * @return - */ - asanaBaseUrl(): string; - - /** - * @returns {String} Generate a new unique state parameter for a request. - * @return - */ - getStateParam(): string; - } - - interface FlowType { - new (options: any): Flow; - } - - interface Flow { - /** - * @returns {String} The URL used to authorize the user for the app. - * @return - */ - authorizeUrl(): string; - - /** - * Run the appropriate parts of the Oauth flow, attempting to establish user - * authorization. - * @returns {Promise} A promise that resolves to the Oauth credentials. - */ - run(): void; - } - } - - namespace errors { - class AsanaError extends Error { - /** - * @param message - * @return - */ - constructor(message: any); - - code: number; - value: any; - } - - class Forbidden extends AsanaError { - /** - * @param value - * @return - */ - constructor(value: any); - } - - - class InvalidRequest extends AsanaError { - /** - * @param value - * @return - */ - constructor(value: any); - } - - class NoAuthorization extends AsanaError { - /** - * @param value - * @return - */ - constructor(value: any); - } - - class NotFound extends AsanaError { - /** - * @param value - * @return - */ - constructor(value: any); - } - - class RateLimitEnforced extends AsanaError { - /** - * @param value - * @return - */ - constructor(value: any); - } - - class ServerError extends AsanaError { - /** - * @param value - * @return - */ - constructor(value: any); - } - } - - namespace resources { - interface AttachmentsStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Attachments; - } - - namespace Attachments { - interface Type extends Resource { - created_at: string; - permanent_url: string; - download_url: string; - view_url: string; - host: string; - parent: Resource; - } - } - - var Attachments: AttachmentsStatic; - - /** - * An _attachment_ object represents any file attached to a task in Asana, - * whether it's an uploaded file or one associated via a third-party service - * such as Dropbox or Google Drive. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Attachments extends Resource { - /** - * * Returns the full record for a single attachment. - * * @param {Number} attachment Globally unique identifier for the attachment. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param attachment - * @param params? - * @param dispatchOptions? - * @return - */ - findById(attachment: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Returns the compact records for all attachments on the task. - * * @param {Number} task Globally unique identifier for the task. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - findByTask(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - } - - interface EventsStatic { - /** - * @param dispatcher - * @return - */ - new (dispatcher: Dispatcher): Events; - } - - var Events: EventsStatic; - - /** - * An _event_ is an object representing a change to a resource that was observed - * by an event subscription. - * - * In general, requesting events on a resource is faster and subject to higher - * rate limits than requesting the resource itself. Additionally, change events - * bubble up - listening to events on a project would include when stories are - * added to tasks in the project, even on subtasks. - * - * Establish an initial sync token by making a request with no sync token. - * The response will be a `412` error - the same as if the sync token had - * expired. - * - * Subsequent requests should always provide the sync token from the immediately - * preceding call. - * - * Sync tokens may not be valid if you attempt to go 'backward' in the history - * by requesting previous tokens, though re-requesting the current sync token - * is generally safe, and will always return the same results. - * - * When you receive a `412 Precondition Failed` error, it means that the - * sync token is either invalid or expired. If you are attempting to keep a set - * of data in sync, this signals you may need to re-crawl the data. - * - * Sync tokens always expire after 24 hours, but may expire sooner, depending on - * load on the service. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Events extends Resource { } - - interface ProjectsStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Projects; - } - - namespace Projects { - interface Type extends Resource { - created_at: string; - modified_at: string; - due_date: string; - current_status: Status; - public: boolean; - archived: boolean; - notes: string; - color: string; - workspace: Resource; - team: Resource; - members: Resource[]; - followers: Resource[]; - } - - interface CreateParams { - name?: string; - team?: number; - public?: boolean; - due_date: string; - notes?: string; - color?: string; - } - - interface FollowersParams { - followers: (number|string)[]; - } - - interface MembersParams { - members: (number|string)[]; - } - - interface Status { - color: string; - text: string; - html_text: string; - modified_at: string; - author: Resource; - } - - interface FindAllParams extends PaginationParams { - team?: number; - archived?: boolean; - } - - interface FindByParams extends PaginationParams { - archived?: boolean; - } - } - - var Projects: ProjectsStatic; - - /** - * A _project_ represents a prioritized list of tasks in Asana. It exists in a - * single workspace or organization and is accessible to a subset of users in - * that workspace or organization, depending on its permissions. - * - * Projects in organizations are shared with a single team. You cannot currently - * change the team of a project via the API. Non-organization workspaces do not - * have teams and so you should not specify the team of project in a - * regular workspace. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Projects extends Resource { - /** - * * Creates a new project in a workspace or team. - * * - * * Every project is required to be created in a specific workspace or - * * organization, and this cannot be changed once set. Note that you can use - * * the `workspace` parameter regardless of whether or not it is an - * * organization. - * * - * * If the workspace for your project _is_ an organization, you must also - * * supply a `team` to share the project with. - * * - * * Returns the full record of the newly created project. - * * @param {Object} data Data for the request - * * @param {String} data.workspace The workspace or organization to create the project in. - * * @param {String} [data.team] If creating in an organization, the specific team to create the - * * project in. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param data - * @param dispatchOptions? - * @return - */ - create(data: Projects.CreateParams & { workspace: number }, dispatchOptions?: any): Promise; - - /** - * * If the workspace for your project _is_ an organization, you must also - * * supply a `team` to share the project with. - * * - * * Returns the full record of the newly created project. - * * @param {Number} workspace The workspace or organization to create the project in. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param data - * @param dispatchOptions? - * @return - */ - createInWorkspace(workspace: number, data: Projects.CreateParams, dispatchOptions?: any): Promise; - - /** - * * Creates a project shared with the given team. - * * - * * Returns the full record of the newly created project. - * * @param {Number} team The team to create the project in. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param team - * @param data - * @param dispatchOptions? - * @return - */ - createInTeam(team: number, data: Projects.CreateParams, dispatchOptions?: any): Promise; - - /** - * * Returns the complete project record for a single project. - * * @param {Number} project The project to get. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param project - * @param params? - * @param dispatchOptions? - * @return - */ - findById(project: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * A specific, existing project can be updated by making a PUT request on the - * * URL for that project. Only the fields provided in the `data` block will be - * * updated; any unspecified fields will remain unchanged. - * * - * * When using this method, it is best to specify only those fields you wish - * * to change, or else you may overwrite changes made by another user since - * * you last retrieved the task. - * * - * * Returns the complete updated project record. - * * @param {Number} project The project to update. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param data - * @param dispatchOptions? - * @return - */ - update(project: number, data: Projects.CreateParams, dispatchOptions?: any): Promise; - - /** - * * A specific, existing project can be deleted by making a DELETE request - * * on the URL for that project. - * * - * * Returns an empty data record. - * * @param {Number} project The project to delete. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param dispatchOptions? - * @return - */ - delete(project: number, dispatchOptions?: any): Promise; - - /** - * * Returns the compact project records for some filtered set of projects. - * * Use one or more of the parameters provided to filter the projects returned. - * * @param {Object} [params] Parameters for the request - * * @param {String} [params.workspace] The workspace or organization to filter projects on. - * * @param {String} [params.team] The team to filter projects on. - * * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of - * * this parameter. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param params? - * @param dispatchOptions? - * @return - */ - findAll(params?: Projects.FindAllParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact project records for all projects in the workspace. - * * @param {Number} workspace The workspace or organization to find projects in. - * * @param {Object} [params] Parameters for the request - * * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of - * * this parameter. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param params? - * @param dispatchOptions? - * @return - */ - findByWorkspace(workspace: number, params?: Projects.FindByParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact project records for all projects in the team. - * * @param {Number} team The team to find projects in. - * * @param {Object} [params] Parameters for the request - * * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of - * * this parameter. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param team - * @param params? - * @param dispatchOptions? - * @return - */ - findByTeam(team: number, params?: Projects.FindByParams, dispatchOptions?: any): Promise>; - - /** - * * Returns compact records for all sections in the specified project. - * * @param {Number} project The project to get sections from. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param params? - * @param dispatchOptions? - * @return - */ - sections(project: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact task records for all tasks within the given project, - * * ordered by their priority within the project. Tasks can exist in more than one project at a time. - * * @param {Number} project The project in which to search for tasks. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param params? - * @param dispatchOptions? - * @return - */ - tasks(project: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Adds the specified list of users as followers to the project. Followers are a subset of members, therefore if - * * the users are not already members of the project they will also become members as a result of this operation. - * * Returns the updated project record. - * * @param {Number} project The project to add followers to. - * * @param {Object} data Data for the request - * * @param {Array} data.followers An array of followers to add to the project. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param data - * @param dispatchOptions? - * @return - */ - addFollowers(project: number, data: Projects.FollowersParams, dispatchOptions?: any): Promise; - - /** - * * Removes the specified list of users from following the project, this will not affect project membership status. - * * Returns the updated project record. - * * @param {Number} project The project to remove followers from. - * * @param {Object} data Data for the request - * * @param {Array} data.followers An array of followers to remove from the project. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param data - * @param dispatchOptions? - * @return - */ - removeFollowers(project: number, data: Projects.FollowersParams, dispatchOptions?: any): Promise; - - /** - * * Adds the specified list of users as members of the project. Returns the updated project record. - * * @param {Number} project The project to add members to. - * * @param {Object} data Data for the request - * * @param {Array} data.members An array of members to add to the project. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param data - * @param dispatchOptions? - * @return - */ - addMembers(project: number, data: Projects.MembersParams, dispatchOptions?: any): Promise; - - /** - * * Removes the specified list of members from the project. Returns the updated project record. - * * @param {Number} project The project to remove members from. - * * @param {Object} data Data for the request - * * @param {Array} data.members An array of members to remove from the project. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param data - * @param dispatchOptions? - * @return - */ - removeMembers(project: number, data: Projects.MembersParams, dispatchOptions?: any): Promise; - } - - interface StoriesStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Stories; - } - - namespace Stories { - interface ShortType extends Resource { - created_at: string; - created_by: Resource; - type: string; - text: string; - } - - interface Type extends ShortType { - html_text: string; - source: string; - target: Resource; - hearts: Type[]; - } - } - - var Stories: StoriesStatic; - - /** - * A _story_ represents an activity associated with an object in the Asana - * system. Stories are generated by the system whenever users take actions such - * as creating or assigning tasks, or moving tasks between projects. _Comments_ - * are also a form of user-generated story. - * - * Stories are a form of history in the system, and as such they are read-only. - * Once generated, it is not possible to modify a story. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Stories extends Resource { - /** - * * Returns the compact records for all stories on the task. - * * @param {Number} task Globally unique identifier for the task. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - findByTask(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the full record for a single story. - * * @param {Number} story Globally unique identifier for the story. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param story - * @param params? - * @param dispatchOptions? - * @return - */ - findById(story: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Adds a comment to a task. The comment will be authored by the - * * currently authenticated user, and timestamped when the server receives - * * the request. - * * - * * Returns the full record for the new story added to the task. - * * @param {Number} task Globally unique identifier for the task. - * * @param {Object} data Data for the request - * * @param {String} data.text The plain text of the comment to add. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - createOnTask(task: number, data: any, dispatchOptions?: any): Promise>; - } - - interface TagsStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Tags; - } - - namespace Tags { - interface Type extends Resource { - created_at: string; - notes: string; - workspace: Resource; - color: string; - followers: Resource[]; - } - - interface FindAllParams extends PaginationParams { - team?: number; - archived?: boolean; - } - } - - var Tags: TagsStatic; - - /** - * A _tag_ is a label that can be attached to any task in Asana. It exists in a - * single workspace or organization. - * - * Tags have some metadata associated with them, but it is possible that we will - * simplify them in the future so it is not encouraged to rely too heavily on it. - * Unlike projects, tags do not provide any ordering on the tasks they - * are associated with. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Tags extends Resource { - /** - * * Creates a new tag in a workspace or organization. - * * - * * Every tag is required to be created in a specific workspace or - * * organization, and this cannot be changed once set. Note that you can use - * * the `workspace` parameter regardless of whether or not it is an - * * organization. - * * - * * Returns the full record of the newly created tag. - * * @param {Object} data Data for the request - * * @param {String} data.workspace The workspace or organization to create the tag in. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param data - * @param dispatchOptions? - * @return - */ - create(data: Tags.Type & { workspace: string }, dispatchOptions?: any): Promise; - - /** - * * Creates a new tag in a workspace or organization. - * * - * * Every tag is required to be created in a specific workspace or - * * organization, and this cannot be changed once set. Note that you can use - * * the `workspace` parameter regardless of whether or not it is an - * * organization. - * * - * * Returns the full record of the newly created tag. - * * @param {Number} workspace The workspace or organization to create the tag in. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param data - * @param dispatchOptions? - * @return - */ - createInWorkspace(workspace: number, data: Tags.Type, dispatchOptions?: any): Promise; - - /** - * * Returns the complete tag record for a single tag. - * * @param {Number} tag The tag to get. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param tag - * @param params? - * @param dispatchOptions? - * @return - */ - findById(tag: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Updates the properties of a tag. Only the fields provided in the `data` - * * block will be updated; any unspecified fields will remain unchanged. - * * - * * When using this method, it is best to specify only those fields you wish - * * to change, or else you may overwrite changes made by another user since - * * you last retrieved the task. - * * - * * Returns the complete updated tag record. - * * @param {Number} tag The tag to update. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param tag - * @param data - * @param dispatchOptions? - * @return - */ - update(tag: number, data: Tags.Type, dispatchOptions?: any): Promise; - - /** - * * A specific, existing tag can be deleted by making a DELETE request - * * on the URL for that tag. - * * - * * Returns an empty data record. - * * @param {Number} tag The tag to delete. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param tag - * @param dispatchOptions? - * @return - */ - delete(tag: number, dispatchOptions?: any): Promise; - - /** - * * Returns the compact tag records for some filtered set of tags. - * * Use one or more of the parameters provided to filter the tags returned. - * * @param {Object} [params] Parameters for the request - * * @param {String} [params.workspace] The workspace or organization to filter tags on. - * * @param {String} [params.team] The team to filter tags on. - * * @param {Boolean} [params.archived] Only return tags whose `archived` field takes on the value of - * * this parameter. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param params? - * @param dispatchOptions? - * @return - */ - findAll(params?: Tags.FindAllParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact tag records for all tags in the workspace. - * * @param {Number} workspace The workspace or organization to find tags in. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param params? - * @param dispatchOptions? - * @return - */ - findByWorkspace(workspace: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact task records for all tasks with the given tag. - * * Tasks can have more than one tag at a time. - * * @param {Number} tag The tag to fetch tasks from. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param tag - * @param params? - * @param dispatchOptions? - * @return - */ - getTasksWithTag(tag: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - } - - interface TasksStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Tasks; - } - - namespace Tasks { - interface Type extends Resource { - created_at: string; - modified_at: string; - completed_at: string; - completed: boolean; - due_on: string; - due_at: string; - assignee_status: string; - assignee: Resource; - notes: string; - workspace: Resource; - num_hearts: number; - hearted: boolean; - parent: Resource; - tags: Resource[]; - projects: Resource[]; - memberships: Membership[]; - followers: Resource[]; - } - - interface CreateParams { - name: string; - completed?: boolean; - hearted?: boolean; - notes?: string; - } - - interface FollowersParams { - followers: (number|string)[]; - } - - interface AddProjectParams { - project: number; - insertBefore?: number; - insertAfter?: number; - section?: number; - } - - interface RemoveProjectParams { - project: number; - } - - interface TagParams { - tag: string; - } - - interface CommentParams { - text: string; - } - - interface FindAllParams extends PaginationParams { - assignee?: number; - workspace: number; - completed_since?: string; - modified_since?: string; - } - } - - var Tasks: TasksStatic; - - /** - * The _task_ is the basic object around which many operations in Asana are - * centered. In the Asana application, multiple tasks populate the middle pane - * according to some view parameters, and the set of selected tasks determines - * the more detailed information presented in the details pane. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Tasks extends Resource { - /** - * * Creating a new task is as easy as POSTing to the `/tasks` endpoint - * * with a data block containing the fields you'd like to set on the task. - * * Any unspecified fields will take on default values. - * * - * * Every task is required to be created in a specific workspace, and this - * * workspace cannot be changed once set. The workspace need not be set - * * explicitly if you specify a `project` or a `parent` task instead. - * * @param {Object} data Data for the request - * * @param {Number} [data.workspace] The workspace to create a task in. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param data - * @param dispatchOptions? - * @return - */ - create(data: Tasks.CreateParams & { workspace: string }, dispatchOptions?: any): Promise; - - /** - * * Creating a new task is as easy as POSTing to the `/tasks` endpoint - * * with a data block containing the fields you'd like to set on the task. - * * Any unspecified fields will take on default values. - * * - * * Every task is required to be created in a specific workspace, and this - * * workspace cannot be changed once set. The workspace need not be set - * * explicitly if you specify a `project` or a `parent` task instead. - * * @param {Number} workspace The workspace to create a task in. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param data - * @param dispatchOptions? - * @return - */ - createInWorkspace(workspace: number, data: Tasks.CreateParams, dispatchOptions?: any): Promise; - - /** - * * Returns the complete task record for a single task. - * * @param {Number} task The task to get. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - findById(task: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * A specific, existing task can be updated by making a PUT request on the - * * URL for that task. Only the fields provided in the `data` block will be - * * updated; any unspecified fields will remain unchanged. - * * - * * When using this method, it is best to specify only those fields you wish - * * to change, or else you may overwrite changes made by another user since - * * you last retrieved the task. - * * - * * Returns the complete updated task record. - * * @param {Number} task The task to update. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - update(task: number, data: Tasks.CreateParams, dispatchOptions?: any): Promise; - - /** - * * A specific, existing task can be deleted by making a DELETE request on the - * * URL for that task. Deleted tasks go into the "trash" of the user making - * * the delete request. Tasks can be recovered from the trash within a period - * * of 30 days; afterward they are completely removed from the system. - * * - * * Returns an empty data record. - * * @param {Number} task The task to delete. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param dispatchOptions? - * @return - */ - delete(task: number, dispatchOptions?: any): Promise; - - /** - * * Returns the compact task records for all tasks within the given project, - * * ordered by their priority within the project. - * * @param {Number} projectId The project in which to search for tasks. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param projectId - * @param params? - * @param dispatchOptions? - * @return - */ - findByProject(projectId: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact task records for all tasks with the given tag. - * * @param {Number} tag The tag in which to search for tasks. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param tag - * @param params? - * @param dispatchOptions? - * @return - */ - findByTag(tag: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact task records for some filtered set of tasks. Use one - * * or more of the parameters provided to filter the tasks returned. - * * @param {Object} [params] Parameters for the request - * * @param {Number} [params.assignee] The assignee to filter tasks on. - * * @param {Number} [params.workspace] The workspace or organization to filter tasks on. - * * @param {Number} [params.completed_since] Only return tasks that are either incomplete or that have been - * * completed since this time. - * * @param {Number} [params.modified_since] Only return tasks that have been modified since the given time. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param params? - * @param dispatchOptions? - * @return - */ - findAll(params?: Tasks.FindAllParams, dispatchOptions?: any): Promise>; - - /** - * * Adds each of the specified followers to the task, if they are not already - * * following. Returns the complete, updated record for the affected task. - * * @param {Number} task The task to add followers to. - * * @param {Object} data Data for the request - * * @param {Array} data.followers An array of followers to add to the task. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - addFollowers(task: number, data: Tasks.FollowersParams, dispatchOptions?: any): Promise; - - /** - * * Removes each of the specified followers from the task if they are - * * following. Returns the complete, updated record for the affected task. - * * @param {Number} task The task to remove followers from. - * * @param {Object} data Data for the request - * * @param {Array} data.followers An array of followers to remove from the task. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - removeFollowers(task: number, data: Tasks.FollowersParams, dispatchOptions?: any): Promise; - - /** - * * Returns a compact representation of all of the projects the task is in. - * * @param {Number} task The task to get projects on. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - projects(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Adds the task to the specified project, in the optional location - * * specified. If no location arguments are given, the task will be added to - * * the beginning of the project. - * * - * * `addProject` can also be used to reorder a task within a project that - * * already contains it. - * * - * * Returns an empty data block. - * * @param {Number} task The task to add to a project. - * * @param {Object} data Data for the request - * * @param {Number} data.project The project to add the task to. - * * @param {Number} [data.insertAfter] A task in the project to insert the task after, or `null` to - * * insert at the beginning of the list. - * * @param {Number} [data.insertBefore] A task in the project to insert the task before, or `null` to - * * insert at the end of the list. - * * @param {Number} [data.section] A section in the project to insert the task into. The task will be - * * inserted at the top of the section. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - addProject(task: number, data: Tasks.AddProjectParams, dispatchOptions?: any): Promise<{}>; - - /** - * * Removes the task from the specified project. The task will still exist - * * in the system, but it will not be in the project anymore. - * * - * * Returns an empty data block. - * * @param {Number} task The task to remove from a project. - * * @param {Object} data Data for the request - * * @param {Number} data.project The project to remove the task from. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - removeProject(task: number, data: Tasks.RemoveProjectParams, dispatchOptions?: any): Promise<{}>; - - /** - * * Returns a compact representation of all of the tags the task has. - * * @param {Number} task The task to get tags on. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - tags(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Adds a tag to a task. Returns an empty data block. - * * @param {Number} task The task to add a tag to. - * * @param {Object} data Data for the request - * * @param {Number} data.tag The tag to add to the task. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - addTag(task: number, data: Tasks.TagParams, dispatchOptions?: any): Promise<{}>; - - /** - * * Removes a tag from the task. Returns an empty data block. - * * @param {Number} task The task to remove a tag from. - * * @param {Object} data Data for the request - * * @param {String} data.tag The tag to remove from the task. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - removeTag(task: number, data: Tasks.TagParams, dispatchOptions?: any): Promise<{}>; - - /** - * * Returns a compact representation of all of the subtasks of a task. - * * @param {Number} task The task to get the subtasks of. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - subtasks(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Creates a new subtask and adds it to the parent task. Returns the full record - * * for the newly created subtask. - * * @param {Number} task The task to add a subtask to. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - addSubtask(task: number, data: Tasks.CreateParams, dispatchOptions?: any): Promise; - - /** - * * Returns a compact representation of all of the stories on the task. - * * @param {Number} task The task containing the stories to get. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - stories(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Adds a comment to a task. The comment will be authored by the - * * currently authenticated user, and timestamped when the server receives - * * the request. - * * - * * Returns the full record for the new story added to the task. - * * @param {Number} task Globally unique identifier for the task. - * * @param {Object} data Data for the request - * * @param {String} data.text The plain text of the comment to add. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - addComment(task: number, data: Tasks.CommentParams, dispatchOptions?: any): Promise; - } - - interface TeamsStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Teams; - } - - namespace Teams { - interface Type extends Resource { - organization: Resource; - } - } - - var Teams: TeamsStatic; - - /** - * A _team_ is used to group related projects and people together within an - * organization. Each project in an organization is associated with a team. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Teams extends Resource { - /** - * * Returns the full record for a single team. - * * @param {Number} team Globally unique identifier for the team. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param team - * @param params? - * @param dispatchOptions? - * @return - */ - findById(team: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Returns the compact records for all teams in the organization visible to - * * the authorized user. - * * @param {Number} organization Globally unique identifier for the workspace or organization. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param organization - * @param params? - * @param dispatchOptions? - * @return - */ - findByOrganization(organization: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Returns the compact records for all users that are members of the team. - * * @param {Number} team Globally unique identifier for the team. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param team - * @param params? - * @param dispatchOptions? - * @return - */ - users(team: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * The user making this call must be a member of the team in order to add others. - * * The user to add must exist in the same organization as the team in order to be added. - * * The user to add can be referenced by their globally unique user ID or their email address. - * * Returns the full user record for the added user. - * * @param {Number} team Globally unique identifier for the team. - * * @param {Object} data Data for the request - * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, - * * the globally unique identifier for the user, or the keyword `me` - * * to indicate the current user making the request. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param team - * @param data - * @param dispatchOptions? - * @return - */ - addUser(team: number, data: UserParams, dispatchOptions?: any): Promise; - - /** - * * The user to remove can be referenced by their globally unique user ID or their email address. - * * Removes the user from the specified team. Returns an empty data record. - * * @param {Number} team Globally unique identifier for the team. - * * @param {Object} data Data for the request - * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, - * * the globally unique identifier for the user, or the keyword `me` - * * to indicate the current user making the request. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param team - * @param data - * @param dispatchOptions? - * @return - */ - removeUser(team: number, data: UserParams, dispatchOptions?: any): Promise; - } - - interface UsersStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Users; - } - - namespace Users { - interface FindAllParams extends PaginationParams { - workspace: number; - } - - interface Type extends Resource { - email: string; - workspaces: Resource[]; - photo: { [key: string]: string }; - } - } - - var Users: UsersStatic; - - /** - * A _user_ object represents an account in Asana that can be given access to - * various workspaces, projects, and tasks. - * - * Like other objects in the system, users are referred to by numerical IDs. - * However, the special string identifier `me` can be used anywhere - * a user ID is accepted, to refer to the current authenticated user. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Users extends Resource { - /** - * * Returns the full user record for the currently authenticated user. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param params? - * @param dispatchOptions? - * @return - */ - me(params?: Params, dispatchOptions?: any): Promise; - - /** - * * Returns the full user record for the single user with the provided ID. - * * @param {Number|String} user An identifier for the user. Can be one of an email address, - * * the globally unique identifier for the user, or the keyword `me` - * * to indicate the current user making the request. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param user - * @param params? - * @param dispatchOptions? - * @return - */ - findById(user: string|number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Returns the user records for all users in the specified workspace or - * * organization. - * * @param {Number} workspace The workspace in which to get users. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param params? - * @param dispatchOptions? - * @return - */ - findByWorkspace(workspace: number, params?: Params, dispatchOptions?: any): Promise>; - - /** - * * Returns the user records for all users in all workspaces and organizations - * * accessible to the authenticated user. Accepts an optional workspace ID - * * parameter. - * * @param {Object} [params] Parameters for the request - * * @param {Number} [params.workspace] The workspace or organization to filter users on. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param params - * @param dispatchOptions? - * @return - */ - findAll(params: Users.FindAllParams, dispatchOptions?: any): Promise; - } - - /** - * **Webhooks are currently in BETA - The information here may change.** - * - * Webhooks allow an application to be notified of changes. This is in addition - * to the ability to fetch those changes directly as - * [Events](/developers/api-reference/events) - in fact, Webhooks are just a way - * to receive Events via HTTP POST at the time they occur instead of polling for - * them. For services accessible via HTTP this is often vastly more convenient, - * and if events are not too frequent can be significantly more efficient. - * - * In both cases, however, changes are represented as Event objects - refer to - * the [Events documentation](/developers/api-reference/events) for more - * information on what data these events contain. - * - * **NOTE:** While Webhooks send arrays of Event objects to their target, the - * Event objects themselves contain *only IDs*, rather than the actual resource - * they are referencing. So while a normal event you receive via GET /events - * would look like this: - * - * {\ - * "resource": {\ - * "id": 1337,\ - * "name": "My Task"\ - * },\ - * "parent": null,\ - * "created_at": "2013-08-21T18:20:37.972Z",\ - * "user": {\ - * "id": 1123,\ - * "name": "Tom Bizarro"\ - * },\ - * "action": "changed",\ - * "type": "task"\ - * } - * - * In a Webhook payload you would instead receive this: - * - * {\ - * "resource": 1337,\ - * "parent": null,\ - * "created_at": "2013-08-21T18:20:37.972Z",\ - * "user": 1123,\ - * "action": "changed",\ - * "type": "task"\ - * } - * - * Webhooks themselves contain only the information necessary to deliver the - * events to the desired target as they are generated. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - class Webhooks extends Resource { - /** - * @param dispatcher - */ - constructor(dispatcher: Dispatcher); - - /** - * * Establishing a webhook is a two-part process. First, a simple HTTP POST - * * similar to any other resource creation. Since you could have multiple - * * webhooks we recommend specifying a unique local id for each target. - * * - * * Next comes the confirmation handshake. When a webhook is created, we will - * * send a test POST to the `target` with an `X-Hook-Secret` header as - * * described in the - * * [Resthooks Security documentation](http://resthooks.org/docs/security/). - * * The target must respond with a `200 OK` and a matching `X-Hook-Secret` - * * header to confirm that this webhook subscription is indeed expected. - * * - * * If you do not acknowledge the webhook's confirmation handshake it will - * * fail to setup, and you will receive an error in response to your attempt - * * to create it. This means you need to be able to receive and complete the - * * webhook *while* the POST request is in-flight. - * * @param {Number} resource A resource ID to subscribe to. The resource can be a task or project. - * * @param {String} target The URL to receive the HTTP POST. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param resource - * @param target - * @param data - * @param dispatchOptions? - * @return - */ - create(resource: number, target: string, data: any, dispatchOptions?: any): Promise; - - /** - * * Returns the compact representation of all webhooks your app has - * * registered for the authenticated user in the given workspace. - * * @param {Number} workspace The workspace to query for webhooks in. - * * @param {Object} [params] Parameters for the request - * * @param {Number} [params.resource] Only return webhooks for the given resource. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param params? - * @param dispatchOptions? - * @return - */ - getAll(workspace: number, params?: any, dispatchOptions?: any): Promise; - - /** - * * Returns the full record for the given webhook. - * * @param {String} webhook The webhook to get. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param webhook - * @param params? - * @param dispatchOptions? - * @return - */ - getById(webhook: string, params?: any, dispatchOptions?: any): Promise; - - /** - * * This method permanently removes a webhook. Note that it may be possible - * * to receive a request that was already in flight after deleting the - * * webhook, but no further requests will be issued. - * * @param {String} webhook The webhook to delete. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param webhook - * @param dispatchOptions? - * @return - */ - deleteById(webhook: string, dispatchOptions?: any): Promise; - } - - interface WorkspacesStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Workspaces; - } - - namespace Workspaces { - interface ShortType extends Resource { - id_organization?: boolean; - } - - interface Type extends Resource { - id_organization: boolean; - email_domains: string[]; - } - - interface TypeaheadParams { - type: string; - query?: string; - count?: number; - } - } - - var Workspaces: WorkspacesStatic; - - /** - * A _workspace_ is the highest-level organizational unit in Asana. All projects - * and tasks have an associated workspace. - * - * An _organization_ is a special kind of workspace that represents a company. - * In an organization, you can group your projects into teams. You can read - * more about how organizations work on the Asana Guide. - * To tell if your workspace is an organization or not, check its - * `is_organization` property. - * - * Over time, we intend to migrate most workspaces into organizations and to - * release more organization-specific functionality. We may eventually deprecate - * using workspace-based APIs for organizations. Currently, and until after - * some reasonable grace period following any further announcements, you can - * still reference organizations in any `workspace` parameter. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Workspaces extends Resource { - /** - * * Returns the full workspace record for a single workspace. - * * @param {Number} workspace Globally unique identifier for the workspace or organization. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param workspace - * @param params? - * @param dispatchOptions? - * @return - */ - findById(workspace: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Returns the compact records for all workspaces visible to the authorized user. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param params? - * @param dispatchOptions? - * @return - */ - findAll(params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * A specific, existing workspace can be updated by making a PUT request on - * * the URL for that workspace. Only the fields provided in the data block - * * will be updated; any unspecified fields will remain unchanged. - * * - * * Currently the only field that can be modified for a workspace is its `name`. - * * - * * Returns the complete, updated workspace record. - * * @param {Number} workspace The workspace to update. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param data - * @param dispatchOptions? - * @return - */ - update(workspace: number, data: { name?: string }, dispatchOptions?: any): Promise; - - /** - * * Retrieves objects in the workspace based on an auto-completion/typeahead - * * search algorithm. This feature is meant to provide results quickly, so do - * * not rely on this API to provide extremely accurate search results. The - * * result set is limited to a single page of results with a maximum size, - * * so you won't be able to fetch large numbers of results. - * * @param {Number} workspace The workspace to fetch objects from. - * * @param {Object} [params] Parameters for the request - * * @param {String} params.type The type of values the typeahead should return. - * * Note that unlike in the names of endpoints, the types listed here are - * * in singular form (e.g. `task`). Using multiple types is not yet supported. - * * @param {String} [params.query] The string that will be used to search for relevant objects. If an - * * empty string is passed in, the API will currently return an empty - * * result set. - * * @param {Number} [params.count] The number of results to return. The default is `20` if this - * * parameter is omitted, with a minimum of `1` and a maximum of `100`. - * * If there are fewer results found than requested, all will be returned. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param params? - * @param dispatchOptions? - * @return - */ - typeahead(workspace: number, params?: Workspaces.TypeaheadParams, dispatchOptions?: any): Promise; - - /** - * * The user can be referenced by their globally unique user ID or their email address. - * * Returns the full user record for the invited user. - * * @param {Number} workspace The workspace or organization to invite the user to. - * * @param {Object} data Data for the request - * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, - * * the globally unique identifier for the user, or the keyword `me` - * * to indicate the current user making the request. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param data - * @param dispatchOptions? - * @return - */ - addUser(workspace: number, data: UserParams, dispatchOptions?: any): Promise; - - /** - * * The user making this call must be an admin in the workspace. - * * Returns an empty data record. - * * @param {Number} workspace The workspace or organization to invite the user to. - * * @param {Object} data Data for the request - * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, - * * the globally unique identifier for the user, or the keyword `me` - * * to indicate the current user making the request. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param data - * @param dispatchOptions? - * @return - */ - removeUser(workspace: number, data: UserParams, dispatchOptions?: any): Promise; - } - - interface ResourceStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Resource; - - /** - * @type {number} Default number of items to get per page. - */ - DEFAULT_PAGE_LIMIT: number; - - /** - * Helper method that dispatches a GET request to the API, where the expected - * result is a collection. - * @param {Dispatcher} dispatcher - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The Collection response for the request - * @param dispatcher - * @param path - * @param query? - * @param dispatchOptions? - */ - getCollection(dispatcher: any, path: string, query?: any, dispatchOptions?: any): Promise; - - /** - * Helper method for any request Promise from the Dispatcher, unwraps the `data` - * value from the payload. - * @param {Promise} promise A promise returned from a `Dispatcher` request. - * @return {Promise} The `data` portion of the response payload. - * @param promise - * @return - */ - unwrap(promise: any): Promise; - } - - var Resource: ResourceStatic; - - /** - * Base class for a resource accessible via the API. Uses a `Dispatcher` to - * access the resources. - * @param {Dispatcher} dispatcher - * @constructor - */ - interface Resource { - /** - * Dispatches a GET request to the API, where the expected result is a - * single resource. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - * @param path - * @param query? - * @param dispatchOptions? - * @return - */ - dispatchGet(path: string, query?: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a GET request to the API, where the expected result is a - * collection. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - * @param path - * @param query? - * @param dispatchOptions? - * @return - */ - dispatchGetCollection(path: string, query?: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a POST request to the API, where the expected response is a - * single resource. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - * @param path - * @param query? - * @param dispatchOptions? - * @return - */ - dispatchPost(path: string, query?: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a POST request to the API, where the expected response is a - * single resource. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - * @param path - * @param query? - * @param dispatchOptions? - * @return - */ - dispatchPut(path: string, query?: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a DELETE request to the API. The expected response is an - * empty resource. - * @param {String} path The path of the API - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - * @param path - * @param dispatchOptions? - * @return - */ - dispatchDelete(path: string, dispatchOptions?: any): Promise; - } - - interface ResourceList { - data: T[]; - _response: { - data: T[]; - next_page?: NextPage; - }; - _dispatcher: { - authenticator: { - apiKey: string; - }; - asanaBaseUrl: string; - retryOnRateLimit: boolean; - requestTimeout: number; - _cachedVersionInfo: VersionInfo; - } - } - - type SimpleResourceList = ResourceList; - - interface NextPage { - offset: string; - uri: string; - path: string; - } - - interface VersionInfo { - version: string; - language: string; - language_version: string; - os: string; - os_version: string; - } - - interface Resource { - id: number; - name: string; - } - - interface PaginationParams extends Params { - limit?: number; - offset?: string; - } - - interface Params { - opt_fields?: string; - opt_expand?: string; - } - - interface UserParams { - user: string|number; - } - - interface Membership { - project: Resource; - section: Resource; - } - } - - var VERSION: string; - } - - export = asana; -} - diff --git a/asana/index.d.ts b/asana/index.d.ts new file mode 100644 index 0000000000..364980b66c --- /dev/null +++ b/asana/index.d.ts @@ -0,0 +1,2472 @@ +// Type definitions for node-asana 0.14.0 +// Project: https://github.com/Asana/node-asana +// Definitions by: Qubo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as Promise from 'bluebird'; + +declare namespace asana { + var Client: ClientStatic; + + interface ClientStatic { + /** + * Constructs a Client with instances of all the resources using the dispatcher. + * It also keeps a reference to the dispatcher so that way the end user can have + * access to it. + * @class + * @classdesc A wrapper for the Asana API which is authenticated for one user + * @param {Dispatcher} dispatcher The request dispatcher to use + * @param {Object} options Options to configure the client + * @param {String} [clientId] ID of the client, required for Oauth + * @param {String} [clientSecret] Secret key, for some Oauth flows + * @param {String} [redirectUri] Default redirect URI for this client + * @param {String} [asanaBaseUrl] Base URL for Asana, for debugging + */ + (dispatcher: Dispatcher, options?: ClientOptions): asana.Client; + /** + * Creates a new client. + * @param {Object} options Options for specifying the client, see constructor. + */ + create(options?: ClientOptions): Client; + } + + /** Options to configure the client */ + interface ClientOptions extends DispatcherOptions { + clientId?: string | number; + clientSecret?: string; + redirectUri?: string; + asanaBaseUrl?: string; + } + + interface Client { + /** + * Ensures the client is authorized to make requests. Kicks off the + * configured Oauth flow, if any. + * + * @returns {Promise} A promise that resolves to this client when + * authorization is complete. + */ + authorize(): Promise; + + /** + * Configure the Client to use a user's API Key and then authenticate + * through HTTP Basic Authentication. This should only be done for testing, + * as requests using Oauth can provide more security, higher rate limits, and + * more features. + * @param {String} apiKey The Asana Api Key of the user + * @return {Client} this + * @param apiKey + * @return + */ + useBasicAuth(apiKey: string): this; + + /** + * Configure the client to authenticate using a Personal Access Token. + * @param {String} accessToken The Personal Access Token to use for + * authenticating requests. + * @return {Client} this + * @param accessToken + * @return + */ + useAccessToken(accessToken: string): this; + + /** + * Configure the client to authenticate via Oauth. Credentials can be + * supplied, or they can be obtained by running an Oauth flow. + * @param {Object} options Options for Oauth. Includes any options for + * the selected flow. + * @option {Function} [flowType] Type of OauthFlow to use to obtain user + * authorization. Defaults to autodetect based on environment. + * @option {Object} [credentials] Credentials to use; no flow required to + * obtain authorization. This object should at a minimum contain an + * `access_token` string field. + * @return {Client} this + * @param options + * @return + */ + useOauth(options?: auth.OauthAuthenticatorOptions): this; + + /** + * The internal dispatcher. This is mostly used by the resources but provided + * for custom requests to the API or API features that have not yet been added + * to the client. + * @type {Dispatcher} + */ + dispatcher: Dispatcher; + /** + * An instance of the Attachments resource. + * @type {Attachments} + */ + attachments: resources.Attachments; + /** + * An instance of the Events resource. + * @type {Events} + */ + events: resources.Events; + /** + * An instance of the Projects resource. + * @type {Projects} + */ + projects: resources.Projects; + /** + * An instance of the Stories resource. + * @type {Stories} + */ + stories: resources.Stories; + /** + * An instance of the Tags resource. + * @type {Tags} + */ + tags: resources.Tags; + /** + * An instance of the Tasks resource. + * @type {Tasks} + */ + tasks: resources.Tasks; + /** + * An instance of the Teams resource. + * @type {Teams} + */ + teams: resources.Teams; + /** + * An instance of the Users resource. + * @type {Users} + */ + users: resources.Users; + /** + * An instance of the Workspaces resource. + * @type {Workspaces} + */ + workspaces: resources.Workspaces; + /** + * Store off Oauth info. + */ + app: auth.App; + } + + var Dispatcher: DispatcherStatic; + + interface DispatcherStatic { + /** + * Creates a dispatcher which will act as a basic wrapper for making HTTP + * requests to the API, and handle authentication. + * @class + * @classdesc A HTTP wrapper for the Asana API + * @param {Object} options for default behavior of the Dispatcher + * @option {Authenticator} [authenticator] Object to use for authentication. + * Can also be set later with `setAuthenticator`. + * @option {String} [retryOnRateLimit] Automatically handle `RateLimitEnforced` + * errors by sleeping and retrying after the waiting period. + * @option {Function} [handleUnauthorized] Automatically handle + * `NoAuthorization` with the callback. If the callback returns `true` + * (or a promise resolving to `true), will retry the request. + * @option {String} [asanaBaseUrl] Base URL for Asana, for debugging + * @option {Number} [requestTimeout] Timeout (in milliseconds) to wait for the + * request to finish. + */ + new (options?: DispatcherOptions): Dispatcher; + + /** + * Default handler for requests that are considered unauthorized. + * Requests that the authenticator try to refresh its credentials if + * possible. + * @return {Promise} True iff refresh was successful, false if not. + * @return + */ + maybeReauthorize(): Promise; + + /** + * The relative API path for the current version of the Asana API. + * @type {String} + */ + API_PATH: string; + } + + interface DispatcherOptions { + authenticator?: auth.Authenticator; + retryOnRateLimit?: boolean; + handleUnauthorized?: () => boolean | Promise; + requestTimeout?: string; + } + + interface Dispatcher { + /** + * Creates an Asana API Url by concatenating the ROOT_URL with path provided. + * @param {String} path The path + * @return {String} The url + * @param path + * @return + */ + url(path: string): string; + + /** + * Configure the authentication mechanism to use. + * @returns {Dispatcher} this + * @param authenticator + * @return + */ + setAuthenticator(authenticator: auth.Authenticator): this; + + /** + * Ensure the dispatcher is authorized to make requests. Call this before + * making any API requests. + * + * @returns {Promise} Resolves when the dispatcher is authorized, rejected if + * there was a problem authorizing. + * @return + */ + authorize(): Promise; + + /** + * Dispatches a request to the Asana API. The request parameters are passed to + * the request module. + * @param {Object} params The params for request + * @param {Object} [dispatchOptions] Options for handling request/response + * @return {Promise} The response for the request + * @param params + * @param dispatchOptions? + * @return + */ + dispatch(params: any, dispatchOptions?: any): Promise; + + /** + * Dispatches a GET request to the Asana API. + * @param {String} path The path of the API + * @param {Object} [query] The query params + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `dispatch`. + * @return {Promise} The response for the request + * @param path + * @param query? + * @param dispatchOptions? + * @return + */ + get(path: string, query?: any, dispatchOptions?: any): Promise; + + /** + * Dispatches a POST request to the Asana API. + * @param {String} path The path of the API + * @param {Object} data The data to be sent + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `dispatch`. + * @return {Promise} The response for the request + * @param path + * @param data + * @param dispatchOptions? + * @return + */ + post(path: string, data: any, dispatchOptions?: any): Promise; + + /** + * Dispatches a PUT request to the Asana API. + * @param {String} path The path of the API + * @param {Object} data The data to be sent + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `dispatch`. + * @return {Promise} The response for the request + * @param path + * @param data + * @param dispatchOptions? + * @return + */ + put(path: string, data: any, dispatchOptions?: any): Promise; + + /** + * Dispatches a DELETE request to the Asana API. + * @param {String} path The path of the API + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `dispatch`. + * @return {Promise} The response for the request + * @param path + * @param dispatchOptions? + * @return + */ + delete(path: string, dispatchOptions?: any): Promise; + + /** + * The base URL for Asana + * @type {String} + */ + asanaBaseUrl: string; + + /** + * Whether requests should be automatically retried if rate limited. + * @type {Boolean} + */ + retryOnRateLimit: boolean; + + /** + * Handler for unauthorized requests which may seek reauthorization. + * Default behavior is available if configured with an Oauth authenticator + * that has a refresh token, and will refresh the current access token. + * @type {Function} + */ + handleUnauthorized: () => boolean | Promise; + + /** + * The amount of time in milliseconds to wait for a request to finish. + * @type {Number} + */ + requestTimeout: number; + } + + namespace auth { + var BasicAuthenticator: BasicAuthenticatorStatic; + + interface BasicAuthenticatorStatic { + /** + * @param apiKey + */ + new (apiKey: string): BasicAuthenticator; + } + + interface BasicAuthenticator extends Authenticator { + /** + * @param {Object} request The request to modify, for the `request` library. + * @return {Object} The `request` parameter, modified to include authentication + * information using the stored credentials. + * @param request + * @return + */ + authenticateRequest(request: BasicAuthenticatorRequest): BasicAuthenticatorRequest; + } + + interface BasicAuthenticatorRequest { + auth: { + username: string; + password: string; + } + } + + var OauthAuthenticator: OauthAuthenticatorStatic; + + interface OauthAuthenticatorStatic { + /** + * Creates an authenticator that uses Oauth for authentication. + * + * @param {Object} options Configure the authenticator; must specify one + * of `flow` or `credentials`. + * @option {App} app The app being authenticated for. + * @option {OauthFlow} [flow] The flow to use to get credentials + * when needed. + * @option {String|Object} [credentials] Initial credentials to use. This can + * be either the object returned from an access token request (which + * contains the token and some other metadata) or just the `access_token` + * field. + * @constructor + */ + new (options: OauthAuthenticatorOptions): OauthAuthenticator; + } + + interface OauthAuthenticatorOptions { + flowType?: auth.FlowType; + credentials?: Credentials | string; + } + + interface Credentials { + access_token?: string; + refresh_token?: string; + } + + interface OauthAuthenticator extends Authenticator { + /** + * @param {Object} request The request to modify, for the `request` library. + * @return {Object} The `request` parameter, modified to include authentication + * information using the stored credentials. + * @param request + * @return + */ + authenticateRequest(request: OauthAuthenticatorRequest): OauthAuthenticatorRequest; + } + + interface OauthAuthenticatorRequest { + /** + * When browserify-d, the `auth` component of the `request` library + * doesn't work so well, so we just manually set the bearer token instead. + */ + headers: { + Authorization: string; + } + } + + /** + * A layer to abstract the differences between using different types of + * authentication (Oauth vs. Basic). The Authenticator is responsible for + * establishing credentials and applying them to outgoing requests. + * @constructor + */ + interface Authenticator { + /** + * Establishes credentials. + * + * @return {Promise} Resolves when initial credentials have been + * completed and `authenticateRequest` calls can expect to succeed. + * @return + */ + establishCredentials(): Promise; + + /** + * Attempts to refresh credentials, if possible, given the current credentials. + * + * @return {Promise} Resolves to `true` if credentials have been successfully + * established and `authenticateRequests` can expect to succeed, else + * resolves to `false`. + * @return + */ + refreshCredentials(): Promise; + } + + var App: AppStatic; + + interface AppStatic { + /** + * An abstraction around an App used with Asana. + * + * @options {Object} Options to construct the app + * @option {String} clientId The ID of the app + * @option {String} [clientSecret] The secret key, if available here + * @option {String} [redirectUri] The default redirect URI + * @option {String} [scope] Scope to use, supports `default` and `scim` + * @option {String} [asanaBaseUrl] Base URL to use for Asana, for debugging + * @constructor + */ + new (options: AppOptions): App; + } + + interface AppOptions extends AsanaAuthorizeUrlOptions { + clientId?: string | number; + clientSecret?: string; + scope?: string; + } + + interface App { + /** + * @param {Object} options Overrides to the app's defaults + * @option {String} asanaBaseUrl + * @option {String} redirectUri + * @returns {String} The URL used to authorize a user for the app. + * @param options + * @return + */ + asanaAuthorizeUrl(options?: AsanaAuthorizeUrlOptions): string; + + /** + * @param {Object} options Overrides to the app's defaults + * @option {String} asanaBaseUrl + * @option {String} redirectUri + * @returns {String} The URL used to acquire an access token. + * @param options + * @return + */ + asanaTokenUrl(options?: AsanaAuthorizeUrlOptions): string; + + /** + * @param {String} code An authorization code obtained via `asanaAuthorizeUrl`. + * @param {Object} options Overrides to the app's defaults + * @option {String} asanaBaseUrl + * @option {String} redirectUri + * @return {Promise} The token, which will include the `access_token` + * used for API access, as well as a `refresh_token` which can be stored + * to get a new access token without going through the flow again. + * @param code + * @param options + * @return + */ + accessTokenFromCode(code: string, options?: AsanaAuthorizeUrlOptions): Promise; + + /** + * @param {String} refreshToken A refresh token obtained via Oauth. + * @param {Object} options Overrides to the app's defaults + * @option {String} asanaBaseUrl + * @option {String} redirectUri + * @return {Promise} The token, which will include the `access_token` + * used for API access. + * @param refreshToken + * @param options + * @return + */ + accessTokenFromRefreshToken(refreshToken: string, options: AsanaAuthorizeUrlOptions): Promise; + + scope: string; + + asanaBaseUrl: string; + } + + interface AsanaAuthorizeUrlOptions { + redirectUri?: string; + asanaBaseUrl?: string; + } + + var OauthError: OauthErrorStatic; + + interface OauthErrorStatic { + /** + * @param options {Object} A data blob parsed from a query string or JSON + * response from the Asana API + * @option {String} error The string code identifying the error. + * @option {String} [error_uri] A link to help and information about the error. + * @option {String} [error_description] A description of the error. + * @constructor + */ + new (options: OauthErrorOptions): OauthError; + } + + interface OauthErrorOptions { + error?: string; + error_uri?: string; + error_description?: string; + } + + interface OauthError extends Error { + } + + /** + * Auto-detects the type of Oauth flow to use that's appropriate to the + * environment. + * + * @returns {Function|null} The type of Oauth flow to use, or null if no + * appropriate type could be determined. + * @param env + * @return + */ + function autoDetect(env: any): Function; + + var RedirectFlow: RedirectFlowStatic; + + interface RedirectFlowStatic extends FlowType { + /** + * An Oauth flow that runs in the browser and requests user authorization by + * redirecting to an authorization page on Asana, and redirecting back with + * the credentials. + * @param {Object} options See `BaseBrowserFlow` for options. + * @constructor + */ + new (options: any): RedirectFlow; + } + + interface RedirectFlow extends BaseBrowserFlow { + } + + var PopupFlow: PopupFlowStatic; + + interface PopupFlowStatic extends FlowType { + /** + * An Oauth flow that runs in the browser and requests user authorization by + * popping up a window and prompting the user. + * @param {Object} options See `BaseBrowserFlow` for options. + * @constructor + */ + new (options: any): PopupFlow; + } + + interface PopupFlow extends BaseBrowserFlow { + /** + * @param popupWidth + * @param popupHeight + */ + _popupParams(popupWidth: number, popupHeight: number): void; + + runReceiver(): void; + } + + var NativeFlow: NativeFlowStatic; + + interface NativeFlowStatic extends FlowType { + /** + * An Oauth flow that can be run from the console or an app that does + * not have the ability to open and manage a browser on its own. + * @param {Object} options + * @option {App} app App to authenticate for + * @option {String function(String)} [instructions] Function returning the + * instructions to output to the user. Passed the authorize url. + * @option {String function()} [prompt] String to output immediately before + * waiting for a line from stdin. + * @constructor + */ + new (options: any): NativeFlow; + } + + interface NativeFlow extends Flow { + /** + * Run the Oauth flow, prompting the user to go to the authorization URL + * and enter the code it displays when finished. + * + * @return {Promise} The access token object, which will include + * `access_token` and `refresh_token`. + */ + run(): void; + + /** + * @param {String} code An authorization code obtained via `asanaAuthorizeUrl`. + * @return {Promise} The token, which will include the `access_token` + * used for API access, as well as a `refresh_token` which can be stored + * to get a new access token without going through the flow again. + * @param code + */ + accessToken(code: string): void; + + /** + * @return {Promise} The access token, which will include a refresh token + * that can be stored in the future to create a client without going + * through the Oauth flow. + * @param url + * @return + */ + promptForCode(url: string): any; + } + + var ChromeExtensionFlow: ChromeExtensionFlowStatic; + + interface ChromeExtensionFlowStatic extends FlowType { + /** + * An Oauth flow that runs in a Chrome browser extension and requests user + * authorization by opening a temporary tab to prompt the user. + * @param {Object} options See `BaseBrowserFlow` for options, plus the below: + * @options {String} [receiverPath] Full path and filename from the base + * directory of the extension to the receiver page. This is an HTML file + * that has been made web-accessible, and that calls the receiver method + * `Asana.auth.ChromeExtensionFlow.runReceiver();`. + * @constructor + */ + new (options: any): ChromeExtensionFlow; + } + + interface ChromeExtensionFlow extends BaseBrowserFlow { + /** + * Runs the receiver code to send the Oauth result to the requesting tab. + */ + runReceiver(): void; + } + + var BaseBrowserFlow: BaseBrowserFlowStatic; + + interface BaseBrowserFlowStatic extends FlowType { + /** + * A base class for any flow that runs in the browser. All subclasses use the + * "implicit grant" flow to authenticate via the browser. + * @param {Object} options + * @option {App} app The app this flow is for + * @option {String} [redirectUri] The URL that Asana should redirect to once + * user authorization is complete. Defaults to the URL configured in + * the app, and if none then the current page URL. + * @constructor + */ + new (options: any): BaseBrowserFlow; + } + + interface BaseBrowserFlow extends Flow { + /** + * @param {String} authUrl The URL the user should be navigated to in order + * to authorize the app. + * @param {String} state The unique state generated for this auth request. + * @return {Promise} Resolved when authorization has successfully started, + * i.e. the user has been navigated to a page requesting authorization. + * @param authUrl + * @param state + * @return + */ + startAuthorization(authUrl: string, state: string): any; + + /** + * @return {Promise} Credentials returned from Oauth. + * @param state + */ + finishAuthorization(state: string): void; + + /** + * @return {String} The URL to redirect to that will receive the + * @return + */ + receiverUrl(): string; + + /** + * @return {String} The URL to redirect to that will receive the + * @return + */ + asanaBaseUrl(): string; + + /** + * @returns {String} Generate a new unique state parameter for a request. + * @return + */ + getStateParam(): string; + } + + interface FlowType { + new (options: any): Flow; + } + + interface Flow { + /** + * @returns {String} The URL used to authorize the user for the app. + * @return + */ + authorizeUrl(): string; + + /** + * Run the appropriate parts of the Oauth flow, attempting to establish user + * authorization. + * @returns {Promise} A promise that resolves to the Oauth credentials. + */ + run(): void; + } + } + + namespace errors { + class AsanaError extends Error { + /** + * @param message + * @return + */ + constructor(message: any); + + code: number; + value: any; + } + + class Forbidden extends AsanaError { + /** + * @param value + * @return + */ + constructor(value: any); + } + + + class InvalidRequest extends AsanaError { + /** + * @param value + * @return + */ + constructor(value: any); + } + + class NoAuthorization extends AsanaError { + /** + * @param value + * @return + */ + constructor(value: any); + } + + class NotFound extends AsanaError { + /** + * @param value + * @return + */ + constructor(value: any); + } + + class RateLimitEnforced extends AsanaError { + /** + * @param value + * @return + */ + constructor(value: any); + } + + class ServerError extends AsanaError { + /** + * @param value + * @return + */ + constructor(value: any); + } + } + + namespace resources { + interface AttachmentsStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Attachments; + } + + namespace Attachments { + interface Type extends Resource { + created_at: string; + permanent_url: string; + download_url: string; + view_url: string; + host: string; + parent: Resource; + } + } + + var Attachments: AttachmentsStatic; + + /** + * An _attachment_ object represents any file attached to a task in Asana, + * whether it's an uploaded file or one associated via a third-party service + * such as Dropbox or Google Drive. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Attachments extends Resource { + /** + * * Returns the full record for a single attachment. + * * @param {Number} attachment Globally unique identifier for the attachment. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param attachment + * @param params? + * @param dispatchOptions? + * @return + */ + findById(attachment: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Returns the compact records for all attachments on the task. + * * @param {Number} task Globally unique identifier for the task. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + findByTask(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + } + + interface EventsStatic { + /** + * @param dispatcher + * @return + */ + new (dispatcher: Dispatcher): Events; + } + + var Events: EventsStatic; + + /** + * An _event_ is an object representing a change to a resource that was observed + * by an event subscription. + * + * In general, requesting events on a resource is faster and subject to higher + * rate limits than requesting the resource itself. Additionally, change events + * bubble up - listening to events on a project would include when stories are + * added to tasks in the project, even on subtasks. + * + * Establish an initial sync token by making a request with no sync token. + * The response will be a `412` error - the same as if the sync token had + * expired. + * + * Subsequent requests should always provide the sync token from the immediately + * preceding call. + * + * Sync tokens may not be valid if you attempt to go 'backward' in the history + * by requesting previous tokens, though re-requesting the current sync token + * is generally safe, and will always return the same results. + * + * When you receive a `412 Precondition Failed` error, it means that the + * sync token is either invalid or expired. If you are attempting to keep a set + * of data in sync, this signals you may need to re-crawl the data. + * + * Sync tokens always expire after 24 hours, but may expire sooner, depending on + * load on the service. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Events extends Resource { } + + interface ProjectsStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Projects; + } + + namespace Projects { + interface Type extends Resource { + created_at: string; + modified_at: string; + due_date: string; + current_status: Status; + public: boolean; + archived: boolean; + notes: string; + color: string; + workspace: Resource; + team: Resource; + members: Resource[]; + followers: Resource[]; + } + + interface CreateParams { + name?: string; + team?: number; + public?: boolean; + due_date: string; + notes?: string; + color?: string; + } + + interface FollowersParams { + followers: (number | string)[]; + } + + interface MembersParams { + members: (number | string)[]; + } + + interface Status { + color: string; + text: string; + html_text: string; + modified_at: string; + author: Resource; + } + + interface FindAllParams extends PaginationParams { + team?: number; + archived?: boolean; + } + + interface FindByParams extends PaginationParams { + archived?: boolean; + } + } + + var Projects: ProjectsStatic; + + /** + * A _project_ represents a prioritized list of tasks in Asana. It exists in a + * single workspace or organization and is accessible to a subset of users in + * that workspace or organization, depending on its permissions. + * + * Projects in organizations are shared with a single team. You cannot currently + * change the team of a project via the API. Non-organization workspaces do not + * have teams and so you should not specify the team of project in a + * regular workspace. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Projects extends Resource { + /** + * * Creates a new project in a workspace or team. + * * + * * Every project is required to be created in a specific workspace or + * * organization, and this cannot be changed once set. Note that you can use + * * the `workspace` parameter regardless of whether or not it is an + * * organization. + * * + * * If the workspace for your project _is_ an organization, you must also + * * supply a `team` to share the project with. + * * + * * Returns the full record of the newly created project. + * * @param {Object} data Data for the request + * * @param {String} data.workspace The workspace or organization to create the project in. + * * @param {String} [data.team] If creating in an organization, the specific team to create the + * * project in. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param data + * @param dispatchOptions? + * @return + */ + create(data: Projects.CreateParams & { workspace: number }, dispatchOptions?: any): Promise; + + /** + * * If the workspace for your project _is_ an organization, you must also + * * supply a `team` to share the project with. + * * + * * Returns the full record of the newly created project. + * * @param {Number} workspace The workspace or organization to create the project in. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param data + * @param dispatchOptions? + * @return + */ + createInWorkspace(workspace: number, data: Projects.CreateParams, dispatchOptions?: any): Promise; + + /** + * * Creates a project shared with the given team. + * * + * * Returns the full record of the newly created project. + * * @param {Number} team The team to create the project in. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param team + * @param data + * @param dispatchOptions? + * @return + */ + createInTeam(team: number, data: Projects.CreateParams, dispatchOptions?: any): Promise; + + /** + * * Returns the complete project record for a single project. + * * @param {Number} project The project to get. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param project + * @param params? + * @param dispatchOptions? + * @return + */ + findById(project: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * A specific, existing project can be updated by making a PUT request on the + * * URL for that project. Only the fields provided in the `data` block will be + * * updated; any unspecified fields will remain unchanged. + * * + * * When using this method, it is best to specify only those fields you wish + * * to change, or else you may overwrite changes made by another user since + * * you last retrieved the task. + * * + * * Returns the complete updated project record. + * * @param {Number} project The project to update. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param data + * @param dispatchOptions? + * @return + */ + update(project: number, data: Projects.CreateParams, dispatchOptions?: any): Promise; + + /** + * * A specific, existing project can be deleted by making a DELETE request + * * on the URL for that project. + * * + * * Returns an empty data record. + * * @param {Number} project The project to delete. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param dispatchOptions? + * @return + */ + delete(project: number, dispatchOptions?: any): Promise; + + /** + * * Returns the compact project records for some filtered set of projects. + * * Use one or more of the parameters provided to filter the projects returned. + * * @param {Object} [params] Parameters for the request + * * @param {String} [params.workspace] The workspace or organization to filter projects on. + * * @param {String} [params.team] The team to filter projects on. + * * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of + * * this parameter. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param params? + * @param dispatchOptions? + * @return + */ + findAll(params?: Projects.FindAllParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact project records for all projects in the workspace. + * * @param {Number} workspace The workspace or organization to find projects in. + * * @param {Object} [params] Parameters for the request + * * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of + * * this parameter. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param params? + * @param dispatchOptions? + * @return + */ + findByWorkspace(workspace: number, params?: Projects.FindByParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact project records for all projects in the team. + * * @param {Number} team The team to find projects in. + * * @param {Object} [params] Parameters for the request + * * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of + * * this parameter. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param team + * @param params? + * @param dispatchOptions? + * @return + */ + findByTeam(team: number, params?: Projects.FindByParams, dispatchOptions?: any): Promise>; + + /** + * * Returns compact records for all sections in the specified project. + * * @param {Number} project The project to get sections from. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param params? + * @param dispatchOptions? + * @return + */ + sections(project: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact task records for all tasks within the given project, + * * ordered by their priority within the project. Tasks can exist in more than one project at a time. + * * @param {Number} project The project in which to search for tasks. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param params? + * @param dispatchOptions? + * @return + */ + tasks(project: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Adds the specified list of users as followers to the project. Followers are a subset of members, therefore if + * * the users are not already members of the project they will also become members as a result of this operation. + * * Returns the updated project record. + * * @param {Number} project The project to add followers to. + * * @param {Object} data Data for the request + * * @param {Array} data.followers An array of followers to add to the project. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param data + * @param dispatchOptions? + * @return + */ + addFollowers(project: number, data: Projects.FollowersParams, dispatchOptions?: any): Promise; + + /** + * * Removes the specified list of users from following the project, this will not affect project membership status. + * * Returns the updated project record. + * * @param {Number} project The project to remove followers from. + * * @param {Object} data Data for the request + * * @param {Array} data.followers An array of followers to remove from the project. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param data + * @param dispatchOptions? + * @return + */ + removeFollowers(project: number, data: Projects.FollowersParams, dispatchOptions?: any): Promise; + + /** + * * Adds the specified list of users as members of the project. Returns the updated project record. + * * @param {Number} project The project to add members to. + * * @param {Object} data Data for the request + * * @param {Array} data.members An array of members to add to the project. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param data + * @param dispatchOptions? + * @return + */ + addMembers(project: number, data: Projects.MembersParams, dispatchOptions?: any): Promise; + + /** + * * Removes the specified list of members from the project. Returns the updated project record. + * * @param {Number} project The project to remove members from. + * * @param {Object} data Data for the request + * * @param {Array} data.members An array of members to remove from the project. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param data + * @param dispatchOptions? + * @return + */ + removeMembers(project: number, data: Projects.MembersParams, dispatchOptions?: any): Promise; + } + + interface StoriesStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Stories; + } + + namespace Stories { + interface ShortType extends Resource { + created_at: string; + created_by: Resource; + type: string; + text: string; + } + + interface Type extends ShortType { + html_text: string; + source: string; + target: Resource; + hearts: Type[]; + } + } + + var Stories: StoriesStatic; + + /** + * A _story_ represents an activity associated with an object in the Asana + * system. Stories are generated by the system whenever users take actions such + * as creating or assigning tasks, or moving tasks between projects. _Comments_ + * are also a form of user-generated story. + * + * Stories are a form of history in the system, and as such they are read-only. + * Once generated, it is not possible to modify a story. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Stories extends Resource { + /** + * * Returns the compact records for all stories on the task. + * * @param {Number} task Globally unique identifier for the task. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + findByTask(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the full record for a single story. + * * @param {Number} story Globally unique identifier for the story. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param story + * @param params? + * @param dispatchOptions? + * @return + */ + findById(story: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Adds a comment to a task. The comment will be authored by the + * * currently authenticated user, and timestamped when the server receives + * * the request. + * * + * * Returns the full record for the new story added to the task. + * * @param {Number} task Globally unique identifier for the task. + * * @param {Object} data Data for the request + * * @param {String} data.text The plain text of the comment to add. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + createOnTask(task: number, data: any, dispatchOptions?: any): Promise>; + } + + interface TagsStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Tags; + } + + namespace Tags { + interface Type extends Resource { + created_at: string; + notes: string; + workspace: Resource; + color: string; + followers: Resource[]; + } + + interface FindAllParams extends PaginationParams { + team?: number; + archived?: boolean; + } + } + + var Tags: TagsStatic; + + /** + * A _tag_ is a label that can be attached to any task in Asana. It exists in a + * single workspace or organization. + * + * Tags have some metadata associated with them, but it is possible that we will + * simplify them in the future so it is not encouraged to rely too heavily on it. + * Unlike projects, tags do not provide any ordering on the tasks they + * are associated with. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Tags extends Resource { + /** + * * Creates a new tag in a workspace or organization. + * * + * * Every tag is required to be created in a specific workspace or + * * organization, and this cannot be changed once set. Note that you can use + * * the `workspace` parameter regardless of whether or not it is an + * * organization. + * * + * * Returns the full record of the newly created tag. + * * @param {Object} data Data for the request + * * @param {String} data.workspace The workspace or organization to create the tag in. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param data + * @param dispatchOptions? + * @return + */ + create(data: Tags.Type & { workspace: string }, dispatchOptions?: any): Promise; + + /** + * * Creates a new tag in a workspace or organization. + * * + * * Every tag is required to be created in a specific workspace or + * * organization, and this cannot be changed once set. Note that you can use + * * the `workspace` parameter regardless of whether or not it is an + * * organization. + * * + * * Returns the full record of the newly created tag. + * * @param {Number} workspace The workspace or organization to create the tag in. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param data + * @param dispatchOptions? + * @return + */ + createInWorkspace(workspace: number, data: Tags.Type, dispatchOptions?: any): Promise; + + /** + * * Returns the complete tag record for a single tag. + * * @param {Number} tag The tag to get. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param tag + * @param params? + * @param dispatchOptions? + * @return + */ + findById(tag: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Updates the properties of a tag. Only the fields provided in the `data` + * * block will be updated; any unspecified fields will remain unchanged. + * * + * * When using this method, it is best to specify only those fields you wish + * * to change, or else you may overwrite changes made by another user since + * * you last retrieved the task. + * * + * * Returns the complete updated tag record. + * * @param {Number} tag The tag to update. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param tag + * @param data + * @param dispatchOptions? + * @return + */ + update(tag: number, data: Tags.Type, dispatchOptions?: any): Promise; + + /** + * * A specific, existing tag can be deleted by making a DELETE request + * * on the URL for that tag. + * * + * * Returns an empty data record. + * * @param {Number} tag The tag to delete. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param tag + * @param dispatchOptions? + * @return + */ + delete(tag: number, dispatchOptions?: any): Promise; + + /** + * * Returns the compact tag records for some filtered set of tags. + * * Use one or more of the parameters provided to filter the tags returned. + * * @param {Object} [params] Parameters for the request + * * @param {String} [params.workspace] The workspace or organization to filter tags on. + * * @param {String} [params.team] The team to filter tags on. + * * @param {Boolean} [params.archived] Only return tags whose `archived` field takes on the value of + * * this parameter. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param params? + * @param dispatchOptions? + * @return + */ + findAll(params?: Tags.FindAllParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact tag records for all tags in the workspace. + * * @param {Number} workspace The workspace or organization to find tags in. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param params? + * @param dispatchOptions? + * @return + */ + findByWorkspace(workspace: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact task records for all tasks with the given tag. + * * Tasks can have more than one tag at a time. + * * @param {Number} tag The tag to fetch tasks from. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param tag + * @param params? + * @param dispatchOptions? + * @return + */ + getTasksWithTag(tag: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + } + + interface TasksStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Tasks; + } + + namespace Tasks { + interface Type extends Resource { + created_at: string; + modified_at: string; + completed_at: string; + completed: boolean; + due_on: string; + due_at: string; + assignee_status: string; + assignee: Resource; + notes: string; + workspace: Resource; + num_hearts: number; + hearted: boolean; + parent: Resource; + tags: Resource[]; + projects: Resource[]; + memberships: Membership[]; + followers: Resource[]; + } + + interface CreateParams { + name: string; + completed?: boolean; + hearted?: boolean; + notes?: string; + } + + interface FollowersParams { + followers: (number | string)[]; + } + + interface AddProjectParams { + project: number; + insertBefore?: number; + insertAfter?: number; + section?: number; + } + + interface RemoveProjectParams { + project: number; + } + + interface TagParams { + tag: string; + } + + interface CommentParams { + text: string; + } + + interface FindAllParams extends PaginationParams { + assignee?: number; + workspace: number; + completed_since?: string; + modified_since?: string; + } + } + + var Tasks: TasksStatic; + + /** + * The _task_ is the basic object around which many operations in Asana are + * centered. In the Asana application, multiple tasks populate the middle pane + * according to some view parameters, and the set of selected tasks determines + * the more detailed information presented in the details pane. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Tasks extends Resource { + /** + * * Creating a new task is as easy as POSTing to the `/tasks` endpoint + * * with a data block containing the fields you'd like to set on the task. + * * Any unspecified fields will take on default values. + * * + * * Every task is required to be created in a specific workspace, and this + * * workspace cannot be changed once set. The workspace need not be set + * * explicitly if you specify a `project` or a `parent` task instead. + * * @param {Object} data Data for the request + * * @param {Number} [data.workspace] The workspace to create a task in. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param data + * @param dispatchOptions? + * @return + */ + create(data: Tasks.CreateParams & { workspace: string }, dispatchOptions?: any): Promise; + + /** + * * Creating a new task is as easy as POSTing to the `/tasks` endpoint + * * with a data block containing the fields you'd like to set on the task. + * * Any unspecified fields will take on default values. + * * + * * Every task is required to be created in a specific workspace, and this + * * workspace cannot be changed once set. The workspace need not be set + * * explicitly if you specify a `project` or a `parent` task instead. + * * @param {Number} workspace The workspace to create a task in. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param data + * @param dispatchOptions? + * @return + */ + createInWorkspace(workspace: number, data: Tasks.CreateParams, dispatchOptions?: any): Promise; + + /** + * * Returns the complete task record for a single task. + * * @param {Number} task The task to get. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + findById(task: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * A specific, existing task can be updated by making a PUT request on the + * * URL for that task. Only the fields provided in the `data` block will be + * * updated; any unspecified fields will remain unchanged. + * * + * * When using this method, it is best to specify only those fields you wish + * * to change, or else you may overwrite changes made by another user since + * * you last retrieved the task. + * * + * * Returns the complete updated task record. + * * @param {Number} task The task to update. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + update(task: number, data: Tasks.CreateParams, dispatchOptions?: any): Promise; + + /** + * * A specific, existing task can be deleted by making a DELETE request on the + * * URL for that task. Deleted tasks go into the "trash" of the user making + * * the delete request. Tasks can be recovered from the trash within a period + * * of 30 days; afterward they are completely removed from the system. + * * + * * Returns an empty data record. + * * @param {Number} task The task to delete. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param dispatchOptions? + * @return + */ + delete(task: number, dispatchOptions?: any): Promise; + + /** + * * Returns the compact task records for all tasks within the given project, + * * ordered by their priority within the project. + * * @param {Number} projectId The project in which to search for tasks. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param projectId + * @param params? + * @param dispatchOptions? + * @return + */ + findByProject(projectId: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact task records for all tasks with the given tag. + * * @param {Number} tag The tag in which to search for tasks. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param tag + * @param params? + * @param dispatchOptions? + * @return + */ + findByTag(tag: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact task records for some filtered set of tasks. Use one + * * or more of the parameters provided to filter the tasks returned. + * * @param {Object} [params] Parameters for the request + * * @param {Number} [params.assignee] The assignee to filter tasks on. + * * @param {Number} [params.workspace] The workspace or organization to filter tasks on. + * * @param {Number} [params.completed_since] Only return tasks that are either incomplete or that have been + * * completed since this time. + * * @param {Number} [params.modified_since] Only return tasks that have been modified since the given time. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param params? + * @param dispatchOptions? + * @return + */ + findAll(params?: Tasks.FindAllParams, dispatchOptions?: any): Promise>; + + /** + * * Adds each of the specified followers to the task, if they are not already + * * following. Returns the complete, updated record for the affected task. + * * @param {Number} task The task to add followers to. + * * @param {Object} data Data for the request + * * @param {Array} data.followers An array of followers to add to the task. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + addFollowers(task: number, data: Tasks.FollowersParams, dispatchOptions?: any): Promise; + + /** + * * Removes each of the specified followers from the task if they are + * * following. Returns the complete, updated record for the affected task. + * * @param {Number} task The task to remove followers from. + * * @param {Object} data Data for the request + * * @param {Array} data.followers An array of followers to remove from the task. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + removeFollowers(task: number, data: Tasks.FollowersParams, dispatchOptions?: any): Promise; + + /** + * * Returns a compact representation of all of the projects the task is in. + * * @param {Number} task The task to get projects on. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + projects(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Adds the task to the specified project, in the optional location + * * specified. If no location arguments are given, the task will be added to + * * the beginning of the project. + * * + * * `addProject` can also be used to reorder a task within a project that + * * already contains it. + * * + * * Returns an empty data block. + * * @param {Number} task The task to add to a project. + * * @param {Object} data Data for the request + * * @param {Number} data.project The project to add the task to. + * * @param {Number} [data.insertAfter] A task in the project to insert the task after, or `null` to + * * insert at the beginning of the list. + * * @param {Number} [data.insertBefore] A task in the project to insert the task before, or `null` to + * * insert at the end of the list. + * * @param {Number} [data.section] A section in the project to insert the task into. The task will be + * * inserted at the top of the section. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + addProject(task: number, data: Tasks.AddProjectParams, dispatchOptions?: any): Promise<{}>; + + /** + * * Removes the task from the specified project. The task will still exist + * * in the system, but it will not be in the project anymore. + * * + * * Returns an empty data block. + * * @param {Number} task The task to remove from a project. + * * @param {Object} data Data for the request + * * @param {Number} data.project The project to remove the task from. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + removeProject(task: number, data: Tasks.RemoveProjectParams, dispatchOptions?: any): Promise<{}>; + + /** + * * Returns a compact representation of all of the tags the task has. + * * @param {Number} task The task to get tags on. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + tags(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Adds a tag to a task. Returns an empty data block. + * * @param {Number} task The task to add a tag to. + * * @param {Object} data Data for the request + * * @param {Number} data.tag The tag to add to the task. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + addTag(task: number, data: Tasks.TagParams, dispatchOptions?: any): Promise<{}>; + + /** + * * Removes a tag from the task. Returns an empty data block. + * * @param {Number} task The task to remove a tag from. + * * @param {Object} data Data for the request + * * @param {String} data.tag The tag to remove from the task. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + removeTag(task: number, data: Tasks.TagParams, dispatchOptions?: any): Promise<{}>; + + /** + * * Returns a compact representation of all of the subtasks of a task. + * * @param {Number} task The task to get the subtasks of. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + subtasks(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Creates a new subtask and adds it to the parent task. Returns the full record + * * for the newly created subtask. + * * @param {Number} task The task to add a subtask to. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + addSubtask(task: number, data: Tasks.CreateParams, dispatchOptions?: any): Promise; + + /** + * * Returns a compact representation of all of the stories on the task. + * * @param {Number} task The task containing the stories to get. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + stories(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Adds a comment to a task. The comment will be authored by the + * * currently authenticated user, and timestamped when the server receives + * * the request. + * * + * * Returns the full record for the new story added to the task. + * * @param {Number} task Globally unique identifier for the task. + * * @param {Object} data Data for the request + * * @param {String} data.text The plain text of the comment to add. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + addComment(task: number, data: Tasks.CommentParams, dispatchOptions?: any): Promise; + } + + interface TeamsStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Teams; + } + + namespace Teams { + interface Type extends Resource { + organization: Resource; + } + } + + var Teams: TeamsStatic; + + /** + * A _team_ is used to group related projects and people together within an + * organization. Each project in an organization is associated with a team. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Teams extends Resource { + /** + * * Returns the full record for a single team. + * * @param {Number} team Globally unique identifier for the team. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param team + * @param params? + * @param dispatchOptions? + * @return + */ + findById(team: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Returns the compact records for all teams in the organization visible to + * * the authorized user. + * * @param {Number} organization Globally unique identifier for the workspace or organization. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param organization + * @param params? + * @param dispatchOptions? + * @return + */ + findByOrganization(organization: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Returns the compact records for all users that are members of the team. + * * @param {Number} team Globally unique identifier for the team. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param team + * @param params? + * @param dispatchOptions? + * @return + */ + users(team: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * The user making this call must be a member of the team in order to add others. + * * The user to add must exist in the same organization as the team in order to be added. + * * The user to add can be referenced by their globally unique user ID or their email address. + * * Returns the full user record for the added user. + * * @param {Number} team Globally unique identifier for the team. + * * @param {Object} data Data for the request + * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, + * * the globally unique identifier for the user, or the keyword `me` + * * to indicate the current user making the request. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param team + * @param data + * @param dispatchOptions? + * @return + */ + addUser(team: number, data: UserParams, dispatchOptions?: any): Promise; + + /** + * * The user to remove can be referenced by their globally unique user ID or their email address. + * * Removes the user from the specified team. Returns an empty data record. + * * @param {Number} team Globally unique identifier for the team. + * * @param {Object} data Data for the request + * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, + * * the globally unique identifier for the user, or the keyword `me` + * * to indicate the current user making the request. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param team + * @param data + * @param dispatchOptions? + * @return + */ + removeUser(team: number, data: UserParams, dispatchOptions?: any): Promise; + } + + interface UsersStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Users; + } + + namespace Users { + interface FindAllParams extends PaginationParams { + workspace: number; + } + + interface Type extends Resource { + email: string; + workspaces: Resource[]; + photo: { [key: string]: string }; + } + } + + var Users: UsersStatic; + + /** + * A _user_ object represents an account in Asana that can be given access to + * various workspaces, projects, and tasks. + * + * Like other objects in the system, users are referred to by numerical IDs. + * However, the special string identifier `me` can be used anywhere + * a user ID is accepted, to refer to the current authenticated user. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Users extends Resource { + /** + * * Returns the full user record for the currently authenticated user. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param params? + * @param dispatchOptions? + * @return + */ + me(params?: Params, dispatchOptions?: any): Promise; + + /** + * * Returns the full user record for the single user with the provided ID. + * * @param {Number|String} user An identifier for the user. Can be one of an email address, + * * the globally unique identifier for the user, or the keyword `me` + * * to indicate the current user making the request. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param user + * @param params? + * @param dispatchOptions? + * @return + */ + findById(user: string | number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Returns the user records for all users in the specified workspace or + * * organization. + * * @param {Number} workspace The workspace in which to get users. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param params? + * @param dispatchOptions? + * @return + */ + findByWorkspace(workspace: number, params?: Params, dispatchOptions?: any): Promise>; + + /** + * * Returns the user records for all users in all workspaces and organizations + * * accessible to the authenticated user. Accepts an optional workspace ID + * * parameter. + * * @param {Object} [params] Parameters for the request + * * @param {Number} [params.workspace] The workspace or organization to filter users on. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param params + * @param dispatchOptions? + * @return + */ + findAll(params: Users.FindAllParams, dispatchOptions?: any): Promise; + } + + /** + * **Webhooks are currently in BETA - The information here may change.** + * + * Webhooks allow an application to be notified of changes. This is in addition + * to the ability to fetch those changes directly as + * [Events](/developers/api-reference/events) - in fact, Webhooks are just a way + * to receive Events via HTTP POST at the time they occur instead of polling for + * them. For services accessible via HTTP this is often vastly more convenient, + * and if events are not too frequent can be significantly more efficient. + * + * In both cases, however, changes are represented as Event objects - refer to + * the [Events documentation](/developers/api-reference/events) for more + * information on what data these events contain. + * + * **NOTE:** While Webhooks send arrays of Event objects to their target, the + * Event objects themselves contain *only IDs*, rather than the actual resource + * they are referencing. So while a normal event you receive via GET /events + * would look like this: + * + * {\ + * "resource": {\ + * "id": 1337,\ + * "name": "My Task"\ + * },\ + * "parent": null,\ + * "created_at": "2013-08-21T18:20:37.972Z",\ + * "user": {\ + * "id": 1123,\ + * "name": "Tom Bizarro"\ + * },\ + * "action": "changed",\ + * "type": "task"\ + * } + * + * In a Webhook payload you would instead receive this: + * + * {\ + * "resource": 1337,\ + * "parent": null,\ + * "created_at": "2013-08-21T18:20:37.972Z",\ + * "user": 1123,\ + * "action": "changed",\ + * "type": "task"\ + * } + * + * Webhooks themselves contain only the information necessary to deliver the + * events to the desired target as they are generated. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + class Webhooks extends Resource { + /** + * @param dispatcher + */ + constructor(dispatcher: Dispatcher); + + /** + * * Establishing a webhook is a two-part process. First, a simple HTTP POST + * * similar to any other resource creation. Since you could have multiple + * * webhooks we recommend specifying a unique local id for each target. + * * + * * Next comes the confirmation handshake. When a webhook is created, we will + * * send a test POST to the `target` with an `X-Hook-Secret` header as + * * described in the + * * [Resthooks Security documentation](http://resthooks.org/docs/security/). + * * The target must respond with a `200 OK` and a matching `X-Hook-Secret` + * * header to confirm that this webhook subscription is indeed expected. + * * + * * If you do not acknowledge the webhook's confirmation handshake it will + * * fail to setup, and you will receive an error in response to your attempt + * * to create it. This means you need to be able to receive and complete the + * * webhook *while* the POST request is in-flight. + * * @param {Number} resource A resource ID to subscribe to. The resource can be a task or project. + * * @param {String} target The URL to receive the HTTP POST. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param resource + * @param target + * @param data + * @param dispatchOptions? + * @return + */ + create(resource: number, target: string, data: any, dispatchOptions?: any): Promise; + + /** + * * Returns the compact representation of all webhooks your app has + * * registered for the authenticated user in the given workspace. + * * @param {Number} workspace The workspace to query for webhooks in. + * * @param {Object} [params] Parameters for the request + * * @param {Number} [params.resource] Only return webhooks for the given resource. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param params? + * @param dispatchOptions? + * @return + */ + getAll(workspace: number, params?: any, dispatchOptions?: any): Promise; + + /** + * * Returns the full record for the given webhook. + * * @param {String} webhook The webhook to get. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param webhook + * @param params? + * @param dispatchOptions? + * @return + */ + getById(webhook: string, params?: any, dispatchOptions?: any): Promise; + + /** + * * This method permanently removes a webhook. Note that it may be possible + * * to receive a request that was already in flight after deleting the + * * webhook, but no further requests will be issued. + * * @param {String} webhook The webhook to delete. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param webhook + * @param dispatchOptions? + * @return + */ + deleteById(webhook: string, dispatchOptions?: any): Promise; + } + + interface WorkspacesStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Workspaces; + } + + namespace Workspaces { + interface ShortType extends Resource { + id_organization?: boolean; + } + + interface Type extends Resource { + id_organization: boolean; + email_domains: string[]; + } + + interface TypeaheadParams { + type: string; + query?: string; + count?: number; + } + } + + var Workspaces: WorkspacesStatic; + + /** + * A _workspace_ is the highest-level organizational unit in Asana. All projects + * and tasks have an associated workspace. + * + * An _organization_ is a special kind of workspace that represents a company. + * In an organization, you can group your projects into teams. You can read + * more about how organizations work on the Asana Guide. + * To tell if your workspace is an organization or not, check its + * `is_organization` property. + * + * Over time, we intend to migrate most workspaces into organizations and to + * release more organization-specific functionality. We may eventually deprecate + * using workspace-based APIs for organizations. Currently, and until after + * some reasonable grace period following any further announcements, you can + * still reference organizations in any `workspace` parameter. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Workspaces extends Resource { + /** + * * Returns the full workspace record for a single workspace. + * * @param {Number} workspace Globally unique identifier for the workspace or organization. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param workspace + * @param params? + * @param dispatchOptions? + * @return + */ + findById(workspace: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Returns the compact records for all workspaces visible to the authorized user. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param params? + * @param dispatchOptions? + * @return + */ + findAll(params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * A specific, existing workspace can be updated by making a PUT request on + * * the URL for that workspace. Only the fields provided in the data block + * * will be updated; any unspecified fields will remain unchanged. + * * + * * Currently the only field that can be modified for a workspace is its `name`. + * * + * * Returns the complete, updated workspace record. + * * @param {Number} workspace The workspace to update. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param data + * @param dispatchOptions? + * @return + */ + update(workspace: number, data: { name?: string }, dispatchOptions?: any): Promise; + + /** + * * Retrieves objects in the workspace based on an auto-completion/typeahead + * * search algorithm. This feature is meant to provide results quickly, so do + * * not rely on this API to provide extremely accurate search results. The + * * result set is limited to a single page of results with a maximum size, + * * so you won't be able to fetch large numbers of results. + * * @param {Number} workspace The workspace to fetch objects from. + * * @param {Object} [params] Parameters for the request + * * @param {String} params.type The type of values the typeahead should return. + * * Note that unlike in the names of endpoints, the types listed here are + * * in singular form (e.g. `task`). Using multiple types is not yet supported. + * * @param {String} [params.query] The string that will be used to search for relevant objects. If an + * * empty string is passed in, the API will currently return an empty + * * result set. + * * @param {Number} [params.count] The number of results to return. The default is `20` if this + * * parameter is omitted, with a minimum of `1` and a maximum of `100`. + * * If there are fewer results found than requested, all will be returned. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param params? + * @param dispatchOptions? + * @return + */ + typeahead(workspace: number, params?: Workspaces.TypeaheadParams, dispatchOptions?: any): Promise; + + /** + * * The user can be referenced by their globally unique user ID or their email address. + * * Returns the full user record for the invited user. + * * @param {Number} workspace The workspace or organization to invite the user to. + * * @param {Object} data Data for the request + * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, + * * the globally unique identifier for the user, or the keyword `me` + * * to indicate the current user making the request. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param data + * @param dispatchOptions? + * @return + */ + addUser(workspace: number, data: UserParams, dispatchOptions?: any): Promise; + + /** + * * The user making this call must be an admin in the workspace. + * * Returns an empty data record. + * * @param {Number} workspace The workspace or organization to invite the user to. + * * @param {Object} data Data for the request + * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, + * * the globally unique identifier for the user, or the keyword `me` + * * to indicate the current user making the request. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param data + * @param dispatchOptions? + * @return + */ + removeUser(workspace: number, data: UserParams, dispatchOptions?: any): Promise; + } + + interface ResourceStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Resource; + + /** + * @type {number} Default number of items to get per page. + */ + DEFAULT_PAGE_LIMIT: number; + + /** + * Helper method that dispatches a GET request to the API, where the expected + * result is a collection. + * @param {Dispatcher} dispatcher + * @param {String} path The path of the API + * @param {Object} [query] The query params + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `Dispatcher.dispatch`. + * @return {Promise} The Collection response for the request + * @param dispatcher + * @param path + * @param query? + * @param dispatchOptions? + */ + getCollection(dispatcher: any, path: string, query?: any, dispatchOptions?: any): Promise; + + /** + * Helper method for any request Promise from the Dispatcher, unwraps the `data` + * value from the payload. + * @param {Promise} promise A promise returned from a `Dispatcher` request. + * @return {Promise} The `data` portion of the response payload. + * @param promise + * @return + */ + unwrap(promise: any): Promise; + } + + var Resource: ResourceStatic; + + /** + * Base class for a resource accessible via the API. Uses a `Dispatcher` to + * access the resources. + * @param {Dispatcher} dispatcher + * @constructor + */ + interface Resource { + /** + * Dispatches a GET request to the API, where the expected result is a + * single resource. + * @param {String} path The path of the API + * @param {Object} [query] The query params + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `Dispatcher.dispatch`. + * @return {Promise} The response for the request + * @param path + * @param query? + * @param dispatchOptions? + * @return + */ + dispatchGet(path: string, query?: any, dispatchOptions?: any): Promise; + + /** + * Dispatches a GET request to the API, where the expected result is a + * collection. + * @param {String} path The path of the API + * @param {Object} [query] The query params + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `Dispatcher.dispatch`. + * @return {Promise} The response for the request + * @param path + * @param query? + * @param dispatchOptions? + * @return + */ + dispatchGetCollection(path: string, query?: any, dispatchOptions?: any): Promise; + + /** + * Dispatches a POST request to the API, where the expected response is a + * single resource. + * @param {String} path The path of the API + * @param {Object} [query] The query params + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `Dispatcher.dispatch`. + * @return {Promise} The response for the request + * @param path + * @param query? + * @param dispatchOptions? + * @return + */ + dispatchPost(path: string, query?: any, dispatchOptions?: any): Promise; + + /** + * Dispatches a POST request to the API, where the expected response is a + * single resource. + * @param {String} path The path of the API + * @param {Object} [query] The query params + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `Dispatcher.dispatch`. + * @return {Promise} The response for the request + * @param path + * @param query? + * @param dispatchOptions? + * @return + */ + dispatchPut(path: string, query?: any, dispatchOptions?: any): Promise; + + /** + * Dispatches a DELETE request to the API. The expected response is an + * empty resource. + * @param {String} path The path of the API + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `Dispatcher.dispatch`. + * @return {Promise} The response for the request + * @param path + * @param dispatchOptions? + * @return + */ + dispatchDelete(path: string, dispatchOptions?: any): Promise; + } + + interface ResourceList { + data: T[]; + _response: { + data: T[]; + next_page?: NextPage; + }; + _dispatcher: { + authenticator: { + apiKey: string; + }; + asanaBaseUrl: string; + retryOnRateLimit: boolean; + requestTimeout: number; + _cachedVersionInfo: VersionInfo; + } + } + + type SimpleResourceList = ResourceList; + + interface NextPage { + offset: string; + uri: string; + path: string; + } + + interface VersionInfo { + version: string; + language: string; + language_version: string; + os: string; + os_version: string; + } + + interface Resource { + id: number; + name: string; + } + + interface PaginationParams extends Params { + limit?: number; + offset?: string; + } + + interface Params { + opt_fields?: string; + opt_expand?: string; + } + + interface UserParams { + user: string | number; + } + + interface Membership { + project: Resource; + section: Resource; + } + } + + var VERSION: string; +} + +export = asana; diff --git a/asana/tsconfig.json b/asana/tsconfig.json new file mode 100644 index 0000000000..b9320b76f5 --- /dev/null +++ b/asana/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "asana-tests.ts" + ] +} \ No newline at end of file diff --git a/asciify/asciify-tests.ts b/asciify/asciify-tests.ts index c95b9c6993..aaee5866e3 100644 --- a/asciify/asciify-tests.ts +++ b/asciify/asciify-tests.ts @@ -1,4 +1,4 @@ -/// + import asciify = require('asciify'); diff --git a/asciify/asciify.d.ts b/asciify/asciify.d.ts deleted file mode 100644 index 4cef1bcc5c..0000000000 --- a/asciify/asciify.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Type definitions for asciify 1.3.5 -// Project: https://www.npmjs.org/package/asciify -// Definitions by: Alan Norbauer -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface AsciifyOptions { - font?: string; - maxWidth?: number; - color?: string; -} - -interface AsciifyCallback { - // err is sometimes a string and sometimes an Error - (err: any, asciifiedText: string): void -} - -declare module "asciify" { - function asciify(text: string, callback: AsciifyCallback): void; - function asciify(text: string, options: string, callback: AsciifyCallback): void; - function asciify(text: string, options: AsciifyOptions, callback: AsciifyCallback): void; - - namespace asciify { - function getFonts(callback: (err: Error, fonts: string[]) => void): void; - } - - export = asciify -} diff --git a/asciify/asciify.ts.tscparams b/asciify/asciify.ts.tscparams deleted file mode 100644 index 85542607d1..0000000000 --- a/asciify/asciify.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ ---noImplicitAny --module commonjs diff --git a/asciify/index.d.ts b/asciify/index.d.ts new file mode 100644 index 0000000000..7d55062213 --- /dev/null +++ b/asciify/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for asciify 1.3.5 +// Project: https://www.npmjs.org/package/asciify +// Definitions by: Alan Norbauer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface AsciifyOptions { + font?: string; + maxWidth?: number; + color?: string; +} + +interface AsciifyCallback { + // err is sometimes a string and sometimes an Error + (err: any, asciifiedText: string): void +} + +declare module "asciify" { + function asciify(text: string, callback: AsciifyCallback): void; + function asciify(text: string, options: string, callback: AsciifyCallback): void; + function asciify(text: string, options: AsciifyOptions, callback: AsciifyCallback): void; + + namespace asciify { + function getFonts(callback: (err: Error, fonts: string[]) => void): void; + } + + export = asciify +} diff --git a/asciify/tsconfig.json b/asciify/tsconfig.json new file mode 100644 index 0000000000..290b21526e --- /dev/null +++ b/asciify/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "asciify-tests.ts" + ] +} \ No newline at end of file diff --git a/aspnet-identity-pw/aspnet-identity-pw-tests.ts b/aspnet-identity-pw/aspnet-identity-pw-tests.ts index 83fb6878ab..235d39dc5a 100644 --- a/aspnet-identity-pw/aspnet-identity-pw-tests.ts +++ b/aspnet-identity-pw/aspnet-identity-pw-tests.ts @@ -1,4 +1,3 @@ -/// import passwordHasher = require('aspnet-identity-pw'); diff --git a/aspnet-identity-pw/aspnet-identity-pw.d.ts b/aspnet-identity-pw/aspnet-identity-pw.d.ts deleted file mode 100644 index 390033602b..0000000000 --- a/aspnet-identity-pw/aspnet-identity-pw.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Type definitions for aspnet-identity-pw 1.0.0 -// Project: https://github.com/Syncbak-Git/aspnet-identity-pw -// Definitions by: jt000 -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "aspnet-identity-pw" { - - export function hashPassword(password: string): string; - export function hashPassword(password: string, callback: (err: any, result: string)=>void): void; - - export function validatePassword(password: string, hashedPass: string): boolean; - export function validatePassword(password: string, hashedPass: string, callback: (err: any, result: boolean) => void): void; -} diff --git a/aspnet-identity-pw/index.d.ts b/aspnet-identity-pw/index.d.ts new file mode 100644 index 0000000000..cadffeef1a --- /dev/null +++ b/aspnet-identity-pw/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for aspnet-identity-pw 1.0.0 +// Project: https://github.com/Syncbak-Git/aspnet-identity-pw +// Definitions by: jt000 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + +export declare function hashPassword(password: string): string; +export declare function hashPassword(password: string, callback: (err: any, result: string) => void): void; + +export declare function validatePassword(password: string, hashedPass: string): boolean; +export declare function validatePassword(password: string, hashedPass: string, callback: (err: any, result: boolean) => void): void; diff --git a/aspnet-identity-pw/tsconfig.json b/aspnet-identity-pw/tsconfig.json new file mode 100644 index 0000000000..55b4805ec9 --- /dev/null +++ b/aspnet-identity-pw/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "aspnet-identity-pw-tests.ts" + ] +} \ No newline at end of file diff --git a/assert/assert-tests.ts b/assert/assert-tests.ts index b01703e4d3..4b194e8700 100644 --- a/assert/assert-tests.ts +++ b/assert/assert-tests.ts @@ -1,4 +1,4 @@ -/// + assert(1 + 1 - 2 === 0, "The universe isn't how it should."); @@ -13,7 +13,7 @@ assert.throws(() => { }, undefined, "DODGED IT"); assert.doesNotThrow(() => { - if (false) { + if (!!false) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); diff --git a/assert/assert.d.ts b/assert/assert.d.ts deleted file mode 100644 index d7cb02eb38..0000000000 --- a/assert/assert.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -// Type definitions for assert and power-assert -// Project: https://github.com/Jxck/assert -// Project: https://github.com/twada/power-assert -// Definitions by: vvakame -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// copy from assert external module in node.d.ts - -declare function assert(value:any, message?:string):void; -declare namespace assert { - export class AssertionError implements Error { - name:string; - message:string; - actual:any; - expected:any; - operator:string; - generatedMessage:boolean; - - constructor(options?:{message?: string; actual?: any; expected?: any; operator?: string; stackStartFunction?: Function}); - } - - export function fail(actual?:any, expected?:any, message?:string, operator?:string):void; - - export function ok(value:any, message?:string):void; - - export function equal(actual:any, expected:any, message?:string):void; - - export function notEqual(actual:any, expected:any, message?:string):void; - - export function deepEqual(actual:any, expected:any, message?:string):void; - - export function notDeepEqual(acutal:any, expected:any, message?:string):void; - - export function strictEqual(actual:any, expected:any, message?:string):void; - - export function notStrictEqual(actual:any, expected:any, message?:string):void; - - export var throws:{ - (block:Function, message?:string): void; - (block:Function, error:Function, message?:string): void; - (block:Function, error:RegExp, message?:string): void; - (block:Function, error:(err:any) => boolean, message?:string): void; - }; - - export var doesNotThrow:{ - (block:Function, message?:string): void; - (block:Function, error:Function, message?:string): void; - (block:Function, error:RegExp, message?:string): void; - (block:Function, error:(err:any) => boolean, message?:string): void; - }; - - export function ifError(value:any):void; -} - -// duplicate to node.d.ts -// declare module "assert" { -// export = assert; -// } - -// move to power-assert.d.ts. do not use this definition file. -declare module "power-assert" { - export = assert; -} diff --git a/assert/index.d.ts b/assert/index.d.ts new file mode 100644 index 0000000000..abd31688f1 --- /dev/null +++ b/assert/index.d.ts @@ -0,0 +1,53 @@ +// Type definitions for assert and power-assert +// Project: https://github.com/Jxck/assert +// Project: https://github.com/twada/power-assert +// Definitions by: vvakame +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// copy from assert external module in node.d.ts + +declare function assert(value:any, message?:string):void; +declare namespace assert { + export class AssertionError implements Error { + name:string; + message:string; + actual:any; + expected:any; + operator:string; + generatedMessage:boolean; + + constructor(options?:{message?: string; actual?: any; expected?: any; operator?: string; stackStartFunction?: Function}); + } + + export function fail(actual?:any, expected?:any, message?:string, operator?:string):void; + + export function ok(value:any, message?:string):void; + + export function equal(actual:any, expected:any, message?:string):void; + + export function notEqual(actual:any, expected:any, message?:string):void; + + export function deepEqual(actual:any, expected:any, message?:string):void; + + export function notDeepEqual(acutal:any, expected:any, message?:string):void; + + export function strictEqual(actual:any, expected:any, message?:string):void; + + export function notStrictEqual(actual:any, expected:any, message?:string):void; + + export var throws:{ + (block:Function, message?:string): void; + (block:Function, error:Function, message?:string): void; + (block:Function, error:RegExp, message?:string): void; + (block:Function, error:(err:any) => boolean, message?:string): void; + }; + + export var doesNotThrow:{ + (block:Function, message?:string): void; + (block:Function, error:Function, message?:string): void; + (block:Function, error:RegExp, message?:string): void; + (block:Function, error:(err:any) => boolean, message?:string): void; + }; + + export function ifError(value:any):void; +} diff --git a/assert/tsconfig.json b/assert/tsconfig.json new file mode 100644 index 0000000000..5c08e1ed04 --- /dev/null +++ b/assert/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "assert-tests.ts" + ] +} \ No newline at end of file diff --git a/assertion-error/assertion-error-tests.ts b/assertion-error/assertion-error-tests.ts index f03e9cb52e..96eb520f1c 100644 --- a/assertion-error/assertion-error-tests.ts +++ b/assertion-error/assertion-error-tests.ts @@ -1,4 +1,3 @@ -/// import AssertionError = require('assertion-error'); diff --git a/assertion-error/assertion-error.d.ts b/assertion-error/assertion-error.d.ts deleted file mode 100644 index a0295bd8b3..0000000000 --- a/assertion-error/assertion-error.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Type definitions for assertion-error 1.0.0 -// Project: https://github.com/chaijs/assertion-error -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module 'assertion-error' { - class AssertionError implements Error { - constructor(message: string, props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; - } - export = AssertionError; -} diff --git a/assertion-error/index.d.ts b/assertion-error/index.d.ts new file mode 100644 index 0000000000..8663df799d --- /dev/null +++ b/assertion-error/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for assertion-error 1.0.0 +// Project: https://github.com/chaijs/assertion-error +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare class AssertionError implements Error { + constructor(message: string, props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; +} +export = AssertionError; diff --git a/assertion-error/tsconfig.json b/assertion-error/tsconfig.json new file mode 100644 index 0000000000..f96d0c19a2 --- /dev/null +++ b/assertion-error/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "assertion-error-tests.ts" + ] +} \ No newline at end of file diff --git a/assertsharp/assertsharp-tests.ts b/assertsharp/assertsharp-tests.ts index 484e3ac774..7616725f8f 100644 --- a/assertsharp/assertsharp-tests.ts +++ b/assertsharp/assertsharp-tests.ts @@ -1,5 +1,3 @@ -/// - import Assert from "assertsharp"; Assert.AreEqual(0, 0, "Pass"); diff --git a/assertsharp/assertsharp.d.ts b/assertsharp/assertsharp.d.ts deleted file mode 100644 index c4cf80e867..0000000000 --- a/assertsharp/assertsharp.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Type definitions for assertsharp -// Project: https://www.npmjs.com/package/assertsharp -// Definitions by: Bruno Leonardo Michels -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "assertsharp" { - export default class Assert { - static AreEqual(expected: T, actual: T, message?: string): void; - static AreNotEqual(notExpected: T, actual: T, message?: string): void; - static AreNotSame(notExpected: T, actual: T, message?: string): void; - static AreSequenceEqual(expected: T[], actual: T[], equals?: (x: any, y: any) => boolean, message?: string): void; - static Fail(message?: string): void; - static IsFalse(actual: boolean, message?: string): void; - static IsInstanceOfType(actual: any, expectedType: Function, message?: string): void; - static IsNotInstanceOfType(actual: any, wrongType: Function, message?: string): void; - static IsNotNull(actual: any, message?: string): void; - static IsNull(actual: any, message?: string): void; - static IsTrue(actual: boolean, message?: string): void; - static Throws(fn: () => void, message?: string): void; - } -} diff --git a/assertsharp/index.d.ts b/assertsharp/index.d.ts new file mode 100644 index 0000000000..a424b28944 --- /dev/null +++ b/assertsharp/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for assertsharp +// Project: https://www.npmjs.com/package/assertsharp +// Definitions by: Bruno Leonardo Michels +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default class Assert { + static AreEqual(expected: T, actual: T, message?: string): void; + static AreNotEqual(notExpected: T, actual: T, message?: string): void; + static AreNotSame(notExpected: T, actual: T, message?: string): void; + static AreSequenceEqual(expected: T[], actual: T[], equals?: (x: any, y: any) => boolean, message?: string): void; + static Fail(message?: string): void; + static IsFalse(actual: boolean, message?: string): void; + static IsInstanceOfType(actual: any, expectedType: Function, message?: string): void; + static IsNotInstanceOfType(actual: any, wrongType: Function, message?: string): void; + static IsNotNull(actual: any, message?: string): void; + static IsNull(actual: any, message?: string): void; + static IsTrue(actual: boolean, message?: string): void; + static Throws(fn: () => void, message?: string): void; +} diff --git a/assertsharp/tsconfig.json b/assertsharp/tsconfig.json new file mode 100644 index 0000000000..88a78ef144 --- /dev/null +++ b/assertsharp/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "assertsharp-tests.ts" + ] +} \ No newline at end of file diff --git a/async-lock/async-lock-tests.ts b/async-lock/async-lock-tests.ts index d3eedf2fda..259749d4f0 100644 --- a/async-lock/async-lock-tests.ts +++ b/async-lock/async-lock-tests.ts @@ -1,4 +1,3 @@ -/// import * as AsyncLock from "async-lock"; const lock = new AsyncLock(); diff --git a/async-lock/async-lock.d.ts b/async-lock/async-lock.d.ts deleted file mode 100644 index e5f8613c73..0000000000 --- a/async-lock/async-lock.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Type definitions for async-lock -// Project: https://github.com/rain1017/async-lock -// Definitions by: Elisée MAURER -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "async-lock" { - interface AsyncLockDoneCallback { - (err?: Error, ret?: any): void; - } - - interface AsyncLockOptions { - timeout?: number; - maxPending?: number; - domainReentrant?: boolean; - Promise?: any; - } - - class AsyncLock { - constructor(options?: AsyncLockOptions); - - acquire(key: string|string[], fn: (done: AsyncLockDoneCallback) => any, cb: AsyncLockDoneCallback, opts?: AsyncLockOptions): void; - acquire(key: string|string[], fn: (done: AsyncLockDoneCallback) => any, opts?: AsyncLockOptions): PromiseLike; - - isBusy(): boolean; - } - - namespace AsyncLock {} - - export = AsyncLock; -} diff --git a/async-lock/index.d.ts b/async-lock/index.d.ts new file mode 100644 index 0000000000..296307300c --- /dev/null +++ b/async-lock/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for async-lock +// Project: https://github.com/rain1017/async-lock +// Definitions by: Elisée MAURER +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +interface AsyncLockDoneCallback { + (err?: Error, ret?: any): void; +} + +interface AsyncLockOptions { + timeout?: number; + maxPending?: number; + domainReentrant?: boolean; + Promise?: any; +} + +declare class AsyncLock { + constructor(options?: AsyncLockOptions); + + acquire(key: string | string[], fn: (done: AsyncLockDoneCallback) => any, cb: AsyncLockDoneCallback, opts?: AsyncLockOptions): void; + acquire(key: string | string[], fn: (done: AsyncLockDoneCallback) => any, opts?: AsyncLockOptions): PromiseLike; + + isBusy(): boolean; +} + +declare namespace AsyncLock { } + +export = AsyncLock; diff --git a/async-lock/tsconfig.json b/async-lock/tsconfig.json new file mode 100644 index 0000000000..180eaf7446 --- /dev/null +++ b/async-lock/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "async-lock-tests.ts" + ] +} \ No newline at end of file diff --git a/async-writer/async-writer-tests.ts b/async-writer/async-writer-tests.ts index c26e31495c..855242c703 100644 --- a/async-writer/async-writer-tests.ts +++ b/async-writer/async-writer-tests.ts @@ -1,4 +1,3 @@ -/// import asyncWriter = require('async-writer'); import stream = require('stream'); diff --git a/async-writer/async-writer.d.ts b/async-writer/async-writer.d.ts deleted file mode 100644 index 56c5bb898b..0000000000 --- a/async-writer/async-writer.d.ts +++ /dev/null @@ -1,78 +0,0 @@ -// Type definitions for async-writer 1.4.1 -// Project: https://github.com/marko-js/async-writer -// Definitions by: Yuce Tekol -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'async-writer' { - import stream = require('stream'); - import events = require('events'); - - namespace async_writer { - interface EventFunction { - (event: string, callback: Function): void; - } - - class StringWriter { - constructor(events: events.EventEmitter); - end(): void; - write(what: string): StringWriter; - toString(): string; - } - - class BufferedWriter { - constructor(wrappedStream: stream.Stream); - flush(): void; - on(event: string, callback: Function): BufferedWriter; - once(event: string, callback: Function): BufferedWriter; - clear(): void; - end(): void; - write(what: string): BufferedWriter; - } - - interface BeginAsyncOptions { - last?: boolean; - timeout?: number; - name?: string; - } - - class AsyncWriter { - static enableAsyncStackTrace():void; - - constructor(writer?: any, global?: {[s: string]: any}, async?: boolean, buffer?: boolean); - isAsyncWriter: AsyncWriter; - sync(): void; - getAttributes(): {[s: string]: any}; - getAttribute(): any; - write(str: string): AsyncWriter; - getOutput(): string; - captureString(func: Function, thisObj: Object): string; - swapWriter(newWriter: StringWriter | BufferedWriter, func: Function, thisObj: Object): void; - createNestedWriter(writer: StringWriter | BufferedWriter): AsyncWriter; - beginAsync(options?: number | BeginAsyncOptions): AsyncWriter; - handleBeginAsync(options: number | BeginAsyncOptions, parent: AsyncWriter): void; - on(event: string, callback: Function): AsyncWriter; - once(event: string, callback: Function): AsyncWriter; - onLast(callback: Function): AsyncWriter; - emit(arg: any): AsyncWriter; - removeListener(): AsyncWriter; - pipe(stream: stream.Stream): AsyncWriter; - error(e: Error): void; - end(data?: any): AsyncWriter; - handleEnd(isAsync: boolean): void; - _finish(): void; - flush(): void; - } - - interface AsyncWriterOptions { - global?: {[s: string]: any}; - buffer?: boolean; - } - - function create(writer?: any, options?: AsyncWriterOptions): AsyncWriter; - function enableAsyncStackTrace(): void; - } - - export = async_writer; -} diff --git a/async-writer/index.d.ts b/async-writer/index.d.ts new file mode 100644 index 0000000000..278800f24a --- /dev/null +++ b/async-writer/index.d.ts @@ -0,0 +1,77 @@ +// Type definitions for async-writer 1.4.1 +// Project: https://github.com/marko-js/async-writer +// Definitions by: Yuce Tekol +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import stream = require('stream'); +import events = require('events'); + +declare namespace async_writer { + interface EventFunction { + (event: string, callback: Function): void; + } + + class StringWriter { + constructor(events: events.EventEmitter); + end(): void; + write(what: string): StringWriter; + toString(): string; + } + + class BufferedWriter { + constructor(wrappedStream: stream.Stream); + flush(): void; + on(event: string, callback: Function): BufferedWriter; + once(event: string, callback: Function): BufferedWriter; + clear(): void; + end(): void; + write(what: string): BufferedWriter; + } + + interface BeginAsyncOptions { + last?: boolean; + timeout?: number; + name?: string; + } + + class AsyncWriter { + static enableAsyncStackTrace(): void; + + constructor(writer?: any, global?: { [s: string]: any }, async?: boolean, buffer?: boolean); + isAsyncWriter: AsyncWriter; + sync(): void; + getAttributes(): { [s: string]: any }; + getAttribute(): any; + write(str: string): AsyncWriter; + getOutput(): string; + captureString(func: Function, thisObj: Object): string; + swapWriter(newWriter: StringWriter | BufferedWriter, func: Function, thisObj: Object): void; + createNestedWriter(writer: StringWriter | BufferedWriter): AsyncWriter; + beginAsync(options?: number | BeginAsyncOptions): AsyncWriter; + handleBeginAsync(options: number | BeginAsyncOptions, parent: AsyncWriter): void; + on(event: string, callback: Function): AsyncWriter; + once(event: string, callback: Function): AsyncWriter; + onLast(callback: Function): AsyncWriter; + emit(arg: any): AsyncWriter; + removeListener(): AsyncWriter; + pipe(stream: stream.Stream): AsyncWriter; + error(e: Error): void; + end(data?: any): AsyncWriter; + handleEnd(isAsync: boolean): void; + _finish(): void; + flush(): void; + } + + interface AsyncWriterOptions { + global?: { [s: string]: any }; + buffer?: boolean; + } + + function create(writer?: any, options?: AsyncWriterOptions): AsyncWriter; + function enableAsyncStackTrace(): void; +} + +export = async_writer; diff --git a/async-writer/tsconfig.json b/async-writer/tsconfig.json new file mode 100644 index 0000000000..654b8d9a85 --- /dev/null +++ b/async-writer/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "async-writer-tests.ts" + ] +} \ No newline at end of file diff --git a/async/async-explicit-tests.ts b/async/async-explicit-tests.ts index 10d8f0bd24..80343cf6b1 100644 --- a/async/async-explicit-tests.ts +++ b/async/async-explicit-tests.ts @@ -1,4 +1,4 @@ -/// + interface StringCallback { (err: Error, result: string): void; } interface AsyncStringGetter { (callback: StringCallback): void; } diff --git a/async/async-tests.ts b/async/async-tests.ts index 037481b6fa..cc8061a468 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -1,4 +1,4 @@ -/// + var fs, path; diff --git a/async/async-tests.ts.tscparams b/async/async-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/async/async-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/async/asyncamd-tests.ts b/async/asyncamd-tests.ts index 3aa8ab92b5..4bf6c2789d 100644 --- a/async/asyncamd-tests.ts +++ b/async/asyncamd-tests.ts @@ -1,4 +1,4 @@ -/// + import async = require("async"); diff --git a/async/async.d.ts b/async/index.d.ts similarity index 100% rename from async/async.d.ts rename to async/index.d.ts diff --git a/async/tsconfig.json b/async/tsconfig.json new file mode 100644 index 0000000000..16ce023eb9 --- /dev/null +++ b/async/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "async-tests.ts" + ] +} \ No newline at end of file diff --git a/asyncblock/asyncblock-tests.ts b/asyncblock/asyncblock-tests.ts index 35707e81ec..472ec80a1b 100644 --- a/asyncblock/asyncblock-tests.ts +++ b/asyncblock/asyncblock-tests.ts @@ -1,5 +1,5 @@ -/// -/// + +/// import asyncblock = require('asyncblock'); import fs = require('fs'); diff --git a/asyncblock/asyncblock.d.ts b/asyncblock/asyncblock.d.ts deleted file mode 100644 index 6ec1ad1579..0000000000 --- a/asyncblock/asyncblock.d.ts +++ /dev/null @@ -1,73 +0,0 @@ -// Type definitions for asyncblock 2.1.23 -// Project: https://github.com/scriby/asyncblock -// Definitions by: Hiroki Horiuchi -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -declare module "asyncblock" { - function asyncblock(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void; - - namespace asyncblock { - export function nostack(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void; - - export interface IFlow { - add(responseFormat?: string[]): IExecuteFunction; - add(key: string, responseFormat?: string[]): IExecuteFunction; - add(key: number, responseFormat?: string[]): IExecuteFunction; - add(options: IFlowOptions): IExecuteFunction; - callback(responseFormat?: string[]): IExecuteFunction; - callback(key: string, responseFormat?: string[]): IExecuteFunction; - callback(key: number, responseFormat?: string[]): IExecuteFunction; - callback(options: IFlowOptions): IExecuteFunction; - wait(key?: string): T; - wait(key?: number): T; - - get(key: string): T; - set(key: string, responseFormat?: string[]): IExecuteFunction; - set(options: IFlowOptions): IExecuteFunction; - del(key: string): void; - - sync(task: any): T; - queue(toExecute: IExecuteFunction): void; - queue(key: string, toExecute: IExecuteFunction): void; - queue(key: number, toExecute: IExecuteFunction): void; - queue(responseFormat: string[], toExecute: IExecuteFunction): void; - queue(key: string, responseFormat: string[], toExecute: IExecuteFunction): void; - queue(key: number, responseFormat: string[], toExecute: IExecuteFunction): void; - queue(options: IFlowOptions, toExecute: IExecuteFunction): void; - doneAdding(): void; - forceWait(): T; - - maxParallel: number; - errorCallback: (err: any) => void; - taskTimeout: number; - timeoutIsError: boolean; - } - - export interface IFlowOptions { - ignoreError?: boolean; // default false - key?: string; // string | number - responseFormat?: string[]; - timeout?: number; - timeoutIsError?: boolean; - dontWait?: boolean; - firstArgIsError?: boolean; // default true - } - - export interface IExecuteFunction { - (err: any, res1: T1, res2: T2, res3: T3): any; - (err: any, res1: T1, res2: T2): any; - (err: any, res: T): any; - (err: any): any; - - // firstArgIsError === false - (res1: T1, res2: T2, res3: T3): any; - (res1: T1, res2: T2): any; - (res: T): any; - } - - } - - export = asyncblock; -} - diff --git a/asyncblock/index.d.ts b/asyncblock/index.d.ts new file mode 100644 index 0000000000..c4f8d3da21 --- /dev/null +++ b/asyncblock/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for asyncblock 2.1.23 +// Project: https://github.com/scriby/asyncblock +// Definitions by: Hiroki Horiuchi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + +declare function asyncblock(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void; + +declare namespace asyncblock { + export function nostack(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void; + + export interface IFlow { + add(responseFormat?: string[]): IExecuteFunction; + add(key: string, responseFormat?: string[]): IExecuteFunction; + add(key: number, responseFormat?: string[]): IExecuteFunction; + add(options: IFlowOptions): IExecuteFunction; + callback(responseFormat?: string[]): IExecuteFunction; + callback(key: string, responseFormat?: string[]): IExecuteFunction; + callback(key: number, responseFormat?: string[]): IExecuteFunction; + callback(options: IFlowOptions): IExecuteFunction; + wait(key?: string): T; + wait(key?: number): T; + + get(key: string): T; + set(key: string, responseFormat?: string[]): IExecuteFunction; + set(options: IFlowOptions): IExecuteFunction; + del(key: string): void; + + sync(task: any): T; + queue(toExecute: IExecuteFunction): void; + queue(key: string, toExecute: IExecuteFunction): void; + queue(key: number, toExecute: IExecuteFunction): void; + queue(responseFormat: string[], toExecute: IExecuteFunction): void; + queue(key: string, responseFormat: string[], toExecute: IExecuteFunction): void; + queue(key: number, responseFormat: string[], toExecute: IExecuteFunction): void; + queue(options: IFlowOptions, toExecute: IExecuteFunction): void; + doneAdding(): void; + forceWait(): T; + + maxParallel: number; + errorCallback: (err: any) => void; + taskTimeout: number; + timeoutIsError: boolean; + } + + export interface IFlowOptions { + ignoreError?: boolean; // default false + key?: string; // string | number + responseFormat?: string[]; + timeout?: number; + timeoutIsError?: boolean; + dontWait?: boolean; + firstArgIsError?: boolean; // default true + } + + export interface IExecuteFunction { + (err: any, res1: T1, res2: T2, res3: T3): any; + (err: any, res1: T1, res2: T2): any; + (err: any, res: T): any; + (err: any): any; + + // firstArgIsError === false + (res1: T1, res2: T2, res3: T3): any; + (res1: T1, res2: T2): any; + (res: T): any; + } + +} + +export = asyncblock; diff --git a/asyncblock/tsconfig.json b/asyncblock/tsconfig.json new file mode 100644 index 0000000000..227b776c55 --- /dev/null +++ b/asyncblock/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "asyncblock-tests.ts" + ] +} \ No newline at end of file diff --git a/atmosphere/atmosphere-tests.ts b/atmosphere/atmosphere-tests.ts index 44c2880a35..b353c2c947 100644 --- a/atmosphere/atmosphere-tests.ts +++ b/atmosphere/atmosphere-tests.ts @@ -1,4 +1,4 @@ -/// + var socket = atmosphere; diff --git a/atmosphere/atmosphere.d.ts b/atmosphere/index.d.ts similarity index 100% rename from atmosphere/atmosphere.d.ts rename to atmosphere/index.d.ts diff --git a/atmosphere/tsconfig.json b/atmosphere/tsconfig.json new file mode 100644 index 0000000000..d185cf16e2 --- /dev/null +++ b/atmosphere/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "atmosphere-tests.ts" + ] +} \ No newline at end of file diff --git a/atom-keymap/atom-keymap-tests.ts b/atom-keymap/atom-keymap-tests.ts index 8882f5b38b..1c92bff5c9 100644 --- a/atom-keymap/atom-keymap-tests.ts +++ b/atom-keymap/atom-keymap-tests.ts @@ -1,4 +1,4 @@ -/// + import { KeymapManager, ICompleteMatchEvent } from "atom-keymap"; diff --git a/atom-keymap/atom-keymap.d.ts b/atom-keymap/atom-keymap.d.ts deleted file mode 100644 index 89b022a67a..0000000000 --- a/atom-keymap/atom-keymap.d.ts +++ /dev/null @@ -1,135 +0,0 @@ -// Type definitions for atom-keymap v5.1.5 -// Project: https://github.com/atom/atom-keymap/ -// Definitions by: Vadim Macagon -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace AtomKeymap { - type Disposable = AtomEventKit.Disposable; - - /** Instance side of KeyBinding class. */ - interface KeyBinding { - enabled: boolean; - source: string; - command: string; - keystrokes: string; - keystrokeCount: number; - selector: string; - specificity: number; - - matches(keystroke: string): boolean; - compare(keyBinding: KeyBinding): number; - } - - interface ICompleteMatchEvent { - /** Keystrokes that matched the binding. */ - keystrokes: string; - /** Binding that was matched to the keystrokes. */ - binding: KeyBinding; - /** DOM element that was the target of the most recent `KeyboardEvent`. */ - keyboardEventTarget: Element; - } - - interface IPartialMatchEvent { - /** Keystrokes that matched the binding. */ - keystrokes: string; - /** Bindings that were partially matched to the keystrokes. */ - partiallyMatchedBindings: KeyBinding[]; - /** DOM element that was the target of the most recent `KeyboardEvent`. */ - keyboardEventTarget: Element; - } - - interface IFailedMatchEvent { - /** Keystrokes that failed to match a binding. */ - keystrokes: string; - /** DOM element that was the target of the most recent `KeyboardEvent`. */ - keyboardEventTarget: Element; - } - - interface IKeymapLoadEvent { - /** Path to a keymap file. */ - path: string; - } - - /** Static side of KeymapManager class. */ - interface KeymapManagerStatic { - prototype: KeymapManager; - new (options?: { defaultTarget?: Element }): KeymapManager; - } - - /** Instance side of KeymapManager class. */ - interface KeymapManager { - constructor: KeymapManagerStatic; - /** Unwatches all watched paths. */ - destroy(): void; - - // Event Subscription - - /** Sets callback to invoke when one or more keystrokes completely match a key binding. */ - onDidMatchBinding(callback: (event: ICompleteMatchEvent) => void): Disposable; - /** Sets callback to invoke when one or more keystrokes partially match a binding. */ - onDidPartiallyMatchBindings(callback: (event: IPartialMatchEvent) => void): Disposable; - /** Sets callback to invoke when one or more keystrokes fail to match any bindings. */ - onDidFailToMatchBinding(callback: (event: IFailedMatchEvent) => void): Disposable; - /** Sets callback to invoke when a keymap file is reloaded. */ - onDidReloadKeymap(callback: (event: IKeymapLoadEvent) => void): Disposable; - /** Sets callback to invoke when a keymap file is unloaded. */ - onDidUnloadKeymap(callback: (event: IKeymapLoadEvent) => void): Disposable; - /** Sets callback to invoke when a keymap file could not to be loaded. */ - onDidFailToReadFile(callback: (error: Error) => void): Disposable; - - // Adding and Removing Bindings - - /** Adds sets of key bindings grouped by CSS selector. */ - add(source: string, keyBindingsBySelector: any): Disposable; - - // Accessing Bindings - - getKeyBindings(): KeyBinding[]; - findKeyBindings(params?: { - keystrokes: string; // e.g. 'ctrl-x ctrl-s' - command: string; // e.g. 'editor:backspace' - target?: Element; - }): KeyBinding[]; - - // Managing Keymap Files - - /** - * Loads the key bindings from the given path. - * - * @param bindingsPath A path to a file or a directory. If the path is a directory all files - * inside it will be loaded. - */ - loadKeymap(bindingsPath: string, options?: { watch: boolean }): void; - /** - * Starts watching the given file/directory for changes, reloading any keymaps at that location - * when changes are detected. - * - * @param filePath A path to a file or a directory. - */ - watchKeymap(filePath: string): void; - - // Managing Keyboard Events - - /** - * Dispatches a custom event associated with the matching key binding for the given - * `KeyboardEvent` if one can be found. - */ - handleKeyboardEvent(event: KeyboardEvent): void; - /** Translates a keydown event to a keystroke string. */ - keystrokeForKeyboardEvent(event: KeyboardEvent): string; - /** - * @return The number of milliseconds allowed before pending states caused by partial matches of - * multi-keystroke bindings are terminated. - */ - getPartialMatchTimeout(): number; - } - - /** Allows commands to be associated with keystrokes in a context-sensitive way.*/ - var KeymapManager: KeymapManagerStatic; -} - -declare module 'atom-keymap' { - export = AtomKeymap; -} diff --git a/atom-keymap/index.d.ts b/atom-keymap/index.d.ts new file mode 100644 index 0000000000..0b425c83d9 --- /dev/null +++ b/atom-keymap/index.d.ts @@ -0,0 +1,133 @@ +// Type definitions for atom-keymap v5.1.5 +// Project: https://github.com/atom/atom-keymap/ +// Definitions by: Vadim Macagon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = AtomKeymap; + +declare namespace AtomKeymap { + type Disposable = AtomEventKit.Disposable; + + /** Instance side of KeyBinding class. */ + interface KeyBinding { + enabled: boolean; + source: string; + command: string; + keystrokes: string; + keystrokeCount: number; + selector: string; + specificity: number; + + matches(keystroke: string): boolean; + compare(keyBinding: KeyBinding): number; + } + + interface ICompleteMatchEvent { + /** Keystrokes that matched the binding. */ + keystrokes: string; + /** Binding that was matched to the keystrokes. */ + binding: KeyBinding; + /** DOM element that was the target of the most recent `KeyboardEvent`. */ + keyboardEventTarget: Element; + } + + interface IPartialMatchEvent { + /** Keystrokes that matched the binding. */ + keystrokes: string; + /** Bindings that were partially matched to the keystrokes. */ + partiallyMatchedBindings: KeyBinding[]; + /** DOM element that was the target of the most recent `KeyboardEvent`. */ + keyboardEventTarget: Element; + } + + interface IFailedMatchEvent { + /** Keystrokes that failed to match a binding. */ + keystrokes: string; + /** DOM element that was the target of the most recent `KeyboardEvent`. */ + keyboardEventTarget: Element; + } + + interface IKeymapLoadEvent { + /** Path to a keymap file. */ + path: string; + } + + /** Static side of KeymapManager class. */ + interface KeymapManagerStatic { + prototype: KeymapManager; + new (options?: { defaultTarget?: Element }): KeymapManager; + } + + /** Instance side of KeymapManager class. */ + interface KeymapManager { + constructor: KeymapManagerStatic; + /** Unwatches all watched paths. */ + destroy(): void; + + // Event Subscription + + /** Sets callback to invoke when one or more keystrokes completely match a key binding. */ + onDidMatchBinding(callback: (event: ICompleteMatchEvent) => void): Disposable; + /** Sets callback to invoke when one or more keystrokes partially match a binding. */ + onDidPartiallyMatchBindings(callback: (event: IPartialMatchEvent) => void): Disposable; + /** Sets callback to invoke when one or more keystrokes fail to match any bindings. */ + onDidFailToMatchBinding(callback: (event: IFailedMatchEvent) => void): Disposable; + /** Sets callback to invoke when a keymap file is reloaded. */ + onDidReloadKeymap(callback: (event: IKeymapLoadEvent) => void): Disposable; + /** Sets callback to invoke when a keymap file is unloaded. */ + onDidUnloadKeymap(callback: (event: IKeymapLoadEvent) => void): Disposable; + /** Sets callback to invoke when a keymap file could not to be loaded. */ + onDidFailToReadFile(callback: (error: Error) => void): Disposable; + + // Adding and Removing Bindings + + /** Adds sets of key bindings grouped by CSS selector. */ + add(source: string, keyBindingsBySelector: any): Disposable; + + // Accessing Bindings + + getKeyBindings(): KeyBinding[]; + findKeyBindings(params?: { + keystrokes: string; // e.g. 'ctrl-x ctrl-s' + command: string; // e.g. 'editor:backspace' + target?: Element; + }): KeyBinding[]; + + // Managing Keymap Files + + /** + * Loads the key bindings from the given path. + * + * @param bindingsPath A path to a file or a directory. If the path is a directory all files + * inside it will be loaded. + */ + loadKeymap(bindingsPath: string, options?: { watch: boolean }): void; + /** + * Starts watching the given file/directory for changes, reloading any keymaps at that location + * when changes are detected. + * + * @param filePath A path to a file or a directory. + */ + watchKeymap(filePath: string): void; + + // Managing Keyboard Events + + /** + * Dispatches a custom event associated with the matching key binding for the given + * `KeyboardEvent` if one can be found. + */ + handleKeyboardEvent(event: KeyboardEvent): void; + /** Translates a keydown event to a keystroke string. */ + keystrokeForKeyboardEvent(event: KeyboardEvent): string; + /** + * @return The number of milliseconds allowed before pending states caused by partial matches of + * multi-keystroke bindings are terminated. + */ + getPartialMatchTimeout(): number; + } + + /** Allows commands to be associated with keystrokes in a context-sensitive way.*/ + var KeymapManager: KeymapManagerStatic; +} diff --git a/atom-keymap/tsconfig.json b/atom-keymap/tsconfig.json new file mode 100644 index 0000000000..7b54753234 --- /dev/null +++ b/atom-keymap/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "atom-keymap-tests.ts" + ] +} \ No newline at end of file diff --git a/atom/atom-tests.ts b/atom/atom-tests.ts index 29dde2d89e..7ce49d23bd 100644 --- a/atom/atom-tests.ts +++ b/atom/atom-tests.ts @@ -1,6 +1,6 @@ -/// -/// -/// +/// + +/// import path = require("path"); import _atom = require("atom"); diff --git a/atom/atom.d.ts b/atom/atom.d.ts deleted file mode 100644 index 31fa76eb4a..0000000000 --- a/atom/atom.d.ts +++ /dev/null @@ -1,1887 +0,0 @@ -// Type definitions for Atom -// Project: https://atom.io/ -// Definitions by: vvakame -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// -/// -/// -/// -/// -/// - -// Policy: this definition file only declare element related to `atom`. -// if js file include to another npm package (e.g. "space-pen", "mixto" and "emissary"). -// you should create a separate file. - -// API documentation : https://atom.io/docs/api/v0.106.0/api/docs/README.md.html - -interface Window { - atom: AtomCore.IAtom; - measure(description:string, fn:Function):any; // return fn result - profile(description:string, fn:Function):any; // return fn result -} - -declare namespace AtomCore { - - // https://atom.io/docs/v0.84.0/advanced/view-system - interface IWorkspaceViewStatic { - new ():IWorkspaceView; - version: number; - configDefaults:any; - content():any; - } - - interface Decoration { - destroy(): void; - } - - /** - * Represents a buffer annotation that remains logically stationary even as the buffer changes. This is used - * to represent cursors, folds, snippet targets, misspelled words, any anything else that needs to track a - * logical location in the buffer over time. - */ - interface Marker { - /** - * Destroys the marker, causing it to emit the 'destroyed' event. Once destroyed, a marker cannot be - * restored by undo/redo operations. - */ - destroy(): void; - - /** - * Gets the screen range of the display marker. - */ - getScreenRange(): Range; - } - - interface IWorkspaceView extends View { - // Delegator.includeInto(WorkspaceView); - - // delegate to model property's property - fullScreen:boolean; - - // delegate to model property's method - open(uri:string, options:any):Q.Promise; - openSync(uri:string, options?:any):any; - saveActivePaneItem():any; - saveActivePaneItemAs():any; - saveAll():void; - destroyActivePaneItem():any; - destroyActivePane():any; - increaseFontSize():void; - decreaseFontSize():void; - - // own property & methods - initialize(model:IWorkspace):any; - initialize(view:View, args:any):void; // do not use - model:IWorkspace; - panes: IPaneContainerView; - getModel():IWorkspace; - installShellCommands():any; - handleFocus():any; - afterAttach(onDom?:any):any; - confirmClose():boolean; - updateTitle():any; - setTitle(title:string):any; - getEditorViews():any[]; // atom.EditorView - prependToTop(element:any):any; - appendToTop(element:any):any; - prependToBottom(element:any):any; - appendToBottom(element:any):any; - prependToLeft(element:any):any; - appendToLeft(element:any):any; - prependToRight(element:any):any; - appendToRight(element:any):any; - getActivePaneView():IPaneView; - getActiveView():View; - focusPreviousPaneView():any; - focusNextPaneView():any; - focusPaneViewAbove():any; - focusPaneViewBelow():any; - focusPaneViewOnLeft():any; - focusPaneViewOnRight():any; - eachPaneView(callback:(paneView:IPaneView)=>any):{ off():any; }; - getPaneViews():IPaneView[]; - eachEditorView(callback:(editorView:any /* EditorView */)=>any):{ off():any; }; - beforeRemove():any; - - command(eventName:string, handler:Function):any; - command(eventName:string, selector:Function, handler:Function):any; - command(eventName:string, options:any, handler:Function):any; - command(eventName:string, selector:Function, options:any, handler:Function):any; - - statusBar:StatusBar.IStatusBarView; - } - - interface IPanes { - // TBD - } - - interface IPaneView { - // TBD - } - - interface IPaneContainerView { - // TBD - } - - interface ITreeView { - // TBD - } - - interface IGutterViewStatic { - new(): IGutterView; - content():any; - } - - interface IGutterView extends View { - firstScreenRow:any; - lastScreenRow:any; - initialize():void; - initialize(view:View, args:any):void; // do not use - afterAttach(onDom?:any):any; - beforeRemove():any; - handleMouseEvents(e:JQueryMouseEventObject):any; - getEditorView():any; /* EditorView */ - getEditor():IEditor; - getLineNumberElements():HTMLCollection; - getLineNumberElementsForClass(klass:string):NodeList; - getLineNumberElement(bufferRow:number):NodeList; - addClassToAllLines(klass:string):boolean; - removeClassFromAllLines(klass:string):boolean; - addClassToLine(bufferRow:number, klass:string):boolean; - removeClassFromLine(bufferRow:number, klass:string):boolean; - updateLineNumbers(changes:any[], startScreenRow?:number, endScreenRow?:number):any; - prependLineElements(lineElements:any):void; - appendLineElements(lineElements:any):void; - removeLineElements(numberOfElements:number):void; - buildLineElements(startScreenRow:any, endScreenRow:any):any; - buildLineElementsHtml(startScreenRow:any, endScreenRow:any):any; - updateFoldableClasses(changes:any[]):any; - removeLineHighlights():void; - addLineHighlight(row:number, emptySelection?:boolean):any; - highlightLines():boolean; - } - - interface ICommandRegistry { - add(target: string, commandName: Object, callback?: (event: any) => void): any; // selector:'atom-editor'|'atom-workspace' - findCommands(params: Object): Object[]; - dispatch(selector: any, name:string): void; - } - - interface ICommandPanel { - // TBD - } - - interface IDisplayBufferStatic { - new(_arg?:any):IDisplayBuffer; - } - - interface IDisplayBuffer /* extends Theorist.Model */ { - // Serializable.includeInto(Editor); - - constructor:IDisplayBufferStatic; - - verticalScrollMargin:number; - horizontalScrollMargin:number; - - declaredPropertyValues:any; - tokenizedBuffer: ITokenizedBuffer; - buffer: TextBuffer.ITextBuffer; - charWidthsByScope:any; - markers:{ [index:number]:IDisplayBufferMarker; }; - foldsByMarkerId:any; - maxLineLength:number; - screenLines:ITokenizedLine[]; - rowMap:any; // return type are RowMap - longestScreenRow:number; - subscriptions:Emissary.ISubscription[]; - subscriptionsByObject:any; // return type are WeakMap - behaviors:any; - subscriptionCounts:any; - eventHandlersByEventName:any; - pendingChangeEvent:any; - - softWrap:boolean; - - serializeParams():{id:number; softWrap:boolean; editorWidthInChars: number; scrollTop: number; scrollLeft: number; tokenizedBuffer: any; }; - deserializeParams(params:any):any; - copy():IDisplayBuffer; - updateAllScreenLines():any; - emitChanged(eventProperties:any, refreshMarkers?:boolean):any; - updateWrappedScreenLines():any; - setVisible(visible:any):any; - getVerticalScrollMargin():number; - setVerticalScrollMargin(verticalScrollMargin:number):number; - getHorizontalScrollMargin():number; - setHorizontalScrollMargin(horizontalScrollMargin:number):number; - getHeight():any; - setHeight(height:any):any; - getWidth():any; - setWidth(newWidth:any):any; - getScrollTop():number; - setScrollTop(scrollTop:number):number; - getScrollBottom():number; - setScrollBottom(scrollBottom:number):number; - getScrollLeft():number; - setScrollLeft(scrollLeft:number):number; - getScrollRight():number; - setScrollRight(scrollRight:number):number; - getLineHeight():any; - setLineHeight(lineHeight:any):any; - getDefaultCharWidth():any; - setDefaultCharWidth(defaultCharWidth:any):any; - getScopedCharWidth(scopeNames:any, char:any):any; - getScopedCharWidths(scopeNames:any):any; - setScopedCharWidth(scopeNames:any, char:any, width:any):any; - setScopedCharWidths(scopeNames:any, charWidths:any):any; - clearScopedCharWidths():any; - getScrollHeight():number; - getScrollWidth():number; - getVisibleRowRange():number[]; - intersectsVisibleRowRange(startRow:any, endRow:any):any; - selectionIntersectsVisibleRowRange(selection:any):any; - scrollToScreenRange(screenRange:any):any; - scrollToScreenPosition(screenPosition:any):any; - scrollToBufferPosition(bufferPosition:any):any; - pixelRectForScreenRange(screenRange:TextBuffer.IRange):any; - getTabLength():number; - setTabLength(tabLength:number):any; - setSoftWrap(softWrap:boolean):boolean; - getSoftWrap():boolean; - setEditorWidthInChars(editorWidthInChars:number):any; - getEditorWidthInChars():number; - getSoftWrapColumn():number; - lineForRow(row:number):any; - linesForRows(startRow:number, endRow:number):any; - getLines():any[]; - indentLevelForLine(line:any):any; - bufferRowsForScreenRows(startScreenRow:any, endScreenRow:any):any; - createFold(startRow:number, endRow:number):IFold; - isFoldedAtBufferRow(bufferRow:number):boolean; - isFoldedAtScreenRow(screenRow:number):boolean; - destroyFoldWithId(id:number):any; - unfoldBufferRow(bufferRow:number):any[]; - largestFoldStartingAtBufferRow(bufferRow:number):any; - foldsStartingAtBufferRow(bufferRow:number):any; - largestFoldStartingAtScreenRow(screenRow:any):any; - largestFoldContainingBufferRow(bufferRow:any):any; - outermostFoldsInBufferRowRange(startRow:any, endRow:any):any[]; - foldsContainingBufferRow(bufferRow:any):any[]; - screenRowForBufferRow(bufferRow:number):number; - lastScreenRowForBufferRow(bufferRow:number):number; - bufferRowForScreenRow(screenRow:number):number; - - screenRangeForBufferRange(bufferRange:TextBuffer.IPoint[]):TextBuffer.IRange; - - screenRangeForBufferRange(bufferRange:TextBuffer.IRange):TextBuffer.IRange; - - screenRangeForBufferRange(bufferRange:{start: TextBuffer.IPoint; end: TextBuffer.IPoint}):TextBuffer.IRange; - screenRangeForBufferRange(bufferRange:{start: number[]; end: TextBuffer.IPoint}):TextBuffer.IRange; - screenRangeForBufferRange(bufferRange:{start: {row:number; col:number;}; end: TextBuffer.IPoint}):TextBuffer.IRange; - - screenRangeForBufferRange(bufferRange:{start: TextBuffer.IPoint; end: number[]}):TextBuffer.IRange; - screenRangeForBufferRange(bufferRange:{start: number[]; end: number[]}):TextBuffer.IRange; - screenRangeForBufferRange(bufferRange:{start: {row:number; col:number;}; end: number[]}):TextBuffer.IRange; - - screenRangeForBufferRange(bufferRange:{start: TextBuffer.IPoint; end: {row:number; col:number;}}):TextBuffer.IRange; - screenRangeForBufferRange(bufferRange:{start: number[]; end: {row:number; col:number;}}):TextBuffer.IRange; - screenRangeForBufferRange(bufferRange:{start: {row:number; col:number;}; end: {row:number; col:number;}}):TextBuffer.IRange; - - bufferRangeForScreenRange(screenRange:TextBuffer.IPoint[]):TextBuffer.IRange; - - bufferRangeForScreenRange(screenRange:TextBuffer.IRange):TextBuffer.IRange; - - bufferRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: TextBuffer.IPoint}):TextBuffer.IRange; - bufferRangeForScreenRange(screenRange:{start: number[]; end: TextBuffer.IPoint}):TextBuffer.IRange; - bufferRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: TextBuffer.IPoint}):TextBuffer.IRange; - - bufferRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: number[]}):TextBuffer.IRange; - bufferRangeForScreenRange(screenRange:{start: number[]; end: number[]}):TextBuffer.IRange; - bufferRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: number[]}):TextBuffer.IRange; - - bufferRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: {row:number; col:number;}}):TextBuffer.IRange; - bufferRangeForScreenRange(screenRange:{start: number[]; end: {row:number; col:number;}}):TextBuffer.IRange; - bufferRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: {row:number; col:number;}}):TextBuffer.IRange; - - pixelRangeForScreenRange(screenRange:TextBuffer.IPoint[], clip?:boolean):TextBuffer.IRange; - - pixelRangeForScreenRange(screenRange:TextBuffer.IRange, clip?:boolean):TextBuffer.IRange; - - pixelRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: TextBuffer.IPoint}, clip?:boolean):TextBuffer.IRange; - pixelRangeForScreenRange(screenRange:{start: number[]; end: TextBuffer.IPoint}, clip?:boolean):TextBuffer.IRange; - pixelRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: TextBuffer.IPoint}, clip?:boolean):TextBuffer.IRange; - - pixelRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: number[]}, clip?:boolean):TextBuffer.IRange; - pixelRangeForScreenRange(screenRange:{start: number[]; end: number[]}, clip?:boolean):TextBuffer.IRange; - pixelRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: number[]}, clip?:boolean):TextBuffer.IRange; - - pixelRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: {row:number; col:number;}}, clip?:boolean):TextBuffer.IRange; - pixelRangeForScreenRange(screenRange:{start: number[]; end: {row:number; col:number;}}, clip?:boolean):TextBuffer.IRange; - pixelRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: {row:number; col:number;}}, clip?:boolean):TextBuffer.IRange; - - pixelPositionForScreenPosition(screenPosition:TextBuffer.IPoint, clip?:boolean):TextBuffer.IPoint; - pixelPositionForScreenPosition(screenPosition:number[], clip?:boolean):TextBuffer.IPoint; - pixelPositionForScreenPosition(screenPosition:{row:number; col:number;}, clip?:boolean):TextBuffer.IPoint; - - screenPositionForPixelPosition(pixelPosition:any):TextBuffer.IPoint; - - pixelPositionForBufferPosition(bufferPosition:any):any; - getLineCount():number; - getLastRow():number; - getMaxLineLength():number; - screenPositionForBufferPosition(bufferPosition:any, options:any):any; - bufferPositionForScreenPosition(bufferPosition:any, options:any):any; - scopesForBufferPosition(bufferPosition:any):any; - bufferRangeForScopeAtPosition(selector:any, position:any):any; - tokenForBufferPosition(bufferPosition:any):any; - getGrammar():IGrammar; - setGrammar(grammar:IGrammar):any; - reloadGrammar():any; - clipScreenPosition(screenPosition:any, options:any):any; - findWrapColumn(line:any, softWrapColumn:any):any; - rangeForAllLines():TextBuffer.IRange; - getMarker(id:number):IDisplayBufferMarker; - getMarkers():IDisplayBufferMarker[]; - getMarkerCount():number; - markScreenRange(range:TextBuffer.IRange, ...args:any[]):IDisplayBufferMarker; - markBufferRange(range:TextBuffer.IRange, options?:any):IDisplayBufferMarker; - markScreenPosition(screenPosition:TextBuffer.IPoint, options?:any):IDisplayBufferMarker; - markBufferPosition(bufferPosition:TextBuffer.IPoint, options?:any):IDisplayBufferMarker; - destroyMarker(id:number):any; - findMarker(params?:any):IDisplayBufferMarker; - findMarkers(params?:any):IDisplayBufferMarker[]; - translateToBufferMarkerParams(params?:any):any; - findFoldMarker(attributes:any):IMarker; - findFoldMarkers(attributes:any):IMarker[]; - getFoldMarkerAttributes(attributes?:any):any; - pauseMarkerObservers():any; - resumeMarkerObservers():any; - refreshMarkerScreenPositions():any; - destroy():any; - logLines(start:number, end:number):any[]; - handleTokenizedBufferChange(tokenizedBufferChange:any):any; - updateScreenLines(startBufferRow:any, endBufferRow:any, bufferDelta?:number, options?:any):any; - buildScreenLines(startBufferRow:any, endBufferRow:any):any; - findMaxLineLength(startScreenRow:any, endScreenRow:any, newScreenLines:any):any; - handleBufferMarkersUpdated():any; - handleBufferMarkerCreated(marker:any):any; - createFoldForMarker(maker:any):IFold; - foldForMarker(marker:any):any; - } - - interface IViewRegistry { - getView(selector:any):any; - } - - interface ICursorStatic { - new (arg:{editor:IEditor; marker:IDisplayBufferMarker; id: number;}):ICursor; - } - - interface ScopeDescriptor { - scopes: string[]; - } - - interface ICursor /* extends Theorist.Model */ { - getScopeDescriptor(): ScopeDescriptor; - screenPosition:any; - bufferPosition:any; - goalColumn:any; - visible:boolean; - needsAutoscroll:boolean; - - editor:IEditor; - marker:IDisplayBufferMarker; - id: number; - - destroy():any; - changePosition(options:any, fn:Function):any; - getPixelRect():any; - setScreenPosition(screenPosition:any, options?:any):any; - getScreenPosition():TextBuffer.IPoint; - getScreenRange():TextBuffer.IRange; - setBufferPosition(bufferPosition:any, options?:any):any; - getBufferPosition():TextBuffer.IPoint; - autoscroll():any; - updateVisibility():any; - setVisible(visible:boolean):any; - isVisible():boolean; - wordRegExp(arg?:any):any; - isLastCursor():boolean; - isSurroundedByWhitespace():boolean; - isBetweenWordAndNonWord():boolean; - isInsideWord():boolean; - clearAutoscroll():void; - clearSelection():void; - getScreenRow():number; - getScreenColumn():number; - getBufferRow():number; - getBufferColumn():number; - getCurrentBufferLine():string; - moveUp(rowCount:number, arg?:any):any; - moveDown(rowCount:number, arg?:any):any; - moveLeft(arg?:any):any; - moveRight(arg?:any):any; - moveToTop():any; - moveToBottom():void; - moveToBeginningOfScreenLine():void; - moveToBeginningOfLine():void; - moveToFirstCharacterOfLine():void; - moveToEndOfScreenLine():void; - moveToEndOfLine():void; - moveToBeginningOfWord():void; - moveToEndOfWord():void; - moveToBeginningOfNextWord():void; - moveToPreviousWordBoundary():void; - moveToNextWordBoundary():void; - getBeginningOfCurrentWordBufferPosition(options?:any):TextBuffer.IPoint; - getPreviousWordBoundaryBufferPosition(options?:any):TextBuffer.IPoint; - getMoveNextWordBoundaryBufferPosition(options?:any):TextBuffer.IPoint; - getEndOfCurrentWordBufferPosition(options?:any):TextBuffer.IPoint; - getBeginningOfNextWordBufferPosition(options?:any):TextBuffer.IPoint; - getCurrentWordBufferRange(options?:any):TextBuffer.IPoint; - getCurrentLineBufferRange(options?:any):TextBuffer.IPoint; - getCurrentParagraphBufferRange():any; - getCurrentWordPrefix():string; - isAtBeginningOfLine():boolean; - getIndentLevel():number; - isAtEndOfLine():boolean; - getScopes():string[]; - hasPrecedingCharactersOnLine():boolean; - getMarker(): Marker; - } - - interface ILanguageMode { - // TBD - } - - interface ISelection /* extends Theorist.Model */ { - cursor:ICursor; - marker:IDisplayBufferMarker; - editor:IEditor; - initialScreenRange:any; - wordwise:boolean; - needsAutoscroll:boolean; - retainSelection:boolean; - subscriptionCounts:any; - - destroy():any; - finalize():any; - clearAutoscroll():any; - isEmpty():boolean; - isReversed():boolean; - isSingleScreenLine():boolean; - getScreenRange():TextBuffer.IRange; - setScreenRange(screenRange:any, options:any):any; - getBufferRange():TextBuffer.IRange; - setBufferRange(bufferRange:any, options:any):any; - getBufferRowRange():number[]; - autoscroll():void; - getText():string; - clear():boolean; - selectWord():TextBuffer.IRange; - expandOverWord():any; - selectLine(row?:any):TextBuffer.IRange; - expandOverLine():boolean; - selectToScreenPosition(position:any):any; - selectToBufferPosition(position:any):any; - selectRight():boolean; - selectLeft():boolean; - selectUp(rowCount?:any):boolean; - selectDown(rowCount?:any):boolean; - selectToTop():any; - selectToBottom():any; - selectAll():any; - selectToBeginningOfLine():any; - selectToFirstCharacterOfLine():any; - selectToEndOfLine():any; - selectToBeginningOfWord():any; - selectToEndOfWord():any; - selectToBeginningOfNextWord():any; - selectToPreviousWordBoundary():any; - selectToNextWordBoundary():any; - addSelectionBelow():any; - getGoalBufferRange():any; - addSelectionAbove():any[]; - insertText(text:string, options?:any):any; - normalizeIndents(text:string, indentBasis:number):any; - indent(_arg?:any):any; - indentSelectedRows():TextBuffer.IRange[]; - setIndentationForLine(line:string, indentLevel:number):any; - backspace():any; - backspaceToBeginningOfWord():any; - backspaceToBeginningOfLine():any; - delete():any; - deleteToEndOfWord():any; - deleteSelectedText():any; - deleteLine():any; - joinLines():any; - outdentSelectedRows():any[]; - autoIndentSelectedRows():any; - toggleLineComments():any; - cutToEndOfLine(maintainClipboard:any):any; - cut(maintainClipboard:any):any; - copy(maintainClipboard:any):any; - fold():any; - modifySelection(fn:()=>any):any; - plantTail():any; - intersectsBufferRange(bufferRange:any):any; - intersectsWith(otherSelection:any):any; - merge(otherSelection:any, options:any):any; - compare(otherSelection:any):any; - getRegionRects():any[]; - screenRangeChanged():any; - } - - interface IDecorationParams { - id?: number; - class: string; - type: any /* string or string[] */; - } - - interface IDecorationStatic { - isType(decorationParams:IDecorationParams, type:any /* string or string[] */):boolean; - new (marker:IDisplayBufferMarker, displayBuffer:IDisplayBuffer, params: IDecorationParams): IDecoration; - } - - interface IDecoration extends Emissary.IEmitter { - marker: IDisplayBufferMarker; - displayBuffer: IDisplayBuffer; - params: IDecorationParams - id: number; - flashQueue: any[]; - isDestroyed: boolean; - - destroy():void; - update(newParams:IDecorationParams):void; - getMarker():IDisplayBufferMarker; - getParams():IDecorationParams; - isType(type:string):boolean; - matchesPattern(decorationPattern:{[key:string]:IDecorationParams;}):boolean; - flash(klass:string, duration?:number):void; - consumeNextFlash():any; - } - - interface IEditor { - // Serializable.includeInto(Editor); - // Delegator.includeInto(Editor); - - deserializing:boolean; - callDisplayBufferCreatedHook:boolean; - registerEditor:boolean; - buffer:TextBuffer.ITextBuffer; - languageMode: ILanguageMode; - cursors:ICursor[]; - selections: ISelection[]; - suppressSelectionMerging:boolean; - updateBatchDepth: number; - selectionFlashDuration: number; - softTabs: boolean; - displayBuffer: IDisplayBuffer; - - id:number; - behaviors:any; - declaredPropertyValues: any; - eventHandlersByEventName: any; - eventHandlersByNamespace: any; - lastOpened: number; - subscriptionCounts: any; - subscriptionsByObject: any; /* WeakMap */ - subscriptions: Emissary.ISubscription[]; - destroy():void; - - mini: any; - - serializeParams():{id:number; softTabs:boolean; scrollTop:number; scrollLeft:number; displayBuffer:any;}; - deserializeParams(params:any):any; - subscribeToBuffer():void; - subscribeToDisplayBuffer():void; - getViewClass():any; // return type are EditorView - destroyed():void; - isDestroyed():boolean; - copy():IEditor; - getTitle():string; - getLongTitle():string; - setVisible(visible:boolean):void; - setMini(mini:any):void; - setScrollTop(scrollTop:any):void; - getScrollTop():number; - setScrollLeft(scrollLeft:any):void; - getScrollLeft():number; - setEditorWidthInChars(editorWidthInChars:any):void; - getSoftWrapColumn():number; - getSoftTabs():boolean; - setSoftTabs(softTabs:boolean):void; - getSoftWrap():boolean; - setSoftWrap(softWrap:any):void; - getTabText():string; - getTabLength():number; - setTabLength(tabLength:any):void; - usesSoftTabs():boolean; - clipBufferPosition(bufferPosition:any):void; - clipBufferRange(range:any):void; - indentationForBufferRow(bufferRow:any):void; - setIndentationForBufferRow(bufferRow:any, newLevel:any, _arg:any):void; - indentLevelForLine(line:any):number; - buildIndentString(number:any):string; - save():void; - saveAs(filePath:any):void; - copyPathToClipboard():void; - getPath():string; - getText():string; - setText(text:any):void; - getTextInRange(range:any):any; - getLineCount():number; - getBuffer():TextBuffer.ITextBuffer; - getURI():string; - isBufferRowBlank(bufferRow:any):boolean; - isBufferRowCommented(bufferRow:any):void; - nextNonBlankBufferRow(bufferRow:any):void; - getEofBufferPosition():TextBuffer.IPoint; - getLastBufferRow():number; - bufferRangeForBufferRow(row:any, options:any):TextBuffer.IRange; - lineForBufferRow(row:number):string; - lineLengthForBufferRow(row:number):number; - scan():any; - scanInBufferRange():any; - backwardsScanInBufferRange():any; - isModified():boolean; - isEmpty():boolean; - shouldPromptToSave():boolean; - screenPositionForBufferPosition(bufferPosition:any, options?:any):TextBuffer.IPoint; - bufferPositionForScreenPosition(screenPosition:any, options?:any):TextBuffer.IPoint; - screenRangeForBufferRange(bufferRange:any):TextBuffer.IRange; - bufferRangeForScreenRange(screenRange:any):TextBuffer.IRange; - clipScreenPosition(screenPosition:any, options:any):TextBuffer.IRange; - lineForScreenRow(row:any):ITokenizedLine; - linesForScreenRows(start?:any, end?:any):ITokenizedLine[]; - getScreenLineCount():number; - getMaxScreenLineLength():number; - getLastScreenRow():number; - bufferRowsForScreenRows(startRow:any, endRow:any):any[]; - bufferRowForScreenRow(row:any):number; - scopesForBufferPosition(bufferPosition:any):string[]; - bufferRangeForScopeAtCursor(selector:string):any; - tokenForBufferPosition(bufferPosition:any):IToken; - getCursorScopes():string[]; - logCursorScope():void; - insertText(text:string, options?:any):TextBuffer.IRange[]; - insertNewline():TextBuffer.IRange[]; - insertNewlineBelow():TextBuffer.IRange[]; - insertNewlineAbove():any; - indent(options?:any):any; - backspace():any[]; - // deprecated backspaceToBeginningOfWord():any[]; - // deprecated backspaceToBeginningOfLine():any[]; - deleteToBeginningOfWord():any[]; - deleteToBeginningOfLine():any[]; - delete():any[]; - deleteToEndOfLine():any[]; - deleteToEndOfWord():any[]; - deleteLine():TextBuffer.IRange[]; - indentSelectedRows():TextBuffer.IRange[][]; - outdentSelectedRows():TextBuffer.IRange[][]; - toggleLineCommentsInSelection():TextBuffer.IRange[]; - autoIndentSelectedRows():TextBuffer.IRange[][]; - normalizeTabsInBufferRange(bufferRange:any):any; - cutToEndOfLine():boolean[]; - cutSelectedText():boolean[]; - copySelectedText():boolean[]; - pasteText(options?:any):TextBuffer.IRange[]; - undo():any[]; - redo():any[]; - foldCurrentRow():any; - unfoldCurrentRow():any[]; - foldSelectedLines():any[]; - foldAll():any[]; - unfoldAll():any[]; - foldAllAtIndentLevel(level:any):any; - foldBufferRow(bufferRow:any):any; - unfoldBufferRow(bufferRow:any):any; - isFoldableAtBufferRow(bufferRow:any):boolean; - isFoldableAtScreenRow(screenRow:any):boolean; - createFold(startRow:any, endRow:any):IFold; - destroyFoldWithId(id:any):any; - destroyFoldsIntersectingBufferRange(bufferRange:any):any; - toggleFoldAtBufferRow(bufferRow:any):any; - isFoldedAtCursorRow():boolean; - isFoldedAtBufferRow(bufferRow:any):boolean; - isFoldedAtScreenRow(screenRow:any):boolean; - largestFoldContainingBufferRow(bufferRow:any):boolean; - largestFoldStartingAtScreenRow(screenRow:any):any; - outermostFoldsInBufferRowRange(startRow:any, endRow:any):any[]; - moveLineUp():ISelection[]; - moveLineDown():ISelection[]; - duplicateLines():any[][]; - // duprecated duplicateLine():any[][]; - mutateSelectedText(fn:(selection:ISelection)=>any):any; - replaceSelectedText(options:any, fn:(selection:string)=>any):any; - decorationsForScreenRowRange(startScreenRow:any, endScreenRow:any):{[id:number]: IDecoration[]}; - decorateMarker(marker:IDisplayBufferMarker, decorationParams: {type:string; class: string;}):IDecoration; - decorationForId(id:number):IDecoration; - getMarker(id:number):IDisplayBufferMarker; - getMarkers():IDisplayBufferMarker[]; - findMarkers(...args:any[]):IDisplayBufferMarker[]; - markScreenRange(...args:any[]):IDisplayBufferMarker; - markBufferRange(...args:any[]):IDisplayBufferMarker; - markScreenPosition(...args:any[]):IDisplayBufferMarker; - markBufferPosition(...args:any[]):IDisplayBufferMarker; - destroyMarker(...args:any[]):boolean; - getMarkerCount():number; - hasMultipleCursors():boolean; - getCursors():ICursor[]; - getCursor():ICursor; - addCursorAtScreenPosition(screenPosition:any):ICursor; - addCursorAtBufferPosition(bufferPosition:any):ICursor; - addCursor(marker:any):ICursor; - removeCursor(cursor:any):ICursor[]; - addSelection(marker:any, options:any):ISelection; - addSelectionForBufferRange(bufferRange:any, options:any):ISelection; - setSelectedBufferRange(bufferRange:any, options:any):any; - setSelectedBufferRanges(bufferRanges:any, options:any):any; - removeSelection(selection:ISelection):any; - clearSelections():boolean; - consolidateSelections():boolean; - selectionScreenRangeChanged(selection:any):void; - getSelections():ISelection[]; - getSelection(index?:number):ISelection; - getLastSelection():ISelection; - getSelectionsOrderedByBufferPosition():ISelection[]; - getLastSelectionInBuffer():ISelection; - selectionIntersectsBufferRange(bufferRange:any):any; - setCursorScreenPosition(position:TextBuffer.IPoint, options?:any):any; - getCursorScreenPosition():TextBuffer.IPoint; - getCursorScreenRow():number; - setCursorBufferPosition(position:any, options?:any):any; - getCursorBufferPosition():TextBuffer.IPoint; - getSelectedScreenRange():TextBuffer.IRange; - getSelectedBufferRange():TextBuffer.IRange; - getSelectedBufferRanges():TextBuffer.IRange[]; - getSelectedText():string; - getTextInBufferRange(range:TextBuffer.IRange):string; - setTextInBufferRange(range:TextBuffer.IRange | any[], text:string):any; - getCurrentParagraphBufferRange():TextBuffer.IRange; - getWordUnderCursor(options?:any):string; - moveCursorUp(lineCount?:number):void; - moveCursorDown(lineCount?:number):void; - moveCursorLeft():void; - moveCursorRight():void; - moveCursorToTop():void; - moveCursorToBottom():void; - moveCursorToBeginningOfScreenLine():void; - moveCursorToBeginningOfLine():void; - moveCursorToFirstCharacterOfLine():void; - moveCursorToEndOfScreenLine():void; - moveCursorToEndOfLine():void; - moveCursorToBeginningOfWord():void; - moveCursorToEndOfWord():void; - moveCursorToBeginningOfNextWord():void; - moveCursorToPreviousWordBoundary():void; - moveCursorToNextWordBoundary():void; - moveCursorToBeginningOfNextParagraph():void; - moveCursorToBeginningOfPreviousParagraph():void; - moveToBottom():void; - scrollToCursorPosition(options:any):any; - pageUp():void; - pageDown():void; - selectPageUp():void; - selectPageDown():void; - getRowsPerPage():number; - moveCursors(fn:(cursor:ICursor)=>any):any; - cursorMoved(event:any):void; - selectToScreenPosition(position:TextBuffer.IPoint):any; - selectRight():ISelection[]; - selectLeft():ISelection[]; - selectUp(rowCount?:number):ISelection[]; - selectDown(rowCount?:number):ISelection[]; - selectToTop():ISelection[]; - selectAll():ISelection[]; - selectToBottom():ISelection[]; - selectToBeginningOfLine():ISelection[]; - selectToFirstCharacterOfLine():ISelection[]; - selectToEndOfLine():ISelection[]; - selectToPreviousWordBoundary():ISelection[]; - selectToNextWordBoundary():ISelection[]; - selectLine():ISelection[]; - selectLinesContainingCursors():ISelection[]; - addSelectionBelow():ISelection[]; - addSelectionAbove():ISelection[]; - splitSelectionsIntoLines():any[]; - transpose():TextBuffer.IRange[]; - upperCase():boolean[]; - lowerCase():boolean[]; - joinLines():any[]; - selectToBeginningOfWord():ISelection[]; - selectToEndOfWord():ISelection[]; - selectToBeginningOfNextWord():ISelection[]; - selectWord():ISelection[]; - selectToBeginningOfNextParagraph():ISelection[]; - selectToBeginningOfPreviousParagraph():ISelection[]; - selectMarker(marker:any):any; - mergeCursors():number[]; - expandSelectionsForward():any; - expandSelectionsBackward(fn:(selection:ISelection)=>any):ISelection[]; - finalizeSelections():boolean[]; - mergeIntersectingSelections():any; - preserveCursorPositionOnBufferReload():Emissary.ISubscription; - getGrammar(): IGrammar; - setGrammar(grammer:IGrammar):void; - reloadGrammar():any; - shouldAutoIndent():boolean; - shouldShowInvisibles():boolean; - updateInvisibles():void; - transact(fn:Function):any; - beginTransaction():ITransaction; - commitTransaction():any; - abortTransaction():any[]; - inspect():string; - logScreenLines(start:number, end:number):any[]; - handleTokenization():void; - handleGrammarChange():void; - handleMarkerCreated(marker:any):any; - getSelectionMarkerAttributes():{type: string; editorId: number; invalidate: string; }; - getVerticalScrollMargin():number; - setVerticalScrollMargin(verticalScrollMargin:number):void; - getHorizontalScrollMargin():number; - setHorizontalScrollMargin(horizontalScrollMargin:number):void; - getLineHeightInPixels():number; - setLineHeightInPixels(lineHeightInPixels:number):void; - batchCharacterMeasurement(fn:Function):void; - getScopedCharWidth(scopeNames:any, char:any):any; - setScopedCharWidth(scopeNames:any, char:any, width:any):any; - getScopedCharWidths(scopeNames:any):any; - clearScopedCharWidths():any; - getDefaultCharWidth():number; - setDefaultCharWidth(defaultCharWidth:number):void; - setHeight(height:number):void; - getHeight():number; - getClientHeight():number; - setWidth(width:number):void; - getWidth():number; - getScrollTop():number; - setScrollTop(scrollTop:number):void; - getScrollBottom():number; - setScrollBottom(scrollBottom:number):void; - getScrollLeft():number; - setScrollLeft(scrollLeft:number):void; - getScrollRight():number; - setScrollRight(scrollRight:number):void; - getScrollHeight():number; - getScrollWidth():number; - getVisibleRowRange():number; - intersectsVisibleRowRange(startRow:any, endRow:any):any; - selectionIntersectsVisibleRowRange(selection:any):any; - pixelPositionForScreenPosition(screenPosition:any):any; - pixelPositionForBufferPosition(bufferPosition:any):any; - screenPositionForPixelPosition(pixelPosition:any):any; - pixelRectForScreenRange(screenRange:any):any; - scrollToScreenRange(screenRange:any, options:any):any; - scrollToScreenPosition(screenPosition:any, options:any):any; - scrollToBufferPosition(bufferPosition:any, options:any):any; - horizontallyScrollable():any; - verticallyScrollable():any; - getHorizontalScrollbarHeight():any; - setHorizontalScrollbarHeight(height:any):any; - getVerticalScrollbarWidth():any; - setVerticalScrollbarWidth(width:any):any; - // deprecated joinLine():any; - - onDidChange(callback: Function): Disposable; - onDidDestroy(callback: Function): Disposable; - onDidStopChanging(callback: Function): Disposable; - onDidChangeCursorPosition(callback: Function): Disposable; - onDidSave(callback: (event: { path: string }) => void): Disposable; - - decorateMarker(marker: Marker, options: any): Decoration; - getLastCursor(): ICursor; - } - - interface IGrammar { - bundledPackage: boolean; - emitter: any; - fileTypes: [string]; - firstLineRegex: any; - foldingStopMarker: any; - includedGrammarScopes: [any]; - initialRule: any; - injectionSelector: any; - injections: any; - maxTokensPerLine: Number; - name: string; - packageName: string; - path: string; - rawPatterns: [any]; - rawRepository: any; - registration: Disposable; - registry: any; - repository: Object; - scopeName: string; - // TBD - - } - - interface IPane /* extends Theorist.Model */ { - itemForURI: (uri:string)=>IEditor; - items:any[]; - activeItem:any; - - serializeParams():any; - deserializeParams(params:any):any; - getViewClass():any; // return type are PaneView - isActive():boolean; - isDestroyed():boolean; - focus():void; - blur():void; - activate():void; - getPanes():IPane[]; - getItems():any[]; - getActiveItem():any; - getActiveEditor():any; - itemAtIndex(index:number):any; - activateNextItem():any; - activatePreviousItem():any; - getActiveItemIndex():number; - activateItemAtIndex(index:number):any; - activateItem(item:any):any; - addItem(item:any, index:number):any; - addItems(items:any[], index:number):any[]; - removeItem(item:any, destroying:any):void; - moveItem(item:any, newIndex:number):void; - moveItemToPane(item:any, pane:IPane, index:number):void; - destroyActiveItem():boolean; // always return false - destroyItem(item:any):boolean; - destroyItems():any[]; - destroyInactiveItems():any[]; - destroy():void; - destroyed():any[]; - promptToSaveItem(item:any):boolean; - saveActiveItem():void; - saveActiveItemAs():void; - saveItem(item:any, nextAction:Function):void; - saveItemAs(item:any, nextAction:Function):void; - saveItems():any[]; - activateItemForURI(uri:any):any; - copyActiveItem():void; - splitLeft(params:any):IPane; - splitRight(params:any):IPane; - splitUp(params:any):IPane; - splitDown(params:any):IPane; - split(orientation:string, side:string, params:any):IPane; - findLeftmostSibling():IPane; - findOrCreateRightmostSibling():IPane; - } - - // https://atom.io/docs/v0.84.0/advanced/serialization - interface ISerializationStatic { - deserialize(data:ISerializationInfo):T; - new (data:T): ISerialization; - } - - interface ISerialization { - serialize():ISerializationInfo; - } - - interface ISerializationInfo { - deserializer: string; - } - - interface IBrowserWindow { - getPosition():number[]; - getSize():number[]; - } - - interface IAtomWindowDimentions { - x:number; - y:number; - width:number; - height:number; - } - - interface IProjectStatic { - pathForRepositoryUrl(repoUrl:string):string; - - new (arg?:{path:any; buffers:any[];}):IProject; - } - - interface IProject /* extends Theorist.Model */ { - // Serializable.includeInto(Project); - - path:string; - /** deprecated */ - rootDirectory?:PathWatcher.IDirectory; - rootDirectories:PathWatcher.IDirectory[]; - - serializeParams():any; - deserializeParams(params:any):any; - destroyed():any; - destroyRepo():any; - destroyUnretainedBuffers():any; - getRepo():IGit; - getPath():string; - setPath(projectPath:string):any; - getRootDirectory():PathWatcher.IDirectory; - resolve(uri:string):string; - relativize(fullPath:string):string; - contains(pathToCheck:string):boolean; - open(filePath:string, options?:any):Q.Promise; - openSync(filePath:string, options?:any):IEditor; - getBuffers():TextBuffer.ITextBuffer; - isPathModified(filePath:string):boolean; - findBufferForPath(filePath:string):TextBuffer.ITextBuffer; - bufferForPathSync(filePath:string):TextBuffer.ITextBuffer; - bufferForPath(filePath:string):Q.Promise; - bufferForId(id:any):TextBuffer.ITextBuffer; - buildBufferSync(absoluteFilePath:string):TextBuffer.ITextBuffer; - buildBuffer(absoluteFilePath:string):Q.Promise; - addBuffer(buffer:TextBuffer.ITextBuffer, options?:any):any; - addBufferAtIndex(buffer:TextBuffer.ITextBuffer, index:number, options?:any):any; - scan(regex:any, options:any, iterator:any):Q.Promise; - replace(regex:any, replacementText:any, filePaths:any, iterator:any):Q.Promise; - buildEditorForBuffer(buffer:any, editorOptions:any):IEditor; - eachBuffer(...args:any[]):any; - - onDidChangePaths(callback: Function): Disposable; - } - - interface IWorkspaceStatic { - new():IWorkspace; - } - - interface IWorkspacePanelOptions{ - item:any; - visible?:boolean; - priority?:number; - } - - interface Panel{ - getItem():any; - getPriority():any; - isVisible():boolean; - show():void; - hide():void; - } - - interface IWorkspace { - addBottomPanel(options:IWorkspacePanelOptions):Panel; - addLeftPanel(options:IWorkspacePanelOptions):Panel; - addRightPanel(options:IWorkspacePanelOptions):Panel; - addTopPanel(options:IWorkspacePanelOptions):Panel; - addModalPanel(options:IWorkspacePanelOptions):Panel; - addOpener(opener: Function): any; - - deserializeParams(params:any):any; - serializeParams():{paneContainer:any;fullScreen:boolean;}; - eachEditor(callback: Function): void; - getTextEditors():IEditor[]; - open(uri:string, options:any):Q.Promise; - openLicense():void; - openSync(uri:string, options:any):any; - openUriInPane(uri: string, pane: any, options: any): Q.Promise; - observeTextEditors(callback: Function): Disposable; - reopenItemSync():any; - registerOpener(opener:(urlToOpen:string)=>any):void; - unregisterOpener(opener:Function):void; - getOpeners():any; - getActivePane(): IPane; - getActivePaneItem(): IPane; - getActiveTextEditor(): IEditor; - getPanes():any; - saveAll():void; - activateNextPane():any; - activatePreviousPane():any; - paneForURI: (uri:string) => IPane; - saveActivePaneItem():any; - saveActivePaneItemAs():any; - destroyActivePaneItem():any; - destroyActivePane():any; - getActiveEditor():IEditor; - increaseFontSize():void; - decreaseFontSize():void; - resetFontSize():void; - itemOpened(item:any):void; - onPaneItemDestroyed(item:any):void; - destroyed():void; - isTextEditor(object: any): boolean; - - onDidChangeActivePaneItem(item:any):Disposable; - } - - interface IAtomSettings { - appVersion: string; - bootstrapScript: string; - devMode: boolean; - initialPath: string; - pathToOpen: string; - resourcePath: string; - shellLoadTime: number; - windowState:string; - } - - interface IAtomState { - mode:string; - packageStates:any; - project:any; - syntax:any; - version:number; - windowDimensions:any; - workspace:any; - } - - interface IDeserializerManager { - deserializers:Function; - add:Function; - remove:Function; - deserialize:Function; - get:Function; - } - - interface IConfig { - get(keyPath:string):any; - // TBD - } - - interface IKeymapManager { - defaultTarget:HTMLElement; - // TBD - } - - interface IPackage { - mainModulePath: string; - mainModule: any; - enable(): void; - disable(): void; - isTheme(): boolean; - getType(): string; - getStylesheetType(): string; - load(): IPackage; - reset(): void; - activate(): Q.Promise; - activateNow(): void; - // TBD - } - - interface IPackageManager extends Emissary.IEmitter { - packageDirPaths:string[]; - loadedPackages:any; - activePackages:any; - packageStates:any; - packageActivators:any[]; - - getApmPath():string; - getPackageDirPaths():string; - getPackageState(name:string):any; - setPackageState(name:string, state:any):void; - enablePackage(name:string):any; - disablePackage(name:string):any; - activate():void; - registerPackageActivator(activator:any, types:any):void; - activatePackages(packages:any):void; - activatePackage(name:string):Q.Promise; - deactivatePackages():void; - deactivatePackage(name:string):void; - getActivePackages():any; - getActivePackage(name:string):any; - isPackageActive(name:string):boolean; - unobserveDisabledPackages():void; - observeDisabledPackages():void; - loadPackages():void; - loadPackage(nameOrPath:string):void; - unloadPackages():void; - unloadPackage(name:string):void; - getLoadedPackage(name:string):any; - isPackageLoaded(name:string):boolean; - getLoadedPackages():any; - getLoadedPackagesForTypes(types:any):any[]; - resolvePackagePath(name:string):string; - isPackageDisabled(name:string):boolean; - hasAtomEngine(packagePath:string):boolean; - isBundledPackage(name:string):boolean; - getPackageDependencies():any; - getAvailablePackagePaths():any[]; - getAvailablePackageNames():any[]; - getAvailablePackageMetadata():any[]; - } - - interface INotifications { - addInfo: Function; - addError: Function; - addSuccess: Function; - addWarning: Function; - } - - interface IThemeManager { - // TBD - } - - interface IContextMenuManager { - // TBD - } - - interface IMenuManager { - // TBD - } - - interface IClipboard { - write(text:string, metadata?:any):any; - read():string; - } - - interface ISyntax { - // TBD - } - - interface IWindowEventHandler { - // TBD - } - - interface IAtomStatic extends ISerializationStatic { - version: number; - loadSettings: IAtomSettings; - - /* Load or create the Atom environment in the given mode */ - loadOrCreate(mode:'editor'):IAtom; - /* Load or create the Atom environment in the given mode */ - loadOrCreate(mode:'spec'):IAtom; - /* Load or create the Atom environment in the given mode */ - loadOrCreate(mode:string):IAtom; - - loadState(mode:any):void; - getStatePath(mode:any):string; - getConfigDirPath():string; - getStorageDirPath():string; - getLoadSettings():IAtomSettings; - getCurrentWindow():IBrowserWindow; - getVersion():string; - isReleasedVersion():boolean; - - new(state:IAtomState):IAtom; - } - - class Disposable { - constructor(disposalAction:any) - dispose():void - } - - // https://atom.io/docs/api/v0.106.0/api/classes/Atom.html - /* Global Atom class : instance members */ - interface IAtom { - constructor:IAtomStatic; - - state:IAtomState; - mode:string; - deserializers:IDeserializerManager; - config: IConfig; - commands: ICommandRegistry; - keymaps: IKeymapManager; - keymap: IKeymapManager; - packages: IPackageManager; - themes: IThemeManager; - contextManu: IContextMenuManager; - menu: IMenuManager; - notifications: INotifications; // https://github.com/atom/notifications - clipboard:IClipboard; - syntax:ISyntax; - views: IViewRegistry; - windowEventHandler: IWindowEventHandler; - - // really exists? start - subscribe:Function; - unsubscribe:Function; - loadTime:number; - workspaceViewParentSelector:string; - - project: IProject; - workspaceView: IWorkspaceView; - workspace: IWorkspace; - // really exists? end - - initialize:Function; - // registerRepresentationClass:Function; - // registerRepresentationClasses:Function; - setBodyPlatformClass:Function; - getCurrentWindow():IBrowserWindow; - getWindowDimensions:Function; - setWindowDimensions:Function; - restoreWindowDimensions:Function; - storeWindowDimensions:Function; - getLoadSettings:Function; - deserializeProject: Function; - deserializeWorkspaceView:Function; - deserializePackageStates:Function; - deserializeEditorWindow:Function; - startEditorWindow:Function; - unloadEditorWindow:Function; - loadThemes:Function; - watchThemes:Function; - open:Function; - confirm:Function; - showSaveDialog:Function; - showSaveDialogSync:Function; - openDevTools:Function; - toggleDevTools:Function; - executeJavaScriptInDevTools:Function; - reload:Function; - focus:Function; - show:Function; - hide:Function; - setSize:Function; - setPosition:Function; - center:Function; - displayWindow:Function; - close:Function; - exit:Function; - inDevMode:Function; - inSpecMode:Function; - toggleFullScreen:Function; - setFullScreen:Function; - isFullScreen:Function; - getVersion:Function; - isReleasedVersion:Function; - getGitHubAuthTokenName:Function; - setGitHubAuthToken:Function; - getGitHubAuthToken:Function; - getConfigDirPath:Function; - saveSync:Function; - getWindowLoadTime():number; - crashMainProcess:Function; - crashRenderProcess:Function; - beep:Function; - getUserInitScriptPath:Function; - requireUserInitScript:Function; - requireWithGlobals:Function; - - services: any; // TODO: New services api - } - - interface IBufferedNodeProcessStatic { - new (arg:any):IBufferedNodeProcess; - } - - interface IBufferedNodeProcess extends IBufferedProcess { - } - - interface IBufferedProcessStatic { - new (arg:any):IBufferedProcess; - } - - interface IBufferedProcess { - process:Function; - killed:boolean; - - bufferStream:Function; - kill:Function; - } - - interface IGitStatic { - new(path:any, options:any):IGit; - } - - interface IGit { - } - - interface ITokenizedBuffer { - // TBD - } - - interface ITokenizedLine { - // TBD - } - - interface IToken { - // TBD - } - - interface IFoldStatic { - new (displayBuffer:IDisplayBuffer, marker:IMarker):IFold; - // TBD - } - - interface IFold { - id:number; - displayBuffer:IDisplayBuffer; - marker:IMarker; - - // TBD - } - - interface IDisplayBufferMarkerStatic { - new (_arg:{bufferMarker:IMarker; displayBuffer: IDisplayBuffer}):IDisplayBufferMarker; - } - - interface IDisplayBufferMarker extends Emissary.IEmitter, Emissary.ISubscriber { - constructor:IDisplayBufferMarkerStatic; - - id: number; - - bufferMarkerSubscription:any; - oldHeadBufferPosition:TextBuffer.IPoint; - oldHeadScreenPosition:TextBuffer.IPoint; - oldTailBufferPosition:TextBuffer.IPoint; - oldTailScreenPosition:TextBuffer.IPoint; - wasValid:boolean; - - bufferMarker: IMarker; - displayBuffer: IDisplayBuffer; - globalPauseCount:number; - globalQueuedEvents:any; - - subscriptions:Emissary.ISubscription[]; - subscriptionsByObject:any; // WeakMap - - copy(attributes?:any /* maybe IMarker */):IDisplayBufferMarker; - getScreenRange():TextBuffer.IRange; - setScreenRange(screenRange:any, options:any):any; - getBufferRange():TextBuffer.IRange; - setBufferRange(bufferRange:any, options:any):any; - getPixelRange():any; - getHeadScreenPosition():TextBuffer.IPoint; - setHeadScreenPosition(screenPosition:any, options:any):any; - getHeadBufferPosition():TextBuffer.IPoint; - setHeadBufferPosition(bufferPosition:any):any; - getTailScreenPosition():TextBuffer.IPoint; - setTailScreenPosition(screenPosition:any, options:any):any; - getTailBufferPosition():TextBuffer.IPoint; - setTailBufferPosition(bufferPosition:any):any; - plantTail():boolean; - clearTail():boolean; - hasTail():boolean; - isReversed():boolean; - isValid():boolean; - isDestroyed():boolean; - getAttributes():any; - setAttributes(attributes:any):any; - matchesAttributes(attributes:any):any; - destroy():any; - isEqual(other:IDisplayBufferMarker):boolean; - compare(other:IDisplayBufferMarker):boolean; - inspect():string; - destroyed():any; - notifyObservers(_arg:any):any; - } - - interface ITransaction { - // TBD - } - - interface IMarker extends Emissary.IEmitter { - // Serializable.includeInto(Editor); - // Delegator.includeInto(Editor); - - // TBD - } - - interface ITaskStatic { - new(taskPath:any):ITask; - } - - interface ITask { - // TBD - } -} - -declare var atom:AtomCore.IAtom; - -declare module "atom" { - import spacePen = require("space-pen"); - - var $:typeof spacePen.$; - var $$:typeof spacePen.$$; - var $$$:typeof spacePen.$$$; - - var BufferedNodeProcess:AtomCore.IBufferedNodeProcessStatic; - var BufferedProcess:AtomCore.IBufferedProcessStatic; - var Git:AtomCore.IGitStatic; - var Point:TextBuffer.IPointStatic; - var Range:TextBuffer.IRangeStatic; - - class View extends spacePen.View implements Emissary.ISubscriber { - // Subscriber.includeInto(spacePen.View); - - // inherit from Subscriber - subscribeWith(eventEmitter:any, methodName:string, args:any):any; - - addSubscription(subscription:any):any; - - subscribe(eventEmitterOrSubscription:any, ...args:any[]):any; - - subscribeToCommand(eventEmitter:any, ...args:any[]):any; - - unsubscribe(object?:any):any; - } - - class EditorView extends View { - static characterWidthCache:any; - static configDefaults:any; - static nextEditorId:number; - - static content(params:any):void; - - static classes(_arg?:{mini?:any}):string; - - vScrollMargin:number; - hScrollMargin:number; - lineHeight:any; - charWidth:any; - charHeight:any; - cursorViews:any[]; - selectionViews:any[]; - lineCache:any[]; - isFocused:any; - editor:AtomCore.IEditor; - attached:any; - lineOverdraw:number; - pendingChanges:any[]; - newCursors:any[]; - newSelections:any[]; - redrawOnReattach:any; - bottomPaddingInLines:number; - active:boolean; - - id:number; - - gutter:AtomCore.IGutterView; - overlayer:JQuery; - scrollView:JQuery; - renderedLines:JQuery; - underlayer:JQuery; - hiddenInput:JQuery; - verticalScrollbar:JQuery; - verticalScrollbarContent:JQuery; - - constructor(editor:AtomCore.IEditor); - - initialize(editorOrOptions:AtomCore.IEditor):void; // return type are same as editor method. - initialize(editorOrOptions?:{editor: AtomCore.IEditor; mini:any; placeholderText:any}):void; - - initialize(editorOrOptions:{}):void; // compatible for spacePen.View - - bindKeys():void; - - getEditor():AtomCore.IEditor; - - getText():string; - - setText(text:string):void; - - insertText(text:string, options?:any):TextBuffer.IRange[]; - - setHeightInLines(heightInLines:number):number; - - setWidthInChars(widthInChars:number):number; - - pageDown():void; - - pageUp():void; - - getPageRows():number; - - setShowInvisibles(showInvisibles:boolean):void; - - setInvisibles(invisibles:{ eol:string; space: string; tab: string; cr: string; }):void; - - setShowIndentGuide(showIndentGuide:boolean):void; - - setPlaceholderText(placeholderText:string):void; - - getPlaceholderText():string; - - checkoutHead():boolean; - - configure():Emissary.ISubscription; - - handleEvents():void; - - handleInputEvents():void; - - bringHiddenInputIntoView():JQuery; - - selectOnMousemoveUntilMouseup():any; - - afterAttach(onDom:any):any; - - edit(editor:AtomCore.IEditor):any; - - getModel():AtomCore.IEditor; - - setModel(editor:AtomCore.IEditor):any; - - showBufferConflictAlert(editor:AtomCore.IEditor):any; - - scrollTop(scrollTop:number, options?:any):any; - - scrollBottom(scrollBottom?:number):any; - - scrollLeft(scrollLeft?:number):number; - - scrollRight(scrollRight?:number):any; - - scrollToBottom():any; - - scrollToCursorPosition():any; - - scrollToBufferPosition(bufferPosition:any, options:any):any; - - scrollToScreenPosition(screenPosition:any, options:any):any; - - scrollToPixelPosition(pixelPosition:any, options:any):any; - - highlightFoldsContainingBufferRange(bufferRange:any):any; - - saveScrollPositionForEditor():any; - - toggleSoftTabs():any; - - toggleSoftWrap():any; - - calculateWidthInChars():number; - - calculateHeightInLines():number; - - getScrollbarWidth():number; - - setSoftWrap(softWrap:boolean):any; - - setFontSize(fontSize:number):any; - - getFontSize():number; - - setFontFamily(fontFamily?:string):any; - - getFontFamily():string; - - setLineHeight(lineHeight:number):any; - - redraw():any; - - splitLeft():any; - - splitRight():any; - - splitUp():any; - - splitDown():any; - - getPane():any; // return type are PaneView - - remove(selector:any, keepData:any):any; - - beforeRemove():any; - - getCursorView(index?:number):any; // return type are CursorView - - getCursorViews():any[]; // return type are CursorView[] - - addCursorView(cursor:any, options:any):any; // return type are CursorView - - removeCursorView(cursorView:any):any; - - getSelectionView(index?:number):any; // return type are SelectionView - - getSelectionViews():any[]; // return type are SelectionView[] - - addSelectionView(selection:any):any; - - removeSelectionView(selectionView:any):any; - - removeAllCursorAndSelectionViews():any[]; - - appendToLinesView(view:any):any; - - scrollVertically(pixelPosition:any, _arg:any):any; - - scrollHorizontally(pixelPosition:any):any; - - calculateDimensions():number; - - recalculateDimensions():any; - - updateLayerDimensions():any; - - isHidden():boolean; - - clearRenderedLines():void; - - resetDisplay():any; - - requestDisplayUpdate():any; - - updateDisplay(options?:any):any; - - updateCursorViews():any; - - shouldUpdateCursor(cursorView:any):any; - - updateSelectionViews():any[]; - - shouldUpdateSelection(selectionView:any):any; - - syncCursorAnimations():any[]; - - autoscroll(suppressAutoscroll?:any):any[]; - - updatePlaceholderText():any; - - updateRenderedLines(scrollViewWidth:any):any; - - computeSurroundingEmptyLineChanges(change:any):any; - - computeIntactRanges(renderFrom:any, renderTo:any):any; - - truncateIntactRanges(intactRanges:any, renderFrom:any, renderTo:any):any; - - clearDirtyRanges(intactRanges:any):any; - - clearLine(lineElement:any):any; - - fillDirtyRanges(intactRanges:any, renderFrom:any, renderTo:any):any; - - updatePaddingOfRenderedLines():any; - - getFirstVisibleScreenRow():number; - - getLastVisibleScreenRow():number; - - isScreenRowVisible():boolean; - - handleScreenLinesChange(change:any):any; - - buildLineElementForScreenRow(screenRow:any):any; - - buildLineElementsForScreenRows(startRow:any, endRow:any):any; - - htmlForScreenRows(startRow:any, endRow:any):any; - - htmlForScreenLine(screenLine:any, screenRow:any):any; - - buildIndentation(screenRow:any, editor:any):any; - - buildHtmlEndOfLineInvisibles(screenLine:any):any; - - getEndOfLineInvisibles(screenLine:any):any; - - lineElementForScreenRow(screenRow:any):any; - - toggleLineCommentsInSelection():any; - - pixelPositionForBufferPosition(position:any):any; - - pixelPositionForScreenPosition(position:any):any; - - positionLeftForLineAndColumn(lineElement:any, screenRow:any, screenColumn:any):any; - - measureToColumn(lineElement:any, tokenizedLine:any, screenColumn:any):any; - - getCharacterWidthCache(scopes:any, char:any):any; - - setCharacterWidthCache(scopes:any, char:any, val:any):any; - - clearCharacterWidthCache():any; - - pixelOffsetForScreenPosition(position:any):any; - - screenPositionFromMouseEvent(e:any):any; - - highlightCursorLine():any; - - copyPathToClipboard():any; - - buildLineHtml(_arg:any):any; - - updateScopeStack(line:any, scopeStack:any, desiredScopes:any):any; - - pushScope(line:any, scopeStack:any, scope:any):any; - - popScope(line:any, scopeStack:any):any; - - buildEmptyLineHtml(showIndentGuide:any, eolInvisibles:any, htmlEolInvisibles:any, indentation:any, editor:any, mini:any):any; - - replaceSelectedText(replaceFn:(str:string)=>string):any; - - consolidateSelections(e:any):any; - - logCursorScope():any; - - logScreenLines(start:any, end:any):any; - - logRenderedLines():any; - } - - class ScrollView extends View { - // TBD - } - - interface ISelectListItem { - /** e.g. application:about */ - eventName:string; - /** e.g. Application: About */ - eventDescription:string; - } - - class SelectListView extends View { - static content():any; - - maxItems:number; - scheduleTimeout:any; - inputThrottle:number; - cancelling:boolean; - items:any[]; - list:JQuery; - filterEditorView: JQuery; - - previouslyFocusedElement:JQuery; - - initialize():any; - - schedulePopulateList():number; - - setItems(items:any[]):any; - - setError(message?:string):any; - - setLoading(message?:string):any; - - getFilterQuery():string; - - populateList():any; - - getEmptyMessage(itemCount?:any, filteredItemCount?:any):string; - - setMaxItems(maxItems:number):void; - - selectPreviousItemView():any; - - selectNextItemView():any; - - selectItemView(view:any):any; - - scrollToItemView(view:any):any; - - getSelectedItemView():any; - - getSelectedItem():any; - - confirmSelection():any; - - viewForItem(item:any):JQuery|string|HTMLElement|View; // You must override this method! - confirmed(item:any):any; // You must override this method! - getFilterKey():any; - - focusFilterEditor():any; - - storeFocusedElement():any; - - restoreFocus():any; - - cancelled():any; - - cancel():any; - } - - - - var WorkspaceView:AtomCore.IWorkspaceViewStatic; - - var Task:AtomCore.ITaskStatic; - var Workspace:AtomCore.IWorkspaceStatic; -} diff --git a/atom/index.d.ts b/atom/index.d.ts new file mode 100644 index 0000000000..fe243bf33b --- /dev/null +++ b/atom/index.d.ts @@ -0,0 +1,1887 @@ +// Type definitions for Atom +// Project: https://atom.io/ +// Definitions by: vvakame +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// +/// +/// +/// +/// + +// Policy: this definition file only declare element related to `atom`. +// if js file include to another npm package (e.g. "space-pen", "mixto" and "emissary"). +// you should create a separate file. + +// API documentation : https://atom.io/docs/api/v0.106.0/api/docs/README.md.html + +interface Window { + atom: AtomCore.IAtom; + measure(description:string, fn:Function):any; // return fn result + profile(description:string, fn:Function):any; // return fn result +} + +declare namespace AtomCore { + + // https://atom.io/docs/v0.84.0/advanced/view-system + interface IWorkspaceViewStatic { + new ():IWorkspaceView; + version: number; + configDefaults:any; + content():any; + } + + interface Decoration { + destroy(): void; + } + + /** + * Represents a buffer annotation that remains logically stationary even as the buffer changes. This is used + * to represent cursors, folds, snippet targets, misspelled words, any anything else that needs to track a + * logical location in the buffer over time. + */ + interface Marker { + /** + * Destroys the marker, causing it to emit the 'destroyed' event. Once destroyed, a marker cannot be + * restored by undo/redo operations. + */ + destroy(): void; + + /** + * Gets the screen range of the display marker. + */ + getScreenRange(): Range; + } + + interface IWorkspaceView extends View { + // Delegator.includeInto(WorkspaceView); + + // delegate to model property's property + fullScreen:boolean; + + // delegate to model property's method + open(uri:string, options:any):Q.Promise; + openSync(uri:string, options?:any):any; + saveActivePaneItem():any; + saveActivePaneItemAs():any; + saveAll():void; + destroyActivePaneItem():any; + destroyActivePane():any; + increaseFontSize():void; + decreaseFontSize():void; + + // own property & methods + initialize(model:IWorkspace):any; + initialize(view:View, args:any):void; // do not use + model:IWorkspace; + panes: IPaneContainerView; + getModel():IWorkspace; + installShellCommands():any; + handleFocus():any; + afterAttach(onDom?:any):any; + confirmClose():boolean; + updateTitle():any; + setTitle(title:string):any; + getEditorViews():any[]; // atom.EditorView + prependToTop(element:any):any; + appendToTop(element:any):any; + prependToBottom(element:any):any; + appendToBottom(element:any):any; + prependToLeft(element:any):any; + appendToLeft(element:any):any; + prependToRight(element:any):any; + appendToRight(element:any):any; + getActivePaneView():IPaneView; + getActiveView():View; + focusPreviousPaneView():any; + focusNextPaneView():any; + focusPaneViewAbove():any; + focusPaneViewBelow():any; + focusPaneViewOnLeft():any; + focusPaneViewOnRight():any; + eachPaneView(callback:(paneView:IPaneView)=>any):{ off():any; }; + getPaneViews():IPaneView[]; + eachEditorView(callback:(editorView:any /* EditorView */)=>any):{ off():any; }; + beforeRemove():any; + + command(eventName:string, handler:Function):any; + command(eventName:string, selector:Function, handler:Function):any; + command(eventName:string, options:any, handler:Function):any; + command(eventName:string, selector:Function, options:any, handler:Function):any; + + statusBar:StatusBar.IStatusBarView; + } + + interface IPanes { + // TBD + } + + interface IPaneView { + // TBD + } + + interface IPaneContainerView { + // TBD + } + + interface ITreeView { + // TBD + } + + interface IGutterViewStatic { + new(): IGutterView; + content():any; + } + + interface IGutterView extends View { + firstScreenRow:any; + lastScreenRow:any; + initialize():void; + initialize(view:View, args:any):void; // do not use + afterAttach(onDom?:any):any; + beforeRemove():any; + handleMouseEvents(e:JQueryMouseEventObject):any; + getEditorView():any; /* EditorView */ + getEditor():IEditor; + getLineNumberElements():HTMLCollection; + getLineNumberElementsForClass(klass:string):NodeList; + getLineNumberElement(bufferRow:number):NodeList; + addClassToAllLines(klass:string):boolean; + removeClassFromAllLines(klass:string):boolean; + addClassToLine(bufferRow:number, klass:string):boolean; + removeClassFromLine(bufferRow:number, klass:string):boolean; + updateLineNumbers(changes:any[], startScreenRow?:number, endScreenRow?:number):any; + prependLineElements(lineElements:any):void; + appendLineElements(lineElements:any):void; + removeLineElements(numberOfElements:number):void; + buildLineElements(startScreenRow:any, endScreenRow:any):any; + buildLineElementsHtml(startScreenRow:any, endScreenRow:any):any; + updateFoldableClasses(changes:any[]):any; + removeLineHighlights():void; + addLineHighlight(row:number, emptySelection?:boolean):any; + highlightLines():boolean; + } + + interface ICommandRegistry { + add(target: string, commandName: Object, callback?: (event: any) => void): any; // selector:'atom-editor'|'atom-workspace' + findCommands(params: Object): Object[]; + dispatch(selector: any, name:string): void; + } + + interface ICommandPanel { + // TBD + } + + interface IDisplayBufferStatic { + new(_arg?:any):IDisplayBuffer; + } + + interface IDisplayBuffer /* extends Theorist.Model */ { + // Serializable.includeInto(Editor); + + constructor:IDisplayBufferStatic; + + verticalScrollMargin:number; + horizontalScrollMargin:number; + + declaredPropertyValues:any; + tokenizedBuffer: ITokenizedBuffer; + buffer: TextBuffer.ITextBuffer; + charWidthsByScope:any; + markers:{ [index:number]:IDisplayBufferMarker; }; + foldsByMarkerId:any; + maxLineLength:number; + screenLines:ITokenizedLine[]; + rowMap:any; // return type are RowMap + longestScreenRow:number; + subscriptions:Emissary.ISubscription[]; + subscriptionsByObject:any; // return type are WeakMap + behaviors:any; + subscriptionCounts:any; + eventHandlersByEventName:any; + pendingChangeEvent:any; + + softWrap:boolean; + + serializeParams():{id:number; softWrap:boolean; editorWidthInChars: number; scrollTop: number; scrollLeft: number; tokenizedBuffer: any; }; + deserializeParams(params:any):any; + copy():IDisplayBuffer; + updateAllScreenLines():any; + emitChanged(eventProperties:any, refreshMarkers?:boolean):any; + updateWrappedScreenLines():any; + setVisible(visible:any):any; + getVerticalScrollMargin():number; + setVerticalScrollMargin(verticalScrollMargin:number):number; + getHorizontalScrollMargin():number; + setHorizontalScrollMargin(horizontalScrollMargin:number):number; + getHeight():any; + setHeight(height:any):any; + getWidth():any; + setWidth(newWidth:any):any; + getScrollTop():number; + setScrollTop(scrollTop:number):number; + getScrollBottom():number; + setScrollBottom(scrollBottom:number):number; + getScrollLeft():number; + setScrollLeft(scrollLeft:number):number; + getScrollRight():number; + setScrollRight(scrollRight:number):number; + getLineHeight():any; + setLineHeight(lineHeight:any):any; + getDefaultCharWidth():any; + setDefaultCharWidth(defaultCharWidth:any):any; + getScopedCharWidth(scopeNames:any, char:any):any; + getScopedCharWidths(scopeNames:any):any; + setScopedCharWidth(scopeNames:any, char:any, width:any):any; + setScopedCharWidths(scopeNames:any, charWidths:any):any; + clearScopedCharWidths():any; + getScrollHeight():number; + getScrollWidth():number; + getVisibleRowRange():number[]; + intersectsVisibleRowRange(startRow:any, endRow:any):any; + selectionIntersectsVisibleRowRange(selection:any):any; + scrollToScreenRange(screenRange:any):any; + scrollToScreenPosition(screenPosition:any):any; + scrollToBufferPosition(bufferPosition:any):any; + pixelRectForScreenRange(screenRange:TextBuffer.IRange):any; + getTabLength():number; + setTabLength(tabLength:number):any; + setSoftWrap(softWrap:boolean):boolean; + getSoftWrap():boolean; + setEditorWidthInChars(editorWidthInChars:number):any; + getEditorWidthInChars():number; + getSoftWrapColumn():number; + lineForRow(row:number):any; + linesForRows(startRow:number, endRow:number):any; + getLines():any[]; + indentLevelForLine(line:any):any; + bufferRowsForScreenRows(startScreenRow:any, endScreenRow:any):any; + createFold(startRow:number, endRow:number):IFold; + isFoldedAtBufferRow(bufferRow:number):boolean; + isFoldedAtScreenRow(screenRow:number):boolean; + destroyFoldWithId(id:number):any; + unfoldBufferRow(bufferRow:number):any[]; + largestFoldStartingAtBufferRow(bufferRow:number):any; + foldsStartingAtBufferRow(bufferRow:number):any; + largestFoldStartingAtScreenRow(screenRow:any):any; + largestFoldContainingBufferRow(bufferRow:any):any; + outermostFoldsInBufferRowRange(startRow:any, endRow:any):any[]; + foldsContainingBufferRow(bufferRow:any):any[]; + screenRowForBufferRow(bufferRow:number):number; + lastScreenRowForBufferRow(bufferRow:number):number; + bufferRowForScreenRow(screenRow:number):number; + + screenRangeForBufferRange(bufferRange:TextBuffer.IPoint[]):TextBuffer.IRange; + + screenRangeForBufferRange(bufferRange:TextBuffer.IRange):TextBuffer.IRange; + + screenRangeForBufferRange(bufferRange:{start: TextBuffer.IPoint; end: TextBuffer.IPoint}):TextBuffer.IRange; + screenRangeForBufferRange(bufferRange:{start: number[]; end: TextBuffer.IPoint}):TextBuffer.IRange; + screenRangeForBufferRange(bufferRange:{start: {row:number; col:number;}; end: TextBuffer.IPoint}):TextBuffer.IRange; + + screenRangeForBufferRange(bufferRange:{start: TextBuffer.IPoint; end: number[]}):TextBuffer.IRange; + screenRangeForBufferRange(bufferRange:{start: number[]; end: number[]}):TextBuffer.IRange; + screenRangeForBufferRange(bufferRange:{start: {row:number; col:number;}; end: number[]}):TextBuffer.IRange; + + screenRangeForBufferRange(bufferRange:{start: TextBuffer.IPoint; end: {row:number; col:number;}}):TextBuffer.IRange; + screenRangeForBufferRange(bufferRange:{start: number[]; end: {row:number; col:number;}}):TextBuffer.IRange; + screenRangeForBufferRange(bufferRange:{start: {row:number; col:number;}; end: {row:number; col:number;}}):TextBuffer.IRange; + + bufferRangeForScreenRange(screenRange:TextBuffer.IPoint[]):TextBuffer.IRange; + + bufferRangeForScreenRange(screenRange:TextBuffer.IRange):TextBuffer.IRange; + + bufferRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: TextBuffer.IPoint}):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:{start: number[]; end: TextBuffer.IPoint}):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: TextBuffer.IPoint}):TextBuffer.IRange; + + bufferRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: number[]}):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:{start: number[]; end: number[]}):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: number[]}):TextBuffer.IRange; + + bufferRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: {row:number; col:number;}}):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:{start: number[]; end: {row:number; col:number;}}):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: {row:number; col:number;}}):TextBuffer.IRange; + + pixelRangeForScreenRange(screenRange:TextBuffer.IPoint[], clip?:boolean):TextBuffer.IRange; + + pixelRangeForScreenRange(screenRange:TextBuffer.IRange, clip?:boolean):TextBuffer.IRange; + + pixelRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: TextBuffer.IPoint}, clip?:boolean):TextBuffer.IRange; + pixelRangeForScreenRange(screenRange:{start: number[]; end: TextBuffer.IPoint}, clip?:boolean):TextBuffer.IRange; + pixelRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: TextBuffer.IPoint}, clip?:boolean):TextBuffer.IRange; + + pixelRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: number[]}, clip?:boolean):TextBuffer.IRange; + pixelRangeForScreenRange(screenRange:{start: number[]; end: number[]}, clip?:boolean):TextBuffer.IRange; + pixelRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: number[]}, clip?:boolean):TextBuffer.IRange; + + pixelRangeForScreenRange(screenRange:{start: TextBuffer.IPoint; end: {row:number; col:number;}}, clip?:boolean):TextBuffer.IRange; + pixelRangeForScreenRange(screenRange:{start: number[]; end: {row:number; col:number;}}, clip?:boolean):TextBuffer.IRange; + pixelRangeForScreenRange(screenRange:{start: {row:number; col:number;}; end: {row:number; col:number;}}, clip?:boolean):TextBuffer.IRange; + + pixelPositionForScreenPosition(screenPosition:TextBuffer.IPoint, clip?:boolean):TextBuffer.IPoint; + pixelPositionForScreenPosition(screenPosition:number[], clip?:boolean):TextBuffer.IPoint; + pixelPositionForScreenPosition(screenPosition:{row:number; col:number;}, clip?:boolean):TextBuffer.IPoint; + + screenPositionForPixelPosition(pixelPosition:any):TextBuffer.IPoint; + + pixelPositionForBufferPosition(bufferPosition:any):any; + getLineCount():number; + getLastRow():number; + getMaxLineLength():number; + screenPositionForBufferPosition(bufferPosition:any, options:any):any; + bufferPositionForScreenPosition(bufferPosition:any, options:any):any; + scopesForBufferPosition(bufferPosition:any):any; + bufferRangeForScopeAtPosition(selector:any, position:any):any; + tokenForBufferPosition(bufferPosition:any):any; + getGrammar():IGrammar; + setGrammar(grammar:IGrammar):any; + reloadGrammar():any; + clipScreenPosition(screenPosition:any, options:any):any; + findWrapColumn(line:any, softWrapColumn:any):any; + rangeForAllLines():TextBuffer.IRange; + getMarker(id:number):IDisplayBufferMarker; + getMarkers():IDisplayBufferMarker[]; + getMarkerCount():number; + markScreenRange(range:TextBuffer.IRange, ...args:any[]):IDisplayBufferMarker; + markBufferRange(range:TextBuffer.IRange, options?:any):IDisplayBufferMarker; + markScreenPosition(screenPosition:TextBuffer.IPoint, options?:any):IDisplayBufferMarker; + markBufferPosition(bufferPosition:TextBuffer.IPoint, options?:any):IDisplayBufferMarker; + destroyMarker(id:number):any; + findMarker(params?:any):IDisplayBufferMarker; + findMarkers(params?:any):IDisplayBufferMarker[]; + translateToBufferMarkerParams(params?:any):any; + findFoldMarker(attributes:any):IMarker; + findFoldMarkers(attributes:any):IMarker[]; + getFoldMarkerAttributes(attributes?:any):any; + pauseMarkerObservers():any; + resumeMarkerObservers():any; + refreshMarkerScreenPositions():any; + destroy():any; + logLines(start:number, end:number):any[]; + handleTokenizedBufferChange(tokenizedBufferChange:any):any; + updateScreenLines(startBufferRow:any, endBufferRow:any, bufferDelta?:number, options?:any):any; + buildScreenLines(startBufferRow:any, endBufferRow:any):any; + findMaxLineLength(startScreenRow:any, endScreenRow:any, newScreenLines:any):any; + handleBufferMarkersUpdated():any; + handleBufferMarkerCreated(marker:any):any; + createFoldForMarker(maker:any):IFold; + foldForMarker(marker:any):any; + } + + interface IViewRegistry { + getView(selector:any):any; + } + + interface ICursorStatic { + new (arg:{editor:IEditor; marker:IDisplayBufferMarker; id: number;}):ICursor; + } + + interface ScopeDescriptor { + scopes: string[]; + } + + interface ICursor /* extends Theorist.Model */ { + getScopeDescriptor(): ScopeDescriptor; + screenPosition:any; + bufferPosition:any; + goalColumn:any; + visible:boolean; + needsAutoscroll:boolean; + + editor:IEditor; + marker:IDisplayBufferMarker; + id: number; + + destroy():any; + changePosition(options:any, fn:Function):any; + getPixelRect():any; + setScreenPosition(screenPosition:any, options?:any):any; + getScreenPosition():TextBuffer.IPoint; + getScreenRange():TextBuffer.IRange; + setBufferPosition(bufferPosition:any, options?:any):any; + getBufferPosition():TextBuffer.IPoint; + autoscroll():any; + updateVisibility():any; + setVisible(visible:boolean):any; + isVisible():boolean; + wordRegExp(arg?:any):any; + isLastCursor():boolean; + isSurroundedByWhitespace():boolean; + isBetweenWordAndNonWord():boolean; + isInsideWord():boolean; + clearAutoscroll():void; + clearSelection():void; + getScreenRow():number; + getScreenColumn():number; + getBufferRow():number; + getBufferColumn():number; + getCurrentBufferLine():string; + moveUp(rowCount:number, arg?:any):any; + moveDown(rowCount:number, arg?:any):any; + moveLeft(arg?:any):any; + moveRight(arg?:any):any; + moveToTop():any; + moveToBottom():void; + moveToBeginningOfScreenLine():void; + moveToBeginningOfLine():void; + moveToFirstCharacterOfLine():void; + moveToEndOfScreenLine():void; + moveToEndOfLine():void; + moveToBeginningOfWord():void; + moveToEndOfWord():void; + moveToBeginningOfNextWord():void; + moveToPreviousWordBoundary():void; + moveToNextWordBoundary():void; + getBeginningOfCurrentWordBufferPosition(options?:any):TextBuffer.IPoint; + getPreviousWordBoundaryBufferPosition(options?:any):TextBuffer.IPoint; + getMoveNextWordBoundaryBufferPosition(options?:any):TextBuffer.IPoint; + getEndOfCurrentWordBufferPosition(options?:any):TextBuffer.IPoint; + getBeginningOfNextWordBufferPosition(options?:any):TextBuffer.IPoint; + getCurrentWordBufferRange(options?:any):TextBuffer.IPoint; + getCurrentLineBufferRange(options?:any):TextBuffer.IPoint; + getCurrentParagraphBufferRange():any; + getCurrentWordPrefix():string; + isAtBeginningOfLine():boolean; + getIndentLevel():number; + isAtEndOfLine():boolean; + getScopes():string[]; + hasPrecedingCharactersOnLine():boolean; + getMarker(): Marker; + } + + interface ILanguageMode { + // TBD + } + + interface ISelection /* extends Theorist.Model */ { + cursor:ICursor; + marker:IDisplayBufferMarker; + editor:IEditor; + initialScreenRange:any; + wordwise:boolean; + needsAutoscroll:boolean; + retainSelection:boolean; + subscriptionCounts:any; + + destroy():any; + finalize():any; + clearAutoscroll():any; + isEmpty():boolean; + isReversed():boolean; + isSingleScreenLine():boolean; + getScreenRange():TextBuffer.IRange; + setScreenRange(screenRange:any, options:any):any; + getBufferRange():TextBuffer.IRange; + setBufferRange(bufferRange:any, options:any):any; + getBufferRowRange():number[]; + autoscroll():void; + getText():string; + clear():boolean; + selectWord():TextBuffer.IRange; + expandOverWord():any; + selectLine(row?:any):TextBuffer.IRange; + expandOverLine():boolean; + selectToScreenPosition(position:any):any; + selectToBufferPosition(position:any):any; + selectRight():boolean; + selectLeft():boolean; + selectUp(rowCount?:any):boolean; + selectDown(rowCount?:any):boolean; + selectToTop():any; + selectToBottom():any; + selectAll():any; + selectToBeginningOfLine():any; + selectToFirstCharacterOfLine():any; + selectToEndOfLine():any; + selectToBeginningOfWord():any; + selectToEndOfWord():any; + selectToBeginningOfNextWord():any; + selectToPreviousWordBoundary():any; + selectToNextWordBoundary():any; + addSelectionBelow():any; + getGoalBufferRange():any; + addSelectionAbove():any[]; + insertText(text:string, options?:any):any; + normalizeIndents(text:string, indentBasis:number):any; + indent(_arg?:any):any; + indentSelectedRows():TextBuffer.IRange[]; + setIndentationForLine(line:string, indentLevel:number):any; + backspace():any; + backspaceToBeginningOfWord():any; + backspaceToBeginningOfLine():any; + delete():any; + deleteToEndOfWord():any; + deleteSelectedText():any; + deleteLine():any; + joinLines():any; + outdentSelectedRows():any[]; + autoIndentSelectedRows():any; + toggleLineComments():any; + cutToEndOfLine(maintainClipboard:any):any; + cut(maintainClipboard:any):any; + copy(maintainClipboard:any):any; + fold():any; + modifySelection(fn:()=>any):any; + plantTail():any; + intersectsBufferRange(bufferRange:any):any; + intersectsWith(otherSelection:any):any; + merge(otherSelection:any, options:any):any; + compare(otherSelection:any):any; + getRegionRects():any[]; + screenRangeChanged():any; + } + + interface IDecorationParams { + id?: number; + class: string; + type: any /* string or string[] */; + } + + interface IDecorationStatic { + isType(decorationParams:IDecorationParams, type:any /* string or string[] */):boolean; + new (marker:IDisplayBufferMarker, displayBuffer:IDisplayBuffer, params: IDecorationParams): IDecoration; + } + + interface IDecoration extends Emissary.IEmitter { + marker: IDisplayBufferMarker; + displayBuffer: IDisplayBuffer; + params: IDecorationParams + id: number; + flashQueue: any[]; + isDestroyed: boolean; + + destroy():void; + update(newParams:IDecorationParams):void; + getMarker():IDisplayBufferMarker; + getParams():IDecorationParams; + isType(type:string):boolean; + matchesPattern(decorationPattern:{[key:string]:IDecorationParams;}):boolean; + flash(klass:string, duration?:number):void; + consumeNextFlash():any; + } + + interface IEditor { + // Serializable.includeInto(Editor); + // Delegator.includeInto(Editor); + + deserializing:boolean; + callDisplayBufferCreatedHook:boolean; + registerEditor:boolean; + buffer:TextBuffer.ITextBuffer; + languageMode: ILanguageMode; + cursors:ICursor[]; + selections: ISelection[]; + suppressSelectionMerging:boolean; + updateBatchDepth: number; + selectionFlashDuration: number; + softTabs: boolean; + displayBuffer: IDisplayBuffer; + + id:number; + behaviors:any; + declaredPropertyValues: any; + eventHandlersByEventName: any; + eventHandlersByNamespace: any; + lastOpened: number; + subscriptionCounts: any; + subscriptionsByObject: any; /* WeakMap */ + subscriptions: Emissary.ISubscription[]; + destroy():void; + + mini: any; + + serializeParams():{id:number; softTabs:boolean; scrollTop:number; scrollLeft:number; displayBuffer:any;}; + deserializeParams(params:any):any; + subscribeToBuffer():void; + subscribeToDisplayBuffer():void; + getViewClass():any; // return type are EditorView + destroyed():void; + isDestroyed():boolean; + copy():IEditor; + getTitle():string; + getLongTitle():string; + setVisible(visible:boolean):void; + setMini(mini:any):void; + setScrollTop(scrollTop:any):void; + getScrollTop():number; + setScrollLeft(scrollLeft:any):void; + getScrollLeft():number; + setEditorWidthInChars(editorWidthInChars:any):void; + getSoftWrapColumn():number; + getSoftTabs():boolean; + setSoftTabs(softTabs:boolean):void; + getSoftWrap():boolean; + setSoftWrap(softWrap:any):void; + getTabText():string; + getTabLength():number; + setTabLength(tabLength:any):void; + usesSoftTabs():boolean; + clipBufferPosition(bufferPosition:any):void; + clipBufferRange(range:any):void; + indentationForBufferRow(bufferRow:any):void; + setIndentationForBufferRow(bufferRow:any, newLevel:any, _arg:any):void; + indentLevelForLine(line:any):number; + buildIndentString(number:any):string; + save():void; + saveAs(filePath:any):void; + copyPathToClipboard():void; + getPath():string; + getText():string; + setText(text:any):void; + getTextInRange(range:any):any; + getLineCount():number; + getBuffer():TextBuffer.ITextBuffer; + getURI():string; + isBufferRowBlank(bufferRow:any):boolean; + isBufferRowCommented(bufferRow:any):void; + nextNonBlankBufferRow(bufferRow:any):void; + getEofBufferPosition():TextBuffer.IPoint; + getLastBufferRow():number; + bufferRangeForBufferRow(row:any, options:any):TextBuffer.IRange; + lineForBufferRow(row:number):string; + lineLengthForBufferRow(row:number):number; + scan():any; + scanInBufferRange():any; + backwardsScanInBufferRange():any; + isModified():boolean; + isEmpty():boolean; + shouldPromptToSave():boolean; + screenPositionForBufferPosition(bufferPosition:any, options?:any):TextBuffer.IPoint; + bufferPositionForScreenPosition(screenPosition:any, options?:any):TextBuffer.IPoint; + screenRangeForBufferRange(bufferRange:any):TextBuffer.IRange; + bufferRangeForScreenRange(screenRange:any):TextBuffer.IRange; + clipScreenPosition(screenPosition:any, options:any):TextBuffer.IRange; + lineForScreenRow(row:any):ITokenizedLine; + linesForScreenRows(start?:any, end?:any):ITokenizedLine[]; + getScreenLineCount():number; + getMaxScreenLineLength():number; + getLastScreenRow():number; + bufferRowsForScreenRows(startRow:any, endRow:any):any[]; + bufferRowForScreenRow(row:any):number; + scopesForBufferPosition(bufferPosition:any):string[]; + bufferRangeForScopeAtCursor(selector:string):any; + tokenForBufferPosition(bufferPosition:any):IToken; + getCursorScopes():string[]; + logCursorScope():void; + insertText(text:string, options?:any):TextBuffer.IRange[]; + insertNewline():TextBuffer.IRange[]; + insertNewlineBelow():TextBuffer.IRange[]; + insertNewlineAbove():any; + indent(options?:any):any; + backspace():any[]; + // deprecated backspaceToBeginningOfWord():any[]; + // deprecated backspaceToBeginningOfLine():any[]; + deleteToBeginningOfWord():any[]; + deleteToBeginningOfLine():any[]; + delete():any[]; + deleteToEndOfLine():any[]; + deleteToEndOfWord():any[]; + deleteLine():TextBuffer.IRange[]; + indentSelectedRows():TextBuffer.IRange[][]; + outdentSelectedRows():TextBuffer.IRange[][]; + toggleLineCommentsInSelection():TextBuffer.IRange[]; + autoIndentSelectedRows():TextBuffer.IRange[][]; + normalizeTabsInBufferRange(bufferRange:any):any; + cutToEndOfLine():boolean[]; + cutSelectedText():boolean[]; + copySelectedText():boolean[]; + pasteText(options?:any):TextBuffer.IRange[]; + undo():any[]; + redo():any[]; + foldCurrentRow():any; + unfoldCurrentRow():any[]; + foldSelectedLines():any[]; + foldAll():any[]; + unfoldAll():any[]; + foldAllAtIndentLevel(level:any):any; + foldBufferRow(bufferRow:any):any; + unfoldBufferRow(bufferRow:any):any; + isFoldableAtBufferRow(bufferRow:any):boolean; + isFoldableAtScreenRow(screenRow:any):boolean; + createFold(startRow:any, endRow:any):IFold; + destroyFoldWithId(id:any):any; + destroyFoldsIntersectingBufferRange(bufferRange:any):any; + toggleFoldAtBufferRow(bufferRow:any):any; + isFoldedAtCursorRow():boolean; + isFoldedAtBufferRow(bufferRow:any):boolean; + isFoldedAtScreenRow(screenRow:any):boolean; + largestFoldContainingBufferRow(bufferRow:any):boolean; + largestFoldStartingAtScreenRow(screenRow:any):any; + outermostFoldsInBufferRowRange(startRow:any, endRow:any):any[]; + moveLineUp():ISelection[]; + moveLineDown():ISelection[]; + duplicateLines():any[][]; + // duprecated duplicateLine():any[][]; + mutateSelectedText(fn:(selection:ISelection)=>any):any; + replaceSelectedText(options:any, fn:(selection:string)=>any):any; + decorationsForScreenRowRange(startScreenRow:any, endScreenRow:any):{[id:number]: IDecoration[]}; + decorateMarker(marker:IDisplayBufferMarker, decorationParams: {type:string; class: string;}):IDecoration; + decorationForId(id:number):IDecoration; + getMarker(id:number):IDisplayBufferMarker; + getMarkers():IDisplayBufferMarker[]; + findMarkers(...args:any[]):IDisplayBufferMarker[]; + markScreenRange(...args:any[]):IDisplayBufferMarker; + markBufferRange(...args:any[]):IDisplayBufferMarker; + markScreenPosition(...args:any[]):IDisplayBufferMarker; + markBufferPosition(...args:any[]):IDisplayBufferMarker; + destroyMarker(...args:any[]):boolean; + getMarkerCount():number; + hasMultipleCursors():boolean; + getCursors():ICursor[]; + getCursor():ICursor; + addCursorAtScreenPosition(screenPosition:any):ICursor; + addCursorAtBufferPosition(bufferPosition:any):ICursor; + addCursor(marker:any):ICursor; + removeCursor(cursor:any):ICursor[]; + addSelection(marker:any, options:any):ISelection; + addSelectionForBufferRange(bufferRange:any, options:any):ISelection; + setSelectedBufferRange(bufferRange:any, options:any):any; + setSelectedBufferRanges(bufferRanges:any, options:any):any; + removeSelection(selection:ISelection):any; + clearSelections():boolean; + consolidateSelections():boolean; + selectionScreenRangeChanged(selection:any):void; + getSelections():ISelection[]; + getSelection(index?:number):ISelection; + getLastSelection():ISelection; + getSelectionsOrderedByBufferPosition():ISelection[]; + getLastSelectionInBuffer():ISelection; + selectionIntersectsBufferRange(bufferRange:any):any; + setCursorScreenPosition(position:TextBuffer.IPoint, options?:any):any; + getCursorScreenPosition():TextBuffer.IPoint; + getCursorScreenRow():number; + setCursorBufferPosition(position:any, options?:any):any; + getCursorBufferPosition():TextBuffer.IPoint; + getSelectedScreenRange():TextBuffer.IRange; + getSelectedBufferRange():TextBuffer.IRange; + getSelectedBufferRanges():TextBuffer.IRange[]; + getSelectedText():string; + getTextInBufferRange(range:TextBuffer.IRange):string; + setTextInBufferRange(range:TextBuffer.IRange | any[], text:string):any; + getCurrentParagraphBufferRange():TextBuffer.IRange; + getWordUnderCursor(options?:any):string; + moveCursorUp(lineCount?:number):void; + moveCursorDown(lineCount?:number):void; + moveCursorLeft():void; + moveCursorRight():void; + moveCursorToTop():void; + moveCursorToBottom():void; + moveCursorToBeginningOfScreenLine():void; + moveCursorToBeginningOfLine():void; + moveCursorToFirstCharacterOfLine():void; + moveCursorToEndOfScreenLine():void; + moveCursorToEndOfLine():void; + moveCursorToBeginningOfWord():void; + moveCursorToEndOfWord():void; + moveCursorToBeginningOfNextWord():void; + moveCursorToPreviousWordBoundary():void; + moveCursorToNextWordBoundary():void; + moveCursorToBeginningOfNextParagraph():void; + moveCursorToBeginningOfPreviousParagraph():void; + moveToBottom():void; + scrollToCursorPosition(options:any):any; + pageUp():void; + pageDown():void; + selectPageUp():void; + selectPageDown():void; + getRowsPerPage():number; + moveCursors(fn:(cursor:ICursor)=>any):any; + cursorMoved(event:any):void; + selectToScreenPosition(position:TextBuffer.IPoint):any; + selectRight():ISelection[]; + selectLeft():ISelection[]; + selectUp(rowCount?:number):ISelection[]; + selectDown(rowCount?:number):ISelection[]; + selectToTop():ISelection[]; + selectAll():ISelection[]; + selectToBottom():ISelection[]; + selectToBeginningOfLine():ISelection[]; + selectToFirstCharacterOfLine():ISelection[]; + selectToEndOfLine():ISelection[]; + selectToPreviousWordBoundary():ISelection[]; + selectToNextWordBoundary():ISelection[]; + selectLine():ISelection[]; + selectLinesContainingCursors():ISelection[]; + addSelectionBelow():ISelection[]; + addSelectionAbove():ISelection[]; + splitSelectionsIntoLines():any[]; + transpose():TextBuffer.IRange[]; + upperCase():boolean[]; + lowerCase():boolean[]; + joinLines():any[]; + selectToBeginningOfWord():ISelection[]; + selectToEndOfWord():ISelection[]; + selectToBeginningOfNextWord():ISelection[]; + selectWord():ISelection[]; + selectToBeginningOfNextParagraph():ISelection[]; + selectToBeginningOfPreviousParagraph():ISelection[]; + selectMarker(marker:any):any; + mergeCursors():number[]; + expandSelectionsForward():any; + expandSelectionsBackward(fn:(selection:ISelection)=>any):ISelection[]; + finalizeSelections():boolean[]; + mergeIntersectingSelections():any; + preserveCursorPositionOnBufferReload():Emissary.ISubscription; + getGrammar(): IGrammar; + setGrammar(grammer:IGrammar):void; + reloadGrammar():any; + shouldAutoIndent():boolean; + shouldShowInvisibles():boolean; + updateInvisibles():void; + transact(fn:Function):any; + beginTransaction():ITransaction; + commitTransaction():any; + abortTransaction():any[]; + inspect():string; + logScreenLines(start:number, end:number):any[]; + handleTokenization():void; + handleGrammarChange():void; + handleMarkerCreated(marker:any):any; + getSelectionMarkerAttributes():{type: string; editorId: number; invalidate: string; }; + getVerticalScrollMargin():number; + setVerticalScrollMargin(verticalScrollMargin:number):void; + getHorizontalScrollMargin():number; + setHorizontalScrollMargin(horizontalScrollMargin:number):void; + getLineHeightInPixels():number; + setLineHeightInPixels(lineHeightInPixels:number):void; + batchCharacterMeasurement(fn:Function):void; + getScopedCharWidth(scopeNames:any, char:any):any; + setScopedCharWidth(scopeNames:any, char:any, width:any):any; + getScopedCharWidths(scopeNames:any):any; + clearScopedCharWidths():any; + getDefaultCharWidth():number; + setDefaultCharWidth(defaultCharWidth:number):void; + setHeight(height:number):void; + getHeight():number; + getClientHeight():number; + setWidth(width:number):void; + getWidth():number; + getScrollTop():number; + setScrollTop(scrollTop:number):void; + getScrollBottom():number; + setScrollBottom(scrollBottom:number):void; + getScrollLeft():number; + setScrollLeft(scrollLeft:number):void; + getScrollRight():number; + setScrollRight(scrollRight:number):void; + getScrollHeight():number; + getScrollWidth():number; + getVisibleRowRange():number; + intersectsVisibleRowRange(startRow:any, endRow:any):any; + selectionIntersectsVisibleRowRange(selection:any):any; + pixelPositionForScreenPosition(screenPosition:any):any; + pixelPositionForBufferPosition(bufferPosition:any):any; + screenPositionForPixelPosition(pixelPosition:any):any; + pixelRectForScreenRange(screenRange:any):any; + scrollToScreenRange(screenRange:any, options:any):any; + scrollToScreenPosition(screenPosition:any, options:any):any; + scrollToBufferPosition(bufferPosition:any, options:any):any; + horizontallyScrollable():any; + verticallyScrollable():any; + getHorizontalScrollbarHeight():any; + setHorizontalScrollbarHeight(height:any):any; + getVerticalScrollbarWidth():any; + setVerticalScrollbarWidth(width:any):any; + // deprecated joinLine():any; + + onDidChange(callback: Function): Disposable; + onDidDestroy(callback: Function): Disposable; + onDidStopChanging(callback: Function): Disposable; + onDidChangeCursorPosition(callback: Function): Disposable; + onDidSave(callback: (event: { path: string }) => void): Disposable; + + decorateMarker(marker: Marker, options: any): Decoration; + getLastCursor(): ICursor; + } + + interface IGrammar { + bundledPackage: boolean; + emitter: any; + fileTypes: [string]; + firstLineRegex: any; + foldingStopMarker: any; + includedGrammarScopes: [any]; + initialRule: any; + injectionSelector: any; + injections: any; + maxTokensPerLine: Number; + name: string; + packageName: string; + path: string; + rawPatterns: [any]; + rawRepository: any; + registration: Disposable; + registry: any; + repository: Object; + scopeName: string; + // TBD + + } + + interface IPane /* extends Theorist.Model */ { + itemForURI: (uri:string)=>IEditor; + items:any[]; + activeItem:any; + + serializeParams():any; + deserializeParams(params:any):any; + getViewClass():any; // return type are PaneView + isActive():boolean; + isDestroyed():boolean; + focus():void; + blur():void; + activate():void; + getPanes():IPane[]; + getItems():any[]; + getActiveItem():any; + getActiveEditor():any; + itemAtIndex(index:number):any; + activateNextItem():any; + activatePreviousItem():any; + getActiveItemIndex():number; + activateItemAtIndex(index:number):any; + activateItem(item:any):any; + addItem(item:any, index:number):any; + addItems(items:any[], index:number):any[]; + removeItem(item:any, destroying:any):void; + moveItem(item:any, newIndex:number):void; + moveItemToPane(item:any, pane:IPane, index:number):void; + destroyActiveItem():boolean; // always return false + destroyItem(item:any):boolean; + destroyItems():any[]; + destroyInactiveItems():any[]; + destroy():void; + destroyed():any[]; + promptToSaveItem(item:any):boolean; + saveActiveItem():void; + saveActiveItemAs():void; + saveItem(item:any, nextAction:Function):void; + saveItemAs(item:any, nextAction:Function):void; + saveItems():any[]; + activateItemForURI(uri:any):any; + copyActiveItem():void; + splitLeft(params:any):IPane; + splitRight(params:any):IPane; + splitUp(params:any):IPane; + splitDown(params:any):IPane; + split(orientation:string, side:string, params:any):IPane; + findLeftmostSibling():IPane; + findOrCreateRightmostSibling():IPane; + } + + // https://atom.io/docs/v0.84.0/advanced/serialization + interface ISerializationStatic { + deserialize(data:ISerializationInfo):T; + new (data:T): ISerialization; + } + + interface ISerialization { + serialize():ISerializationInfo; + } + + interface ISerializationInfo { + deserializer: string; + } + + interface IBrowserWindow { + getPosition():number[]; + getSize():number[]; + } + + interface IAtomWindowDimentions { + x:number; + y:number; + width:number; + height:number; + } + + interface IProjectStatic { + pathForRepositoryUrl(repoUrl:string):string; + + new (arg?:{path:any; buffers:any[];}):IProject; + } + + interface IProject /* extends Theorist.Model */ { + // Serializable.includeInto(Project); + + path:string; + /** deprecated */ + rootDirectory?:PathWatcher.IDirectory; + rootDirectories:PathWatcher.IDirectory[]; + + serializeParams():any; + deserializeParams(params:any):any; + destroyed():any; + destroyRepo():any; + destroyUnretainedBuffers():any; + getRepo():IGit; + getPath():string; + setPath(projectPath:string):any; + getRootDirectory():PathWatcher.IDirectory; + resolve(uri:string):string; + relativize(fullPath:string):string; + contains(pathToCheck:string):boolean; + open(filePath:string, options?:any):Q.Promise; + openSync(filePath:string, options?:any):IEditor; + getBuffers():TextBuffer.ITextBuffer; + isPathModified(filePath:string):boolean; + findBufferForPath(filePath:string):TextBuffer.ITextBuffer; + bufferForPathSync(filePath:string):TextBuffer.ITextBuffer; + bufferForPath(filePath:string):Q.Promise; + bufferForId(id:any):TextBuffer.ITextBuffer; + buildBufferSync(absoluteFilePath:string):TextBuffer.ITextBuffer; + buildBuffer(absoluteFilePath:string):Q.Promise; + addBuffer(buffer:TextBuffer.ITextBuffer, options?:any):any; + addBufferAtIndex(buffer:TextBuffer.ITextBuffer, index:number, options?:any):any; + scan(regex:any, options:any, iterator:any):Q.Promise; + replace(regex:any, replacementText:any, filePaths:any, iterator:any):Q.Promise; + buildEditorForBuffer(buffer:any, editorOptions:any):IEditor; + eachBuffer(...args:any[]):any; + + onDidChangePaths(callback: Function): Disposable; + } + + interface IWorkspaceStatic { + new():IWorkspace; + } + + interface IWorkspacePanelOptions{ + item:any; + visible?:boolean; + priority?:number; + } + + interface Panel{ + getItem():any; + getPriority():any; + isVisible():boolean; + show():void; + hide():void; + } + + interface IWorkspace { + addBottomPanel(options:IWorkspacePanelOptions):Panel; + addLeftPanel(options:IWorkspacePanelOptions):Panel; + addRightPanel(options:IWorkspacePanelOptions):Panel; + addTopPanel(options:IWorkspacePanelOptions):Panel; + addModalPanel(options:IWorkspacePanelOptions):Panel; + addOpener(opener: Function): any; + + deserializeParams(params:any):any; + serializeParams():{paneContainer:any;fullScreen:boolean;}; + eachEditor(callback: Function): void; + getTextEditors():IEditor[]; + open(uri:string, options:any):Q.Promise; + openLicense():void; + openSync(uri:string, options:any):any; + openUriInPane(uri: string, pane: any, options: any): Q.Promise; + observeTextEditors(callback: Function): Disposable; + reopenItemSync():any; + registerOpener(opener:(urlToOpen:string)=>any):void; + unregisterOpener(opener:Function):void; + getOpeners():any; + getActivePane(): IPane; + getActivePaneItem(): IPane; + getActiveTextEditor(): IEditor; + getPanes():any; + saveAll():void; + activateNextPane():any; + activatePreviousPane():any; + paneForURI: (uri:string) => IPane; + saveActivePaneItem():any; + saveActivePaneItemAs():any; + destroyActivePaneItem():any; + destroyActivePane():any; + getActiveEditor():IEditor; + increaseFontSize():void; + decreaseFontSize():void; + resetFontSize():void; + itemOpened(item:any):void; + onPaneItemDestroyed(item:any):void; + destroyed():void; + isTextEditor(object: any): boolean; + + onDidChangeActivePaneItem(item:any):Disposable; + } + + interface IAtomSettings { + appVersion: string; + bootstrapScript: string; + devMode: boolean; + initialPath: string; + pathToOpen: string; + resourcePath: string; + shellLoadTime: number; + windowState:string; + } + + interface IAtomState { + mode:string; + packageStates:any; + project:any; + syntax:any; + version:number; + windowDimensions:any; + workspace:any; + } + + interface IDeserializerManager { + deserializers:Function; + add:Function; + remove:Function; + deserialize:Function; + get:Function; + } + + interface IConfig { + get(keyPath:string):any; + // TBD + } + + interface IKeymapManager { + defaultTarget:HTMLElement; + // TBD + } + + interface IPackage { + mainModulePath: string; + mainModule: any; + enable(): void; + disable(): void; + isTheme(): boolean; + getType(): string; + getStylesheetType(): string; + load(): IPackage; + reset(): void; + activate(): Q.Promise; + activateNow(): void; + // TBD + } + + interface IPackageManager extends Emissary.IEmitter { + packageDirPaths:string[]; + loadedPackages:any; + activePackages:any; + packageStates:any; + packageActivators:any[]; + + getApmPath():string; + getPackageDirPaths():string; + getPackageState(name:string):any; + setPackageState(name:string, state:any):void; + enablePackage(name:string):any; + disablePackage(name:string):any; + activate():void; + registerPackageActivator(activator:any, types:any):void; + activatePackages(packages:any):void; + activatePackage(name:string):Q.Promise; + deactivatePackages():void; + deactivatePackage(name:string):void; + getActivePackages():any; + getActivePackage(name:string):any; + isPackageActive(name:string):boolean; + unobserveDisabledPackages():void; + observeDisabledPackages():void; + loadPackages():void; + loadPackage(nameOrPath:string):void; + unloadPackages():void; + unloadPackage(name:string):void; + getLoadedPackage(name:string):any; + isPackageLoaded(name:string):boolean; + getLoadedPackages():any; + getLoadedPackagesForTypes(types:any):any[]; + resolvePackagePath(name:string):string; + isPackageDisabled(name:string):boolean; + hasAtomEngine(packagePath:string):boolean; + isBundledPackage(name:string):boolean; + getPackageDependencies():any; + getAvailablePackagePaths():any[]; + getAvailablePackageNames():any[]; + getAvailablePackageMetadata():any[]; + } + + interface INotifications { + addInfo: Function; + addError: Function; + addSuccess: Function; + addWarning: Function; + } + + interface IThemeManager { + // TBD + } + + interface IContextMenuManager { + // TBD + } + + interface IMenuManager { + // TBD + } + + interface IClipboard { + write(text:string, metadata?:any):any; + read():string; + } + + interface ISyntax { + // TBD + } + + interface IWindowEventHandler { + // TBD + } + + interface IAtomStatic extends ISerializationStatic { + version: number; + loadSettings: IAtomSettings; + + /* Load or create the Atom environment in the given mode */ + loadOrCreate(mode:'editor'):IAtom; + /* Load or create the Atom environment in the given mode */ + loadOrCreate(mode:'spec'):IAtom; + /* Load or create the Atom environment in the given mode */ + loadOrCreate(mode:string):IAtom; + + loadState(mode:any):void; + getStatePath(mode:any):string; + getConfigDirPath():string; + getStorageDirPath():string; + getLoadSettings():IAtomSettings; + getCurrentWindow():IBrowserWindow; + getVersion():string; + isReleasedVersion():boolean; + + new(state:IAtomState):IAtom; + } + + class Disposable { + constructor(disposalAction:any) + dispose():void + } + + // https://atom.io/docs/api/v0.106.0/api/classes/Atom.html + /* Global Atom class : instance members */ + interface IAtom { + constructor:IAtomStatic; + + state:IAtomState; + mode:string; + deserializers:IDeserializerManager; + config: IConfig; + commands: ICommandRegistry; + keymaps: IKeymapManager; + keymap: IKeymapManager; + packages: IPackageManager; + themes: IThemeManager; + contextManu: IContextMenuManager; + menu: IMenuManager; + notifications: INotifications; // https://github.com/atom/notifications + clipboard:IClipboard; + syntax:ISyntax; + views: IViewRegistry; + windowEventHandler: IWindowEventHandler; + + // really exists? start + subscribe:Function; + unsubscribe:Function; + loadTime:number; + workspaceViewParentSelector:string; + + project: IProject; + workspaceView: IWorkspaceView; + workspace: IWorkspace; + // really exists? end + + initialize:Function; + // registerRepresentationClass:Function; + // registerRepresentationClasses:Function; + setBodyPlatformClass:Function; + getCurrentWindow():IBrowserWindow; + getWindowDimensions:Function; + setWindowDimensions:Function; + restoreWindowDimensions:Function; + storeWindowDimensions:Function; + getLoadSettings:Function; + deserializeProject: Function; + deserializeWorkspaceView:Function; + deserializePackageStates:Function; + deserializeEditorWindow:Function; + startEditorWindow:Function; + unloadEditorWindow:Function; + loadThemes:Function; + watchThemes:Function; + open:Function; + confirm:Function; + showSaveDialog:Function; + showSaveDialogSync:Function; + openDevTools:Function; + toggleDevTools:Function; + executeJavaScriptInDevTools:Function; + reload:Function; + focus:Function; + show:Function; + hide:Function; + setSize:Function; + setPosition:Function; + center:Function; + displayWindow:Function; + close:Function; + exit:Function; + inDevMode:Function; + inSpecMode:Function; + toggleFullScreen:Function; + setFullScreen:Function; + isFullScreen:Function; + getVersion:Function; + isReleasedVersion:Function; + getGitHubAuthTokenName:Function; + setGitHubAuthToken:Function; + getGitHubAuthToken:Function; + getConfigDirPath:Function; + saveSync:Function; + getWindowLoadTime():number; + crashMainProcess:Function; + crashRenderProcess:Function; + beep:Function; + getUserInitScriptPath:Function; + requireUserInitScript:Function; + requireWithGlobals:Function; + + services: any; // TODO: New services api + } + + interface IBufferedNodeProcessStatic { + new (arg:any):IBufferedNodeProcess; + } + + interface IBufferedNodeProcess extends IBufferedProcess { + } + + interface IBufferedProcessStatic { + new (arg:any):IBufferedProcess; + } + + interface IBufferedProcess { + process:Function; + killed:boolean; + + bufferStream:Function; + kill:Function; + } + + interface IGitStatic { + new(path:any, options:any):IGit; + } + + interface IGit { + } + + interface ITokenizedBuffer { + // TBD + } + + interface ITokenizedLine { + // TBD + } + + interface IToken { + // TBD + } + + interface IFoldStatic { + new (displayBuffer:IDisplayBuffer, marker:IMarker):IFold; + // TBD + } + + interface IFold { + id:number; + displayBuffer:IDisplayBuffer; + marker:IMarker; + + // TBD + } + + interface IDisplayBufferMarkerStatic { + new (_arg:{bufferMarker:IMarker; displayBuffer: IDisplayBuffer}):IDisplayBufferMarker; + } + + interface IDisplayBufferMarker extends Emissary.IEmitter, Emissary.ISubscriber { + constructor:IDisplayBufferMarkerStatic; + + id: number; + + bufferMarkerSubscription:any; + oldHeadBufferPosition:TextBuffer.IPoint; + oldHeadScreenPosition:TextBuffer.IPoint; + oldTailBufferPosition:TextBuffer.IPoint; + oldTailScreenPosition:TextBuffer.IPoint; + wasValid:boolean; + + bufferMarker: IMarker; + displayBuffer: IDisplayBuffer; + globalPauseCount:number; + globalQueuedEvents:any; + + subscriptions:Emissary.ISubscription[]; + subscriptionsByObject:any; // WeakMap + + copy(attributes?:any /* maybe IMarker */):IDisplayBufferMarker; + getScreenRange():TextBuffer.IRange; + setScreenRange(screenRange:any, options:any):any; + getBufferRange():TextBuffer.IRange; + setBufferRange(bufferRange:any, options:any):any; + getPixelRange():any; + getHeadScreenPosition():TextBuffer.IPoint; + setHeadScreenPosition(screenPosition:any, options:any):any; + getHeadBufferPosition():TextBuffer.IPoint; + setHeadBufferPosition(bufferPosition:any):any; + getTailScreenPosition():TextBuffer.IPoint; + setTailScreenPosition(screenPosition:any, options:any):any; + getTailBufferPosition():TextBuffer.IPoint; + setTailBufferPosition(bufferPosition:any):any; + plantTail():boolean; + clearTail():boolean; + hasTail():boolean; + isReversed():boolean; + isValid():boolean; + isDestroyed():boolean; + getAttributes():any; + setAttributes(attributes:any):any; + matchesAttributes(attributes:any):any; + destroy():any; + isEqual(other:IDisplayBufferMarker):boolean; + compare(other:IDisplayBufferMarker):boolean; + inspect():string; + destroyed():any; + notifyObservers(_arg:any):any; + } + + interface ITransaction { + // TBD + } + + interface IMarker extends Emissary.IEmitter { + // Serializable.includeInto(Editor); + // Delegator.includeInto(Editor); + + // TBD + } + + interface ITaskStatic { + new(taskPath:any):ITask; + } + + interface ITask { + // TBD + } +} + +declare var atom:AtomCore.IAtom; + +declare module "atom" { + import spacePen = require("space-pen"); + + var $:typeof spacePen.$; + var $$:typeof spacePen.$$; + var $$$:typeof spacePen.$$$; + + var BufferedNodeProcess:AtomCore.IBufferedNodeProcessStatic; + var BufferedProcess:AtomCore.IBufferedProcessStatic; + var Git:AtomCore.IGitStatic; + var Point:TextBuffer.IPointStatic; + var Range:TextBuffer.IRangeStatic; + + class View extends spacePen.View implements Emissary.ISubscriber { + // Subscriber.includeInto(spacePen.View); + + // inherit from Subscriber + subscribeWith(eventEmitter:any, methodName:string, args:any):any; + + addSubscription(subscription:any):any; + + subscribe(eventEmitterOrSubscription:any, ...args:any[]):any; + + subscribeToCommand(eventEmitter:any, ...args:any[]):any; + + unsubscribe(object?:any):any; + } + + class EditorView extends View { + static characterWidthCache:any; + static configDefaults:any; + static nextEditorId:number; + + static content(params:any):void; + + static classes(_arg?:{mini?:any}):string; + + vScrollMargin:number; + hScrollMargin:number; + lineHeight:any; + charWidth:any; + charHeight:any; + cursorViews:any[]; + selectionViews:any[]; + lineCache:any[]; + isFocused:any; + editor:AtomCore.IEditor; + attached:any; + lineOverdraw:number; + pendingChanges:any[]; + newCursors:any[]; + newSelections:any[]; + redrawOnReattach:any; + bottomPaddingInLines:number; + active:boolean; + + id:number; + + gutter:AtomCore.IGutterView; + overlayer:JQuery; + scrollView:JQuery; + renderedLines:JQuery; + underlayer:JQuery; + hiddenInput:JQuery; + verticalScrollbar:JQuery; + verticalScrollbarContent:JQuery; + + constructor(editor:AtomCore.IEditor); + + initialize(editorOrOptions:AtomCore.IEditor):void; // return type are same as editor method. + initialize(editorOrOptions?:{editor: AtomCore.IEditor; mini:any; placeholderText:any}):void; + + initialize(editorOrOptions:{}):void; // compatible for spacePen.View + + bindKeys():void; + + getEditor():AtomCore.IEditor; + + getText():string; + + setText(text:string):void; + + insertText(text:string, options?:any):TextBuffer.IRange[]; + + setHeightInLines(heightInLines:number):number; + + setWidthInChars(widthInChars:number):number; + + pageDown():void; + + pageUp():void; + + getPageRows():number; + + setShowInvisibles(showInvisibles:boolean):void; + + setInvisibles(invisibles:{ eol:string; space: string; tab: string; cr: string; }):void; + + setShowIndentGuide(showIndentGuide:boolean):void; + + setPlaceholderText(placeholderText:string):void; + + getPlaceholderText():string; + + checkoutHead():boolean; + + configure():Emissary.ISubscription; + + handleEvents():void; + + handleInputEvents():void; + + bringHiddenInputIntoView():JQuery; + + selectOnMousemoveUntilMouseup():any; + + afterAttach(onDom:any):any; + + edit(editor:AtomCore.IEditor):any; + + getModel():AtomCore.IEditor; + + setModel(editor:AtomCore.IEditor):any; + + showBufferConflictAlert(editor:AtomCore.IEditor):any; + + scrollTop(scrollTop:number, options?:any):any; + + scrollBottom(scrollBottom?:number):any; + + scrollLeft(scrollLeft?:number):number; + + scrollRight(scrollRight?:number):any; + + scrollToBottom():any; + + scrollToCursorPosition():any; + + scrollToBufferPosition(bufferPosition:any, options:any):any; + + scrollToScreenPosition(screenPosition:any, options:any):any; + + scrollToPixelPosition(pixelPosition:any, options:any):any; + + highlightFoldsContainingBufferRange(bufferRange:any):any; + + saveScrollPositionForEditor():any; + + toggleSoftTabs():any; + + toggleSoftWrap():any; + + calculateWidthInChars():number; + + calculateHeightInLines():number; + + getScrollbarWidth():number; + + setSoftWrap(softWrap:boolean):any; + + setFontSize(fontSize:number):any; + + getFontSize():number; + + setFontFamily(fontFamily?:string):any; + + getFontFamily():string; + + setLineHeight(lineHeight:number):any; + + redraw():any; + + splitLeft():any; + + splitRight():any; + + splitUp():any; + + splitDown():any; + + getPane():any; // return type are PaneView + + remove(selector:any, keepData:any):any; + + beforeRemove():any; + + getCursorView(index?:number):any; // return type are CursorView + + getCursorViews():any[]; // return type are CursorView[] + + addCursorView(cursor:any, options:any):any; // return type are CursorView + + removeCursorView(cursorView:any):any; + + getSelectionView(index?:number):any; // return type are SelectionView + + getSelectionViews():any[]; // return type are SelectionView[] + + addSelectionView(selection:any):any; + + removeSelectionView(selectionView:any):any; + + removeAllCursorAndSelectionViews():any[]; + + appendToLinesView(view:any):any; + + scrollVertically(pixelPosition:any, _arg:any):any; + + scrollHorizontally(pixelPosition:any):any; + + calculateDimensions():number; + + recalculateDimensions():any; + + updateLayerDimensions():any; + + isHidden():boolean; + + clearRenderedLines():void; + + resetDisplay():any; + + requestDisplayUpdate():any; + + updateDisplay(options?:any):any; + + updateCursorViews():any; + + shouldUpdateCursor(cursorView:any):any; + + updateSelectionViews():any[]; + + shouldUpdateSelection(selectionView:any):any; + + syncCursorAnimations():any[]; + + autoscroll(suppressAutoscroll?:any):any[]; + + updatePlaceholderText():any; + + updateRenderedLines(scrollViewWidth:any):any; + + computeSurroundingEmptyLineChanges(change:any):any; + + computeIntactRanges(renderFrom:any, renderTo:any):any; + + truncateIntactRanges(intactRanges:any, renderFrom:any, renderTo:any):any; + + clearDirtyRanges(intactRanges:any):any; + + clearLine(lineElement:any):any; + + fillDirtyRanges(intactRanges:any, renderFrom:any, renderTo:any):any; + + updatePaddingOfRenderedLines():any; + + getFirstVisibleScreenRow():number; + + getLastVisibleScreenRow():number; + + isScreenRowVisible():boolean; + + handleScreenLinesChange(change:any):any; + + buildLineElementForScreenRow(screenRow:any):any; + + buildLineElementsForScreenRows(startRow:any, endRow:any):any; + + htmlForScreenRows(startRow:any, endRow:any):any; + + htmlForScreenLine(screenLine:any, screenRow:any):any; + + buildIndentation(screenRow:any, editor:any):any; + + buildHtmlEndOfLineInvisibles(screenLine:any):any; + + getEndOfLineInvisibles(screenLine:any):any; + + lineElementForScreenRow(screenRow:any):any; + + toggleLineCommentsInSelection():any; + + pixelPositionForBufferPosition(position:any):any; + + pixelPositionForScreenPosition(position:any):any; + + positionLeftForLineAndColumn(lineElement:any, screenRow:any, screenColumn:any):any; + + measureToColumn(lineElement:any, tokenizedLine:any, screenColumn:any):any; + + getCharacterWidthCache(scopes:any, char:any):any; + + setCharacterWidthCache(scopes:any, char:any, val:any):any; + + clearCharacterWidthCache():any; + + pixelOffsetForScreenPosition(position:any):any; + + screenPositionFromMouseEvent(e:any):any; + + highlightCursorLine():any; + + copyPathToClipboard():any; + + buildLineHtml(_arg:any):any; + + updateScopeStack(line:any, scopeStack:any, desiredScopes:any):any; + + pushScope(line:any, scopeStack:any, scope:any):any; + + popScope(line:any, scopeStack:any):any; + + buildEmptyLineHtml(showIndentGuide:any, eolInvisibles:any, htmlEolInvisibles:any, indentation:any, editor:any, mini:any):any; + + replaceSelectedText(replaceFn:(str:string)=>string):any; + + consolidateSelections(e:any):any; + + logCursorScope():any; + + logScreenLines(start:any, end:any):any; + + logRenderedLines():any; + } + + class ScrollView extends View { + // TBD + } + + interface ISelectListItem { + /** e.g. application:about */ + eventName:string; + /** e.g. Application: About */ + eventDescription:string; + } + + class SelectListView extends View { + static content():any; + + maxItems:number; + scheduleTimeout:any; + inputThrottle:number; + cancelling:boolean; + items:any[]; + list:JQuery; + filterEditorView: JQuery; + + previouslyFocusedElement:JQuery; + + initialize():any; + + schedulePopulateList():number; + + setItems(items:any[]):any; + + setError(message?:string):any; + + setLoading(message?:string):any; + + getFilterQuery():string; + + populateList():any; + + getEmptyMessage(itemCount?:any, filteredItemCount?:any):string; + + setMaxItems(maxItems:number):void; + + selectPreviousItemView():any; + + selectNextItemView():any; + + selectItemView(view:any):any; + + scrollToItemView(view:any):any; + + getSelectedItemView():any; + + getSelectedItem():any; + + confirmSelection():any; + + viewForItem(item:any):JQuery|string|HTMLElement|View; // You must override this method! + confirmed(item:any):any; // You must override this method! + getFilterKey():any; + + focusFilterEditor():any; + + storeFocusedElement():any; + + restoreFocus():any; + + cancelled():any; + + cancel():any; + } + + + + var WorkspaceView:AtomCore.IWorkspaceViewStatic; + + var Task:AtomCore.ITaskStatic; + var Workspace:AtomCore.IWorkspaceStatic; +} diff --git a/atom/tsconfig.json b/atom/tsconfig.json new file mode 100644 index 0000000000..eeea2c90a3 --- /dev/null +++ b/atom/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "atom-tests.ts" + ] +} \ No newline at end of file diff --git a/atpl/atpl-tests.ts b/atpl/atpl-tests.ts index f1751d9015..287c75ed38 100644 --- a/atpl/atpl-tests.ts +++ b/atpl/atpl-tests.ts @@ -1,4 +1,3 @@ -/// import atpl = require('atpl'); diff --git a/atpl/atpl.d.ts b/atpl/atpl.d.ts deleted file mode 100644 index a966a8383f..0000000000 --- a/atpl/atpl.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// Type definitions for atpl -// Project: https://github.com/soywiz/atpl.js -// Definitions by: Carlos Ballesteros Velasco -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// Imported from: https://github.com/soywiz/typescript-node-definitions/atpl.d.ts - -declare module "atpl" { - export function compile(templateString: string, options: any): (context:any) => string; - export function __express(filename: string, options: any, callback: Function): any; - - export function registerExtension(items: any): void; - export function registerTags(items: any): void; - export function registerFunctions(items: any): void; - export function registerFilters(items: any): void; - export function registerTests(items: any): void; - - export function renderFileSync(viewsPath: string, filename: string, parameters: any, cache: boolean ): string; - export function renderFile(viewsPath: string, filename: string, parameters: any, cache: boolean, done: (err: Error, result?: string) => void): void; -} diff --git a/atpl/index.d.ts b/atpl/index.d.ts new file mode 100644 index 0000000000..1a97a957ff --- /dev/null +++ b/atpl/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for atpl +// Project: https://github.com/soywiz/atpl.js +// Definitions by: Carlos Ballesteros Velasco +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/atpl.d.ts + + +export declare function compile(templateString: string, options: any): (context: any) => string; +export declare function __express(filename: string, options: any, callback: Function): any; + +export declare function registerExtension(items: any): void; +export declare function registerTags(items: any): void; +export declare function registerFunctions(items: any): void; +export declare function registerFilters(items: any): void; +export declare function registerTests(items: any): void; + +export declare function renderFileSync(viewsPath: string, filename: string, parameters: any, cache: boolean): string; +export declare function renderFile(viewsPath: string, filename: string, parameters: any, cache: boolean, done: (err: Error, result?: string) => void): void; diff --git a/atpl/tsconfig.json b/atpl/tsconfig.json new file mode 100644 index 0000000000..131c3604ae --- /dev/null +++ b/atpl/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "atpl-tests.ts" + ] +} \ No newline at end of file diff --git a/auth0-angular/auth0-angular-tests.ts b/auth0-angular/auth0-angular-tests.ts index 1abd9fdc3d..f9700c1410 100644 --- a/auth0-angular/auth0-angular-tests.ts +++ b/auth0-angular/auth0-angular-tests.ts @@ -1,4 +1,4 @@ -/// + var authProvider: auth0.angular.IAuth0ServiceProvider; diff --git a/auth0-angular/auth0-angular.d.ts b/auth0-angular/auth0-angular.d.ts deleted file mode 100644 index fef9dbd3ef..0000000000 --- a/auth0-angular/auth0-angular.d.ts +++ /dev/null @@ -1,167 +0,0 @@ -// Type definitions for auth0-angular -// Project: https://github.com/auth0/auth0-angular -// Definitions by: Matt Emory -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace auth0.angular { - - interface IAuth0ClientOptions { - /** - * Login url if you're using ngRoute - */ - loginUrl?: string; - - /** - * Login state if you're using ui-router - */ - loginState?: string; - - /** - * Client identifier of your Auth0 application - */ - clientID: string; - - /** - * Domain of your Auth0 account - */ - domain: string; - - /** - * Use single signon - */ - sso?: boolean; - } - - interface ITokenOptions { - - targetClientId?: string; - api?: string; - } - - interface IAuth0Options { - /** - * Connection name - */ - connection?: string; - - /** - * Username - */ - username?: string; - - /** - * Email address - */ - email?: string; - } - - interface ISuccessCallback { - (profile?: string, idToken?: string, accessToken?: string, state?: string, refreshToken?: string): void; - } - - interface IErrorCallback { - (error: any): void; - } - - interface IAuth0Service { - /** - * Hooks to internal Angular events so that a user will be redirected to the login page if trying to visit a restricted resource - */ - hookEvents(): void; - - /** - * Performs a token delegation request exchanging th ecurrent token for another one. - * @param options Token options - */ - getToken(options?: ITokenOptions): ng.IPromise; - - /** - * Refreshes the Id token - * @param refreshToken Refresh token to use when renewing - */ - refreshIdToken(refreshToken: string): ng.IPromise; - - /** - * Renews the Id Token with the same scopes as the original token - * @param id_token Id Token - */ - renewIdToken(id_token: string): ng.IPromise; - - /** - * Logs in a user, returning tokens and profile information - * @param options Options to bypass displaying the Lock UI - * @param successCallback Callback on successful login - * @param errorCallback Callback on failed login - */ - signin(options?: IAuth0Options, successCallback?: ISuccessCallback, errorCallback?: IErrorCallback): void; - - /** - * Displays Lock in signup mode, and logs the user in immediately after a successful signup. - * @param options Options to bypass displaying the Lock UI - * @param successCallback Callback on successful signup - * @param errorCallback Callback on failed signup - */ - signup(options?: IAuth0Options, successCallback?: ISuccessCallback, errorCallback?: IErrorCallback): void; - - /** - * Performs the "forgot your password" flow. - * @param options Options to bypass displaying the Lock UI - * @param successCallback Callback on successful reset - * @param errorCallback Callback on failed reset - */ - reset(options?: IAuth0Options, successCallback?: ISuccessCallback, errorCallback?: IErrorCallback): void; - - /** - * Validates the user - * @param options Options to bypass displaying the Lock UI - * @param successCallback Callback on successful validation - * @param errorCallback Callback on failed validation - */ - validateUser(options: IAuth0Options, successCallback?: ISuccessCallback, errorCallback?: IErrorCallback): void; - - /** - * Logs the user out locally by deleting their token from local storage. - */ - signout(): void; - - /** - * Reauthenticates the user by using a stored profile and token without going through the login flow. - * @param profile Profile of the user - * @param idToken Id token - * @param accessToken Access token - * @param state State - * @param refreshToken Flag to indicate refreshing the token - */ - authenticate(profile?: any, idToken?: string, accessToken?: string, state?: any, refreshToken?: boolean): ng.IPromise; - - /** - * Gets the user's profile - * @param idToken Id token - */ - getProfile(idToken?: string): ng.IPromise; - - // Properties - - accessToken: string; - idToken: string; - profile: any; - isAuthenticated: boolean; - config: any; - } - - interface IAuth0ServiceProvider { - /** - * Configures the auth service - * @param options Client options passed into Auth0 - */ - init(options: IAuth0ClientOptions): void; - - /** - * @param event Name of the event to handle. - * @param handler Event handler - */ - on(event: string, handler: (...args: any[]) => any): void; - } -} diff --git a/auth0-angular/index.d.ts b/auth0-angular/index.d.ts new file mode 100644 index 0000000000..0ecca371bd --- /dev/null +++ b/auth0-angular/index.d.ts @@ -0,0 +1,167 @@ +// Type definitions for auth0-angular +// Project: https://github.com/auth0/auth0-angular +// Definitions by: Matt Emory +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace auth0.angular { + + interface IAuth0ClientOptions { + /** + * Login url if you're using ngRoute + */ + loginUrl?: string; + + /** + * Login state if you're using ui-router + */ + loginState?: string; + + /** + * Client identifier of your Auth0 application + */ + clientID: string; + + /** + * Domain of your Auth0 account + */ + domain: string; + + /** + * Use single signon + */ + sso?: boolean; + } + + interface ITokenOptions { + + targetClientId?: string; + api?: string; + } + + interface IAuth0Options { + /** + * Connection name + */ + connection?: string; + + /** + * Username + */ + username?: string; + + /** + * Email address + */ + email?: string; + } + + interface ISuccessCallback { + (profile?: string, idToken?: string, accessToken?: string, state?: string, refreshToken?: string): void; + } + + interface IErrorCallback { + (error: any): void; + } + + interface IAuth0Service { + /** + * Hooks to internal Angular events so that a user will be redirected to the login page if trying to visit a restricted resource + */ + hookEvents(): void; + + /** + * Performs a token delegation request exchanging th ecurrent token for another one. + * @param options Token options + */ + getToken(options?: ITokenOptions): ng.IPromise; + + /** + * Refreshes the Id token + * @param refreshToken Refresh token to use when renewing + */ + refreshIdToken(refreshToken: string): ng.IPromise; + + /** + * Renews the Id Token with the same scopes as the original token + * @param id_token Id Token + */ + renewIdToken(id_token: string): ng.IPromise; + + /** + * Logs in a user, returning tokens and profile information + * @param options Options to bypass displaying the Lock UI + * @param successCallback Callback on successful login + * @param errorCallback Callback on failed login + */ + signin(options?: IAuth0Options, successCallback?: ISuccessCallback, errorCallback?: IErrorCallback): void; + + /** + * Displays Lock in signup mode, and logs the user in immediately after a successful signup. + * @param options Options to bypass displaying the Lock UI + * @param successCallback Callback on successful signup + * @param errorCallback Callback on failed signup + */ + signup(options?: IAuth0Options, successCallback?: ISuccessCallback, errorCallback?: IErrorCallback): void; + + /** + * Performs the "forgot your password" flow. + * @param options Options to bypass displaying the Lock UI + * @param successCallback Callback on successful reset + * @param errorCallback Callback on failed reset + */ + reset(options?: IAuth0Options, successCallback?: ISuccessCallback, errorCallback?: IErrorCallback): void; + + /** + * Validates the user + * @param options Options to bypass displaying the Lock UI + * @param successCallback Callback on successful validation + * @param errorCallback Callback on failed validation + */ + validateUser(options: IAuth0Options, successCallback?: ISuccessCallback, errorCallback?: IErrorCallback): void; + + /** + * Logs the user out locally by deleting their token from local storage. + */ + signout(): void; + + /** + * Reauthenticates the user by using a stored profile and token without going through the login flow. + * @param profile Profile of the user + * @param idToken Id token + * @param accessToken Access token + * @param state State + * @param refreshToken Flag to indicate refreshing the token + */ + authenticate(profile?: any, idToken?: string, accessToken?: string, state?: any, refreshToken?: boolean): ng.IPromise; + + /** + * Gets the user's profile + * @param idToken Id token + */ + getProfile(idToken?: string): ng.IPromise; + + // Properties + + accessToken: string; + idToken: string; + profile: any; + isAuthenticated: boolean; + config: any; + } + + interface IAuth0ServiceProvider { + /** + * Configures the auth service + * @param options Client options passed into Auth0 + */ + init(options: IAuth0ClientOptions): void; + + /** + * @param event Name of the event to handle. + * @param handler Event handler + */ + on(event: string, handler: (...args: any[]) => any): void; + } +} diff --git a/auth0-angular/tsconfig.json b/auth0-angular/tsconfig.json new file mode 100644 index 0000000000..2fa462742c --- /dev/null +++ b/auth0-angular/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "auth0-angular-tests.ts" + ] +} \ No newline at end of file diff --git a/auth0.lock/auth0.lock-tests.ts b/auth0-lock/auth0.lock-tests.ts similarity index 79% rename from auth0.lock/auth0.lock-tests.ts rename to auth0-lock/auth0.lock-tests.ts index fd646ee1bb..070ef984df 100644 --- a/auth0.lock/auth0.lock-tests.ts +++ b/auth0-lock/auth0.lock-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + var lock: Auth0LockStatic = new Auth0Lock("dsa7d77dsa7d7", "mine.auth0.com"); diff --git a/auth0-lock/index.d.ts b/auth0-lock/index.d.ts new file mode 100644 index 0000000000..9d95bed3e2 --- /dev/null +++ b/auth0-lock/index.d.ts @@ -0,0 +1,83 @@ +// Type definitions for Auth0Widget.js +// Project: http://auth0.com +// Definitions by: Robert McLaws +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface Auth0LockPopupOptions { + width: number; + height: number; + left: number; + top: number; +} + +interface Auth0LockOptions { + authParams?: any; + callbackURL?: string; + connections?: string[]; + container?: string; + closable?: boolean; + dict?: any; + defaultUserPasswordConnection?: string; + defaultADUsernameFromEmailPrefix?: boolean; + disableResetAction?: boolean; + disableSignupAction?: boolean; + focusInput?: boolean; + forceJSONP?: boolean; + gravatar?: boolean; + integratedWindowsLogin?: boolean; + icon?: string; + loginAfterSignup?: boolean; + popup?: boolean; + popupOptions?: Auth0LockPopupOptions; + rememberLastLogin?: boolean; + resetLink?: string; + responseType?: string; + signupLink?: string; + socialBigButtons?: boolean; + sso?: boolean; + theme?: string; + usernameStyle?: any; +} + +interface Auth0LockConstructorOptions { + cdn?: string; + assetsUrl?: string; + useCordovaSocialPlugins?: boolean; +} + +interface Auth0LockStatic { + new (clientId: string, domain: string, options?: Auth0LockConstructorOptions): Auth0LockStatic; + + show(): void; + show(options: Auth0LockOptions): void; + show(callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; + show(options: Auth0LockOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; + + showSignin(): void; + showSignin(options: Auth0LockOptions): void; + showSignin(callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; + showSignin(options: Auth0LockOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; + + showSignup(): void; + showSignup(options: Auth0LockOptions): void; + showSignup(callback: (error?: Auth0Error) => void) : void; + showSignup(options: Auth0LockOptions, callback: (error?: Auth0Error) => void) : void; + + showReset(): void; + showReset(options: Auth0LockOptions): void; + showReset(callback: (error?: Auth0Error) => void) : void; + showReset(options: Auth0LockOptions, callback: (error?: Auth0Error) => void) : void; + + hide(callback: () => void): void; + logout(callback: () => void): void; + + getClient(): Auth0Static; +} + +declare var Auth0Lock: Auth0LockStatic; + +declare module "auth0-lock" { + export = Auth0Lock; +} diff --git a/auth0-lock/tsconfig.json b/auth0-lock/tsconfig.json new file mode 100644 index 0000000000..d6afa58500 --- /dev/null +++ b/auth0-lock/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "auth0.lock-tests.ts" + ] +} \ No newline at end of file diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts deleted file mode 100644 index 15f767984b..0000000000 --- a/auth0.lock/auth0.lock.d.ts +++ /dev/null @@ -1,83 +0,0 @@ -// Type definitions for Auth0Widget.js -// Project: http://auth0.com -// Definitions by: Robert McLaws -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface Auth0LockPopupOptions { - width: number; - height: number; - left: number; - top: number; -} - -interface Auth0LockOptions { - authParams?: any; - callbackURL?: string; - connections?: string[]; - container?: string; - closable?: boolean; - dict?: any; - defaultUserPasswordConnection?: string; - defaultADUsernameFromEmailPrefix?: boolean; - disableResetAction?: boolean; - disableSignupAction?: boolean; - focusInput?: boolean; - forceJSONP?: boolean; - gravatar?: boolean; - integratedWindowsLogin?: boolean; - icon?: string; - loginAfterSignup?: boolean; - popup?: boolean; - popupOptions?: Auth0LockPopupOptions; - rememberLastLogin?: boolean; - resetLink?: string; - responseType?: string; - signupLink?: string; - socialBigButtons?: boolean; - sso?: boolean; - theme?: string; - usernameStyle?: any; -} - -interface Auth0LockConstructorOptions { - cdn?: string; - assetsUrl?: string; - useCordovaSocialPlugins?: boolean; -} - -interface Auth0LockStatic { - new (clientId: string, domain: string, options?: Auth0LockConstructorOptions): Auth0LockStatic; - - show(): void; - show(options: Auth0LockOptions): void; - show(callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; - show(options: Auth0LockOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; - - showSignin(): void; - showSignin(options: Auth0LockOptions): void; - showSignin(callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; - showSignin(options: Auth0LockOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; - - showSignup(): void; - showSignup(options: Auth0LockOptions): void; - showSignup(callback: (error?: Auth0Error) => void) : void; - showSignup(options: Auth0LockOptions, callback: (error?: Auth0Error) => void) : void; - - showReset(): void; - showReset(options: Auth0LockOptions): void; - showReset(callback: (error?: Auth0Error) => void) : void; - showReset(options: Auth0LockOptions, callback: (error?: Auth0Error) => void) : void; - - hide(callback: () => void): void; - logout(callback: () => void): void; - - getClient(): Auth0Static; -} - -declare var Auth0Lock: Auth0LockStatic; - -declare module "auth0-lock" { - export = Auth0Lock; -} diff --git a/auth0.widget/auth0.widget-tests.ts b/auth0.widget/auth0.widget-tests.ts index 012e9b9769..79f1a2a7a7 100644 --- a/auth0.widget/auth0.widget-tests.ts +++ b/auth0.widget/auth0.widget-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + var widget: Auth0WidgetStatic = new Auth0Widget({ domain: 'mine.auth0.com', diff --git a/auth0.widget/auth0.widget.d.ts b/auth0.widget/auth0.widget.d.ts deleted file mode 100644 index 20694526c3..0000000000 --- a/auth0.widget/auth0.widget.d.ts +++ /dev/null @@ -1,48 +0,0 @@ -// Type definitions for Auth0Widget.js -// Project: http://auth0.com -// Definitions by: Robert McLaws -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - - -interface Auth0WidgetStatic { - new(params: Auth0Constructor): Auth0WidgetStatic; - - getClient(): Auth0Static; - getProfile(token: string, callback: Function): Auth0UserProfile; - parseHash(hash: string): Auth0DecodedHash; - reset(options: Auth0Options, callback?: Function): Auth0WidgetStatic; - signin(options: Auth0Options, widgetLoadedCallback?: Function, popupCallback?: Function): Auth0WidgetStatic; - signup(options: Auth0Options, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): Auth0WidgetStatic; - } - -interface Auth0Constructor extends Auth0ClientOptions { - assetsUrl?: string; - cdn?: string; - dict?: any; - } - -interface Auth0Options { - access_token?: string; - connections?: string[]; - container?: string; - enableReturnUserExperience?: boolean; - extraParameters?: any; - icon?: string; - protocol?: string; - request_id?: string; - scope?: string; - showIcon?: boolean; - showForgot?: boolean; - showSignup?: boolean; - state?: any; - userPwdConnectionName?: string; - username_style?: string; -} - -declare var Auth0Widget: Auth0WidgetStatic; - -declare module "Auth0Widget" { - export = Auth0Widget -} diff --git a/auth0.widget/index.d.ts b/auth0.widget/index.d.ts new file mode 100644 index 0000000000..ed6a2f341b --- /dev/null +++ b/auth0.widget/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for Auth0Widget.js +// Project: http://auth0.com +// Definitions by: Robert McLaws +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +interface Auth0WidgetStatic { + new(params: Auth0Constructor): Auth0WidgetStatic; + + getClient(): Auth0Static; + getProfile(token: string, callback: Function): Auth0UserProfile; + parseHash(hash: string): Auth0DecodedHash; + reset(options: Auth0Options, callback?: Function): Auth0WidgetStatic; + signin(options: Auth0Options, widgetLoadedCallback?: Function, popupCallback?: Function): Auth0WidgetStatic; + signup(options: Auth0Options, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): Auth0WidgetStatic; + } + +interface Auth0Constructor extends Auth0ClientOptions { + assetsUrl?: string; + cdn?: string; + dict?: any; + } + +interface Auth0Options { + access_token?: string; + connections?: string[]; + container?: string; + enableReturnUserExperience?: boolean; + extraParameters?: any; + icon?: string; + protocol?: string; + request_id?: string; + scope?: string; + showIcon?: boolean; + showForgot?: boolean; + showSignup?: boolean; + state?: any; + userPwdConnectionName?: string; + username_style?: string; +} + +declare var Auth0Widget: Auth0WidgetStatic; diff --git a/auth0.widget/tsconfig.json b/auth0.widget/tsconfig.json new file mode 100644 index 0000000000..df978e1482 --- /dev/null +++ b/auth0.widget/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "auth0.widget-tests.ts" + ] +} \ No newline at end of file diff --git a/auth0/auth0-tests.ts b/auth0/auth0-tests.ts index 9cd903b306..7f48274eaf 100644 --- a/auth0/auth0-tests.ts +++ b/auth0/auth0-tests.ts @@ -1,4 +1,4 @@ -/// +/// var auth0 = new Auth0({ domain: 'mine.auth0.com', diff --git a/auth0/auth0.d.ts b/auth0/index.d.ts similarity index 100% rename from auth0/auth0.d.ts rename to auth0/index.d.ts diff --git a/auth0/tsconfig.json b/auth0/tsconfig.json new file mode 100644 index 0000000000..0a16ee2b8f --- /dev/null +++ b/auth0/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "auth0-tests.ts" + ] +} \ No newline at end of file diff --git a/auto-launch/auto-launch-tests.ts b/auto-launch/auto-launch-tests.ts index 24d6aad14a..ae6ace9620 100644 --- a/auto-launch/auto-launch-tests.ts +++ b/auto-launch/auto-launch-tests.ts @@ -1,4 +1,4 @@ -/// + import AutoLaunch = require('auto-launch'); diff --git a/auto-launch/auto-launch.d.ts b/auto-launch/index.d.ts similarity index 100% rename from auto-launch/auto-launch.d.ts rename to auto-launch/index.d.ts diff --git a/auto-launch/tsconfig.json b/auto-launch/tsconfig.json new file mode 100644 index 0000000000..369ba5cc5c --- /dev/null +++ b/auto-launch/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "auto-launch-tests.ts" + ] +} \ No newline at end of file diff --git a/autobahn/autobahn-tests.ts b/autobahn/autobahn-tests.ts index 5cdc4f95c6..141a43547e 100644 --- a/autobahn/autobahn-tests.ts +++ b/autobahn/autobahn-tests.ts @@ -1,5 +1,3 @@ -/// - import autobahn = require("autobahn"); class MyClass { diff --git a/autobahn/autobahn.d.ts b/autobahn/autobahn.d.ts deleted file mode 100644 index 9ca4c562cc..0000000000 --- a/autobahn/autobahn.d.ts +++ /dev/null @@ -1,268 +0,0 @@ -// Type definitions for AutobahnJS v0.9.6 -// Project: http://autobahn.ws/js/ -// Definitions by: Elad Zelingher , Andy Hawkins -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace autobahn { - - export class Session { - id: number; - realm: string; - isOpen: boolean; - features: any; - caller_disclose_me: boolean; - publisher_disclose_me: boolean; - subscriptions: ISubscription[][]; - registrations: IRegistration[]; - - constructor(transport: ITransport, defer: DeferFactory, challenge: OnChallengeHandler); - - join(realm: string, authmethods: string[], authid: string): void; - - leave(reason: string, message: string): void; - - call(procedure: string, args?: any[], kwargs?: any, options?: ICallOptions): When.Promise; - - publish(topic: string, args?: any[], kwargs?: any, options?: IPublishOptions): When.Promise; - - subscribe(topic: string, handler: SubscribeHandler, options?: ISubscribeOptions): When.Promise; - - register(procedure: string, endpoint: RegisterEndpoint, options?: IRegisterOptions): When.Promise; - - unsubscribe(subscription: ISubscription): When.Promise; - - unregister(registration: IRegistration): When.Promise; - - prefix(prefix: string, uri: string): void; - - resolve(curie: string): string; - - onjoin: (roleFeatures: any) => void; - onleave: (reason: string, details: any) => void; - } - - interface IInvocation { - caller?: number; - progress?: boolean; - procedure: string; - } - - class Invocation implements IInvocation { - constructor(caller?: number, progress?: boolean, procedure?: string); - - procedure: string; - } - - interface IEvent { - publication: number; - publisher?: number; - topic: string; - } - - class Event implements IEvent { - constructor(publication?: number, publisher?: string, topic?: string); - - publication: number; - topic: string; - } - - interface IResult { - args: any[]; - kwargs: any; - } - - class Result implements IResult { - constructor(args?: any[], kwargs?: any); - - args: any[]; - kwargs: any; - } - - interface IError { - error: string; - args: any[]; - kwargs: any; - } - - class Error implements IError { - constructor(error?: string, args?: any[], kwargs?: any); - - error: string; - args: any[]; - kwargs: any; - } - - type SubscribeHandler = (args?: any[], kwargs?: any, details?: IEvent) => void; - - interface ISubscription { - topic: string; - handler: SubscribeHandler; - options: ISubscribeOptions; - session: Session; - id: number; - active: boolean; - unsubscribe(): When.Promise; - } - - class Subscription implements ISubscription { - constructor(topic? : string, handler?: SubscribeHandler, options?: ISubscribeOptions, session?: Session, id?: number); - - handler: SubscribeHandler; - - unsubscribe(): When.Promise; - - topic: string; - options: ISubscribeOptions; - session: Session; - id: number; - active: boolean; - } - - type RegisterEndpoint = (args?: any[], kwargs?: any, details?: IInvocation) => void; - - interface IRegistration { - procedure: string; - endpoint: RegisterEndpoint; - options: IRegisterOptions; - session: Session; - id: number; - active: boolean; - unregister(): When.Promise; - } - - class Registration implements IRegistration { - constructor(procedure?: string, endpoint?: RegisterEndpoint, options?: IRegisterOptions, session?: Session, id?: number); - - endpoint: RegisterEndpoint; - - unregister(): When.Promise; - - procedure: string; - options: IRegisterOptions; - session: Session; - id: number; - active: boolean; - } - - interface IPublication { - id: number; - } - - class Publication implements IPublication { - constructor(id: number); - - id: number; - } - - interface ICallOptions { - timeout?: number; - receive_progress?: boolean; - disclose_me?: boolean; - } - - interface IPublishOptions { - exclude?: number[]; - eligible?: number[]; - disclose_me?: Boolean; - } - - interface ISubscribeOptions { - match?: string; - } - - interface IRegisterOptions { - disclose_caller?: boolean; - } - - export class Connection { - constructor(options?: IConnectionOptions); - - open(): void; - - close(reason: string, message: string): void; - - onopen: (session: Session, details: any) => void; - onclose: (reason: string, details: any) => boolean; - } - - interface ITransportDefinition { - url?: string; - protocols?: string[]; - type: string; - } - - type DeferFactory = () => When.Promise; - - type OnChallengeHandler = (session: Session, method: string, extra: any) => When.Promise; - - interface IConnectionOptions { - use_es6_promises?: boolean; - // use explicit deferred factory, e.g. jQuery.Deferred or Q.defer - use_deferred?: DeferFactory; - transports?: ITransportDefinition[]; - retry_if_unreachable?: boolean; - max_retries?: number; - initial_retry_delay?: number; - max_retry_delay?: number; - retry_delay_growth?: number; - retry_delay_jitter?: number; - url?: string; - protocols?: string[]; - onchallenge?: (session: Session, method: string, extra: any) => OnChallengeHandler; - realm?: string; - authmethods?: string[]; - authid?: string; - } - - interface ICloseEventDetails { - wasClean: boolean; - reason: string; - code: number; - } - - interface ITransport { - onopen: () => void; - onmessage: (message: any[]) => void; - onclose: (details: ICloseEventDetails) => void; - - send(message: any[]): void; - close(errorCode: number, reason?: string): void; - } - - interface ITransportFactory { - // constructor(options: any); - type: string; - create(): ITransport; - } - - interface ITransports { - register(name: string, factory: any): void; - isRegistered(name: string): boolean; - get(name: string): any; - list(): string[]; - } - - interface ILog { - debug(...args: any[]): void; - } - - interface IUtil { - assert(condition: boolean, message: string): void; - } - - interface IAuthCra { - derive_key(secret: string, salt: string, iterations: number, keylen: number): string; - sign(key: string, challenge: string): string; - } - - var util: IUtil; - var log: ILog; - var transports: ITransports; - var auth_cra: IAuthCra; -} - -declare module "autobahn" { - export = autobahn; -} diff --git a/autobahn/index.d.ts b/autobahn/index.d.ts new file mode 100644 index 0000000000..29c8217d10 --- /dev/null +++ b/autobahn/index.d.ts @@ -0,0 +1,266 @@ +// Type definitions for AutobahnJS v0.9.6 +// Project: http://autobahn.ws/js/ +// Definitions by: Elad Zelingher , Andy Hawkins +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = autobahn; + +declare namespace autobahn { + + export class Session { + id: number; + realm: string; + isOpen: boolean; + features: any; + caller_disclose_me: boolean; + publisher_disclose_me: boolean; + subscriptions: ISubscription[][]; + registrations: IRegistration[]; + + constructor(transport: ITransport, defer: DeferFactory, challenge: OnChallengeHandler); + + join(realm: string, authmethods: string[], authid: string): void; + + leave(reason: string, message: string): void; + + call(procedure: string, args?: any[], kwargs?: any, options?: ICallOptions): When.Promise; + + publish(topic: string, args?: any[], kwargs?: any, options?: IPublishOptions): When.Promise; + + subscribe(topic: string, handler: SubscribeHandler, options?: ISubscribeOptions): When.Promise; + + register(procedure: string, endpoint: RegisterEndpoint, options?: IRegisterOptions): When.Promise; + + unsubscribe(subscription: ISubscription): When.Promise; + + unregister(registration: IRegistration): When.Promise; + + prefix(prefix: string, uri: string): void; + + resolve(curie: string): string; + + onjoin: (roleFeatures: any) => void; + onleave: (reason: string, details: any) => void; + } + + interface IInvocation { + caller?: number; + progress?: boolean; + procedure: string; + } + + class Invocation implements IInvocation { + constructor(caller?: number, progress?: boolean, procedure?: string); + + procedure: string; + } + + interface IEvent { + publication: number; + publisher?: number; + topic: string; + } + + class Event implements IEvent { + constructor(publication?: number, publisher?: string, topic?: string); + + publication: number; + topic: string; + } + + interface IResult { + args: any[]; + kwargs: any; + } + + class Result implements IResult { + constructor(args?: any[], kwargs?: any); + + args: any[]; + kwargs: any; + } + + interface IError { + error: string; + args: any[]; + kwargs: any; + } + + class Error implements IError { + constructor(error?: string, args?: any[], kwargs?: any); + + error: string; + args: any[]; + kwargs: any; + } + + type SubscribeHandler = (args?: any[], kwargs?: any, details?: IEvent) => void; + + interface ISubscription { + topic: string; + handler: SubscribeHandler; + options: ISubscribeOptions; + session: Session; + id: number; + active: boolean; + unsubscribe(): When.Promise; + } + + class Subscription implements ISubscription { + constructor(topic? : string, handler?: SubscribeHandler, options?: ISubscribeOptions, session?: Session, id?: number); + + handler: SubscribeHandler; + + unsubscribe(): When.Promise; + + topic: string; + options: ISubscribeOptions; + session: Session; + id: number; + active: boolean; + } + + type RegisterEndpoint = (args?: any[], kwargs?: any, details?: IInvocation) => void; + + interface IRegistration { + procedure: string; + endpoint: RegisterEndpoint; + options: IRegisterOptions; + session: Session; + id: number; + active: boolean; + unregister(): When.Promise; + } + + class Registration implements IRegistration { + constructor(procedure?: string, endpoint?: RegisterEndpoint, options?: IRegisterOptions, session?: Session, id?: number); + + endpoint: RegisterEndpoint; + + unregister(): When.Promise; + + procedure: string; + options: IRegisterOptions; + session: Session; + id: number; + active: boolean; + } + + interface IPublication { + id: number; + } + + class Publication implements IPublication { + constructor(id: number); + + id: number; + } + + interface ICallOptions { + timeout?: number; + receive_progress?: boolean; + disclose_me?: boolean; + } + + interface IPublishOptions { + exclude?: number[]; + eligible?: number[]; + disclose_me?: Boolean; + } + + interface ISubscribeOptions { + match?: string; + } + + interface IRegisterOptions { + disclose_caller?: boolean; + } + + export class Connection { + constructor(options?: IConnectionOptions); + + open(): void; + + close(reason: string, message: string): void; + + onopen: (session: Session, details: any) => void; + onclose: (reason: string, details: any) => boolean; + } + + interface ITransportDefinition { + url?: string; + protocols?: string[]; + type: string; + } + + type DeferFactory = () => When.Promise; + + type OnChallengeHandler = (session: Session, method: string, extra: any) => When.Promise; + + interface IConnectionOptions { + use_es6_promises?: boolean; + // use explicit deferred factory, e.g. jQuery.Deferred or Q.defer + use_deferred?: DeferFactory; + transports?: ITransportDefinition[]; + retry_if_unreachable?: boolean; + max_retries?: number; + initial_retry_delay?: number; + max_retry_delay?: number; + retry_delay_growth?: number; + retry_delay_jitter?: number; + url?: string; + protocols?: string[]; + onchallenge?: (session: Session, method: string, extra: any) => OnChallengeHandler; + realm?: string; + authmethods?: string[]; + authid?: string; + } + + interface ICloseEventDetails { + wasClean: boolean; + reason: string; + code: number; + } + + interface ITransport { + onopen: () => void; + onmessage: (message: any[]) => void; + onclose: (details: ICloseEventDetails) => void; + + send(message: any[]): void; + close(errorCode: number, reason?: string): void; + } + + interface ITransportFactory { + // constructor(options: any); + type: string; + create(): ITransport; + } + + interface ITransports { + register(name: string, factory: any): void; + isRegistered(name: string): boolean; + get(name: string): any; + list(): string[]; + } + + interface ILog { + debug(...args: any[]): void; + } + + interface IUtil { + assert(condition: boolean, message: string): void; + } + + interface IAuthCra { + derive_key(secret: string, salt: string, iterations: number, keylen: number): string; + sign(key: string, challenge: string): string; + } + + var util: IUtil; + var log: ILog; + var transports: ITransports; + var auth_cra: IAuthCra; +} diff --git a/autobahn/tsconfig.json b/autobahn/tsconfig.json new file mode 100644 index 0000000000..f7e6072fce --- /dev/null +++ b/autobahn/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "autobahn-tests.ts" + ] +} \ No newline at end of file diff --git a/autolinker/autolinker-tests.ts b/autolinker/autolinker-tests.ts index c25bedbbc4..afd7e1d629 100644 --- a/autolinker/autolinker-tests.ts +++ b/autolinker/autolinker-tests.ts @@ -1,5 +1,3 @@ -/// - import AutolinkerCJS = require('autolinker'); () => { diff --git a/autolinker/autolinker.d.ts b/autolinker/index.d.ts similarity index 100% rename from autolinker/autolinker.d.ts rename to autolinker/index.d.ts diff --git a/autolinker/tsconfig.json b/autolinker/tsconfig.json new file mode 100644 index 0000000000..be87717ae2 --- /dev/null +++ b/autolinker/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "autolinker-tests.ts" + ] +} \ No newline at end of file diff --git a/autoprefixer-core/autoprefixer-core-tests.ts b/autoprefixer-core/autoprefixer-core-tests.ts index 9ff4e7695f..906514e9c9 100644 --- a/autoprefixer-core/autoprefixer-core-tests.ts +++ b/autoprefixer-core/autoprefixer-core-tests.ts @@ -1,4 +1,4 @@ -/// + import autoprefixer = require("autoprefixer-core"); var css: string; diff --git a/autoprefixer-core/autoprefixer-core.d.ts b/autoprefixer-core/autoprefixer-core.d.ts deleted file mode 100644 index 2463880441..0000000000 --- a/autoprefixer-core/autoprefixer-core.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Type definitions for Autoprefixer Core 5.1.11 -// Project: https://github.com/postcss/autoprefixer-core -// Definitions by: Asana -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "autoprefixer-core" { - interface Config { - browsers?: string[]; - cascade?: boolean; - remove?: boolean; - } - - interface Options { - from?: string; - to?: string; - safe?: boolean; - map?: { - inline?: boolean; - prev?: string | Object; - } - } - - interface Result { - css: string; - map: string; - opts: Options; - } - - interface Processor { - postcss: any; - info(): string; - process(css: string, opts?: Options): Result; - } - - interface Exports { - (config: Config): Processor; - postcss: any; - info(): string; - process(css: string, opts?: Options): Result; - } - - var exports: Exports; - export = exports; -} diff --git a/autoprefixer-core/index.d.ts b/autoprefixer-core/index.d.ts new file mode 100644 index 0000000000..1b04092a71 --- /dev/null +++ b/autoprefixer-core/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for Autoprefixer Core 5.1.11 +// Project: https://github.com/postcss/autoprefixer-core +// Definitions by: Asana +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +interface Config { + browsers?: string[]; + cascade?: boolean; + remove?: boolean; +} + +interface Options { + from?: string; + to?: string; + safe?: boolean; + map?: { + inline?: boolean; + prev?: string | Object; + } +} + +interface Result { + css: string; + map: string; + opts: Options; +} + +interface Processor { + postcss: any; + info(): string; + process(css: string, opts?: Options): Result; +} + +interface Exports { + (config: Config): Processor; + postcss: any; + info(): string; + process(css: string, opts?: Options): Result; +} + +declare var exports: Exports; +export = exports; diff --git a/autoprefixer-core/tsconfig.json b/autoprefixer-core/tsconfig.json new file mode 100644 index 0000000000..c66535de52 --- /dev/null +++ b/autoprefixer-core/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "autoprefixer-core-tests.ts" + ] +} \ No newline at end of file diff --git a/aws-sdk/aws-sdk-tests.ts b/aws-sdk/aws-sdk-tests.ts index 7411beb930..7ec672ae4b 100644 --- a/aws-sdk/aws-sdk-tests.ts +++ b/aws-sdk/aws-sdk-tests.ts @@ -1,4 +1,3 @@ -/// import AWS = require('aws-sdk'); diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts deleted file mode 100644 index eb54a5991d..0000000000 --- a/aws-sdk/aws-sdk.d.ts +++ /dev/null @@ -1,1197 +0,0 @@ -// Type definitions for aws-sdk -// Project: https://github.com/aws/aws-sdk-js -// Definitions by: midknight41 -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// Imported from: https://github.com/soywiz/typescript-node-definitions/aws-sdk.d.ts - -/// - -declare module "aws-sdk" { - - export var config: ClientConfig; - - export function Config(json: any): void; - - export class Credentials { - constructor(accessKeyId: string, secretAccessKey: string, sessionToken?: string); - accessKeyId: string; - } - - export interface Logger { - write?: (chunk: any, encoding?: string, callback?: () => void) => void; - log?: (...messages: any[]) => void; - } - - export interface HttpOptions { - proxy?: string; - agent?: any; - timeout?: number; - xhrAsync?: boolean; - xhrWithCredentials?: boolean; - } - - export class Endpoint { - constructor(endpoint:string); - - host:string; - hostname:string; - href:string; - port:number; - protocol:string; - } - - export interface Services { - autoscaling?: any; - cloudformation?: any; - cloudfront?: any; - cloudsearch?: any; - cloudsearchdomain?: any; - cloudtrail?: any; - cloudwatch?: any; - cloudwatchlogs?: any; - cognitoidentity?: any; - cognitosync?: any; - datapipeline?: any; - directconnect?: any; - dynamodb?: any; - ec2?: any; - ecs?: any; - elasticache?: any; - elasticbeanstalk?: any; - elastictranscoder?: any; - elb?: any; - emr?: any; - glacier?: any; - httpOptions?: HttpOptions; - iam?: any; - importexport?: any; - kinesis?: any; - opsworks?: any; - rds?: any; - redshift?: any; - route53?: any; - route53domains?: any; - s3?: any; - ses?: any; - simpledb?: any; - sns?: any; - sqs?: any; - storagegateway?: any; - sts?: any; - support?: any; - swf?: any; - } - - export interface ClientConfigPartial extends Services { - credentials?: Credentials; - region?: string; - computeChecksums?: boolean; - convertResponseTypes?: boolean; - logger?: Logger; - maxRedirects?: number; - maxRetries?: number; - paramValidation?: boolean; - s3ForcePathStyle?: boolean; - apiVersion?: any; - apiVersions?: Services; - signatureVersion?: string; - sslEnabled?: boolean; - systemClockOffset?: number; - } - - export interface ClientConfig extends ClientConfigPartial { - update?: (options: ClientConfigPartial, allUnknownKeys?: boolean) => void; - getCredentials?: (callback: (err?: any) => void) => void ; - loadFromPath?: (path: string) => void; - credentials: Credentials; - region: string; - } - - export class SQS { - constructor(options?: any); - endpoint:Endpoint; - - addPermission(params: SQS.AddPermissionParams, callback: (err:Error, data:any) => void): void; - changeMessageVisibility(params: SQS.ChangeMessageVisibilityParams, callback: (err:Error, data:any) => void): void; - changeMessageVisibilityBatch(params: SQS.ChangeMessageVisibilityBatchParams, callback: (err:Error, data:SQS.ChangeMessageVisibilityBatchResponse) => void): void; - createQueue(params: SQS.CreateQueueParams, callback: (err: Error, data: SQS.CreateQueueResult) => void): void; - deleteMessage(params: SQS.DeleteMessageParams, callback: (err: Error, data: any) => void): void; - deleteMessageBatch(params: SQS.DeleteMessageBatchParams, callback: (err: Error, data: SQS.DeleteMessageBatchResult) => void): void; - deleteQueue(params: { QueueUrl: string; }, callback: (err: Error, data: any) => void): void; - getQueueAttributes(params: SQS.GetQueueAttributesParams, callback: (err: Error, data: SQS.GetQueueAttributesResult) => void): void; - getQueueUrl(params: SQS.GetQueueUrlParams, callback: (err: Error, data: { QueueUrl: string; }) => void): void; - listDeadLetterSourceQueues(params: {QueueUrl:string}, callback: (err: Error, data: {queueUrls: string[]}) => void): void; - listQueues(params: {QueueNamePrefix?:string}, callback: (err: Error, data: {QueueUrls: string[]}) => void): void; - purgeQueue(params: {QueueUrl: string}, callback: (err: Error, data: any) => void): void; - receiveMessage(params: SQS.ReceiveMessageParams, callback: (err: Error, data: SQS.ReceiveMessageResult) => void): void; - removePermission(params: {QueueUrl: string, Label: string}, callback: (err: Error, data: any) => void): void; - sendMessage(params: SQS.SendMessageParams, callback: (err: Error, data: SQS.SendMessageResult) => void): void; - sendMessageBatch(params: SQS.SendMessageBatchParams, callback: (err: Error, data: SQS.SendMessageBatchResult) => void): void; - setQueueAttributes(params: SQS.SetQueueAttributesParams, callback: (err: Error, data: any) => void): void; - } - - export class SES { - constructor(options?: any); - public client: Ses.Client; - } - - export class SNS { - constructor(options?: any); - public client: Sns.Client; - } - - export class SimpleWorkflow { - constructor(options?: any); - public client: Swf.Client; - } - - export class S3 { - constructor(options?: any); - putObject(params: s3.PutObjectRequest, callback: (err: any, data: any) => void): void; - getObject(params: s3.GetObjectRequest, callback: (err: any, data: any) => void): void; - } - - export class ECS { - constructor(options?: any); - - createService(params: ecs.CreateServicesParams, callback: (err: any, data: any) => void): void; - describeServices(params: ecs.DescribeServicesParams, callback: (err: any, data: any) => void): void; - describeTaskDefinition(params: ecs.DescribeTaskDefinitionParams, callback: (err: any, data: any) => void): void; - registerTaskDefinition(params: ecs.RegisterTaskDefinitionParams, callback: (err: any, data: any) => void): void; - updateService(params: ecs.UpdateServiceParams, callback: (err: any, data: any) => void): void; - } - - export class DynamoDB { - constructor(options?: any); - } - - export module DynamoDB { - export class DocumentClient { - constructor(options?: any); - } - } - - export module SQS { - - export interface SqsOptions { - params?: any; - endpoint?: string; - accessKeyId?: string; - secretAccessKey?: string; - sessionToken?: Credentials; - credentials?: Credentials; - credentialProvider?: any; - region?: string; - maxRetries?: number; - maxRedirects?: number; - sslEnabled?: boolean; - paramValidation?: boolean; - computeChecksums?: boolean; - convertResponseTypes?: boolean; - correctClockSkew?: boolean; - s3ForcePathStyle?: boolean; - s3BucketEndpoint?: boolean; - httpOptions?: HttpOptions; - apiVersion?: string; - apiVersions?: { [serviceName:string]: string}; - logger?: Logger; - systemClockOffset?: number; - signatureVersion?: string; - signatureCache?: boolean; - } - - export interface AddPermissionParams { - QueueUrl: string; - Label: string; - AWSAccountIds:string[]; - Actions:string[]; - } - - export interface ChangeMessageVisibilityParams { - QueueUrl: string, - ReceiptHandle: string, - VisibilityTimeout: number - } - - export interface ChangeMessageVisibilityBatchParams { - QueueUrl: string, - Entries: { Id: string; ReceiptHandle: string; VisibilityTimeout?: number; }[] - } - - export interface ChangeMessageVisibilityBatchResponse { - Successful: { Id:string }[]; - Failed: BatchResultErrorEntry[]; - } - - export interface SendMessageParams { - QueueUrl: string; - MessageBody: string; - DelaySeconds?: number; - MessageAttributes?: { [name:string]: MessageAttribute; } - } - - export interface ReceiveMessageParams { - QueueUrl: string; - MaxNumberOfMessages?: number; - VisibilityTimeout?: number; - AttributeNames?: string[]; - MessageAttributeNames?: string[]; - WaitTimeSeconds?:number; - } - - export interface DeleteMessageBatchParams { - QueueUrl: string; - Entries: DeleteMessageBatchRequestEntry[]; - } - - export interface DeleteMessageBatchRequestEntry { - Id: string; - ReceiptHandle: string; - } - - export interface DeleteMessageParams { - QueueUrl: string; - ReceiptHandle: string; - } - - export interface SendMessageBatchParams { - QueueUrl: string; - Entries: SendMessageBatchRequestEntry[]; - } - - export interface SendMessageBatchRequestEntry { - Id: string; - MessageBody: string; - DelaySeconds?: number; - MessageAttributes?: { [name:string]: MessageAttribute; } - } - - export interface CreateQueueParams { - QueueName: string; - Attributes: QueueAttributes; - } - - export interface QueueAttributes { - [name:string]: any; - DelaySeconds?: number; - MaximumMessageSize?: number; - MessageRetentionPeriod?: number; - Policy?: any; - ReceiveMessageWaitTimeSeconds?: number; - VisibilityTimeout?: number; - RedrivePolicy?: any; - } - - export interface GetQueueAttributesParams { - QueueUrl: string; - AttributeNames: string[]; - } - - export interface GetQueueAttributesResult { - Attributes: {[name:string]: string}; - } - - export interface GetQueueUrlParams { - QueueName: string; - QueueOwnerAWSAccountId?: string; - } - - export interface SendMessageResult { - MessageId: string; - MD5OfMessageBody: string; - MD5OfMessageAttributes: string; - } - - export interface ReceiveMessageResult { - Messages: Message[]; - } - - export interface Message { - MessageId: string; - ReceiptHandle: string; - MD5OfBody: string; - Body: string; - Attributes: { [name:string]:any }; - MD5OfMessageAttributes:string; - MessageAttributes: { [name:string]: MessageAttribute; } - } - - export interface MessageAttribute { - StringValue?: string; - BinaryValue?: any; //(Buffer, Typed Array, Blob, String) - StringListValues?: string[]; - BinaryListValues?: any[]; - DataType: string; - } - - export interface DeleteMessageBatchResult { - Successful: DeleteMessageBatchResultEntry[]; - Failed: BatchResultErrorEntry[]; - } - - export interface DeleteMessageBatchResultEntry { - Id: string; - } - - export interface BatchResultErrorEntry { - Id: string; - Code: string; - Message?: string; - SenderFault: boolean; - } - - export interface SendMessageBatchResult { - Successful: SendMessageBatchResultEntry[]; - Failed: BatchResultErrorEntry[]; - } - - export interface SendMessageBatchResultEntry { - Id: string; - MessageId: string; - MD5OfMessageBody: string; - MD5OfMessageAttributes:string; - } - - export interface CreateQueueResult { - QueueUrl: string; - } - - export interface SetQueueAttributesParams { - QueueUrl: string; - Attributes: QueueAttributes; - } - - } - - export module Ses { - - export interface Client { - config: ClientConfig; - - sendEmail(params: any, callback: (err: any, data: SendEmailResult) => void): void; - } - - export interface SendEmailRequest { - Source: string; - Destination: Destination; - Message: Message; - ReplyToAddresses: string[]; - ReturnPath: string; - } - - export class Destination { - ToAddresses: string[]; - CcAddresses: string[]; - BccAddresses: string[]; - } - - export class Message { - Subject: Content; - Body: Body; - } - - export class Content { - Data: string; - Charset: string; - } - - export class Body { - Text: Content; - Html: Content; - } - - export class SendEmailResult { - MessageId: string; - } - - } - - export module Swf { - - export class Client { - //constructor(options?: any); - public config: ClientConfig; - - countClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - countOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - countPendingActivityTasks(params: any, callback: (err: any, data: any) => void): void; - countPendingDecisionTasks(params: any, callback: (err: any, data: any) => void): void; - deprecateActivityType(params: any, callback: (err: any, data: any) => void): void; - deprecateDomain(params: any, callback: (err: any, data: any) => void): void; - deprecateWorkflowType(params: any, callback: (err: any, data: any) => void): void; - describeActivityType(params: any, callback: (err: any, data: any) => void): void; - describeDomain(params: any, callback: (err: any, data: any) => void): void; - describeWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - describeWorkflowType(params: any, callback: (err: any, data: any) => void): void; - getWorkflowExecutionHistory(params: any, callback: (err: any, data: any) => void): void; - listActivityTypes(params: any, callback: (err: any, data: any) => void): void; - listClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - listDomains(params: any, callback: (err: any, data: any) => void): void; - listOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - listWorkflowTypes(params: any, callback: (err: any, data: any) => void): void; - pollForActivityTask(params: any, callback: (err: any, data: ActivityTask) => void): void; - pollForDecisionTask(params: any, callback: (err: any, data: DecisionTask) => void): void; - recordActivityTaskHeartbeat(params: any, callback: (err: any, data: any) => void): void; - registerActivityType(params: any, callback: (err: any, data: any) => void): void; - registerDomain(params: any, callback: (err: any, data: any) => void): void; - registerWorkflowType(params: any, callback: (err: any, data: any) => void): void; - requestCancelWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - respondActivityTaskCanceled(params: RespondActivityTaskCanceledRequest, callback: (err: any, data: any) => void): void; - respondActivityTaskCompleted(params: RespondActivityTaskCompletedRequest, callback: (err: any, data: any) => void): void; - respondActivityTaskFailed(params: RespondActivityTaskFailedRequest, callback: (err: any, data: any) => void): void; - respondDecisionTaskCompleted(params: RespondDecisionTaskCompletedRequest, callback: (err: any, data: any) => void): void; - signalWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - startWorkflowExecution(params: any, callback: (err: any, data: StartWorkflowExecutionResult) => void): void; - terminateWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - } - - export interface PollForActivityTaskRequest { - domain?: string; - taskList?: TaskList; - identity?: string; - } - - export interface TaskList { - name?: string; - } - - export interface PollForDecisionTaskRequest { - domain?: string; - taskList?: TaskList; - identity?: string; - nextPageToken?: string; - maximumPageSize?: number; - reverseOrder?: Boolean; - } - - export interface StartWorkflowExecutionRequest { - domain?: string; - workflowId?: string; - workflowType?: WorkflowType; - taskList?: TaskList; - input?: string; - executionStartToCloseTimeout?: string; - tagList?: string[]; - taskStartToCloseTimeout?: string; - childPolicy?: string; - } - - export interface WorkflowType { - name?: string; - version?: string; - } - - export interface RespondDecisionTaskCompletedRequest { - taskToken?: string; - decisions?: Decision[]; - executionContext?: string; - } - - export interface Decision { - decisionType?: string; - scheduleActivityTaskDecisionAttributes?: ScheduleActivityTaskDecisionAttributes; - requestCancelActivityTaskDecisionAttributes?: RequestCancelActivityTaskDecisionAttributes; - completeWorkflowExecutionDecisionAttributes?: CompleteWorkflowExecutionDecisionAttributes; - failWorkflowExecutionDecisionAttributes?: FailWorkflowExecutionDecisionAttributes; - cancelWorkflowExecutionDecisionAttributes?: CancelWorkflowExecutionDecisionAttributes; - continueAsNewWorkflowExecutionDecisionAttributes?: ContinueAsNewWorkflowExecutionDecisionAttributes; - recordMarkerDecisionAttributes?: RecordMarkerDecisionAttributes; - startTimerDecisionAttributes?: StartTimerDecisionAttributes; - cancelTimerDecisionAttributes?: CancelTimerDecisionAttributes; - signalExternalWorkflowExecutionDecisionAttributes?: SignalExternalWorkflowExecutionDecisionAttributes; - requestCancelExternalWorkflowExecutionDecisionAttributes?: RequestCancelExternalWorkflowExecutionDecisionAttributes; - startChildWorkflowExecutionDecisionAttributes?: StartChildWorkflowExecutionDecisionAttributes; - } - - export interface ScheduleActivityTaskDecisionAttributes { - activityType?: ActivityType; - activityId?: string; - control?: string; - input?: string; - scheduleToCloseTimeout?: string; - taskList?: TaskList; - scheduleToStartTimeout?: string; - startToCloseTimeout?: string; - heartbeatTimeout?: string; - } - - export interface ActivityType { - name?: string; - version?: string; - } - - export interface RequestCancelActivityTaskDecisionAttributes { - activityId?: string; - } - - export interface CompleteWorkflowExecutionDecisionAttributes { - result?: string; - } - - export interface FailWorkflowExecutionDecisionAttributes { - reason?: string; - details?: string; - } - - export interface CancelWorkflowExecutionDecisionAttributes { - details?: string; - } - - export interface ContinueAsNewWorkflowExecutionDecisionAttributes { - input?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - taskStartToCloseTimeout?: string; - childPolicy?: string; - tagList?: string[]; - workflowTypeVersion?: string; - } - - export interface RecordMarkerDecisionAttributes { - markerName?: string; - details?: string; - } - - export interface StartTimerDecisionAttributes { - timerId?: string; - control?: string; - startToFireTimeout?: string; - } - - export interface CancelTimerDecisionAttributes { - timerId?: string; - } - - export interface SignalExternalWorkflowExecutionDecisionAttributes { - workflowId?: string; - runId?: string; - signalName?: string; - input?: string; - control?: string; - } - - export interface RequestCancelExternalWorkflowExecutionDecisionAttributes { - workflowId?: string; - runId?: string; - control?: string; - } - - export interface StartChildWorkflowExecutionDecisionAttributes { - workflowType?: WorkflowType; - workflowId?: string; - control?: string; - input?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - taskStartToCloseTimeout?: string; - childPolicy?: string; - tagList?: string[]; - } - - export interface RespondActivityTaskCompletedRequest { - taskToken?: string; - result?: string; - } - - export interface RespondActivityTaskFailedRequest { - taskToken?: string; - reason?: string; - details?: string; - } - - export interface RespondActivityTaskCanceledRequest { - taskToken?: string; - details?: string; - } - - export interface DecisionTask { - taskToken?: string; - startedEventId?: number; - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - events?: HistoryEvent[]; - nextPageToken?: string; - previousStartedEventId?: number; - } - - export interface WorkflowExecution { - workflowId?: string; - runId?: string; - } - - export interface HistoryEvent { - eventTimestamp?: any; - eventType?: string; - eventId?: number; - workflowExecutionStartedEventAttributes?: WorkflowExecutionStartedEventAttributes; - workflowExecutionCompletedEventAttributes?: WorkflowExecutionCompletedEventAttributes; - completeWorkflowExecutionFailedEventAttributes?: CompleteWorkflowExecutionFailedEventAttributes; - workflowExecutionFailedEventAttributes?: WorkflowExecutionFailedEventAttributes; - failWorkflowExecutionFailedEventAttributes?: FailWorkflowExecutionFailedEventAttributes; - workflowExecutionTimedOutEventAttributes?: WorkflowExecutionTimedOutEventAttributes; - workflowExecutionCanceledEventAttributes?: WorkflowExecutionCanceledEventAttributes; - cancelWorkflowExecutionFailedEventAttributes?: CancelWorkflowExecutionFailedEventAttributes; - workflowExecutionContinuedAsNewEventAttributes?: WorkflowExecutionContinuedAsNewEventAttributes; - continueAsNewWorkflowExecutionFailedEventAttributes?: ContinueAsNewWorkflowExecutionFailedEventAttributes; - workflowExecutionTerminatedEventAttributes?: WorkflowExecutionTerminatedEventAttributes; - workflowExecutionCancelRequestedEventAttributes?: WorkflowExecutionCancelRequestedEventAttributes; - decisionTaskScheduledEventAttributes?: DecisionTaskScheduledEventAttributes; - decisionTaskStartedEventAttributes?: DecisionTaskStartedEventAttributes; - decisionTaskCompletedEventAttributes?: DecisionTaskCompletedEventAttributes; - decisionTaskTimedOutEventAttributes?: DecisionTaskTimedOutEventAttributes; - activityTaskScheduledEventAttributes?: ActivityTaskScheduledEventAttributes; - activityTaskStartedEventAttributes?: ActivityTaskStartedEventAttributes; - activityTaskCompletedEventAttributes?: ActivityTaskCompletedEventAttributes; - activityTaskFailedEventAttributes?: ActivityTaskFailedEventAttributes; - activityTaskTimedOutEventAttributes?: ActivityTaskTimedOutEventAttributes; - activityTaskCanceledEventAttributes?: ActivityTaskCanceledEventAttributes; - activityTaskCancelRequestedEventAttributes?: ActivityTaskCancelRequestedEventAttributes; - workflowExecutionSignaledEventAttributes?: WorkflowExecutionSignaledEventAttributes; - markerRecordedEventAttributes?: MarkerRecordedEventAttributes; - timerStartedEventAttributes?: TimerStartedEventAttributes; - timerFiredEventAttributes?: TimerFiredEventAttributes; - timerCanceledEventAttributes?: TimerCanceledEventAttributes; - startChildWorkflowExecutionInitiatedEventAttributes?: StartChildWorkflowExecutionInitiatedEventAttributes; - childWorkflowExecutionStartedEventAttributes?: ChildWorkflowExecutionStartedEventAttributes; - childWorkflowExecutionCompletedEventAttributes?: ChildWorkflowExecutionCompletedEventAttributes; - childWorkflowExecutionFailedEventAttributes?: ChildWorkflowExecutionFailedEventAttributes; - childWorkflowExecutionTimedOutEventAttributes?: ChildWorkflowExecutionTimedOutEventAttributes; - childWorkflowExecutionCanceledEventAttributes?: ChildWorkflowExecutionCanceledEventAttributes; - childWorkflowExecutionTerminatedEventAttributes?: ChildWorkflowExecutionTerminatedEventAttributes; - signalExternalWorkflowExecutionInitiatedEventAttributes?: SignalExternalWorkflowExecutionInitiatedEventAttributes; - externalWorkflowExecutionSignaledEventAttributes?: ExternalWorkflowExecutionSignaledEventAttributes; - signalExternalWorkflowExecutionFailedEventAttributes?: SignalExternalWorkflowExecutionFailedEventAttributes; - externalWorkflowExecutionCancelRequestedEventAttributes?: ExternalWorkflowExecutionCancelRequestedEventAttributes; - requestCancelExternalWorkflowExecutionInitiatedEventAttributes?: RequestCancelExternalWorkflowExecutionInitiatedEventAttributes; - requestCancelExternalWorkflowExecutionFailedEventAttributes?: RequestCancelExternalWorkflowExecutionFailedEventAttributes; - scheduleActivityTaskFailedEventAttributes?: ScheduleActivityTaskFailedEventAttributes; - requestCancelActivityTaskFailedEventAttributes?: RequestCancelActivityTaskFailedEventAttributes; - startTimerFailedEventAttributes?: StartTimerFailedEventAttributes; - cancelTimerFailedEventAttributes?: CancelTimerFailedEventAttributes; - startChildWorkflowExecutionFailedEventAttributes?: StartChildWorkflowExecutionFailedEventAttributes; - } - - export interface WorkflowExecutionStartedEventAttributes { - input?: string; - executionStartToCloseTimeout?: string; - taskStartToCloseTimeout?: string; - childPolicy?: string; - taskList?: TaskList; - workflowType?: WorkflowType; - tagList?: string[]; - continuedExecutionRunId?: string; - parentWorkflowExecution?: WorkflowExecution; - parentInitiatedEventId?: number; - } - - export interface WorkflowExecutionCompletedEventAttributes { - result?: string; - decisionTaskCompletedEventId?: number; - } - - export interface CompleteWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionFailedEventAttributes { - reason?: string; - details?: string; - decisionTaskCompletedEventId?: number; - } - - export interface FailWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionTimedOutEventAttributes { - timeoutType?: string; - childPolicy?: string; - } - - export interface WorkflowExecutionCanceledEventAttributes { - details?: string; - decisionTaskCompletedEventId?: number; - } - - export interface CancelWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionContinuedAsNewEventAttributes { - input?: string; - decisionTaskCompletedEventId?: number; - newExecutionRunId?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - taskStartToCloseTimeout?: string; - childPolicy?: string; - tagList?: string[]; - workflowType?: WorkflowType; - } - - export interface ContinueAsNewWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionTerminatedEventAttributes { - reason?: string; - details?: string; - childPolicy?: string; - cause?: string; - } - - export interface WorkflowExecutionCancelRequestedEventAttributes { - externalWorkflowExecution?: WorkflowExecution; - externalInitiatedEventId?: number; - cause?: string; - } - - export interface DecisionTaskScheduledEventAttributes { - taskList?: TaskList; - startToCloseTimeout?: string; - } - - export interface DecisionTaskStartedEventAttributes { - identity?: string; - scheduledEventId?: number; - } - - export interface DecisionTaskCompletedEventAttributes { - executionContext?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface DecisionTaskTimedOutEventAttributes { - timeoutType?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface ActivityTaskScheduledEventAttributes { - activityType?: ActivityType; - activityId?: string; - input?: string; - control?: string; - scheduleToStartTimeout?: string; - scheduleToCloseTimeout?: string; - startToCloseTimeout?: string; - taskList?: TaskList; - decisionTaskCompletedEventId?: number; - heartbeatTimeout?: string; - } - - export interface ActivityTaskStartedEventAttributes { - identity?: string; - scheduledEventId?: number; - } - - export interface ActivityTaskCompletedEventAttributes { - result?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface ActivityTaskFailedEventAttributes { - reason?: string; - details?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface ActivityTaskTimedOutEventAttributes { - timeoutType?: string; - scheduledEventId?: number; - startedEventId?: number; - details?: string; - } - - export interface ActivityTaskCanceledEventAttributes { - details?: string; - scheduledEventId?: number; - startedEventId?: number; - latestCancelRequestedEventId?: number; - } - - export interface ActivityTaskCancelRequestedEventAttributes { - decisionTaskCompletedEventId?: number; - activityId?: string; - } - - export interface WorkflowExecutionSignaledEventAttributes { - signalName?: string; - input?: string; - externalWorkflowExecution?: WorkflowExecution; - externalInitiatedEventId?: number; - } - - export interface MarkerRecordedEventAttributes { - markerName?: string; - details?: string; - decisionTaskCompletedEventId?: number; - } - - export interface TimerStartedEventAttributes { - timerId?: string; - control?: string; - startToFireTimeout?: string; - decisionTaskCompletedEventId?: number; - } - - export interface TimerFiredEventAttributes { - timerId?: string; - startedEventId?: number; - } - - export interface TimerCanceledEventAttributes { - timerId?: string; - startedEventId?: number; - decisionTaskCompletedEventId?: number; - } - - export interface StartChildWorkflowExecutionInitiatedEventAttributes { - workflowId?: string; - workflowType?: WorkflowType; - control?: string; - input?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - decisionTaskCompletedEventId?: number; - childPolicy?: string; - taskStartToCloseTimeout?: string; - tagList?: string[]; - } - - export interface ChildWorkflowExecutionStartedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - initiatedEventId?: number; - } - - export interface ChildWorkflowExecutionCompletedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - result?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionFailedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - reason?: string; - details?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionTimedOutEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - timeoutType?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionCanceledEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - details?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionTerminatedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface SignalExternalWorkflowExecutionInitiatedEventAttributes { - workflowId?: string; - runId?: string; - signalName?: string; - input?: string; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ExternalWorkflowExecutionSignaledEventAttributes { - workflowExecution?: WorkflowExecution; - initiatedEventId?: number; - } - - export interface SignalExternalWorkflowExecutionFailedEventAttributes { - workflowId?: string; - runId?: string; - cause?: string; - initiatedEventId?: number; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ExternalWorkflowExecutionCancelRequestedEventAttributes { - workflowExecution?: WorkflowExecution; - initiatedEventId?: number; - } - - export interface RequestCancelExternalWorkflowExecutionInitiatedEventAttributes { - workflowId?: string; - runId?: string; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface RequestCancelExternalWorkflowExecutionFailedEventAttributes { - workflowId?: string; - runId?: string; - cause?: string; - initiatedEventId?: number; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ScheduleActivityTaskFailedEventAttributes { - activityType?: ActivityType; - activityId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface RequestCancelActivityTaskFailedEventAttributes { - activityId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface StartTimerFailedEventAttributes { - timerId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface CancelTimerFailedEventAttributes { - timerId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface StartChildWorkflowExecutionFailedEventAttributes { - workflowType?: WorkflowType; - cause?: string; - workflowId?: string; - initiatedEventId?: number; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ActivityTask { - taskToken?: string; - activityId?: string; - startedEventId?: number; - workflowExecution?: WorkflowExecution; - activityType?: ActivityType; - input?: string; - } - - export interface PollForActivityTaskResult { - activityTask?: ActivityTask; - } - - export interface PollForDecisionTaskResult { - decisionTask?: DecisionTask; - } - - export interface StartWorkflowExecutionResult { - run?: Run; - } - - export interface Run { - runId?: string; - } - - } - - export module Sns { - - export interface Client { - config: ClientConfig; - - publicTopic(params: PublishRequest, callback: (err: any, data: PublishResult) => void): void; - createTopic(params: CreateTopicRequest, callback: (err: any, data: CreateTopicResult) => void): void; - deleteTopic(params: DeleteTopicRequest, callback: (err: any, data: any) => void): void; - } - - export interface PublishRequest { - TopicArn?: string; - Message?: string; - MessageStructure?: string; - Subject?: string; - } - - export interface PublishResult { - MessageId?: string; - } - - export interface CreateTopicRequest { - Name?: string; - } - - export interface CreateTopicResult { - TopicArn?: string; - } - - export interface DeleteTopicRequest { - TopicArn?: string; - } - - } - - export module s3 { - - export interface PutObjectRequest { - ACL?: string; - Body?: any; - Bucket: string; - CacheControl?: string; - ContentDisposition?: string; - ContentEncoding?: string; - ContentLanguage?: string; - ContentLength?: string; - ContentMD5?: string; - ContentType?: string; - Expires?: any; - GrantFullControl?: string; - GrantRead?: string; - GrantReadACP?: string; - GrantWriteACP?: string; - Key: string; - Metadata?: string[]; - ServerSideEncryption?: string; - StorageClass?: string; - WebsiteRedirectLocation?: string; - } - - export interface GetObjectRequest { - Bucket: string; - IfMatch?: string; - IfModifiedSince?: any; - IfNoneMatch?: string; - IfUnmodifiedSince?: any; - Key: string; - Range?: string; - ResponseCacheControl?: string; - ResponseContentDisposition?: string; - ResponseContentEncoding?: string; - ResponseContentLanguage?: string; - ResponseContentType?: string; - ResponseExpires?: any; - VersionId?: string; - } - - } - - export module ecs { - export interface CreateServicesParams { - desiredCount: number; - serviceName: string; - taskDefinition: string; - clientToken?: string; - cluster?: string; - deploymentConfiguration?: { - maximumPercent?: number; - minimumHealthyPercent?: number; - }; - loadBalancers?: { - containerName?: string; - containerPort?: number; - loadBalancerName?: string; - }[]; - role?: string; - } - - export interface DescribeServicesParams { - services: string[]; - cluster: string; - } - - export interface DescribeTaskDefinitionParams { - taskDefinition: string; - } - - export interface RegisterTaskDefinitionParams { - containerDefinitions: { - command?: string[], - cpu?: number, - disableNetworking?: boolean, - dnsSearchDomains?: string[], - dnsServers?: string[], - dockerLabels?: any, - dockerSecurityOptions?: string[], - entryPoint?: string[], - environment?: any[], - essential?: boolean, - extraHosts?: { - hostName: string, - ipAddress: string - }[]; - hostname?: string, - image?: string, - links?: string[], - logConfiguration?: { - logDriver: string, - options: any - }[], - memory?: number, - mountPoints?: { - containerPath: string, - readOnly: boolean, - sourceVolume: string - }[]; - name?: string, - portMappings?: { - containerPort?: number, - hostPort?: number, - protocol: string - }[]; - privileged?: boolean, - readonlyRootFilesystem?: boolean, - ulimits?: { - hardLimit: number, - name: string, - softLimit: number - }[]; - user?: string, - volumesFrom?: { - readOnly?: boolean, - sourceContainer?: string - }[], - workingDirectory?: string - }[]; - family: string; - volumes?: { - host: { - sourcePath: string - }, - name: string - }[]; - } - - export interface UpdateServiceParams { - service: string; - cluster?: string; - deploymentConfiguration?: { - maximumPercent: number; - minimumHealthyPercent: number; - }; - desiredCount?: number; - taskDefinition: string; - } - } -} diff --git a/aws-sdk/index.d.ts b/aws-sdk/index.d.ts new file mode 100644 index 0000000000..89b6cfa2f6 --- /dev/null +++ b/aws-sdk/index.d.ts @@ -0,0 +1,1196 @@ +// Type definitions for aws-sdk +// Project: https://github.com/aws/aws-sdk-js +// Definitions by: midknight41 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Imported from: https://github.com/soywiz/typescript-node-definitions/aws-sdk.d.ts + +/// + + + +export declare var config: ClientConfig; + +export declare function Config(json: any): void; + +export declare class Credentials { + constructor(accessKeyId: string, secretAccessKey: string, sessionToken?: string); + accessKeyId: string; +} + +export interface Logger { + write?: (chunk: any, encoding?: string, callback?: () => void) => void; + log?: (...messages: any[]) => void; +} + +export interface HttpOptions { + proxy?: string; + agent?: any; + timeout?: number; + xhrAsync?: boolean; + xhrWithCredentials?: boolean; +} + +export declare class Endpoint { + constructor(endpoint: string); + + host: string; + hostname: string; + href: string; + port: number; + protocol: string; +} + +export interface Services { + autoscaling?: any; + cloudformation?: any; + cloudfront?: any; + cloudsearch?: any; + cloudsearchdomain?: any; + cloudtrail?: any; + cloudwatch?: any; + cloudwatchlogs?: any; + cognitoidentity?: any; + cognitosync?: any; + datapipeline?: any; + directconnect?: any; + dynamodb?: any; + ec2?: any; + ecs?: any; + elasticache?: any; + elasticbeanstalk?: any; + elastictranscoder?: any; + elb?: any; + emr?: any; + glacier?: any; + httpOptions?: HttpOptions; + iam?: any; + importexport?: any; + kinesis?: any; + opsworks?: any; + rds?: any; + redshift?: any; + route53?: any; + route53domains?: any; + s3?: any; + ses?: any; + simpledb?: any; + sns?: any; + sqs?: any; + storagegateway?: any; + sts?: any; + support?: any; + swf?: any; +} + +export interface ClientConfigPartial extends Services { + credentials?: Credentials; + region?: string; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + logger?: Logger; + maxRedirects?: number; + maxRetries?: number; + paramValidation?: boolean; + s3ForcePathStyle?: boolean; + apiVersion?: any; + apiVersions?: Services; + signatureVersion?: string; + sslEnabled?: boolean; + systemClockOffset?: number; +} + +export interface ClientConfig extends ClientConfigPartial { + update?: (options: ClientConfigPartial, allUnknownKeys?: boolean) => void; + getCredentials?: (callback: (err?: any) => void) => void; + loadFromPath?: (path: string) => void; + credentials: Credentials; + region: string; +} + +export declare class SQS { + constructor(options?: any); + endpoint: Endpoint; + + addPermission(params: SQS.AddPermissionParams, callback: (err: Error, data: any) => void): void; + changeMessageVisibility(params: SQS.ChangeMessageVisibilityParams, callback: (err: Error, data: any) => void): void; + changeMessageVisibilityBatch(params: SQS.ChangeMessageVisibilityBatchParams, callback: (err: Error, data: SQS.ChangeMessageVisibilityBatchResponse) => void): void; + createQueue(params: SQS.CreateQueueParams, callback: (err: Error, data: SQS.CreateQueueResult) => void): void; + deleteMessage(params: SQS.DeleteMessageParams, callback: (err: Error, data: any) => void): void; + deleteMessageBatch(params: SQS.DeleteMessageBatchParams, callback: (err: Error, data: SQS.DeleteMessageBatchResult) => void): void; + deleteQueue(params: { QueueUrl: string; }, callback: (err: Error, data: any) => void): void; + getQueueAttributes(params: SQS.GetQueueAttributesParams, callback: (err: Error, data: SQS.GetQueueAttributesResult) => void): void; + getQueueUrl(params: SQS.GetQueueUrlParams, callback: (err: Error, data: { QueueUrl: string; }) => void): void; + listDeadLetterSourceQueues(params: { QueueUrl: string }, callback: (err: Error, data: { queueUrls: string[] }) => void): void; + listQueues(params: { QueueNamePrefix?: string }, callback: (err: Error, data: { QueueUrls: string[] }) => void): void; + purgeQueue(params: { QueueUrl: string }, callback: (err: Error, data: any) => void): void; + receiveMessage(params: SQS.ReceiveMessageParams, callback: (err: Error, data: SQS.ReceiveMessageResult) => void): void; + removePermission(params: { QueueUrl: string, Label: string }, callback: (err: Error, data: any) => void): void; + sendMessage(params: SQS.SendMessageParams, callback: (err: Error, data: SQS.SendMessageResult) => void): void; + sendMessageBatch(params: SQS.SendMessageBatchParams, callback: (err: Error, data: SQS.SendMessageBatchResult) => void): void; + setQueueAttributes(params: SQS.SetQueueAttributesParams, callback: (err: Error, data: any) => void): void; +} + +export declare class SES { + constructor(options?: any); + public client: Ses.Client; +} + +export declare class SNS { + constructor(options?: any); + public client: Sns.Client; +} + +export declare class SimpleWorkflow { + constructor(options?: any); + public client: Swf.Client; +} + +export declare class S3 { + constructor(options?: any); + putObject(params: s3.PutObjectRequest, callback: (err: any, data: any) => void): void; + getObject(params: s3.GetObjectRequest, callback: (err: any, data: any) => void): void; +} + +export declare class ECS { + constructor(options?: any); + + createService(params: ecs.CreateServicesParams, callback: (err: any, data: any) => void): void; + describeServices(params: ecs.DescribeServicesParams, callback: (err: any, data: any) => void): void; + describeTaskDefinition(params: ecs.DescribeTaskDefinitionParams, callback: (err: any, data: any) => void): void; + registerTaskDefinition(params: ecs.RegisterTaskDefinitionParams, callback: (err: any, data: any) => void): void; + updateService(params: ecs.UpdateServiceParams, callback: (err: any, data: any) => void): void; +} + +export declare class DynamoDB { + constructor(options?: any); +} + +export declare module DynamoDB { + export class DocumentClient { + constructor(options?: any); + } +} + +export declare module SQS { + + export interface SqsOptions { + params?: any; + endpoint?: string; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: Credentials; + credentials?: Credentials; + credentialProvider?: any; + region?: string; + maxRetries?: number; + maxRedirects?: number; + sslEnabled?: boolean; + paramValidation?: boolean; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + correctClockSkew?: boolean; + s3ForcePathStyle?: boolean; + s3BucketEndpoint?: boolean; + httpOptions?: HttpOptions; + apiVersion?: string; + apiVersions?: { [serviceName: string]: string }; + logger?: Logger; + systemClockOffset?: number; + signatureVersion?: string; + signatureCache?: boolean; + } + + export interface AddPermissionParams { + QueueUrl: string; + Label: string; + AWSAccountIds: string[]; + Actions: string[]; + } + + export interface ChangeMessageVisibilityParams { + QueueUrl: string, + ReceiptHandle: string, + VisibilityTimeout: number + } + + export interface ChangeMessageVisibilityBatchParams { + QueueUrl: string, + Entries: { Id: string; ReceiptHandle: string; VisibilityTimeout?: number; }[] + } + + export interface ChangeMessageVisibilityBatchResponse { + Successful: { Id: string }[]; + Failed: BatchResultErrorEntry[]; + } + + export interface SendMessageParams { + QueueUrl: string; + MessageBody: string; + DelaySeconds?: number; + MessageAttributes?: { [name: string]: MessageAttribute; } + } + + export interface ReceiveMessageParams { + QueueUrl: string; + MaxNumberOfMessages?: number; + VisibilityTimeout?: number; + AttributeNames?: string[]; + MessageAttributeNames?: string[]; + WaitTimeSeconds?: number; + } + + export interface DeleteMessageBatchParams { + QueueUrl: string; + Entries: DeleteMessageBatchRequestEntry[]; + } + + export interface DeleteMessageBatchRequestEntry { + Id: string; + ReceiptHandle: string; + } + + export interface DeleteMessageParams { + QueueUrl: string; + ReceiptHandle: string; + } + + export interface SendMessageBatchParams { + QueueUrl: string; + Entries: SendMessageBatchRequestEntry[]; + } + + export interface SendMessageBatchRequestEntry { + Id: string; + MessageBody: string; + DelaySeconds?: number; + MessageAttributes?: { [name: string]: MessageAttribute; } + } + + export interface CreateQueueParams { + QueueName: string; + Attributes: QueueAttributes; + } + + export interface QueueAttributes { + [name: string]: any; + DelaySeconds?: number; + MaximumMessageSize?: number; + MessageRetentionPeriod?: number; + Policy?: any; + ReceiveMessageWaitTimeSeconds?: number; + VisibilityTimeout?: number; + RedrivePolicy?: any; + } + + export interface GetQueueAttributesParams { + QueueUrl: string; + AttributeNames: string[]; + } + + export interface GetQueueAttributesResult { + Attributes: { [name: string]: string }; + } + + export interface GetQueueUrlParams { + QueueName: string; + QueueOwnerAWSAccountId?: string; + } + + export interface SendMessageResult { + MessageId: string; + MD5OfMessageBody: string; + MD5OfMessageAttributes: string; + } + + export interface ReceiveMessageResult { + Messages: Message[]; + } + + export interface Message { + MessageId: string; + ReceiptHandle: string; + MD5OfBody: string; + Body: string; + Attributes: { [name: string]: any }; + MD5OfMessageAttributes: string; + MessageAttributes: { [name: string]: MessageAttribute; } + } + + export interface MessageAttribute { + StringValue?: string; + BinaryValue?: any; //(Buffer, Typed Array, Blob, String) + StringListValues?: string[]; + BinaryListValues?: any[]; + DataType: string; + } + + export interface DeleteMessageBatchResult { + Successful: DeleteMessageBatchResultEntry[]; + Failed: BatchResultErrorEntry[]; + } + + export interface DeleteMessageBatchResultEntry { + Id: string; + } + + export interface BatchResultErrorEntry { + Id: string; + Code: string; + Message?: string; + SenderFault: boolean; + } + + export interface SendMessageBatchResult { + Successful: SendMessageBatchResultEntry[]; + Failed: BatchResultErrorEntry[]; + } + + export interface SendMessageBatchResultEntry { + Id: string; + MessageId: string; + MD5OfMessageBody: string; + MD5OfMessageAttributes: string; + } + + export interface CreateQueueResult { + QueueUrl: string; + } + + export interface SetQueueAttributesParams { + QueueUrl: string; + Attributes: QueueAttributes; + } + +} + +export declare module Ses { + + export interface Client { + config: ClientConfig; + + sendEmail(params: any, callback: (err: any, data: SendEmailResult) => void): void; + } + + export interface SendEmailRequest { + Source: string; + Destination: Destination; + Message: Message; + ReplyToAddresses: string[]; + ReturnPath: string; + } + + export class Destination { + ToAddresses: string[]; + CcAddresses: string[]; + BccAddresses: string[]; + } + + export class Message { + Subject: Content; + Body: Body; + } + + export class Content { + Data: string; + Charset: string; + } + + export class Body { + Text: Content; + Html: Content; + } + + export class SendEmailResult { + MessageId: string; + } + +} + +export declare module Swf { + + export class Client { + //constructor(options?: any); + public config: ClientConfig; + + countClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countPendingActivityTasks(params: any, callback: (err: any, data: any) => void): void; + countPendingDecisionTasks(params: any, callback: (err: any, data: any) => void): void; + deprecateActivityType(params: any, callback: (err: any, data: any) => void): void; + deprecateDomain(params: any, callback: (err: any, data: any) => void): void; + deprecateWorkflowType(params: any, callback: (err: any, data: any) => void): void; + describeActivityType(params: any, callback: (err: any, data: any) => void): void; + describeDomain(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowType(params: any, callback: (err: any, data: any) => void): void; + getWorkflowExecutionHistory(params: any, callback: (err: any, data: any) => void): void; + listActivityTypes(params: any, callback: (err: any, data: any) => void): void; + listClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listDomains(params: any, callback: (err: any, data: any) => void): void; + listOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listWorkflowTypes(params: any, callback: (err: any, data: any) => void): void; + pollForActivityTask(params: any, callback: (err: any, data: ActivityTask) => void): void; + pollForDecisionTask(params: any, callback: (err: any, data: DecisionTask) => void): void; + recordActivityTaskHeartbeat(params: any, callback: (err: any, data: any) => void): void; + registerActivityType(params: any, callback: (err: any, data: any) => void): void; + registerDomain(params: any, callback: (err: any, data: any) => void): void; + registerWorkflowType(params: any, callback: (err: any, data: any) => void): void; + requestCancelWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + respondActivityTaskCanceled(params: RespondActivityTaskCanceledRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskCompleted(params: RespondActivityTaskCompletedRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskFailed(params: RespondActivityTaskFailedRequest, callback: (err: any, data: any) => void): void; + respondDecisionTaskCompleted(params: RespondDecisionTaskCompletedRequest, callback: (err: any, data: any) => void): void; + signalWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + startWorkflowExecution(params: any, callback: (err: any, data: StartWorkflowExecutionResult) => void): void; + terminateWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + } + + export interface PollForActivityTaskRequest { + domain?: string; + taskList?: TaskList; + identity?: string; + } + + export interface TaskList { + name?: string; + } + + export interface PollForDecisionTaskRequest { + domain?: string; + taskList?: TaskList; + identity?: string; + nextPageToken?: string; + maximumPageSize?: number; + reverseOrder?: Boolean; + } + + export interface StartWorkflowExecutionRequest { + domain?: string; + workflowId?: string; + workflowType?: WorkflowType; + taskList?: TaskList; + input?: string; + executionStartToCloseTimeout?: string; + tagList?: string[]; + taskStartToCloseTimeout?: string; + childPolicy?: string; + } + + export interface WorkflowType { + name?: string; + version?: string; + } + + export interface RespondDecisionTaskCompletedRequest { + taskToken?: string; + decisions?: Decision[]; + executionContext?: string; + } + + export interface Decision { + decisionType?: string; + scheduleActivityTaskDecisionAttributes?: ScheduleActivityTaskDecisionAttributes; + requestCancelActivityTaskDecisionAttributes?: RequestCancelActivityTaskDecisionAttributes; + completeWorkflowExecutionDecisionAttributes?: CompleteWorkflowExecutionDecisionAttributes; + failWorkflowExecutionDecisionAttributes?: FailWorkflowExecutionDecisionAttributes; + cancelWorkflowExecutionDecisionAttributes?: CancelWorkflowExecutionDecisionAttributes; + continueAsNewWorkflowExecutionDecisionAttributes?: ContinueAsNewWorkflowExecutionDecisionAttributes; + recordMarkerDecisionAttributes?: RecordMarkerDecisionAttributes; + startTimerDecisionAttributes?: StartTimerDecisionAttributes; + cancelTimerDecisionAttributes?: CancelTimerDecisionAttributes; + signalExternalWorkflowExecutionDecisionAttributes?: SignalExternalWorkflowExecutionDecisionAttributes; + requestCancelExternalWorkflowExecutionDecisionAttributes?: RequestCancelExternalWorkflowExecutionDecisionAttributes; + startChildWorkflowExecutionDecisionAttributes?: StartChildWorkflowExecutionDecisionAttributes; + } + + export interface ScheduleActivityTaskDecisionAttributes { + activityType?: ActivityType; + activityId?: string; + control?: string; + input?: string; + scheduleToCloseTimeout?: string; + taskList?: TaskList; + scheduleToStartTimeout?: string; + startToCloseTimeout?: string; + heartbeatTimeout?: string; + } + + export interface ActivityType { + name?: string; + version?: string; + } + + export interface RequestCancelActivityTaskDecisionAttributes { + activityId?: string; + } + + export interface CompleteWorkflowExecutionDecisionAttributes { + result?: string; + } + + export interface FailWorkflowExecutionDecisionAttributes { + reason?: string; + details?: string; + } + + export interface CancelWorkflowExecutionDecisionAttributes { + details?: string; + } + + export interface ContinueAsNewWorkflowExecutionDecisionAttributes { + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + workflowTypeVersion?: string; + } + + export interface RecordMarkerDecisionAttributes { + markerName?: string; + details?: string; + } + + export interface StartTimerDecisionAttributes { + timerId?: string; + control?: string; + startToFireTimeout?: string; + } + + export interface CancelTimerDecisionAttributes { + timerId?: string; + } + + export interface SignalExternalWorkflowExecutionDecisionAttributes { + workflowId?: string; + runId?: string; + signalName?: string; + input?: string; + control?: string; + } + + export interface RequestCancelExternalWorkflowExecutionDecisionAttributes { + workflowId?: string; + runId?: string; + control?: string; + } + + export interface StartChildWorkflowExecutionDecisionAttributes { + workflowType?: WorkflowType; + workflowId?: string; + control?: string; + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + } + + export interface RespondActivityTaskCompletedRequest { + taskToken?: string; + result?: string; + } + + export interface RespondActivityTaskFailedRequest { + taskToken?: string; + reason?: string; + details?: string; + } + + export interface RespondActivityTaskCanceledRequest { + taskToken?: string; + details?: string; + } + + export interface DecisionTask { + taskToken?: string; + startedEventId?: number; + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + events?: HistoryEvent[]; + nextPageToken?: string; + previousStartedEventId?: number; + } + + export interface WorkflowExecution { + workflowId?: string; + runId?: string; + } + + export interface HistoryEvent { + eventTimestamp?: any; + eventType?: string; + eventId?: number; + workflowExecutionStartedEventAttributes?: WorkflowExecutionStartedEventAttributes; + workflowExecutionCompletedEventAttributes?: WorkflowExecutionCompletedEventAttributes; + completeWorkflowExecutionFailedEventAttributes?: CompleteWorkflowExecutionFailedEventAttributes; + workflowExecutionFailedEventAttributes?: WorkflowExecutionFailedEventAttributes; + failWorkflowExecutionFailedEventAttributes?: FailWorkflowExecutionFailedEventAttributes; + workflowExecutionTimedOutEventAttributes?: WorkflowExecutionTimedOutEventAttributes; + workflowExecutionCanceledEventAttributes?: WorkflowExecutionCanceledEventAttributes; + cancelWorkflowExecutionFailedEventAttributes?: CancelWorkflowExecutionFailedEventAttributes; + workflowExecutionContinuedAsNewEventAttributes?: WorkflowExecutionContinuedAsNewEventAttributes; + continueAsNewWorkflowExecutionFailedEventAttributes?: ContinueAsNewWorkflowExecutionFailedEventAttributes; + workflowExecutionTerminatedEventAttributes?: WorkflowExecutionTerminatedEventAttributes; + workflowExecutionCancelRequestedEventAttributes?: WorkflowExecutionCancelRequestedEventAttributes; + decisionTaskScheduledEventAttributes?: DecisionTaskScheduledEventAttributes; + decisionTaskStartedEventAttributes?: DecisionTaskStartedEventAttributes; + decisionTaskCompletedEventAttributes?: DecisionTaskCompletedEventAttributes; + decisionTaskTimedOutEventAttributes?: DecisionTaskTimedOutEventAttributes; + activityTaskScheduledEventAttributes?: ActivityTaskScheduledEventAttributes; + activityTaskStartedEventAttributes?: ActivityTaskStartedEventAttributes; + activityTaskCompletedEventAttributes?: ActivityTaskCompletedEventAttributes; + activityTaskFailedEventAttributes?: ActivityTaskFailedEventAttributes; + activityTaskTimedOutEventAttributes?: ActivityTaskTimedOutEventAttributes; + activityTaskCanceledEventAttributes?: ActivityTaskCanceledEventAttributes; + activityTaskCancelRequestedEventAttributes?: ActivityTaskCancelRequestedEventAttributes; + workflowExecutionSignaledEventAttributes?: WorkflowExecutionSignaledEventAttributes; + markerRecordedEventAttributes?: MarkerRecordedEventAttributes; + timerStartedEventAttributes?: TimerStartedEventAttributes; + timerFiredEventAttributes?: TimerFiredEventAttributes; + timerCanceledEventAttributes?: TimerCanceledEventAttributes; + startChildWorkflowExecutionInitiatedEventAttributes?: StartChildWorkflowExecutionInitiatedEventAttributes; + childWorkflowExecutionStartedEventAttributes?: ChildWorkflowExecutionStartedEventAttributes; + childWorkflowExecutionCompletedEventAttributes?: ChildWorkflowExecutionCompletedEventAttributes; + childWorkflowExecutionFailedEventAttributes?: ChildWorkflowExecutionFailedEventAttributes; + childWorkflowExecutionTimedOutEventAttributes?: ChildWorkflowExecutionTimedOutEventAttributes; + childWorkflowExecutionCanceledEventAttributes?: ChildWorkflowExecutionCanceledEventAttributes; + childWorkflowExecutionTerminatedEventAttributes?: ChildWorkflowExecutionTerminatedEventAttributes; + signalExternalWorkflowExecutionInitiatedEventAttributes?: SignalExternalWorkflowExecutionInitiatedEventAttributes; + externalWorkflowExecutionSignaledEventAttributes?: ExternalWorkflowExecutionSignaledEventAttributes; + signalExternalWorkflowExecutionFailedEventAttributes?: SignalExternalWorkflowExecutionFailedEventAttributes; + externalWorkflowExecutionCancelRequestedEventAttributes?: ExternalWorkflowExecutionCancelRequestedEventAttributes; + requestCancelExternalWorkflowExecutionInitiatedEventAttributes?: RequestCancelExternalWorkflowExecutionInitiatedEventAttributes; + requestCancelExternalWorkflowExecutionFailedEventAttributes?: RequestCancelExternalWorkflowExecutionFailedEventAttributes; + scheduleActivityTaskFailedEventAttributes?: ScheduleActivityTaskFailedEventAttributes; + requestCancelActivityTaskFailedEventAttributes?: RequestCancelActivityTaskFailedEventAttributes; + startTimerFailedEventAttributes?: StartTimerFailedEventAttributes; + cancelTimerFailedEventAttributes?: CancelTimerFailedEventAttributes; + startChildWorkflowExecutionFailedEventAttributes?: StartChildWorkflowExecutionFailedEventAttributes; + } + + export interface WorkflowExecutionStartedEventAttributes { + input?: string; + executionStartToCloseTimeout?: string; + taskStartToCloseTimeout?: string; + childPolicy?: string; + taskList?: TaskList; + workflowType?: WorkflowType; + tagList?: string[]; + continuedExecutionRunId?: string; + parentWorkflowExecution?: WorkflowExecution; + parentInitiatedEventId?: number; + } + + export interface WorkflowExecutionCompletedEventAttributes { + result?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CompleteWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionFailedEventAttributes { + reason?: string; + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface FailWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionTimedOutEventAttributes { + timeoutType?: string; + childPolicy?: string; + } + + export interface WorkflowExecutionCanceledEventAttributes { + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CancelWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionContinuedAsNewEventAttributes { + input?: string; + decisionTaskCompletedEventId?: number; + newExecutionRunId?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + workflowType?: WorkflowType; + } + + export interface ContinueAsNewWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionTerminatedEventAttributes { + reason?: string; + details?: string; + childPolicy?: string; + cause?: string; + } + + export interface WorkflowExecutionCancelRequestedEventAttributes { + externalWorkflowExecution?: WorkflowExecution; + externalInitiatedEventId?: number; + cause?: string; + } + + export interface DecisionTaskScheduledEventAttributes { + taskList?: TaskList; + startToCloseTimeout?: string; + } + + export interface DecisionTaskStartedEventAttributes { + identity?: string; + scheduledEventId?: number; + } + + export interface DecisionTaskCompletedEventAttributes { + executionContext?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface DecisionTaskTimedOutEventAttributes { + timeoutType?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskScheduledEventAttributes { + activityType?: ActivityType; + activityId?: string; + input?: string; + control?: string; + scheduleToStartTimeout?: string; + scheduleToCloseTimeout?: string; + startToCloseTimeout?: string; + taskList?: TaskList; + decisionTaskCompletedEventId?: number; + heartbeatTimeout?: string; + } + + export interface ActivityTaskStartedEventAttributes { + identity?: string; + scheduledEventId?: number; + } + + export interface ActivityTaskCompletedEventAttributes { + result?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskFailedEventAttributes { + reason?: string; + details?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskTimedOutEventAttributes { + timeoutType?: string; + scheduledEventId?: number; + startedEventId?: number; + details?: string; + } + + export interface ActivityTaskCanceledEventAttributes { + details?: string; + scheduledEventId?: number; + startedEventId?: number; + latestCancelRequestedEventId?: number; + } + + export interface ActivityTaskCancelRequestedEventAttributes { + decisionTaskCompletedEventId?: number; + activityId?: string; + } + + export interface WorkflowExecutionSignaledEventAttributes { + signalName?: string; + input?: string; + externalWorkflowExecution?: WorkflowExecution; + externalInitiatedEventId?: number; + } + + export interface MarkerRecordedEventAttributes { + markerName?: string; + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface TimerStartedEventAttributes { + timerId?: string; + control?: string; + startToFireTimeout?: string; + decisionTaskCompletedEventId?: number; + } + + export interface TimerFiredEventAttributes { + timerId?: string; + startedEventId?: number; + } + + export interface TimerCanceledEventAttributes { + timerId?: string; + startedEventId?: number; + decisionTaskCompletedEventId?: number; + } + + export interface StartChildWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + workflowType?: WorkflowType; + control?: string; + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + decisionTaskCompletedEventId?: number; + childPolicy?: string; + taskStartToCloseTimeout?: string; + tagList?: string[]; + } + + export interface ChildWorkflowExecutionStartedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + initiatedEventId?: number; + } + + export interface ChildWorkflowExecutionCompletedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + result?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionFailedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + reason?: string; + details?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionTimedOutEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + timeoutType?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionCanceledEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + details?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionTerminatedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface SignalExternalWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + runId?: string; + signalName?: string; + input?: string; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ExternalWorkflowExecutionSignaledEventAttributes { + workflowExecution?: WorkflowExecution; + initiatedEventId?: number; + } + + export interface SignalExternalWorkflowExecutionFailedEventAttributes { + workflowId?: string; + runId?: string; + cause?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ExternalWorkflowExecutionCancelRequestedEventAttributes { + workflowExecution?: WorkflowExecution; + initiatedEventId?: number; + } + + export interface RequestCancelExternalWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + runId?: string; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface RequestCancelExternalWorkflowExecutionFailedEventAttributes { + workflowId?: string; + runId?: string; + cause?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ScheduleActivityTaskFailedEventAttributes { + activityType?: ActivityType; + activityId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface RequestCancelActivityTaskFailedEventAttributes { + activityId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface StartTimerFailedEventAttributes { + timerId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CancelTimerFailedEventAttributes { + timerId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface StartChildWorkflowExecutionFailedEventAttributes { + workflowType?: WorkflowType; + cause?: string; + workflowId?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ActivityTask { + taskToken?: string; + activityId?: string; + startedEventId?: number; + workflowExecution?: WorkflowExecution; + activityType?: ActivityType; + input?: string; + } + + export interface PollForActivityTaskResult { + activityTask?: ActivityTask; + } + + export interface PollForDecisionTaskResult { + decisionTask?: DecisionTask; + } + + export interface StartWorkflowExecutionResult { + run?: Run; + } + + export interface Run { + runId?: string; + } + +} + +export declare module Sns { + + export interface Client { + config: ClientConfig; + + publicTopic(params: PublishRequest, callback: (err: any, data: PublishResult) => void): void; + createTopic(params: CreateTopicRequest, callback: (err: any, data: CreateTopicResult) => void): void; + deleteTopic(params: DeleteTopicRequest, callback: (err: any, data: any) => void): void; + } + + export interface PublishRequest { + TopicArn?: string; + Message?: string; + MessageStructure?: string; + Subject?: string; + } + + export interface PublishResult { + MessageId?: string; + } + + export interface CreateTopicRequest { + Name?: string; + } + + export interface CreateTopicResult { + TopicArn?: string; + } + + export interface DeleteTopicRequest { + TopicArn?: string; + } + +} + +export declare module s3 { + + export interface PutObjectRequest { + ACL?: string; + Body?: any; + Bucket: string; + CacheControl?: string; + ContentDisposition?: string; + ContentEncoding?: string; + ContentLanguage?: string; + ContentLength?: string; + ContentMD5?: string; + ContentType?: string; + Expires?: any; + GrantFullControl?: string; + GrantRead?: string; + GrantReadACP?: string; + GrantWriteACP?: string; + Key: string; + Metadata?: string[]; + ServerSideEncryption?: string; + StorageClass?: string; + WebsiteRedirectLocation?: string; + } + + export interface GetObjectRequest { + Bucket: string; + IfMatch?: string; + IfModifiedSince?: any; + IfNoneMatch?: string; + IfUnmodifiedSince?: any; + Key: string; + Range?: string; + ResponseCacheControl?: string; + ResponseContentDisposition?: string; + ResponseContentEncoding?: string; + ResponseContentLanguage?: string; + ResponseContentType?: string; + ResponseExpires?: any; + VersionId?: string; + } + +} + +export declare module ecs { + export interface CreateServicesParams { + desiredCount: number; + serviceName: string; + taskDefinition: string; + clientToken?: string; + cluster?: string; + deploymentConfiguration?: { + maximumPercent?: number; + minimumHealthyPercent?: number; + }; + loadBalancers?: { + containerName?: string; + containerPort?: number; + loadBalancerName?: string; + }[]; + role?: string; + } + + export interface DescribeServicesParams { + services: string[]; + cluster: string; + } + + export interface DescribeTaskDefinitionParams { + taskDefinition: string; + } + + export interface RegisterTaskDefinitionParams { + containerDefinitions: { + command?: string[], + cpu?: number, + disableNetworking?: boolean, + dnsSearchDomains?: string[], + dnsServers?: string[], + dockerLabels?: any, + dockerSecurityOptions?: string[], + entryPoint?: string[], + environment?: any[], + essential?: boolean, + extraHosts?: { + hostName: string, + ipAddress: string + }[]; + hostname?: string, + image?: string, + links?: string[], + logConfiguration?: { + logDriver: string, + options: any + }[], + memory?: number, + mountPoints?: { + containerPath: string, + readOnly: boolean, + sourceVolume: string + }[]; + name?: string, + portMappings?: { + containerPort?: number, + hostPort?: number, + protocol: string + }[]; + privileged?: boolean, + readonlyRootFilesystem?: boolean, + ulimits?: { + hardLimit: number, + name: string, + softLimit: number + }[]; + user?: string, + volumesFrom?: { + readOnly?: boolean, + sourceContainer?: string + }[], + workingDirectory?: string + }[]; + family: string; + volumes?: { + host: { + sourcePath: string + }, + name: string + }[]; + } + + export interface UpdateServiceParams { + service: string; + cluster?: string; + deploymentConfiguration?: { + maximumPercent: number; + minimumHealthyPercent: number; + }; + desiredCount?: number; + taskDefinition: string; + } +} diff --git a/aws-sdk/tsconfig.json b/aws-sdk/tsconfig.json new file mode 100644 index 0000000000..62ac20f152 --- /dev/null +++ b/aws-sdk/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "aws-sdk-tests.ts" + ] +} \ No newline at end of file diff --git a/axios/axios-tests.ts b/axios/axios-tests.ts index 040994531b..9c39031ae5 100644 --- a/axios/axios-tests.ts +++ b/axios/axios-tests.ts @@ -1,4 +1,4 @@ -/// + enum HttpMethod { GET, PUT, POST, DELETE, CONNECT, HEAD, OPTIONS, TRACE, PATCH } enum ResponseType { arraybuffer, blob, document, json, text } diff --git a/axios/axios.d.ts b/axios/index.d.ts similarity index 100% rename from axios/axios.d.ts rename to axios/index.d.ts diff --git a/axios/tsconfig.json b/axios/tsconfig.json new file mode 100644 index 0000000000..25612e2961 --- /dev/null +++ b/axios/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "axios-tests.ts" + ] +} \ No newline at end of file diff --git a/azure-mobile-apps/azure-mobile-apps-tests.ts b/azure-mobile-apps/azure-mobile-apps-tests.ts index 093932c2fb..b20ea37773 100644 --- a/azure-mobile-apps/azure-mobile-apps-tests.ts +++ b/azure-mobile-apps/azure-mobile-apps-tests.ts @@ -1,4 +1,4 @@ -/// + import express = require('express'); import mobileApps = require('azure-mobile-apps'); diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts deleted file mode 100644 index 0a42fa9ecf..0000000000 --- a/azure-mobile-apps/azure-mobile-apps.d.ts +++ /dev/null @@ -1,279 +0,0 @@ -// Type definitions for azure-mobile-apps v2.0.0-beta3 -// Project: https://github.com/Azure/azure-mobile-apps-node/ -// Definitions by: Microsoft Azure -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare module "azure-mobile-apps" { - interface AzureMobileApps { - (configuration?: Azure.MobileApps.Configuration): Azure.MobileApps.Platforms.Express.MobileApp; - table(): Azure.MobileApps.Platforms.Express.Table; - logger: Azure.MobileApps.Logger; - query: Azure.MobileApps.Query; - } - - var out: AzureMobileApps; - export = out; -} -declare module "azure-mobile-apps/src/logger" { - var logger: Azure.MobileApps.Logger; - export = logger; -} - -declare module "azure-mobile-apps/src/query" { - var query: Azure.MobileApps.Query; - export = query; -} - -declare namespace Azure.MobileApps { - // the additional Platforms namespace is required to avoid collisions with the main Express namespace - export module Platforms { - export module Express { - interface MobileApp { - configuration: Configuration; - tables: Tables; - table(): Table; - api: Api; - use(...middleware: Middleware[]): MobileApp; - use(middleware: Middleware[]): MobileApp; - } - - interface Api { - add(name: string, definition: ApiDefinition): void; - import(fileOrFolder: string): void; - } - - interface Table { - authorize?: boolean; - autoIncrement?: boolean; - dynamicSchema?: boolean; - name: string; - columns?: any; - schema: string; - - use(...middleware: Middleware[]): Table; - use(middleware: Middleware[]): Table; - read: TableOperation; - update: TableOperation; - insert: TableOperation; - delete: TableOperation; - undelete: TableOperation; - } - - interface TableOperation { - (operationHandler: (context: Context) => void): Table; - use(...middleware: Middleware[]): Table; - use(middleware: Middleware[]): Table; - } - - interface Tables { - configuration: Configuration; - add(name: string, definition?: Table | TableDefinition): void; - import(fileOrFolder: string): void; - initialize(): Thenable; - } - } - } - - export module Data { - interface Table { - read(query: QueryJs): Thenable; - update(item: any, query: QueryJs): Thenable; - insert(item: any): Thenable; - delete(query: QueryJs, version: string): Thenable; - undelete(query: QueryJs, version: string): Thenable; - truncate(): Thenable; - initialize(): Thenable; - schema(): Thenable; - } - - interface Column { - name: string; - type: string; - } - } - - // auth - interface User { - id: string; - claims: any[]; - token: string; - getIdentity(provider: string): Thenable; - } - - interface Auth { - validate(token: string): Thenable; - decode(token: string): User; - sign(payload: any): string; - } - - // configuration - interface Configuration { - platform?: string; - basePath?: string; - configFile?: string; - promiseConstructor?: (resolve: (result: any) => void, reject: (error: any) => void) => Thenable; - apiRootPath?: string; - tableRootPath?: string; - notificationRootPath?: string; - swaggerPath?: string; - authStubRoute?: string; - debug?: boolean; - version?: string; - apiVersion?: string; - homePage?: boolean; - swagger?: boolean; - maxTop?: number; - pageSize?: number; - logging?: Configuration.Logging; - data?: Configuration.Data; - auth?: Configuration.Auth; - cors?: Configuration.Cors; - notifications?: Configuration.Notifications; - } - - export module Configuration { - // it would be nice to have the config for various providers in separate interfaces, - // but this is the simplest solution to support variations of the current setup - interface Data { - provider: string; - user?: string; - password?: string; - server?: string; - port?: number; - database?: string; - connectionTimeout?: string; - options?: { encrypt: boolean }; - schema?: string; - dynamicSchema?: boolean; - } - - interface Auth { - secret: string; - validateTokens?: boolean; - } - - interface Logging { - level?: string; - transports?: LoggingTransport[]; - } - - interface LoggingTransport { } - - interface Cors { - maxAge?: number; - origins: string[]; - } - - interface Notifications { - hubName: string; - connectionString?: string; - endpoint?: string; - sharedAccessKeyName?: string; - sharedAccessKeyValue?: string; - } - } - - // query - interface Query { - create(tableName: string): QueryJs; - fromRequest(req: Express.Request): QueryJs; - toOData(query: QueryJs): OData; - } - - interface QueryJs { - includeTotalCount?: boolean; - orderBy(properties: string): QueryJs; - orderByDescending(properties: string): QueryJs; - select(properties: string): QueryJs; - skip(count: number): QueryJs; - take(count: number): QueryJs; - where(filter: any): QueryJs; - // these are properties added by the SDK - id?: string | number; - single?: boolean; - } - - interface OData { - table: string; - filters?: string; - ordering?: string; - orderClauses?: string; - skip?: number; - take?: number; - selections?: string; - includeTotalCount?: boolean; - } - - // general - var nh: Azure.ServiceBus.NotificationHubService; - interface Context { - query: QueryJs; - id: string | number; - item: any; - req: Express.Request; - res: Express.Response; - data: (table: TableDefinition) => Data.Table; - tables: (tableName: string) => Data.Table; - user: User; - push: typeof nh; - logger: Logger; - execute(): Thenable; - } - - interface TableDefinition { - authorize?: boolean; - autoIncrement?: boolean; - dynamicSchema?: boolean; - name?: string; - columns?: any; - schema?: string; - } - - interface ApiDefinition { - authorize?: boolean; - get?: Middleware | Middleware[]; - post?: Middleware | Middleware[]; - patch?: Middleware | Middleware[]; - put?: Middleware | Middleware[]; - delete?: Middleware | Middleware[]; - } - - interface Thenable { - then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; - then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Thenable; - catch(onRejected?: (error: any) => U | Thenable): Thenable; - catch(onRejected?: (error: any) => void): Thenable; - } - - interface Logger { - log(level: string, ...message: any[]): void; - silly(...message: any[]): void; - debug(...message: any[]): void; - verbose(...message: any[]): void; - info(...message: any[]): void; - warn(...message: any[]): void; - error(...message: any[]): void; - } - - interface Middleware { - (req: Express.Request, res: Express.Response, next: NextMiddleware): void; - } - - interface NextMiddleware { - (error?: any): void; - } -} - -// additions to the Express modules -declare namespace Express { - interface Request { - azureMobile: Azure.MobileApps.Context - } - - interface Response { - results?: any; - } -} diff --git a/azure-mobile-apps/index.d.ts b/azure-mobile-apps/index.d.ts new file mode 100644 index 0000000000..956418d158 --- /dev/null +++ b/azure-mobile-apps/index.d.ts @@ -0,0 +1,279 @@ +// Type definitions for azure-mobile-apps v2.0.0-beta3 +// Project: https://github.com/Azure/azure-mobile-apps-node/ +// Definitions by: Microsoft Azure +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +declare module "azure-mobile-apps" { + interface AzureMobileApps { + (configuration?: Azure.MobileApps.Configuration): Azure.MobileApps.Platforms.Express.MobileApp; + table(): Azure.MobileApps.Platforms.Express.Table; + logger: Azure.MobileApps.Logger; + query: Azure.MobileApps.Query; + } + + var out: AzureMobileApps; + export = out; +} +declare module "azure-mobile-apps/src/logger" { + var logger: Azure.MobileApps.Logger; + export = logger; +} + +declare module "azure-mobile-apps/src/query" { + var query: Azure.MobileApps.Query; + export = query; +} + +declare namespace Azure.MobileApps { + // the additional Platforms namespace is required to avoid collisions with the main Express namespace + export module Platforms { + export module Express { + interface MobileApp { + configuration: Configuration; + tables: Tables; + table(): Table; + api: Api; + use(...middleware: Middleware[]): MobileApp; + use(middleware: Middleware[]): MobileApp; + } + + interface Api { + add(name: string, definition: ApiDefinition): void; + import(fileOrFolder: string): void; + } + + interface Table { + authorize?: boolean; + autoIncrement?: boolean; + dynamicSchema?: boolean; + name: string; + columns?: any; + schema: string; + + use(...middleware: Middleware[]): Table; + use(middleware: Middleware[]): Table; + read: TableOperation; + update: TableOperation; + insert: TableOperation; + delete: TableOperation; + undelete: TableOperation; + } + + interface TableOperation { + (operationHandler: (context: Context) => void): Table; + use(...middleware: Middleware[]): Table; + use(middleware: Middleware[]): Table; + } + + interface Tables { + configuration: Configuration; + add(name: string, definition?: Table | TableDefinition): void; + import(fileOrFolder: string): void; + initialize(): Thenable; + } + } + } + + export module Data { + interface Table { + read(query: QueryJs): Thenable; + update(item: any, query: QueryJs): Thenable; + insert(item: any): Thenable; + delete(query: QueryJs, version: string): Thenable; + undelete(query: QueryJs, version: string): Thenable; + truncate(): Thenable; + initialize(): Thenable; + schema(): Thenable; + } + + interface Column { + name: string; + type: string; + } + } + + // auth + interface User { + id: string; + claims: any[]; + token: string; + getIdentity(provider: string): Thenable; + } + + interface Auth { + validate(token: string): Thenable; + decode(token: string): User; + sign(payload: any): string; + } + + // configuration + interface Configuration { + platform?: string; + basePath?: string; + configFile?: string; + promiseConstructor?: (resolve: (result: any) => void, reject: (error: any) => void) => Thenable; + apiRootPath?: string; + tableRootPath?: string; + notificationRootPath?: string; + swaggerPath?: string; + authStubRoute?: string; + debug?: boolean; + version?: string; + apiVersion?: string; + homePage?: boolean; + swagger?: boolean; + maxTop?: number; + pageSize?: number; + logging?: Configuration.Logging; + data?: Configuration.Data; + auth?: Configuration.Auth; + cors?: Configuration.Cors; + notifications?: Configuration.Notifications; + } + + export module Configuration { + // it would be nice to have the config for various providers in separate interfaces, + // but this is the simplest solution to support variations of the current setup + interface Data { + provider: string; + user?: string; + password?: string; + server?: string; + port?: number; + database?: string; + connectionTimeout?: string; + options?: { encrypt: boolean }; + schema?: string; + dynamicSchema?: boolean; + } + + interface Auth { + secret: string; + validateTokens?: boolean; + } + + interface Logging { + level?: string; + transports?: LoggingTransport[]; + } + + interface LoggingTransport { } + + interface Cors { + maxAge?: number; + origins: string[]; + } + + interface Notifications { + hubName: string; + connectionString?: string; + endpoint?: string; + sharedAccessKeyName?: string; + sharedAccessKeyValue?: string; + } + } + + // query + interface Query { + create(tableName: string): QueryJs; + fromRequest(req: Express.Request): QueryJs; + toOData(query: QueryJs): OData; + } + + interface QueryJs { + includeTotalCount?: boolean; + orderBy(properties: string): QueryJs; + orderByDescending(properties: string): QueryJs; + select(properties: string): QueryJs; + skip(count: number): QueryJs; + take(count: number): QueryJs; + where(filter: any): QueryJs; + // these are properties added by the SDK + id?: string | number; + single?: boolean; + } + + interface OData { + table: string; + filters?: string; + ordering?: string; + orderClauses?: string; + skip?: number; + take?: number; + selections?: string; + includeTotalCount?: boolean; + } + + // general + var nh: Azure.ServiceBus.NotificationHubService; + interface Context { + query: QueryJs; + id: string | number; + item: any; + req: Express.Request; + res: Express.Response; + data: (table: TableDefinition) => Data.Table; + tables: (tableName: string) => Data.Table; + user: User; + push: typeof nh; + logger: Logger; + execute(): Thenable; + } + + interface TableDefinition { + authorize?: boolean; + autoIncrement?: boolean; + dynamicSchema?: boolean; + name?: string; + columns?: any; + schema?: string; + } + + interface ApiDefinition { + authorize?: boolean; + get?: Middleware | Middleware[]; + post?: Middleware | Middleware[]; + patch?: Middleware | Middleware[]; + put?: Middleware | Middleware[]; + delete?: Middleware | Middleware[]; + } + + interface Thenable { + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Thenable; + catch(onRejected?: (error: any) => U | Thenable): Thenable; + catch(onRejected?: (error: any) => void): Thenable; + } + + interface Logger { + log(level: string, ...message: any[]): void; + silly(...message: any[]): void; + debug(...message: any[]): void; + verbose(...message: any[]): void; + info(...message: any[]): void; + warn(...message: any[]): void; + error(...message: any[]): void; + } + + interface Middleware { + (req: Express.Request, res: Express.Response, next: NextMiddleware): void; + } + + interface NextMiddleware { + (error?: any): void; + } +} + +// additions to the Express modules +declare namespace Express { + interface Request { + azureMobile: Azure.MobileApps.Context + } + + interface Response { + results?: any; + } +} diff --git a/azure-mobile-apps/tsconfig.json b/azure-mobile-apps/tsconfig.json new file mode 100644 index 0000000000..b17f58aae2 --- /dev/null +++ b/azure-mobile-apps/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "azure-mobile-apps-tests.ts" + ] +} \ No newline at end of file diff --git a/azure-mobile-services-client/AzureMobileServicesClient-tests.ts b/azure-mobile-services-client/AzureMobileServicesClient-tests.ts index 7a3b9b9561..d86667fe98 100644 --- a/azure-mobile-services-client/AzureMobileServicesClient-tests.ts +++ b/azure-mobile-services-client/AzureMobileServicesClient-tests.ts @@ -1,4 +1,4 @@ -/// + //create base client istance and read properties @@ -32,8 +32,8 @@ tableTodoItems.read() //define simple handler used in callback calls for insert/update and delete -function handlerInsUpd(e, i) { if (!e) data.push( i); }; -function handlerDelErr(e) { if (e) alert("ERROR: " + e); } +function handlerInsUpd(e: any, i: any) { if (!e) data.push( i); }; +function handlerDelErr(e: any) { if (e) alert("ERROR: " + e); } //insert one data passing info in POST + custom data in QueryString + simple callback handler diff --git a/azure-mobile-services-client/AzureMobileServicesClient-tests.ts.tscparams b/azure-mobile-services-client/AzureMobileServicesClient-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/azure-mobile-services-client/AzureMobileServicesClient-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/azure-mobile-services-client/AzureMobileServicesClient.d.ts b/azure-mobile-services-client/AzureMobileServicesClient.d.ts deleted file mode 100644 index f93ca868c7..0000000000 --- a/azure-mobile-services-client/AzureMobileServicesClient.d.ts +++ /dev/null @@ -1,107 +0,0 @@ -// Type definitions for Microsoft Windows AzureMobile Service 1.0.0 -// Project: http://www.windowsazure.com/en-us/develop/mobile/ -// Definitions by: Morosinotto Daniele -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Microsoft.WindowsAzure { - - // MobileServiceClient object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554219.aspx - interface MobileServiceClient { - new (applicationUrl: string, applicationKey: string): MobileServiceClient; - applicationUrl: string; - applicationKey: string; - currentUser: User; - //for provider:string use one of ProviderEnum: 'microsoftaccount', 'facebook', 'twitter', 'google' - login(provider: string, token: string, callback: (error: any, user: User) => void ): void; - login(provider: string, token: string): asyncPromise; - login(provider: string, callback: (error: any, user: User) => void ): void; - login(provider: string): asyncPromise; - logout(): void; - getTable(tableName: string): MobileServiceTable; - withFilter(serviceFilter: (request: any, next: (request: any, callback: (error:any, response: any) => void ) => void, callback: (error: any, response: any) => void ) => void ) : MobileServiceClient; - invokeApi(apiName: string, options?:InvokeApiOptions): asyncPromise; - } - - interface InvokeApiOptions - { - method?: string; - body?: any; - headers?: Object; - parameters?: Object; - } - - // User object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554220.aspx - interface User { - getIdentities(): any;// { [providerName: string]: { userId: string, accessToken: string, accessTokenSecret?: string }; }; - accessTokens: any; // { [providerName: string]: string; } - level: string; //for level:string use one of LevelEnum: 'admin','anonymous','authenticated' - userId: string; - } - - - // Interface to Platform.async(func) => Platform.Promise based on code MobileServices.Web-1.0.0.js - interface asyncPromise { - then(onSuccess: (result: any) => any, onError?: (error: any) => any): asyncPromise; - done(onSuccess?: (result: any) => void , onError?: (error: any) => void ): void; - } - - // MobileServiceTable object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554239.aspx - interface MobileServiceTable extends IQuery { - new (tableName: string, client: MobileServiceClient): MobileServiceTable; - getTableName(): string; - getMobileServiceClient(): MobileServiceClient; - - insert(instance: any, paramsQS: Object, callback: (error: any, retInserted: any) => any): void; - insert(instance: any, paramsQS: Object): asyncPromise; - insert(instance: any): asyncPromise; - - update(instance: any, paramsQS: Object, callback: (error: any, retUpdated: any) => any): void; - update(instance: any, paramsQS: Object): asyncPromise; - update(instance: any): asyncPromise; - - lookup(id: number, paramsQS: Object, callback: (error: any, retValue: any) => any): void; - lookup(id: number, paramsQS: Object): asyncPromise; - lookup(id: number): asyncPromise; - - del(instance: any, paramsQS: Object, callback: (error?: any) => void ): void; - del(instance: any, paramsQS: Object): asyncPromise; - del(instance: any): asyncPromise; - - - read(query: IQuery, paramsQS: Object, callback: (error: any, retValues: any) => any): void; - read(query: IQuery, paramsQS: Object): asyncPromise; - read(query: IQuery): asyncPromise; - read(): asyncPromise; - } - - - // Interface to describe Query object fluent creation based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj613353.aspx - interface IQuery { - read(paramsQS?: Object): asyncPromise; - - orderBy(...propName: string[]): IQuery; - orderByDescending(...propName: string[]): IQuery; - select(...propNameSelected: string[]): IQuery; - select(funcProjectionFromThis: () => any): IQuery; - where(mapObjFilterCriteria: any): IQuery; - where(funcPredicateOnThis: (...qParams: any[]) => boolean, ...qValues: any[]): IQuery; - skip(n: number): IQuery; - take(n: number): IQuery; - includeTotalCount(): IQuery; - - //internals found looking into code MobileServices.Web-1.0.0.js - //new (tableName: string, context: any): IQuery; - //getComponents(): any; - //toOData(): string; - } - - interface WindowsAzureStatic { - MobileServiceClient: MobileServiceClient; - } -} - -declare module "WindowsAzure" { - export = WindowsAzure; -} - -declare var WindowsAzure: Microsoft.WindowsAzure.WindowsAzureStatic; diff --git a/azure-mobile-services-client/index.d.ts b/azure-mobile-services-client/index.d.ts new file mode 100644 index 0000000000..f1605d634f --- /dev/null +++ b/azure-mobile-services-client/index.d.ts @@ -0,0 +1,103 @@ +// Type definitions for Microsoft Windows AzureMobile Service 1.0.0 +// Project: http://www.windowsazure.com/en-us/develop/mobile/ +// Definitions by: Morosinotto Daniele +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Microsoft.WindowsAzure { + + // MobileServiceClient object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554219.aspx + interface MobileServiceClient { + new (applicationUrl: string, applicationKey: string): MobileServiceClient; + applicationUrl: string; + applicationKey: string; + currentUser: User; + //for provider:string use one of ProviderEnum: 'microsoftaccount', 'facebook', 'twitter', 'google' + login(provider: string, token: string, callback: (error: any, user: User) => void ): void; + login(provider: string, token: string): asyncPromise; + login(provider: string, callback: (error: any, user: User) => void ): void; + login(provider: string): asyncPromise; + logout(): void; + getTable(tableName: string): MobileServiceTable; + withFilter(serviceFilter: (request: any, next: (request: any, callback: (error:any, response: any) => void ) => void, callback: (error: any, response: any) => void ) => void ) : MobileServiceClient; + invokeApi(apiName: string, options?:InvokeApiOptions): asyncPromise; + } + + interface InvokeApiOptions + { + method?: string; + body?: any; + headers?: Object; + parameters?: Object; + } + + // User object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554220.aspx + interface User { + getIdentities(): any;// { [providerName: string]: { userId: string, accessToken: string, accessTokenSecret?: string }; }; + accessTokens: any; // { [providerName: string]: string; } + level: string; //for level:string use one of LevelEnum: 'admin','anonymous','authenticated' + userId: string; + } + + + // Interface to Platform.async(func) => Platform.Promise based on code MobileServices.Web-1.0.0.js + interface asyncPromise { + then(onSuccess: (result: any) => any, onError?: (error: any) => any): asyncPromise; + done(onSuccess?: (result: any) => void , onError?: (error: any) => void ): void; + } + + // MobileServiceTable object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554239.aspx + interface MobileServiceTable extends IQuery { + new (tableName: string, client: MobileServiceClient): MobileServiceTable; + getTableName(): string; + getMobileServiceClient(): MobileServiceClient; + + insert(instance: any, paramsQS: Object, callback: (error: any, retInserted: any) => any): void; + insert(instance: any, paramsQS: Object): asyncPromise; + insert(instance: any): asyncPromise; + + update(instance: any, paramsQS: Object, callback: (error: any, retUpdated: any) => any): void; + update(instance: any, paramsQS: Object): asyncPromise; + update(instance: any): asyncPromise; + + lookup(id: number, paramsQS: Object, callback: (error: any, retValue: any) => any): void; + lookup(id: number, paramsQS: Object): asyncPromise; + lookup(id: number): asyncPromise; + + del(instance: any, paramsQS: Object, callback: (error?: any) => void ): void; + del(instance: any, paramsQS: Object): asyncPromise; + del(instance: any): asyncPromise; + + + read(query: IQuery, paramsQS: Object, callback: (error: any, retValues: any) => any): void; + read(query: IQuery, paramsQS: Object): asyncPromise; + read(query: IQuery): asyncPromise; + read(): asyncPromise; + } + + + // Interface to describe Query object fluent creation based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj613353.aspx + interface IQuery { + read(paramsQS?: Object): asyncPromise; + + orderBy(...propName: string[]): IQuery; + orderByDescending(...propName: string[]): IQuery; + select(...propNameSelected: string[]): IQuery; + select(funcProjectionFromThis: () => any): IQuery; + where(mapObjFilterCriteria: any): IQuery; + where(funcPredicateOnThis: (...qParams: any[]) => boolean, ...qValues: any[]): IQuery; + skip(n: number): IQuery; + take(n: number): IQuery; + includeTotalCount(): IQuery; + + //internals found looking into code MobileServices.Web-1.0.0.js + //new (tableName: string, context: any): IQuery; + //getComponents(): any; + //toOData(): string; + } + + interface WindowsAzureStatic { + MobileServiceClient: MobileServiceClient; + } +} + +declare var WindowsAzure: Microsoft.WindowsAzure.WindowsAzureStatic; diff --git a/azure-mobile-services-client/tsconfig.json b/azure-mobile-services-client/tsconfig.json new file mode 100644 index 0000000000..cfb5ee9f10 --- /dev/null +++ b/azure-mobile-services-client/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "AzureMobileServicesClient-tests.ts" + ] +} \ No newline at end of file diff --git a/azure-sb/azure-sb-tests.ts b/azure-sb/azure-sb-tests.ts index 5086851815..68b0fc8df7 100644 --- a/azure-sb/azure-sb-tests.ts +++ b/azure-sb/azure-sb-tests.ts @@ -1,4 +1,4 @@ -/// + var nh = new Azure.ServiceBus.NotificationHubService(); nh.send('tag', '', function (error, result) {}); diff --git a/azure-sb/azure-sb.d.ts b/azure-sb/index.d.ts similarity index 100% rename from azure-sb/azure-sb.d.ts rename to azure-sb/index.d.ts diff --git a/azure-sb/tsconfig.json b/azure-sb/tsconfig.json new file mode 100644 index 0000000000..762e71f4a2 --- /dev/null +++ b/azure-sb/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "azure-sb-tests.ts" + ] +} \ No newline at end of file diff --git a/node-azure/azure-tests.ts b/azure/azure-tests.ts similarity index 87% rename from node-azure/azure-tests.ts rename to azure/azure-tests.ts index be81b87947..2d60803d3b 100644 --- a/node-azure/azure-tests.ts +++ b/azure/azure-tests.ts @@ -1,7 +1,4 @@ -/// - - -import Azure = require("azure"); +import Azure = require("azure"); var ts = new Azure.TableService(); diff --git a/azure/index.d.ts b/azure/index.d.ts new file mode 100644 index 0000000000..59d1b9d114 --- /dev/null +++ b/azure/index.d.ts @@ -0,0 +1,1881 @@ +// Type definitions for Azure SDK for Node v0.9.16 +// Project: https://github.com/WindowsAzure/azure-sdk-for-node +// Definitions by: Andrew Gaspar , +// Anti Veeranna , +// Maxime LUCE +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** +* TODO +*/ + +import events = require("events"); +import stream = require("stream"); +import url = require("url"); + +//#region Services +export declare class TableService extends BatchServiceClient { + static incorrectTableNameErr: string; + static incorrectCallbackErr: string; + static incorrectTableQuery: string; + static incorrectPartitionErr: string; + + //#region Constructors + + /** + * Creates a new TableService object. + * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. + * + * @constructor + * @extends {ServiceClient} + */ + constructor(); + /** + * Creates a new TableService object. + * Uses a connectionString to connect + * + * @constructor + * @extends {ServiceClient} + * @param {string} connectionString The connection string. + */ + constructor(connectionString: string); + /** + * Creates a new TableService object. + * Uses a storage account and an access key. + * + * @constructor + * @extends {ServiceClient} + * @param {string} storageAccount The storage account or the connection string. + * @param {string} storageAccessKey The storage access key. + * @param {string} host The host address. + * @param {object} authenticationProvider The authentication provider. + */ + constructor(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string); + + //#endregion + + //#region Service Methods + + getServiceProperties(callback: StorageServicePropertiesCallback): void; + getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; + + setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; + setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Table Methods + + getTable(table: string, callback?: TableRequestCallback): void; + getTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback): void; + + createTable(table: string, callback?: TableRequestCallback): void; + createTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback): void; + + createTableIfNotExists(table: string, callback?: CreateTableIfNotExistsCallback): void; + createTableIfNotExists(table: string, options: TimeoutIntervalOptions, callback?: CreateTableIfNotExistsCallback): void; + + deleteTable(table: string, callback?: DeleteTableCallback): void; + deleteTable(table: string, options: TimeoutIntervalOptions, callback?: DeleteTableCallback): void; + + queryTables(callback?: QueryTablesCallback): void; + queryTables(options: QueryTablesOptions, callback?: QueryTablesCallback): void; + + //#endregion + + //#region Entities Methods + + queryEntity(table: string, partitionKey: string, rowKey: string, callback?: QueryEntityCallback): void; + queryEntity(table: string, partitionKey: string, rowKey: string, options: TimeoutIntervalOptions, callback?: QueryEntityCallback): void; + + queryEntities(tableQuery: TableQuery, callback?: QueryEntitiesCallback): void; + queryEntities(tableQuery: TableQuery, options: TimeoutIntervalOptions, callback?: QueryEntitiesCallback): void; + + insertEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; + insertEntity(tableName: string, entityDescriptor: Entity, options: TimeoutIntervalOptions, callback?: ModifyEntityCallback): void; + + insertOrReplaceEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; + insertOrReplaceEntity(tableName: string, entityDescriptor: Entity, options: TimeoutIntervalOptions, callback?: ModifyEntityCallback): void; + + updateEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; + updateEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: ModifyEntityCallback): void; + + mergeEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; + mergeEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: ModifyEntityCallback): void; + + insertOrMergeEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; + insertOrMergeEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: ModifyEntityCallback): void; + + deleteEntity(tableName: string, entityDescriptor: Entity, callback?: DeleteEntityCallback): void; + deleteEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: DeleteEntityCallback): void; + + //#endregion +} + +export declare class BlobService extends StorageServiceClient { + singleBlobPutThresholdInBytes: number; + parallelOperationThreadCount: number; + + SpeedSummary: typeof SpeedSummary; + + //#region Constructors + + /** + * Creates a new BlobService object. + * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. + * + * @constructor + * @extends {StorageServiceClient} + */ + constructor(); + + /** + * Creates a new BlobService object. + * Uses a connectionString to connect + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} connectionString The connection string. + */ + constructor(connectionString: string); + + /** + * Creates a new BlobService object. + * Uses a storage account and an access key. + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} storageAccount The storage account or the connection string. + * @param {string} storageAccessKey The storage access key. + * @param {string} host The host address. + * @param {object} sasToken The Shared Access Signature token. + */ + constructor(storageAccount: string, storageAccessKey: string, host?: string, sasToken?: string); + + //#endregion + + //#region Service Methods + + /** + * Gets the properties of a storage account�s Blob service, including Azure Storage Analytics. + */ + getServiceProperties(callback: StorageServicePropertiesCallback): void; + getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; + + /** + * Sets the properties of a storage account�s Blob service, including Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + */ + setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; + setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Containers Methods + + /** + * Lists a segment containing a collection of container items under the specified account. + */ + listContainers(callback: ListContainersCallback): void; + listContainers(options: ListContainersOptions, callback: ListContainersCallback): void; + + /** + * Creates a new container under the specified account. + * If a container with the same name already exists, the operation fails. + */ + createContainer(container: string, callback: StorageCallback): void; + createContainer(container: string, options: CreateContainerOptions, callback: StorageCallback): void; + + /** + * Creates a new container under the specified account if the container does not exists. + */ + createContainerIfNotExists(container: string, callback: StorageCallback): void; + createContainerIfNotExists(container: string, options: CreateContainerOptions, callback: StorageCallback): void; + + /** + * Retrieves a container and its properties from a specified account. + */ + getContainerProperties(container: string, callback: StorageCallback): void; + getContainerProperties(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; + + /** + * Returns all user-defined metadata for the container. + */ + getContainerMetadata(container: string, callback: StorageCallback): void; + getContainerMetadata(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; + + /** + * Sets the container's metadata. + */ + setContainerMetadata(container: string, metadata: StorageMetadata, callback: StorageCallback): void; + setContainerMetadata(container: string, metadata: StorageMetadata, options: AccessConditionsOptions, callback: StorageCallback): void; + + /** + * Gets the container's ACL. + */ + getContainerAcl(container: string, callback: StorageCallback): void; + getContainerAcl(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; + + /** + * Updates the container's ACL. + */ + setContainerAcl(container: string, publicAccessLevel: string, callback: StorageCallback): void; + setContainerAcl(container: string, publicAccessLevel: string, options: StorageAclOptions, callback: StorageCallback): void; + + /** + * Marks the specified container for deletion. + * The container and any blobs contained within it are later deleted during garbage collection. + */ + deleteContainer(container: string, callback: StorageCallbackVoid): void; + deleteContainer(container: string, options: LeaseIdOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Blob Methods + + /** + * Lists all of the blobs in the given container. + */ + listBlobs(container: string, callback: ListBlobsCallback): void; + listBlobs(container: string, options: ListBlobsOptions, callback: ListBlobsCallback): void; + + /** + * Returns all user-defined metadata, standard HTTP properties, and system properties for the blob. + * It does not return or modify the content of the blob. + */ + getBlobProperties(container: string, blob: string, callback: StorageCallback): void; + getBlobProperties(container: string, blob: string, options: GetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Sets user-defined properties for the specified blob or snapshot. + * It does not return or modify the content of the blob. + */ + setBlobProperties(container: string, blob: string, callback: StorageCallback): void; + setBlobProperties(container: string, blob: string, options: SetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Sets user-defined metadata for the specified blob or snapshot as one or more name-value pairs + * It does not return or modify the content of the blob. + */ + setBlobMetadata(container: string, blob: string, metadata: StorageMetadata, callback: StorageCallback): void; + setBlobMetadata(container: string, blob: string, metadata: StorageMetadata, options: GetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Provides a stream to read from a blob. + */ + getBlob(container: string, blob: string, callback: StorageCallback): stream.Readable; + getBlob(container: string, blob: string, options: ReadBlobOptions, callback: StorageCallback): stream.Readable; + + /** + * Downloads a blob into a file. + */ + getBlobToFile(container: string, blob: string, localFileName: string, callback: StorageCallback): void; + getBlobToFile(container: string, blob: string, localFileName: string, options: ReadBlobOptions, callback: StorageCallback): void; + + /** + * Downloads a blob into a stream. + */ + getBlobToStream(container: string, blob: string, stream: stream.Writable, callback: StorageCallback): void; + getBlobToStream(container: string, blob: string, stream: stream.Writable, options: ReadBlobOptions, callback: StorageCallback): void; + + /** + * Downloads a blob into a text string. + */ + getBlobToText(container: string, blob: string, callback: GetBlobToTextCallback): void; + getBlobToText(container: string, blob: string, options: ReadBlobOptions, callback: GetBlobToTextCallback): void; + + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. + * If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, + * or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error + * and nothing will be deleted. + * If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included. + */ + deleteBlob(container: string, blob: string, callback: StorageCallback): void; + deleteBlob(container: string, blob: string, options: DeleteBlobOptions, callback: StorageCallback): void; + + /** + * Creates a read-only snapshot of a blob. + */ + createBlobSnapshot(container: string, blob: string, callback: StorageCallback): void; + createBlobSnapshot(container: string, blob: string, options: BlobSnapshotOptions, callback: StorageCallback): void; + + /** + * Starts to copy a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob. + */ + copyBlob(sourceUri: string, targetContainer: string, targetBlob: string, callback: StorageCallback): void; + copyBlob(sourceUri: string, targetContainer: string, targetBlob: string, options: CopyBlobOptions, callback: StorageCallback): void; + + /** + * Creates a read-only snapshot of a blob. + */ + abortCopyBlob(container: string, blob: string, copyId: string, callback: StorageCallbackVoid): void; + abortCopyBlob(container: string, blob: string, copyId: string, options: LeaseIdOptions, callback: StorageCallbackVoid): void; + + /** + * Retrieves a shared access signature token. + */ + generateSharedAccessSignature(container: string, blob: string, sharedAccessPolicy: SharedAccessPolicy): SharedAccessSignatureResult; + + /** + * Retrieves a blob or container URL. + */ + getBlobUrl(container: string): string; + getBlobUrl(container: string, blob: string): string; + getBlobUrl(container: string, blob: string, sharedAccessPolicy: SharedAccessPolicy): string; + + /** + * Uploads a blob. + */ + createBlob(container: string, blob: string, blobType: string, callback: StorageCallback): stream.Writable; + createBlob(container: string, blob: string, blobType: string, options: UploadBlockBlobOptions, callback: StorageCallback): stream.Writable; + + //#endregion + + //#region Page Blob Methods + + /** + * Creates a page blob of the specified length. + */ + createPageBlob(container: string, blob: string, length: number, callback: StorageCallbackVoid): void; + createPageBlob(container: string, blob: string, length: number, options: SetBlobPropertiesOptions, callback: StorageCallbackVoid): void; + + /** + * Updates a page blob from a stream. + */ + createBlobPagesFromStream(container: string, blob: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, callback: StorageCallback): void; + createBlobPagesFromStream(container: string, blob: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, options: CreatePagesOptions, callback: StorageCallback): void; + + /** + * Updates a page blob from a text string. + */ + createBlobPagesFromText(container: string, blob: string, text: string, rangeStart: number, rangeEnd: number, callback: StorageCallback): void; + createBlobPagesFromText(container: string, blob: string, text: string, rangeStart: number, rangeEnd: number, options: CreatePagesOptions, callback: StorageCallback): void; + + /** + * Lists page ranges. + * Lists all of the page ranges by default, or only the page ranges over a specific range of bytes if rangeStart and rangeEnd are specified. + */ + listBlobRegions(container: string, blob: string, callback: StorageCallback): void; + listBlobRegions(container: string, blob: string, options: PageRangeOptions, callback: StorageCallback): void; + + /** + * Clears a range of pages. + */ + clearBlobPages(container: string, blob: string, rangeStart: number, rangeEnd: number, callback: StorageCallbackVoid): void; + clearBlobPages(container: string, blob: string, rangeStart: number, rangeEnd: number, options: LeaseAccessConditionsOptions, callback: StorageCallbackVoid): void; + + /** + * Resizes a page blob. + */ + resizePageBlob(container: string, blob: string, size: number, callback: StorageCallback): void; + resizePageBlob(container: string, blob: string, size: number, options: LeaseAccessConditionsOptions, callback: StorageCallback): void; + + /** + * Sets the page blob's sequence number. + */ + setPageBlobSequenceNumber(container: string, blob: string, sequenceNumberAction: string, sequenceNumber: string, callback: StorageCallback): void; + setPageBlobSequenceNumber(container: string, blob: string, sequenceNumberAction: string, sequenceNumber: string, options: AccessConditionsOptions, callback: StorageCallback): void; + + //#endregion + + //#region Block Blob Methods + + /** + * Uploads a block blob from file. + */ + putBlockBlobFromFile(container: string, blob: string, localFileName: string, callback: StorageCallback): SpeedSummary; + putBlockBlobFromFile(container: string, blob: string, localFileName: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + createBlockBlobFromFile(container: string, blob: string, localFileName: string, callback: StorageCallback): SpeedSummary; + createBlockBlobFromFile(container: string, blob: string, localFileName: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + + /** + * Uploads a block blob from a stream. + */ + putBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, callback: StorageCallback): SpeedSummary; + putBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + createBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, callback: StorageCallback): SpeedSummary; + createBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + + /** + * Uploads a block blob from a text string. + */ + createBlockBlobFromText(container: string, blob: string, text: string, callback: StorageCallback): SpeedSummary; + createBlockBlobFromText(container: string, blob: string, text: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + + /** + * Creates a new block to be committed as part of a blob. + */ + createBlobBlockFromStream(blockId: string, container: string, blob: string, readStream: stream.Stream, streamLength: number, callback: StorageCallbackVoid): void; + createBlobBlockFromStream(blockId: string, container: string, blob: string, readStream: stream.Stream, streamLength: number, options: CreateBlockOptions, callback: StorageCallbackVoid): void; + + /** + * Creates a new block to be committed as part of a blob. + */ + createBlobBlockFromText(blockId: string, container: string, blob: string, text: string, callback: StorageCallbackVoid): void; + createBlobBlockFromText(blockId: string, container: string, blob: string, text: string, options: CreateBlockOptions, callback: StorageCallbackVoid): void; + + /** + * Writes a blob by specifying the list of block IDs that make up the blob. + * In order to be written as part of a blob, a block must have been successfully written to the server in a prior + * createBlock operation. + */ + commitBlobBlocks(container: string, blob: string, blockList: BlockList, callback: StorageCallback): void; + commitBlobBlocks(container: string, blob: string, blockList: BlockList, options: CreateBlockOptions, callback: StorageCallback): void; + + /** + * Retrieves the list of blocks that have been uploaded as part of a block blob. + */ + listBlobBlocks(container: string, blob: string, blockListType: string, callback: StorageCallback): void; + listBlobBlocks(container: string, blob: string, blockListType: string, options: GetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Generate a random block id prefix. + */ + generateBlockIdPrefix(): string; + /** + * Get a block id according to prefix and block number. + */ + getBlockId(prefix: string, number: number): string; + + //#endregion + + //#region Lease Methods + + /** + * Acquires a new lease. + * If container and blob are specified, acquires a blob lease. + * Otherwise, if only container is specified and blob is null, acquires a container lease. + */ + acquireLease(container: string, blob: string, callback: StorageCallback): void; + acquireLease(container: string, blob: string, options: LeaseOptions, callback: StorageCallback): void; + + /** + * Renews an existing lease. + * If container and blob are specified, renews the blob lease. + * Otherwise, if only container is specified and blob is null, renews the container lease. + */ + renewLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; + renewLease(container: string, blob: string, leaseId: string, options: AccessConditionsOptions, callback: StorageCallback): void; + + /** + * Releases the lease. + * If container and blob are specified, releases the blob lease. + * Otherwise, if only container is specified and blob is null, releases the container lease. + */ + releaseLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; + releaseLease(container: string, blob: string, leaseId: string, options: AccessConditionsOptions, callback: StorageCallback): void; + + /** + * Breaks the lease but ensures that another client cannot acquire a new lease until the current lease period has expired. + * If container and blob are specified, breaks the blob lease. + * Otherwise, if only container is specified and blob is null, breaks the container lease. + */ + breakLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; + breakLease(container: string, blob: string, leaseId: string, options: BreakLeaseOptions, callback: StorageCallback): void; + + //#endregion +} + +export declare class QueueService extends StorageServiceClient { + authenticationProvider: SharedKey; + + //#region Constructors + + /** + * Creates a new BlobService object. + * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. + * + * @constructor + * @extends {StorageServiceClient} + */ + constructor(); + + /** + * Creates a new BlobService object. + * Uses a connectionString to connect + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} connectionString The connection string. + */ + constructor(connectionString: string); + + /** + * Creates a new BlobService object. + * Uses a storage account and an access key. + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} storageAccount The storage account or the connection string. + * @param {string} storageAccessKey The storage access key. + * @param {string} host The host address. + * @param {object} sasToken The Shared Access Signature token. + */ + constructor(storageAccount: string, storageAccessKey: string, host?: string, sasToken?: string); + + //#endregion + + //#region Service Methods + + /** + * Gets the properties of a storage account�s Blob service, including Azure Storage Analytics. + */ + getServiceProperties(callback: StorageServicePropertiesCallback): void; + getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; + + /** + * Sets the properties of a storage account�s Blob service, including Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + */ + setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; + setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Queue Methods + + /** + * Lists all queues under the given account. + */ + listQueues(callback: ListQueuesCallback): void; + listQueues(options: ListQueuesOptions, callback: ListQueuesCallback): void; + + /** + * Creates a new queue under the given account. + */ + createQueue(queue: string, callback: StorageCallback): void; + createQueue(queue: string, options: MetadataOptions, callback: StorageCallback): void; + + /** + * Creates a new queue under the given account if it doesn't exist. + */ + createQueueIfNotExists(queue: string, callback: StorageCallback): void; + createQueueIfNotExists(queue: string, options: MetadataOptions, callback: StorageCallback): void; + + /** + * Permanently deletes the specified queue. + */ + deleteQueue(queue: string, callback: StorageCallback): void; + deleteQueue(queue: string, options: TimeoutIntervalOptions, callback: StorageCallback): void; + + /** + * Returns queue properties, including user-defined metadata. + */ + getQueueMetadata(queue: string, callback: StorageCallback): void; + getQueueMetadata(queue: string, options: TimeoutIntervalOptions, callback: StorageCallback): void; + + /** + * Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. + */ + setQueueMetadata(queue: string, metadata: StorageMetadata, callback: StorageCallback): void; + setQueueMetadata(queue: string, metadata: StorageMetadata, options: TimeoutIntervalOptions, callback: StorageCallback): void; + + //#endregion + + //#region Message Methods + + /** + * Adds a new message to the back of the message queue. A visibility timeout can also be specified to make the message + * invisible until the visibility timeout expires. A message must be in a format that can be included in an XML request + * with UTF-8 encoding. The encoded message can be up to 64KB in size for versions 2011-08-18 and newer, or 8KB in size + * for previous versions. + */ + createMessage(queue: string, messageText: string, callback: StorageCallback): void + createMessage(queue: string, messageText: string, options: CreateQueueMessageOptions, callback: StorageCallback): void + + /** + * Retrieves a message from the queue and makes it invisible to other consumers. + */ + getMessages(queue: string, callback: StorageCallback): void; + getMessages(queue: string, options: GetQueueMessagesOptions, callback: StorageCallback): void; + + /** + * Retrieves a message from the front of the queue, without changing the message visibility. + */ + peekMessages(queue: string, callback: StorageCallback): void; + peekMessages(queue: string, options: PeekQueueMessagesOptions, callback: StorageCallback): void; + + /** + * Deletes a specified message from the queue. + */ + deleteMessage(queue: string, messageId: string, popreceipt: string, callback: StorageCallback): void + deleteMessage(queue: string, messageId: string, popreceipt: string, options: TimeoutIntervalOptions, callback: StorageCallback): void + + /** + * Clears all messages from the queue. + */ + clearMessages(queue: string, callback: StorageCallbackVoid): void; + clearMessages(queue: string, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + /** + * Deletes a specified message from the queue. + */ + updateMessage(queue: string, messageId: string, popreceipt: string, visibilitytimeout: number, callback: StorageCallback): void + updateMessage(queue: string, messageId: string, popreceipt: string, visibilitytimeout: number, options: UpdateQueueMessagesOptions, callback: StorageCallback): void + + //#endregion +} + +export declare class ServiceBusService { + +} + +export declare class SqlService { + +} + +export declare class ServiceManagementService { + +} + +export declare class SqlManagementService { +} +//#endregion + +//#region Service Creators +export declare function createTableService(): TableService; +export declare function createTableService(connectionString: string): TableService; +export declare function createTableService(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string): TableService; + +export declare function createBlobService(): BlobService; +export declare function createBlobService(connectionString: string): BlobService; +export declare function createBlobService(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string): BlobService; + +export declare function createQueueService(): QueueService; +export declare function createQueueService(connectionString: string): QueueService; +export declare function createQueueService(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string): QueueService; + +export declare function createServiceBusService(): ServiceBusService; +export declare function createServiceBusService(connectionString: string): ServiceBusService; +export declare function createServiceBusService(namespace: string, accessKey?: string, issuer?: string, acsNamespace?: string, host?: string, authenticationProvider?: string): ServiceBusService; + +export declare function createSqlService(serverName: string, administratorLogin: string, administratorLoginPassword: string, host?: string, acsHost?: string, authenticationProvider?: string): SqlService; + +export declare function createServiceManagementService(subscriptionId: string, authentication: string, hostOptions: string): ServiceManagementService; + +export declare function createSqlManagementService(subscriptionId: string, authentication: string, hostOptions: string): SqlManagementService; +//#endregion + +//#region RoleEnvironment + +interface RoleEnvironmentInterface extends events.EventEmitter { + incorrectCallbackErr: string; + clientId: string; + VersionEndpointFixedPath: string; + EnvironmentVariables: { + [key: string]: string; + VersionEndpointEnvironmentName: string; + }; + + /** + * Returns a RoleInstance object that represents the role instance + * in which this code is currently executing. + */ + getCurrentRoleInstance(callback: SimpleCallback): void; + + /** + * Returns the deployment ID that uniquely identifies the deployment in + * which this role instance is running. + */ + getDeploymentId(callback: SimpleCallback): void; + + /** + * Indicates whether the role instance is running in the Microsoft Azure + * environment. It is good practice to enclose any code that uses + * service runtime in the isAvailable callback. + */ + isAvailable(callback: SimpleCallback): void; + + /** + * Indicates whether the role instance is running in the development fabric. + */ + isEmulated(callback: SimpleCallback): void; + + /** + * Returns the set of Role objects defined for your service. + * Roles are defined in the service definition file. + */ + getRoles(callback: SimpleCallback>): void; + + /** + * Retrieves the settings in the service configuration file. + * + * A role's configuration settings are defined in the service definition file. + * Values for configuration settings are set in the service configuration file. + * For more information on configuration settings, see the [Service Definition Schema](http://msdn.microsoft.com/en-us/library/windowsazure/ee758711.aspx) + * and [Service Configuration Schema](http://msdn.microsoft.com/en-us/library/windowsazure/ee758710.aspx). + */ + getConfigurationSettings(callback: SimpleCallback>): void; + + /** + * Retrieves the set of named local storage resources, along with the path. + * For example, the DiagnosticStore resource which is defined for every role + * provides a location for runtime diagnostics and logs. + */ + getLocalResources(callback: SimpleCallback>): void; + + /** + * Requests that the current role instance be stopped and restarted. + * + * Before the role instance is recycled, the Microsoft Azure load balancer takes the role instance out of rotation. + * This ensures that no new requests are routed to the instance while it is restarting. + * + * A call to `RequestRecycle` initiates the normal shutdown cycle. Microsoft Azure raises the + * `Stopping` event and calls the `OnStop` method so that you can run the necessary code to + * prepare the instance to be recycled. + */ + requestRecycle(callback: ErrorCallback): void; + + /** + * Sets the status of the role instance. + * + * An instance may indicate that it is in one of two states: Ready or Busy. If an instance's state is Ready, it is + * prepared to receive requests from the load balancer. If the instance's state is Busy, it will not receive + * requests from the load balancer. + */ + setStatus(roleInstanceStatus: string, expirationUtc: Date, callback: ErrorCallback): void; + + /** + * Clears the status of the role instance. + * An instance may indicate that it has completed communicating status by calling this method. + */ + clearStatus(callback: ErrorCallback): void; +} + +export declare var RoleEnvironment: RoleEnvironmentInterface; + +//#endregion + +//#region Export of internal classes +export declare class WebResource { + rawResponse: boolean; + queryString: Dictionary; + + constructor(); + + get(path: string): WebResource; + put(path: string): WebResource; + post(path: string): WebResource; + merge(path: string): WebResource; + head(path: string): WebResource; + del(path: string): WebResource; + + withProperty(name: string, value: string): WebResource; + withRawResponse(rawResponse: boolean): WebResource; + withHeadersOnly(headersOnly: boolean): WebResource; + withQueryOption(name: string, value: string, defaultValue: string): WebResource; + withQueryOptions(queryOptions: Dictionary): WebResource; + withHeader(name: string, value: string): WebResource; + withHeaders(headers: Dictionary): WebResource; + withBody(body: any): WebResource; + addOptionalMetadataHeaders(metadata: StorageMetadata): WebResource; + + validResponse(statusCode: number): boolean; + pipeInput(inputStream: stream.Stream, destStream: stream.Stream): stream.Stream; +} + +export declare class ServiceClient extends events.EventEmitter { + static EnvironmentVariables: any; + static DEVSTORE_STORAGE_ACCOUNT: string; + static DEVSTORE_STORAGE_ACCESS_KEY: string; + static DEVSTORE_BLOB_HOST: string; + static DEVSTORE_QUEUE_HOST: string; + static DEVSTORE_TABLE_HOST: string; + static CLOUD_BLOB_HOST: string; + static CLOUD_QUEUE_HOST: string; + static CLOUD_TABLE_HOST: string; + static CLOUD_SERVICEBUS_HOST: string; + static CLOUD_ACCESS_CONTROL_HOST: string; + static CLOUD_SERVICE_MANAGEMENT_HOST: string; + static CLOUD_DATABASE_HOST: string; + static DEFAULT_SERVICEBUS_ISSUER: string; + static DEFAULT_WRAP_NAMESPACE_SUFFIX: string; + static DEFAULT_PROTOCOL: string; + + constructor(host: string, authenticationProvider: any); + + setHost(host: string): void; + performRequest(webResource: WebResource, outputData: string, options: any, callback: Function): void; + performRequestOutputStream(webResource: WebResource, outputStream: any, options: any, callback: Function): void; + performRequestInputStream(webResource: WebResource, outputData: string, inputStream: any, options: any, callback: Function): void; + withFilter(newFilter: Filter): ServiceClient; + parseMetadataHeaders(headers: any): any; + isEmulated(): boolean; + setProxy(proxyUrl: string, proxyPort: number): void; +} + +export declare class BatchServiceClient extends StorageServiceClient { + operations: any[]; + + constructor(storageAccount: string, storageAccessKey: string, host: string, usePathstyleUri: boolean, authenticationProvider: any); + beginBatch(): void; + isInBatch(): boolean; + rollback(): void; + hasOperations(): boolean; + addOperation(webResource: WebResource, outputData: any): void; + commitBatch(callback: (error: any, operationResponses: any[], response: any) => void): void; + commitBatch(options: any, callback: (error: any, operationResponses: any[], response: any) => void): void; + processResponse(responseObject: any, requestOperations: any[]): any[]; + processOperation(webResource: WebResource, rawResponse: string): any; +} + +export declare class ServiceManagementClient { + +} + +export declare class TableQuery { + static select(...fields: string[]): TableQuery; + from(table: string): TableQuery; + whereKeys(partitionKey: string, rowKey: string): TableQuery; + whereNextKeys(partitionKey: string, rowKey: string): TableQuery; + where(condition: string, ...values: string[]): TableQuery; + and(condition: string, ...args: string[]): TableQuery; + or(condition: string, ...args: string[]): TableQuery; + top(integer: number): TableQuery; + toQueryObject(): any; + toPath(): string; +} + +export declare class BlobResult { + blob: string; + container: string; + + etag: string; + lastModified: string; + contentType: string; + contentEncoding: string; + contentLanguage: string; + contentMD5: string; + cacheControl: string; + contentRange: string; + contentTypeHeader: string; + contentEncodingHeader: string; + contentLanguageHeader: string; + contentMD5Header: string; + cacheControlHeader: string; + contentLength: number; + contentLengthHeader: number; + contentDisposition: string; + contentDispositionHeader: string; + range: string; + rangeHeader: string; + getContentMd5: string; + acceptRanges: string; + blobType: string; + leaseStatus: string; + leaseId: string; + leaseDuration: string; + leaseState: string; + sequenceNumber: string; + copyStatus: string; + copyCompletionTime: string; + copyStatusDescription: string; + copyId: string; + copyProgress: number; + requestId: string; + + metadata: StorageMetadata; + + constructor(); + constructor(container: string); + constructor(container: string, blob: string); + + static parse(blobXml: any): BlobResult; + static setHeadersFromBlob(webResource: WebResource, blob: BlobResult): void; + + getPropertiesFromHeaders(headers: any): void; +} + +export declare class ContainerResult { + name: string; + publicAccessLevel: string; + + etag: string; + lastModified: string; + leaseStatus: string; + leaseDuration: string; + leaseState: string; + requestId: string; + + metadata: StorageMetadata; + signedIdentifiers: SignedIdentifier[]; + + constructor(); + constructor(name: string); + constructor(name: string, publicAccessLevel: string); + + static parse(containerXml: any): ContainerResult; + + getPropertiesFromHeaders(headers: any): void; +} + +export declare class LeaseResult { + container: string; + blob: string; + id: string; + time: string; + etag: string; + lastModified: string; + + constructor(); + constructor(container: string); + constructor(container: string, blob: string); + constructor(container: string, blob: string, id: string); + constructor(container: string, blob: string, id: string, time: string); + + getPropertiesFromHeaders(header: any): void; +} + +export declare class QueueResult { + name: string; + metadata: StorageMetadata; + approximatemessagecount: number; + + constructor(); + constructor(name: string); + constructor(name: string, metadata: StorageMetadata); + + static parse(messageXml: any): QueueResult; + + getPropertiesFromHeaders(headers: any): void; +} + +export declare class QueueMessageResult { + queue: string; + insertiontime: string; + expirationtime: string; + timenextvisible: string; + messagetext: string; + dequeuecount: string; + messageid: string; + popreceipt: string; + metadata: StorageMetadata; + + constructor(); + constructor(queue: string); + constructor(queue: string, messageid: string); + constructor(queue: string, messageid: string, popreceipt: string); + constructor(queue: string, messageid: string, popreceipt: string, metadata: StorageMetadata); + + static serialize(messageJs: string): string; + static parse(messageXml: any): QueueMessageResult; + + getPropertiesFromHeaders(headers: any): void; +} + +export declare class SpeedSummary { + name: string; + totalSize: number; + completeSize: number; + + _startTime: Date; + _timeWindowInSeconds: number; + _timeWindow: number; + _totalWindowSize: number; + _speedTracks: number[]; + _speedTrackPtr: number; + + constructor(name: string); + + /** + * Get running seconds + */ + getElapsedSeconds(): string; + getElapsedSeconds(humanReadable: boolean): number; + + /** + * Get complete percentage + */ + getCompletePercent(): number; + getCompletePercent(len: number): number; + + /** + * Get average upload/download speed + */ + getAverageSpeed(): string; + getAverageSpeed(humanReadable: boolean): number; + + /** + * Get internal speed + */ + getSpeed(): string; + getSpeed(humanReadable: boolean): number; + + /** + * Get auto increment function + */ + getSpeed(size: number): (error: Error, value: any) => void; + + /** + * Get total size + */ + getTotalSize(): string; + getTotalSize(humanReadable: boolean): number; + + /** + * Get completed data size + */ + getCompleteSize(): string; + getCompleteSize(humanReadable: boolean): number; +} + +export declare module Constants { + +} + +export interface Filter { + handle(requestOptions: any, next: Function): void; +} + +export declare class LinearRetryPolicyFilter implements Filter { + constructor(retryCount?: number, retryInterval?: number); + retryCount: number; + retryInterval: number; + handle(requestOptions: any, next: Function): void; +} + +export declare class ExponentialRetryPolicyFilter implements Filter { + constructor(retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number); + retryCount: number; + retryInterval: number; + minRetryInterval: number; + maxRetryInterval: number; + handle(requestOptions: any, next: Function): void; +} + +export declare class HmacSha256Sign { + +} + +export declare class SharedAccessSignature { + storageAccount: string; + storageAccessKey: string; + permissionSet: string[]; + signer: HmacSha256Sign; + + constructor(storageAccount: string, storageAccessKey: string, permissionSet: string[]) + + /** + * Generates the query string for a shared access signature signing. + */ + generateSignedQueryString(path: string, queryString: Dictionary, resourceType: string, sharedAccessPolicy: SharedAccessPolicy): Dictionary; + + /** + * Signs a request with the signature header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Generates the shared access signature for a resource. + */ + _generateSignature(path: string, resourceType: string, sharedAccessPolicy: SharedAccessPolicy): string; + + /** + * Generates the query string for a shared access signature signing. + */ + _permissionMatchesRequest(sharedAccessSignature: string, webResource: WebResource, resourceType: string, requiredPermissions: string[]): string; +} + +export declare class SharedKey { + storageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; + + /** + * Constructs the Canonicalized Headers string. + * + * To construct the CanonicalizedHeaders portion of the signature string, + * follow these steps: 1. Retrieve all headers for the resource that begin + * with x-ms-, including the x-ms-date header. 2. Convert each HTTP header + * name to lowercase. 3. Sort the headers lexicographically by header name, + * in ascending order. Each header may appear only once in the + * string. 4. Unfold the string by replacing any breaking white space with a + * single space. 5. Trim any white space around the colon in the header. 6. + * Finally, append a new line character to each canonicalized header in the + * resulting list. Construct the CanonicalizedHeaders string by + * concatenating all headers in this list into a single string. + */ + _getCanonicalizedHeaders(webResource: WebResource): string; +} + +export declare class SharedKeyLite { + storageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; + + /** + * Constructs the Canonicalized Headers string. + * + * To construct the CanonicalizedHeaders portion of the signature string, + * follow these steps: 1. Retrieve all headers for the resource that begin + * with x-ms-, including the x-ms-date header. 2. Convert each HTTP header + * name to lowercase. 3. Sort the headers lexicographically by header name, + * in ascending order. Each header may appear only once in the + * string. 4. Unfold the string by replacing any breaking white space with a + * single space. 5. Trim any white space around the colon in the header. 6. + * Finally, append a new line character to each canonicalized header in the + * resulting list. Construct the CanonicalizedHeaders string by + * concatenating all headers in this list into a single string. + */ + _getCanonicalizedHeaders(webResource: WebResource): string; +} + +export declare class SharedKeyTable { + storageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; +} + +export declare class SharedKeyLiteTable { + torageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; +} + +export declare module ISO8061Date { + /** + * Formats a date into an iso 8061 string. + */ + export function format(date: Date): string; + + /** + * Parses an ISO 8061 date string into a date object. + */ + export function parse(stringDateTime: string): Date; +} + +export declare class Logger { + level: string; + loggerFunction: (level: string, message: string) => void; + + static LogLevels: { + EMERGENCY: string; + ALERT: string; + CRITICAL: string; + ERROR: string; + WARNING: string; + NOTICE: string; + INFO: string; + DEBUG: string; + }; + static logPriority: string[]; + + log(level: string, message: string): void; + emergency(message: string): void; + alert(message: string): void; + critical(message: string): void; + error(message: string): void; + warning(message: string): void; + notice(message: string): void; + info(message: string): void; + debug(message: string): void; + + defaultLoggerFunction(level: string, message: string): void; +} + +export declare class ConnectionStringParser { + _value: string; + _pos: number; + _state: string; + + constructor(connectionString: string); + + _parse(options: ConnectionStringParseOptions): Dictionary; + + _extractKey(): string; + _extractString(quote: string): string; + _extractValue(): string; + + _skipWhitespaces(): void; + _skipOperator(operator: string): void; + + static parse(connectionString: string): Dictionary; +} + +export declare module ServiceSettings { + export var DEFAULT_PROTOCOL: string; + + export class NoMatchError implements Error { + name: string; + message: string; + constr: any; + + constructor(); + constructor(message: string); + constructor(message: string, constr: any); + } + + /** + * Throws an exception if the connection string format does not match any of the + * available formats. + */ + export function noMatchConnectionString(connectionString: string): void; + + /** + * Throws an exception if the settings dont match any of the available formats. + */ + export function noMatchSettings(settings: any): void; + + /** + * Parses the connection string and then validate that the parsed keys belong to + * the validSettingKeys + */ + export function parseAndValidateKeys(connectionString: string, validKeys: string[]): string[]; + + /** + * Creates an anonymous function that acts as predicate to perform a validation. + */ + export function getValidator(requirements: Dictionary, isRequired: boolean, atLeastOne: boolean): ValidatorFunction; + + /** + * Creates a setting value condition that validates it is one of the passed valid values. + */ + export function setting(name: string): string[]; + + /** + * Creates an "at least one" predicate for the provided list of requirements. + */ + export function atLeastOne(...args: any[]): ValidatorFunction; + + /** + * Creates an optional predicate for the provided list of requirements. + */ + export function optional(...args: any[]): ValidatorFunction; + + /** + * Creates an required predicate for the provided list of requirements. + */ + export function allRequired(...args: any[]): ValidatorFunction; + + /** + * Creates a setting value condition using the passed predicate. + */ + export function settingWithFunc(name: string, predicate: Function): Requirement[]; + + /** + * Tests to see if a given list of settings matches a set of filters exactly. + */ + export function matchedSpecification(settings: Dictionary): boolean; + + /** + * Tests to see if a given list of settings matches a set of filters exactly. + */ + export function parseHost(uri: string): url.Url; +} + +export declare class StorageServiceSettings { + _name: string; + _key: string; + _blobEndpointUri: string; + _queueEndpointUri: string; + _tableEndpointUri: string; + _usePathStyleUri: boolean; + + constructor(name: string, key: string, blobEndpointUri: string, queueEndpointUri: string, tableEndpointUri: string, usePathStyleUri: boolean); + + /** + * Returns a StorageServiceSettings with development storage credentials using + * the specified proxy Uri. + */ + static _getDevelopmentStorageAccount(): StorageServiceSettings; + static _getDevelopmentStorageAccount(proxy: string): StorageServiceSettings; + + /** + * Gets a StorageServiceSettings object that references the development storage + * account. + */ + static getDevelopmentStorageAccountSettings(): StorageServiceSettings; + + /** + * Gets the default service endpoint using the specified protocol and account + * name. + */ + static _getDefaultServiceEndpoint(settings: Dictionary, dns: string): string; + + /** + * Creates StorageServiceSettings object given endpoints uri. + */ + static _createStorageServiceSettings(settings: Dictionary, blobEndpointUri: string, queueEndpointUri: string, tableEndpointUri: string): StorageServiceSettings; + + /** + * Creates a ServiceBusSettings object from a set of settings. + */ + static createFromSettings(settings: Dictionary): StorageServiceSettings; + + /** + * Creates a StorageServiceSettings object from the given connection string. + */ + static createFromConnectionString(connectionString: string): StorageServiceSettings; + + static createExplicitlyOrFromEnvironment(storageAccount: string, storageAccessKey: string, host: string): StorageServiceSettings; + + static isDevelopmentStorage(storageAccount: string, storageAccessKey: string, parsedHost: string): boolean; + + static createFromConfig(config: any): StorageServiceSettings; + + static customizeConfig(config: any): void; +} + +export declare class ServiceBusSettings { + +} + +export declare class ServiceManagementSettinsg { + +} + +export declare module Validate { + /** + * Checks if the given uri is valid or not. + */ + export function isValidUri(uri: string): boolean; + + /** + * Validates that a clusterCreationObject is properly formed. + */ + export function isValidHDInsightCreationObject(clusterCreationObject: ClusterCreationOptions): void; + export function isValidHDInsightCreationObject(clusterCreationObject: ClusterCreationOptions, callback: ErrorCallback): void; + + export function isValidUuid(uuid: string): void; + export function isValidUuid(uuid: string, callback: ErrorCallback): void; + + /** + * Creates a anonymous function that check if a given key is base 64 encoded. + */ + export function isBase64Encoded(key: string): boolean; + + /** + * Validates a function. + */ + export function isValidFunction(functionObject: any, functionName: string): void; + + /** + * Validates that a Service Bus namespace name + * is legally allowable. Does not check availability. + */ + export function namespaceNameIsValid(name: string): boolean; + export function namespaceNameIsValid(name: string, callback: ErrorCallback): boolean; + + /** + * Validates a container name. + */ + export function containerNameIsValid(containerName: string): boolean; + export function containerNameIsValid(containerName: string, callback: ErrorCallback): boolean; + + /** + * Validates a blob name. + */ + export function blobNameIsValid(containerName: string, blob: string): boolean; + export function blobNameIsValid(containerName: string, blob: string, callback: ErrorCallback): boolean; + + /** + * Validates a table name. + */ + export function tableNameIsValid(tableName: string): boolean; + export function tableNameIsValid(tableName: string, callback: ErrorCallback): boolean; + + /** + * Validates a queue name. + */ + export function queueNameIsValid(queueName: string): boolean; + export function queueNameIsValid(queueName: string, callback: ErrorCallback): boolean; + + export function pageRangesAreValid(rangeStart: number, rangeEnd: number, writeBlockSizeInBytes: number): boolean; + export function pageRangesAreValid(rangeStart: number, rangeEnd: number, writeBlockSizeInBytes: number, callback: ErrorCallback): boolean; + + export function validateArgs(functionName: string, validationRules: Function): boolean; +} + +export declare module date { + /** + * Generates a Date object which is in the given days from now. + */ + export function daysFromNow(days: number): Date; + + /** + * Generates a Date object which is in the given hours from now. + */ + export function hoursFromNow(hours: number): Date; + + /** + * Generates a Date object which is in the given minutes from now. + */ + export function minutesFromNow(minutes: number): Date; + + /** + * Generates a Date object which is in the given seconds from now. + */ + export function secondsFromNow(seconds: number): Date; +} +//#endregion + +//#region Non-explicit, undeclared interfaces +export interface WebResponse { + isSuccessful: boolean; + statusCode: number; + body: { + entry: { + id: string; + title: any; + updated: string; + author: { + name: any; + }; + link: any; + category: any; + content: any; + }; + }; + headers: any; + md5: any; +} + +//#region Common Interfaces +export interface SimpleCallback { + (error: Error, result: T): void; +} +export interface ErrorCallback { + (error: Error): void; +} +export interface StorageCallbackVoid { + (err: Error, response: WebResponse): void; +} +export interface StorageCallback { + (err: Error, result: T, response: WebResponse): void; +} +export interface StorageServiceStatsCallback extends StorageCallback { } +export interface StorageServicePropertiesCallback extends StorageCallback { } + +export interface TimeoutIntervalOptions { + locationMode?: string; + timeoutIntervalInMs?: number; + maximumExecutionTimeInMs?: number; +} +export interface MetadataOptions extends TimeoutIntervalOptions { + metadata?: StorageMetadata; +} +export interface StorageAclOptions extends TimeoutIntervalOptions { + leaseId?: string; + signedIdentifiers: SignedIdentifier[] +} + +export interface Dictionary { + [key: string]: T; +} +export interface StorageServiceProperties { + Logging: { + Version: number; + Delete: boolean; + Read: boolean; + Write: boolean; + RetentionPolicy: { + Enabled: boolean; + Days: number; + }; + }; + Metrics: { + Version: number; + Enabled: boolean; + IncludeAPIs: boolean; + RetentionPolicy: { + Enabled: boolean; + Days: number; + }; + }; + DefaultServiceVersion: string; +} +export interface StorageServiceStats { + GeoReplication: { + Status: string; + LastSyncTime: Date; + } +} +export interface SignedIdentifier { + Id: string; + AccessPolicy: SharedAccessPolicy; +} +export interface StorageMetadata { + [key: string]: string; +} +export interface ContinuationToken { + nextMarker: string; + targetLocation: string; +} +export interface SharedAccessPolicy { + Id?: string; + AccessPolicy: { + Start?: Date; + Expiry: Date; + Permission?: string; + } +} +//#endregion +//#region TableService Interfaces +export interface TableRequestCallback { + (error: Error, tableResult: { TableName: string; }, response: WebResponse): void; +} + +export interface CreateTableIfNotExistsCallback { + (error: Error, created: boolean, response: WebResponse): void; +} + +export interface DeleteTableCallback { + (error: Error, successful: boolean, response: WebResponse): void; +} + +export interface QueryTablesCallback { + (error: Error, queryTablesResult: TableResult[], resultsContinuation: QueryResultContinuation, response: WebResponse): void; +} + +export interface QueryResultContinuation { + tableService: TableService; +} + +export interface QueryTablesOptions extends TimeoutIntervalOptions { + nextTableName?: string; +} + +export interface TableResult { + TableName: string; +} + +export interface QueryEntityCallback { + (error: Error, entity: Entity, response: WebResponse): void; +} + +export interface QueryEntitiesCallback { + (error: Error, entities: Entity[], resultContinuation: QueryEntitiesResultContinuation, response: WebResponse): void; +} + +export interface QueryEntitiesResultContinuation extends QueryResultContinuation { + tableQuery: TableQuery; + nextPartitionKey: string; + nextRowKey: string; + getNextPage(callback?: QueryEntitiesCallback): void; + hasNextPage(): boolean; +} + +export interface ModifyEntityCallback { + (error: Error, entity: Entity, response: WebResponse): void; +} + +export interface DeleteEntityCallback { + (error: Error, successful: boolean, response: WebResponse): void; +} + +export interface UpdateEntityOptions extends TimeoutIntervalOptions { + checkEtag?: boolean; +} + +export interface Entity { + PartitionKey: string; + RowKey: string; + Timestamp?: Date; + etag?: string; + [property: string]: string | number | boolean | Date; +} +//#endregion +//#region BlobService Interfaces +export interface LeaseIdOptions extends TimeoutIntervalOptions { + leaseId?: string; +} +export interface AccessConditionsOptions extends TimeoutIntervalOptions { + accessConditions?: StorageAccessCondition; +} +export interface LeaseAccessConditionsOptions extends LeaseIdOptions { + accessConditions?: StorageAccessCondition; +} + +export interface ListContainersOptions extends TimeoutIntervalOptions { + prefix?: string; + maxresults?: number; + marker: string; + include?: string; +} +export interface ListContainersCallback { + (err: Error, containers: ContainerResult[], continuationToken: ContinuationToken, response: WebResponse): void; +} +export interface CreateContainerOptions extends TimeoutIntervalOptions { + metadata?: StorageMetadata; + publicAccessLevel?: string; +} +export interface GetContainerPropertiesOptions extends TimeoutIntervalOptions { + leaseId?: string; +} +export interface GetContainerMetadataOptions extends GetContainerPropertiesOptions { + accessConditions?: StorageAccessCondition; +} + +export interface ListBlobsOptions extends ListContainersOptions { + prefix?: string; + delimiter?: string; +} +export interface ListBlobsCallback { + (err: Error, blobs: BlobResult[], continuationToken: ContinuationToken, response: WebResponse): void; +} +export interface GetBlobPropertiesOptions extends LeaseAccessConditionsOptions { + snapshotId?: string; +} +export interface SetBlobPropertiesOptions extends LeaseAccessConditionsOptions { + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + contentMD5?: string; + cacheControl?: string; + contentDisposition?: string; +} +export interface ReadBlobOptions extends GetBlobPropertiesOptions { + rangeStart?: string; + rangeEnd?: string; + useTransactionalMD5?: boolean; + disableContentMD5Validation?: boolean; +} +export interface GetBlobToTextCallback { + (err: Error, text: string, result: BlobResult, response: WebResponse): void; +} +export interface DeleteBlobOptions extends GetBlobPropertiesOptions { + deleteSnapshots?: string; +} +export interface BlobSnapshotOptions extends GetBlobPropertiesOptions { + metadata?: StorageMetadata; +} +export interface CopyBlobOptions extends BlobSnapshotOptions { + sourceLeaseId?: string; + sourceAccessConditions: StorageAccessCondition; +} + +export interface UploadBlobOptions extends SetBlobPropertiesOptions { + metadata?: StorageMetadata; + speedSummary?: SpeedSummary; + parallelOperationThreadCount?: number; + storeBlobContentMD5?: boolean; + useTransactionalMD5?: boolean; +} +export interface CreatePagesOptions extends LeaseAccessConditionsOptions { + contentMD5?: string; + useTransactionalMD5?: boolean; +} +export interface PageRangeOptions extends LeaseIdOptions { + snapshotId?: string; + rangeStart?: number; + rangeEnd?: number; +} + +export interface UploadBlockBlobOptions extends UploadBlobOptions { + blockIdPrefix?: string; +} +export interface CreateBlockOptions extends LeaseAccessConditionsOptions { + contentMD5?: string; + useTransactionalMD5?: boolean; +} + +export interface LeaseOptions extends AccessConditionsOptions { + leaseDuration?: string; + proposedLeaseId?: string; +} +export interface BreakLeaseOptions extends AccessConditionsOptions { + leaseBreakPeriod?: number; +} + +export interface SharedAccessSignatureResult { + baseUrl: string; + path: string; + queryString: { + se: string; + sp: string; + sr: string; + sv: string; + sig: string; + }; + url: () => string; +} +export interface BlobHeaders { + cacheControl?: string; + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + contentDisposition?: string; +} +export interface PageRange { + start: number; + end: number; +} +export interface BlockList { + LatestBlocks: string[]; + CommittedBlocks: string[]; + UncommittedBlocks: string[]; +} +export interface StorageAccessCondition { + "If-Modified-Since": Date; + "If-Unmodified-Since": Date; + "If-Match": string; + "If-None-Match": string; +} +//#endregion +//#region QueueService Interfaces +export interface ListQueuesOptions extends TimeoutIntervalOptions { + prefix?: string; + maxresults?: number; + marker: string; + include?: string; +} +export interface ListQueuesCallback { + (err: Error, queues: QueueResult[], continuationToken: ContinuationToken, response: WebResponse): void; +} + +export interface CreateQueueMessageOptions extends TimeoutIntervalOptions { + messagettl?: number; + visibilitytimeout?: number; +} +export interface PeekQueueMessagesOptions extends TimeoutIntervalOptions { + numofmessages?: number; +} +export interface GetQueueMessagesOptions extends PeekQueueMessagesOptions { + peekonly?: boolean; + visibilitytimeout?: number; +} +export interface UpdateQueueMessagesOptions extends TimeoutIntervalOptions { + messagetext?: string; +} +//#endregion + +//#region RoleEnvironment Interfaces +export interface Role { + name: string; + instances: { + [instanceId: string]: RoleInstance; + }; +} +export interface RoleInstance { + id: string; + faultDomain: string; + updateDomain: string; + endpoints: { + [endpoint: string]: RoleInstanceEndpoint + }; +} +export interface RoleInstanceEndpoint { + protocol: string; + address: string; + port: number; +} +export interface RoleLocalResource { + name: string; + path: string; + maximumSizeInMegabytes: number; +} +//#endregion +//#region ConnectionStringParser Interfaces +export interface ConnectionStringParseOptions { + skipLowerCase: boolean; +} +//#endregion +//#region Validate Interfaces +export interface ClusterCreationOptions { + name: string; + location: string; + defaultStorageAccountName: string; + defaultStorageAccountKey: string; + defaultStorageContainer: string; + user: string; + password: string; + nodes: number; + additionalStorageAccounts?: { + name: string; + key: string; + }[]; + oozieMetastore?: { + server: string; + database: string; + user: string; + password: string; + }; + hiveMetastore?: { + server: string; + database: string; + user: string; + password: string; + }; +} +//#endregion +//#region ServiceSettings Interfaces +export interface Requirement { + SettingName: string; + SettingPredicate: Function; +} +export interface ValidatorFunction { + (userSettings: Dictionary): any; +} +//#endregion +//#endregion + +//#region Un-exported internal classes +declare class StorageServiceClient extends ServiceClient { + static incorrectStorageAccountErr: string; + static incorrectStorageAccessKeyErr: string; + static getStorageSettings(connectionString: string): StorageServiceSettings; + static getStorageSettings(storageAccount?: string, storageAccessKey?: string, host?: string): StorageServiceSettings; + + apiVersion: string; + usePathStyleUri: string; + + constructor(storageAccount: string, storageAccessKey: string, host: string, usePathStyleUri: boolean, authenticationProvider: any); +} +//#endregion + +export declare function isEmulated(): boolean; diff --git a/azure/tsconfig.json b/azure/tsconfig.json new file mode 100644 index 0000000000..dce73524a2 --- /dev/null +++ b/azure/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "azure-tests.ts" + ] +} \ No newline at end of file diff --git a/babel-core/babel-core-tests.ts b/babel-core/babel-core-tests.ts new file mode 100644 index 0000000000..4c62d3c2f5 --- /dev/null +++ b/babel-core/babel-core-tests.ts @@ -0,0 +1,32 @@ + +import * as babel from "babel-core"; + + +// Example from https://github.com/babel/babel/tree/master/packages/babel-core +const code = `class Example {}`; +const result = babel.transform(code, { /* options */ }); +result.code; // Generated code +result.map; // Sourcemap +result.ast; // AST + + +// Examples from http://babeljs.io/docs/usage/api/ +let options: babel.TransformOptions = { + plugins: [ + "es2015-arrow-functions", + "es2015-block-scoped-functions", + "es2015-block-scoping", + "es2015-classes", + ], + only: /.*\.js/, + ast: false, + sourceMaps: true +}; + +babel.transformFile("filename.js", options, function (err, result) { + result.code; + result.map; + result.ast; +}); + +babel.transformFileSync("filename.js", options).code; diff --git a/babel-core/index.d.ts b/babel-core/index.d.ts new file mode 100644 index 0000000000..a3cd7019ab --- /dev/null +++ b/babel-core/index.d.ts @@ -0,0 +1,144 @@ +// Type definitions for babel-core v6.7 +// Project: https://github.com/babel/babel/tree/master/packages/babel-core +// Definitions by: Troy Gerwien +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + +import * as t from 'babel-types'; +export {t as types}; +type Node = t.Node; +export import template = require('babel-template'); +export var version: string; +import traverse, {Visitor} from "babel-traverse"; +export {traverse, Visitor}; + + +/** Transforms the passed in `code`. Returning an object with the generated code, source map, and AST. */ +export function transform(code: string, opts?: TransformOptions): BabelFileResult; + +/** Asynchronously transforms the entire contents of a file. */ +export function transformFile(filename: string, opts: TransformOptions, callback: (err: any, result: BabelFileResult) => void): void; + +/** Synchronous version of `babel.transformFile`. Returns the transformed contents of the `filename`. */ +export function transformFileSync(filename: string, opts?: TransformOptions): BabelFileResult; + +export function transformFromAst(ast: Node, code?: string, opts?: TransformOptions): BabelFileResult; + +export interface TransformOptions { + + /** Filename to use when reading from stdin - this will be used in source-maps, errors etc. Default: "unknown". */ + filename?: string; + + /** Filename relative to `sourceRoot`. */ + filenameRelative?: string; + + /** A source map object that the output source map will be based on. */ + inputSourceMap?: Object; + + /** + * This is an object of keys that represent different environments. For example, you may have: + * `{ env: { production: { / * specific options * / } } }` + * which will use those options when the enviroment variable `BABEL_ENV` is set to `"production"`. + * If `BABEL_ENV` isn't set then `NODE_ENV` will be used, if it's not set then it defaults to `"development"`. + */ + env?: Object; + + /** Retain line numbers - will result in really ugly code. Default: `false` */ + retainLines?: boolean; + + /** Enable/disable ANSI syntax highlighting of code frames. Default: `true`. */ + highlightCode?: boolean; + + /** List of presets (a set of plugins) to load and use. */ + presets?: any[]; + + /** List of plugins to load and use. */ + plugins?: any[]; + + /** list of glob paths to **not** compile. Opposite to the `only` option. */ + ignore?: string[]; + + /** + * A glob, regex, or mixed array of both, matching paths to only compile. Can also be an array of arrays containing + * paths to explicitly match. When attempting to compile a non-matching file it's returned verbatim. + */ + only?: string | RegExp | Array; + + /** Enable code generation. Default: `true`. */ + code?: boolean; + + /** Include the AST in the returned object. Default: `true`. */ + ast?: boolean; + + /** A path to an .babelrc file to extend. */ + extends?: string; + + /** write comments to generated output. Default: `true`. */ + comments?: boolean; + + /** + * An optional callback that controls whether a comment should be output or not. Called as + * `shouldPrintComment(commentContents)`. **NOTE**: This overrides the `comments` option when used. + */ + shouldPrintComment?: (comment: string) => boolean; + + /** + * Do not include superfluous whitespace characters and line terminators. When set to `"auto"`, `compact` is set to + * `true` on input sizes of >100KB. + */ + compact?: boolean | "auto"; + + /** + * If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a `sourceMappingURL` + * directive is added to the bottom of the returned code. If set to `"both"` then a map property is returned as well + * as a source map comment appended. + */ + sourceMaps?: boolean | "inline" | "both"; + + /** Set `file` on returned source map. */ + sourceMapTarget?: string; + + /** Set `sources[0]` on returned source map. */ + sourceFileName?: string; + + /** The root from which all sources are relative. */ + sourceRoot?: string; + + /** Specify whether or not to use `.babelrc` and `.babelignore` files. Default: `true`. */ + babelrc?: boolean; + + /** Attach a comment before all non-user injected code. */ + auxiliaryCommentBefore?: string; + + /** Attach a comment after all non-user injected code. */ + auxiliaryCommentAfter?: string; + + /** + * Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. + * If falsy value is returned then the generated module id is used. + */ + getModuleId?: (moduleName: string) => string; + + /** Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions. */ + moduleRoot?: string; + + /** + * If truthy, insert an explicit id for modules. By default, all modules are anonymous. + * (Not available for `common` modules). + */ + moduleIds?: boolean; + + /** Specify a custom name for module ids. */ + moduleId?: string; +} + +export interface BabelFileResult { + ast?: Node; + code?: string; + map?: Object; +} +export as namespace babel; + diff --git a/babel-core/tsconfig.json b/babel-core/tsconfig.json new file mode 100644 index 0000000000..70c1c077d6 --- /dev/null +++ b/babel-core/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "babel-core-tests.ts" + ] +} \ No newline at end of file diff --git a/babel-generator/babel-generator-tests.ts b/babel-generator/babel-generator-tests.ts new file mode 100644 index 0000000000..a27fba50c5 --- /dev/null +++ b/babel-generator/babel-generator-tests.ts @@ -0,0 +1,27 @@ +/// + + + +// Example from https://github.com/babel/babel/tree/master/packages/babel-generator +import {parse} from 'babylon'; +import generate from 'babel-generator'; + +const code = 'class Example {}'; +const ast = parse(code); + +ast.type; +ast.loc.start; + +const output = generate(ast, { /* options */ }, code); + + +// Example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-generator +let result = generate(ast, { + retainLines: false, + compact: "auto", + concise: false, + quotes: "double", + // ... +}, code); +result.code; +result.map; diff --git a/babel-generator/index.d.ts b/babel-generator/index.d.ts new file mode 100644 index 0000000000..f30505623f --- /dev/null +++ b/babel-generator/index.d.ts @@ -0,0 +1,101 @@ +// Type definitions for babel-generator v6.7 +// Project: https://github.com/babel/babel/tree/master/packages/babel-generator +// Definitions by: Troy Gerwien +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as t from 'babel-types'; +type Node = t.Node; + +/** + * Turns an AST into code, maintaining sourcemaps, user preferences, and valid output. + * @param ast - the abstract syntax tree from which to generate output code. + * @param opts - used for specifying options for code generation. + * @param code - the original source code, used for source maps. + * @returns - an object containing the output code and source map. + */ +export default function generate(ast: Node, opts?: GeneratorOptions, code?: string | {[filename: string]: string}): GeneratorResult; + +export interface GeneratorOptions { + + /** + * Optional string to add as a block comment at the start of the output file. + */ + auxiliaryCommentBefore?: string; + + /** + * Optional string to add as a block comment at the end of the output file. + */ + auxiliaryCommentAfter?: string; + + /** + * Function that takes a comment (as a string) and returns true if the comment should be included in the output. + * By default, comments are included if `opts.comments` is `true` or if `opts.minifed` is `false` and the comment + * contains `@preserve` or `@license`. + */ + shouldPrintComment?: (comment: string) => boolean; + + /** + * Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces). + * Defaults to `false`. + */ + retainLines?: boolean; + + /** + * Should comments be included in output? Defaults to `true`. + */ + comments?: boolean; + + /** + * Set to true to avoid adding whitespace for formatting. Defaults to the value of `opts.minified`. + */ + compact?: boolean | 'auto'; + + /** + * Should the output be minified. Defaults to `false`. + */ + minified?: boolean; + + /** + * Set to true to reduce whitespace (but not as much as opts.compact). Defaults to `false`. + */ + concise?: boolean; + + /** + * The type of quote to use in the output. If omitted, autodetects based on `ast.tokens`. + */ + quotes?: 'single' | 'double'; + + /** + * Used in warning messages + */ + filename?: string; + + /** + * Enable generating source maps. Defaults to `false`. + */ + sourceMaps?: boolean; + + /** + * The filename of the generated code that the source map will be associated with. + */ + sourceMapTarget?: string; + + /** + * A root for all relative URLs in the source map. + */ + sourceRoot?: string; + + /** + * The filename for the source code (i.e. the code in the `code` argument). + * This will only be used if `code` is a string. + */ + sourceFileName?: string; +} + +export interface GeneratorResult { + map: Object; + code: string; +} + diff --git a/babel-generator/tsconfig.json b/babel-generator/tsconfig.json new file mode 100644 index 0000000000..e46a9e956c --- /dev/null +++ b/babel-generator/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "babel-generator-tests.ts" + ] +} \ No newline at end of file diff --git a/babel-template/babel-template-tests.ts b/babel-template/babel-template-tests.ts new file mode 100644 index 0000000000..b5d4547188 --- /dev/null +++ b/babel-template/babel-template-tests.ts @@ -0,0 +1,21 @@ + +/// +/// + + +// Example from https://github.com/babel/babel/tree/master/packages/babel-template +import template = require('babel-template'); +import generate from 'babel-generator'; +import * as t from 'babel-types'; + +const buildRequire = template(` + var IMPORT_NAME = require(SOURCE); +`); + +const ast = buildRequire({ + IMPORT_NAME: t.identifier('myModule'), + SOURCE: t.stringLiteral('my-module') +}); + +console.log(generate(ast).code); +// var myModule = require('my-module'); diff --git a/babel-template/index.d.ts b/babel-template/index.d.ts new file mode 100644 index 0000000000..7d73adc466 --- /dev/null +++ b/babel-template/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for babel-template v6.7 +// Project: https://github.com/babel/babel/tree/master/packages/babel-template +// Definitions by: Troy Gerwien +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + + +import {BabylonOptions} from 'babylon'; +import * as t from 'babel-types'; +type Node = t.Node; + +// NB: This export doesn't match the handbook example, where `template` is the default export. +// But it does match the runtime behaviour (at least at the time of this writing). For some reason, +// babel-template/lib/index.js has this line at the bottom: module.exports = exports["default"]; +export = template; +declare function template(code: string, opts?: BabylonOptions): UseTemplate; + +type UseTemplate = (nodes?: {[placeholder: string]: Node}) => Node; + diff --git a/babel-template/tsconfig.json b/babel-template/tsconfig.json new file mode 100644 index 0000000000..55e2331c8c --- /dev/null +++ b/babel-template/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "babel-template-tests.ts" + ] +} \ No newline at end of file diff --git a/babel-traverse/babel-traverse-tests.ts b/babel-traverse/babel-traverse-tests.ts new file mode 100644 index 0000000000..c02efe44ad --- /dev/null +++ b/babel-traverse/babel-traverse-tests.ts @@ -0,0 +1,111 @@ + +/// +/// + + +import * as babylon from "babylon"; +import traverse, {Visitor} from 'babel-traverse'; +import * as t from 'babel-types'; + + +// Examples from: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md +const MyVisitor: Visitor = { + Identifier: { + enter() { + console.log("Entered!"); + }, + exit() { + console.log("Exited!"); + } + } +}; + +const MyVisitor2: Visitor = { + Identifier(path) { + console.log("Visiting: " + path.node.name); + } +}; + + +// Example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-traverse +const code = `function square(n) { + return n * n; +}`; + +const ast = babylon.parse(code); + +traverse(ast, { + enter(path) { + let node = path.node; + if (t.isIdentifier(node) && node.name === "n") { + node.name = "x"; + } + } +}); + + +// Examples from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#writing-your-first-babel-plugin + +const v1: Visitor = { + + BinaryExpression(path) { + if (t.isIdentifier(path.node.left)) { + // ... + } + path.replaceWith( + t.binaryExpression("**", path.node.left, t.numericLiteral(2)) + ); + path.parentPath.replaceWith( + t.expressionStatement(t.stringLiteral("Anyway the wind blows, doesn't really matter to me, to me.")) + ); + path.parentPath.remove(); + }, + + Identifier(path) { + if (path.isReferencedIdentifier()) { + // ... + } + if (t.isReferenced(path.node, path.parent)) { + // ... + } + }, + + ReturnStatement(path) { + path.replaceWithMultiple([ + t.expressionStatement(t.stringLiteral("Is this the real life?")), + t.expressionStatement(t.stringLiteral("Is this just fantasy?")), + t.expressionStatement(t.stringLiteral("(Enjoy singing the rest of the song in your head)")), + ]); + }, + + FunctionDeclaration(path, state) { + path.replaceWithSourceString(`function add(a, b) { + return a + b; + }`); + + path.insertBefore(t.expressionStatement(t.stringLiteral("Because I'm easy come, easy go."))); + path.insertAfter(t.expressionStatement(t.stringLiteral("A little high, little low."))); + path.remove(); + + if (path.scope.hasBinding("n")) { + // ... + } + if (path.scope.hasOwnBinding("n")) { + // ... + } + + let id1 = path.scope.generateUidIdentifier("uid"); + id1.type; + id1.name; + let id2 = path.scope.generateUidIdentifier("uid"); + id2.type; + id2.name; + + const id = path.scope.generateUidIdentifierBasedOnNode(path.node.id); + path.remove(); + path.scope.parent.push({ id, init: path.node }); + + path.scope.rename("n", "x"); + path.scope.rename("n"); + } +}; diff --git a/babel-traverse/index.d.ts b/babel-traverse/index.d.ts new file mode 100644 index 0000000000..11d51dc2cb --- /dev/null +++ b/babel-traverse/index.d.ts @@ -0,0 +1,966 @@ +// Type definitions for babel-traverse v6.7 +// Project: https://github.com/babel/babel/tree/master/packages/babel-traverse +// Definitions by: Troy Gerwien +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import * as t from 'babel-types'; +type Node = t.Node; + +export default function traverse(parent: Node | Node[], opts?: TraverseOptions, scope?: Scope, state?: any, parentPath?: NodePath): void; + +export interface TraverseOptions extends Visitor { + scope?: Scope; + noScope?: boolean; +} + +export class Scope { + constructor(path: NodePath, parentScope?: Scope); + path: NodePath; + block: Node; + parentBlock: Node; + parent: Scope; + hub: Hub; + bindings: { [name: string]: Binding; }; + + /** Traverse node with current scope and path. */ + traverse(node: Node | Node[], opts?: TraverseOptions, state?: any): void; + + /** Generate a unique identifier and add it to the current scope. */ + generateDeclaredUidIdentifier(name?: string): t.Identifier; + + /** Generate a unique identifier. */ + generateUidIdentifier(name?: string): t.Identifier; + + /** Generate a unique `_id1` binding. */ + generateUid(name?: string): string; + + /** Generate a unique identifier based on a node. */ + generateUidIdentifierBasedOnNode(parent: Node, defaultName?: string): t.Identifier; + + /** + * Determine whether evaluating the specific input `node` is a consequenceless reference. ie. + * evaluating it wont result in potentially arbitrary code from being ran. The following are + * whitelisted and determined not to cause side effects: + * + * - `this` expressions + * - `super` expressions + * - Bound identifiers + */ + isStatic(node: Node): boolean; + + /** Possibly generate a memoised identifier if it is not static and has consequences. */ + maybeGenerateMemoised(node: Node, dontPush?: boolean): t.Identifier; + + checkBlockScopedCollisions(local: Node, kind: string, name: string, id: Object): void; + + rename(oldName: string, newName?: string, block?: Node): void; + + dump(): void; + + toArray(node: Node, i?: number): Node; + + registerDeclaration(path: NodePath): void; + + buildUndefinedNode(): Node; + + registerConstantViolation(path: NodePath): void; + + registerBinding(kind: string, path: NodePath, bindingPath?: NodePath): void; + + addGlobal(node: Node): void; + + hasUid(name: string): boolean; + + hasGlobal(name: string): boolean; + + hasReference(name: string): boolean; + + isPure(node: Node, constantsOnly?: boolean): boolean; + + setData(key: string, val: any): any; + + getData(key: string): any; + + removeData(key: string): void; + + push(opts: any): void; + + getProgramParent(): Scope; + + getFunctionParent(): Scope; + + getBlockParent(): Scope; + + /** Walks the scope tree and gathers **all** bindings. */ + getAllBindings(...kinds: string[]): Object; + + bindingIdentifierEquals(name: string, node: Node): boolean; + + getBinding(name: string): Binding; + + getOwnBinding(name: string): Binding; + + getBindingIdentifier(name: string): t.Identifier; + + getOwnBindingIdentifier(name: string): t.Identifier; + + hasOwnBinding(name: string): boolean; + + hasBinding(name: string, noGlobals?: boolean): boolean; + + parentHasBinding(name: string, noGlobals?: boolean): boolean; + + /** Move a binding of `name` to another `scope`. */ + moveBindingTo(name: string, scope: Scope): void; + + removeOwnBinding(name: string): void; + + removeBinding(name: string): void; +} + +export class Binding { + constructor(opts: { existing: Binding; identifier: t.Identifier; scope: Scope; path: NodePath; kind: 'var' | 'let' | 'const'; }); + identifier: t.Identifier; + scope: Scope; + path: NodePath; + kind: 'var' | 'let' | 'const'; + referenced: boolean; + references: number; + referencePaths: NodePath[]; + constant: boolean; + constantViolations: NodePath[]; +} + +export interface Visitor extends VisitNodeObject { + ArrayExpression?: VisitNode; + AssignmentExpression?: VisitNode; + LVal?: VisitNode; + Expression?: VisitNode; + BinaryExpression?: VisitNode; + Directive?: VisitNode; + DirectiveLiteral?: VisitNode; + BlockStatement?: VisitNode; + BreakStatement?: VisitNode; + Identifier?: VisitNode; + CallExpression?: VisitNode; + CatchClause?: VisitNode; + ConditionalExpression?: VisitNode; + ContinueStatement?: VisitNode; + DebuggerStatement?: VisitNode; + DoWhileStatement?: VisitNode; + Statement?: VisitNode; + EmptyStatement?: VisitNode; + ExpressionStatement?: VisitNode; + File?: VisitNode; + Program?: VisitNode; + ForInStatement?: VisitNode; + VariableDeclaration?: VisitNode; + ForStatement?: VisitNode; + FunctionDeclaration?: VisitNode; + FunctionExpression?: VisitNode; + IfStatement?: VisitNode; + LabeledStatement?: VisitNode; + StringLiteral?: VisitNode; + NumericLiteral?: VisitNode; + NullLiteral?: VisitNode; + BooleanLiteral?: VisitNode; + RegExpLiteral?: VisitNode; + LogicalExpression?: VisitNode; + MemberExpression?: VisitNode; + NewExpression?: VisitNode; + ObjectExpression?: VisitNode; + ObjectMethod?: VisitNode; + ObjectProperty?: VisitNode; + RestElement?: VisitNode; + ReturnStatement?: VisitNode; + SequenceExpression?: VisitNode; + SwitchCase?: VisitNode; + SwitchStatement?: VisitNode; + ThisExpression?: VisitNode; + ThrowStatement?: VisitNode; + TryStatement?: VisitNode; + UnaryExpression?: VisitNode; + UpdateExpression?: VisitNode; + VariableDeclarator?: VisitNode; + WhileStatement?: VisitNode; + WithStatement?: VisitNode; + AssignmentPattern?: VisitNode; + ArrayPattern?: VisitNode; + ArrowFunctionExpression?: VisitNode; + ClassBody?: VisitNode; + ClassDeclaration?: VisitNode; + ClassExpression?: VisitNode; + ExportAllDeclaration?: VisitNode; + ExportDefaultDeclaration?: VisitNode; + ExportNamedDeclaration?: VisitNode; + Declaration?: VisitNode; + ExportSpecifier?: VisitNode; + ForOfStatement?: VisitNode; + ImportDeclaration?: VisitNode; + ImportDefaultSpecifier?: VisitNode; + ImportNamespaceSpecifier?: VisitNode; + ImportSpecifier?: VisitNode; + MetaProperty?: VisitNode; + ClassMethod?: VisitNode; + ObjectPattern?: VisitNode; + SpreadElement?: VisitNode; + Super?: VisitNode; + TaggedTemplateExpression?: VisitNode; + TemplateLiteral?: VisitNode; + TemplateElement?: VisitNode; + YieldExpression?: VisitNode; + AnyTypeAnnotation?: VisitNode; + ArrayTypeAnnotation?: VisitNode; + BooleanTypeAnnotation?: VisitNode; + BooleanLiteralTypeAnnotation?: VisitNode; + NullLiteralTypeAnnotation?: VisitNode; + ClassImplements?: VisitNode; + ClassProperty?: VisitNode; + DeclareClass?: VisitNode; + DeclareFunction?: VisitNode; + DeclareInterface?: VisitNode; + DeclareModule?: VisitNode; + DeclareTypeAlias?: VisitNode; + DeclareVariable?: VisitNode; + ExistentialTypeParam?: VisitNode; + FunctionTypeAnnotation?: VisitNode; + FunctionTypeParam?: VisitNode; + GenericTypeAnnotation?: VisitNode; + InterfaceExtends?: VisitNode; + InterfaceDeclaration?: VisitNode; + IntersectionTypeAnnotation?: VisitNode; + MixedTypeAnnotation?: VisitNode; + NullableTypeAnnotation?: VisitNode; + NumericLiteralTypeAnnotation?: VisitNode; + NumberTypeAnnotation?: VisitNode; + StringLiteralTypeAnnotation?: VisitNode; + StringTypeAnnotation?: VisitNode; + ThisTypeAnnotation?: VisitNode; + TupleTypeAnnotation?: VisitNode; + TypeofTypeAnnotation?: VisitNode; + TypeAlias?: VisitNode; + TypeAnnotation?: VisitNode; + TypeCastExpression?: VisitNode; + TypeParameterDeclaration?: VisitNode; + TypeParameterInstantiation?: VisitNode; + ObjectTypeAnnotation?: VisitNode; + ObjectTypeCallProperty?: VisitNode; + ObjectTypeIndexer?: VisitNode; + ObjectTypeProperty?: VisitNode; + QualifiedTypeIdentifier?: VisitNode; + UnionTypeAnnotation?: VisitNode; + VoidTypeAnnotation?: VisitNode; + JSXAttribute?: VisitNode; + JSXIdentifier?: VisitNode; + JSXNamespacedName?: VisitNode; + JSXElement?: VisitNode; + JSXExpressionContainer?: VisitNode; + JSXClosingElement?: VisitNode; + JSXMemberExpression?: VisitNode; + JSXOpeningElement?: VisitNode; + JSXEmptyExpression?: VisitNode; + JSXSpreadAttribute?: VisitNode; + JSXText?: VisitNode; + Noop?: VisitNode; + ParenthesizedExpression?: VisitNode; + AwaitExpression?: VisitNode; + BindExpression?: VisitNode; + Decorator?: VisitNode; + DoExpression?: VisitNode; + ExportDefaultSpecifier?: VisitNode; + ExportNamespaceSpecifier?: VisitNode; + RestProperty?: VisitNode; + SpreadProperty?: VisitNode; + Binary?: VisitNode; + Scopable?: VisitNode; + BlockParent?: VisitNode; + Block?: VisitNode; + Terminatorless?: VisitNode; + CompletionStatement?: VisitNode; + Conditional?: VisitNode; + Loop?: VisitNode; + While?: VisitNode; + ExpressionWrapper?: VisitNode; + For?: VisitNode; + ForXStatement?: VisitNode; + Function?: VisitNode; + FunctionParent?: VisitNode; + Pureish?: VisitNode; + Literal?: VisitNode; + Immutable?: VisitNode; + UserWhitespacable?: VisitNode; + Method?: VisitNode; + ObjectMember?: VisitNode; + Property?: VisitNode; + UnaryLike?: VisitNode; + Pattern?: VisitNode; + Class?: VisitNode; + ModuleDeclaration?: VisitNode; + ExportDeclaration?: VisitNode; + ModuleSpecifier?: VisitNode; + Flow?: VisitNode; + FlowBaseAnnotation?: VisitNode; + FlowDeclaration?: VisitNode; + JSX?: VisitNode; +} + +export type VisitNode = VisitNodeFunction | VisitNodeObject; + +export type VisitNodeFunction = (path: NodePath, state: any) => void; + +export interface VisitNodeObject { + enter?(path: NodePath, state: any): void; + exit?(path: NodePath, state: any): void; +} + +export class NodePath { + constructor(hub: Hub, parent: Node); + parent: Node; + hub: Hub; + contexts: TraversalContext[]; + data: Object; + shouldSkip: boolean; + shouldStop: boolean; + removed: boolean; + state: any; + opts: Object; + skipKeys: Object; + parentPath: NodePath; + context: TraversalContext; + container: Object | Object[]; + listKey: string; + inList: boolean; + parentKey: string; + key: string; + node: T; + scope: Scope; + type: string; + typeAnnotation: Object; + + getScope(scope: Scope): Scope; + + setData(key: string, val: any): any; + + getData(key: string, def?: any): any; + + buildCodeFrameError(msg: string, Error: Error): Error; + + traverse(visitor: Visitor, state?: any): void; + + set(key: string, node: Node): void; + + getPathLocation(): string; + + debug(buildMessage: Function): void; + + // ------------------------- ancestry ------------------------- + /** + * Call the provided `callback` with the `NodePath`s of all the parents. + * When the `callback` returns a truthy value, we return that node path. + */ + findParent(callback: (path: NodePath) => boolean): NodePath; + + find(callback: (path: NodePath) => boolean): NodePath; + + /** Get the parent function of the current path. */ + getFunctionParent(): NodePath; + + /** Walk up the tree until we hit a parent node path in a list. */ + getStatementParent(): NodePath; + + /** + * Get the deepest common ancestor and then from it, get the earliest relationship path + * to that ancestor. + * + * Earliest is defined as being "before" all the other nodes in terms of list container + * position and visiting key. + */ + getEarliestCommonAncestorFrom(paths: NodePath[]): NodePath; + + /** Get the earliest path in the tree where the provided `paths` intersect. */ + getDeepestCommonAncestorFrom(paths: NodePath[], filter?: Function): NodePath; + + /** + * Build an array of node paths containing the entire ancestry of the current node path. + * + * NOTE: The current node path is included in this. + */ + getAncestry(): NodePath[]; + + inType(...candidateTypes: string[]): boolean; + + // ------------------------- inference ------------------------- + /** Infer the type of the current `NodePath`. */ + getTypeAnnotation(): t.FlowTypeAnnotation; + + isBaseType(baseName: string, soft?: boolean): boolean; + + couldBeBaseType(name: string): boolean; + + baseTypeStrictlyMatches(right: NodePath): boolean; + + isGenericType(genericName: string): boolean; + + // ------------------------- replacement ------------------------- + /** + * Replace a node with an array of multiple. This method performs the following steps: + * + * - Inherit the comments of first provided node with that of the current node. + * - Insert the provided nodes after the current node. + * - Remove the current node. + */ + replaceWithMultiple(nodes: Node[]): void; + + /** + * Parse a string as an expression and replace the current node with the result. + * + * NOTE: This is typically not a good idea to use. Building source strings when + * transforming ASTs is an antipattern and SHOULD NOT be encouraged. Even if it's + * easier to use, your transforms will be extremely brittle. + */ + replaceWithSourceString(replacement: any): void; + + /** Replace the current node with another. */ + replaceWith(replacement: Node | NodePath): void; + + /** + * This method takes an array of statements nodes and then explodes it + * into expressions. This method retains completion records which is + * extremely important to retain original semantics. + */ + replaceExpressionWithStatements(nodes: Node[]): Node; + + replaceInline(nodes: Node | Node[]): void; + + // ------------------------- evaluation ------------------------- + /** + * Walk the input `node` and statically evaluate if it's truthy. + * + * Returning `true` when we're sure that the expression will evaluate to a + * truthy value, `false` if we're sure that it will evaluate to a falsy + * value and `undefined` if we aren't sure. Because of this please do not + * rely on coercion when using this method and check with === if it's false. + */ + evaluateTruthy(): boolean; + + /** + * Walk the input `node` and statically evaluate it. + * + * Returns an object in the form `{ confident, value }`. `confident` indicates + * whether or not we had to drop out of evaluating the expression because of + * hitting an unknown node that we couldn't confidently find the value of. + * + * Example: + * + * t.evaluate(parse("5 + 5")) // { confident: true, value: 10 } + * t.evaluate(parse("!true")) // { confident: true, value: false } + * t.evaluate(parse("foo + foo")) // { confident: false, value: undefined } + */ + evaluate(): { confident: boolean; value: any }; + + // ------------------------- introspection ------------------------- + /** + * Match the current node if it matches the provided `pattern`. + * + * For example, given the match `React.createClass` it would match the + * parsed nodes of `React.createClass` and `React["createClass"]`. + */ + matchesPattern(pattern: string, allowPartial?: boolean): boolean; + + /** + * Check whether we have the input `key`. If the `key` references an array then we check + * if the array has any items, otherwise we just check if it's falsy. + */ + has(key: string): boolean; + + isStatic(): boolean; + + /** Alias of `has`. */ + is(key: string): boolean; + + /** Opposite of `has`. */ + isnt(key: string): boolean; + + /** Check whether the path node `key` strict equals `value`. */ + equals(key: string, value: any): boolean; + + /** + * Check the type against our stored internal type of the node. This is handy when a node has + * been removed yet we still internally know the type and need it to calculate node replacement. + */ + isNodeType(type: string): boolean; + + /** + * This checks whether or not we're in one of the following positions: + * + * for (KEY in right); + * for (KEY;;); + * + * This is because these spots allow VariableDeclarations AND normal expressions so we need + * to tell the path replacement that it's ok to replace this with an expression. + */ + canHaveVariableDeclarationOrExpression(): boolean; + + /** + * This checks whether we are swapping an arrow function's body between an + * expression and a block statement (or vice versa). + * + * This is because arrow functions may implicitly return an expression, which + * is the same as containing a block statement. + */ + canSwapBetweenExpressionAndStatement(replacement: Node): boolean; + + /** Check whether the current path references a completion record */ + isCompletionRecord(allowInsideFunction?: boolean): boolean; + + /** + * Check whether or not the current `key` allows either a single statement or block statement + * so we can explode it if necessary. + */ + isStatementOrBlock(): boolean; + + /** Check if the currently assigned path references the `importName` of `moduleSource`. */ + referencesImport(moduleSource: string, importName: string): boolean; + + /** Get the source code associated with this node. */ + getSource(): string; + + // ------------------------- context ------------------------- + call(key: string): boolean; + + isBlacklisted(): boolean; + + visit(): boolean; + + skip(): void; + + skipKey(key: string): void; + + stop(): void; + + setScope(): void; + + setContext(context: TraversalContext): NodePath; + + popContext(): void; + + pushContext(context: TraversalContext): void; + + // ------------------------- removal ------------------------- + remove(): void; + + // ------------------------- modification ------------------------- + /** Insert the provided nodes before the current one. */ + insertBefore(nodes: Node | Node[]): any; + + /** + * Insert the provided nodes after the current one. When inserting nodes after an + * expression, ensure that the completion record is correct by pushing the current node. + */ + insertAfter(nodes: Node | Node[]): any; + + /** Update all sibling node paths after `fromIndex` by `incrementBy`. */ + updateSiblingKeys(fromIndex: number, incrementBy: number): void; + + /** Hoist the current node to the highest scope possible and return a UID referencing it. */ + hoist(scope: Scope): void; + + // ------------------------- family ------------------------- + getStatementParent(): NodePath; + + getOpposite(): NodePath; + + getCompletionRecords(): NodePath[]; + + getSibling(key: string): NodePath; + + get(key: string, context?: boolean | TraversalContext): NodePath; + + getBindingIdentifiers(duplicates?: boolean): Node[]; + + getOuterBindingIdentifiers(duplicates?: boolean): Node[]; + + // ------------------------- comments ------------------------- + /** Share comments amongst siblings. */ + shareCommentsWithSiblings(): void; + + addComment(type: string, content: string, line?: boolean): void; + + /** Give node `comments` of the specified `type`. */ + addComments(type: string, comments: any[]): void; + + // ------------------------- isXXX ------------------------- + isArrayExpression(opts?: Object): boolean; + isAssignmentExpression(opts?: Object): boolean; + isBinaryExpression(opts?: Object): boolean; + isDirective(opts?: Object): boolean; + isDirectiveLiteral(opts?: Object): boolean; + isBlockStatement(opts?: Object): boolean; + isBreakStatement(opts?: Object): boolean; + isCallExpression(opts?: Object): boolean; + isCatchClause(opts?: Object): boolean; + isConditionalExpression(opts?: Object): boolean; + isContinueStatement(opts?: Object): boolean; + isDebuggerStatement(opts?: Object): boolean; + isDoWhileStatement(opts?: Object): boolean; + isEmptyStatement(opts?: Object): boolean; + isExpressionStatement(opts?: Object): boolean; + isFile(opts?: Object): boolean; + isForInStatement(opts?: Object): boolean; + isForStatement(opts?: Object): boolean; + isFunctionDeclaration(opts?: Object): boolean; + isFunctionExpression(opts?: Object): boolean; + isIdentifier(opts?: Object): boolean; + isIfStatement(opts?: Object): boolean; + isLabeledStatement(opts?: Object): boolean; + isStringLiteral(opts?: Object): boolean; + isNumericLiteral(opts?: Object): boolean; + isNullLiteral(opts?: Object): boolean; + isBooleanLiteral(opts?: Object): boolean; + isRegExpLiteral(opts?: Object): boolean; + isLogicalExpression(opts?: Object): boolean; + isMemberExpression(opts?: Object): boolean; + isNewExpression(opts?: Object): boolean; + isProgram(opts?: Object): boolean; + isObjectExpression(opts?: Object): boolean; + isObjectMethod(opts?: Object): boolean; + isObjectProperty(opts?: Object): boolean; + isRestElement(opts?: Object): boolean; + isReturnStatement(opts?: Object): boolean; + isSequenceExpression(opts?: Object): boolean; + isSwitchCase(opts?: Object): boolean; + isSwitchStatement(opts?: Object): boolean; + isThisExpression(opts?: Object): boolean; + isThrowStatement(opts?: Object): boolean; + isTryStatement(opts?: Object): boolean; + isUnaryExpression(opts?: Object): boolean; + isUpdateExpression(opts?: Object): boolean; + isVariableDeclaration(opts?: Object): boolean; + isVariableDeclarator(opts?: Object): boolean; + isWhileStatement(opts?: Object): boolean; + isWithStatement(opts?: Object): boolean; + isAssignmentPattern(opts?: Object): boolean; + isArrayPattern(opts?: Object): boolean; + isArrowFunctionExpression(opts?: Object): boolean; + isClassBody(opts?: Object): boolean; + isClassDeclaration(opts?: Object): boolean; + isClassExpression(opts?: Object): boolean; + isExportAllDeclaration(opts?: Object): boolean; + isExportDefaultDeclaration(opts?: Object): boolean; + isExportNamedDeclaration(opts?: Object): boolean; + isExportSpecifier(opts?: Object): boolean; + isForOfStatement(opts?: Object): boolean; + isImportDeclaration(opts?: Object): boolean; + isImportDefaultSpecifier(opts?: Object): boolean; + isImportNamespaceSpecifier(opts?: Object): boolean; + isImportSpecifier(opts?: Object): boolean; + isMetaProperty(opts?: Object): boolean; + isClassMethod(opts?: Object): boolean; + isObjectPattern(opts?: Object): boolean; + isSpreadElement(opts?: Object): boolean; + isSuper(opts?: Object): boolean; + isTaggedTemplateExpression(opts?: Object): boolean; + isTemplateElement(opts?: Object): boolean; + isTemplateLiteral(opts?: Object): boolean; + isYieldExpression(opts?: Object): boolean; + isAnyTypeAnnotation(opts?: Object): boolean; + isArrayTypeAnnotation(opts?: Object): boolean; + isBooleanTypeAnnotation(opts?: Object): boolean; + isBooleanLiteralTypeAnnotation(opts?: Object): boolean; + isNullLiteralTypeAnnotation(opts?: Object): boolean; + isClassImplements(opts?: Object): boolean; + isClassProperty(opts?: Object): boolean; + isDeclareClass(opts?: Object): boolean; + isDeclareFunction(opts?: Object): boolean; + isDeclareInterface(opts?: Object): boolean; + isDeclareModule(opts?: Object): boolean; + isDeclareTypeAlias(opts?: Object): boolean; + isDeclareVariable(opts?: Object): boolean; + isExistentialTypeParam(opts?: Object): boolean; + isFunctionTypeAnnotation(opts?: Object): boolean; + isFunctionTypeParam(opts?: Object): boolean; + isGenericTypeAnnotation(opts?: Object): boolean; + isInterfaceExtends(opts?: Object): boolean; + isInterfaceDeclaration(opts?: Object): boolean; + isIntersectionTypeAnnotation(opts?: Object): boolean; + isMixedTypeAnnotation(opts?: Object): boolean; + isNullableTypeAnnotation(opts?: Object): boolean; + isNumericLiteralTypeAnnotation(opts?: Object): boolean; + isNumberTypeAnnotation(opts?: Object): boolean; + isStringLiteralTypeAnnotation(opts?: Object): boolean; + isStringTypeAnnotation(opts?: Object): boolean; + isThisTypeAnnotation(opts?: Object): boolean; + isTupleTypeAnnotation(opts?: Object): boolean; + isTypeofTypeAnnotation(opts?: Object): boolean; + isTypeAlias(opts?: Object): boolean; + isTypeAnnotation(opts?: Object): boolean; + isTypeCastExpression(opts?: Object): boolean; + isTypeParameterDeclaration(opts?: Object): boolean; + isTypeParameterInstantiation(opts?: Object): boolean; + isObjectTypeAnnotation(opts?: Object): boolean; + isObjectTypeCallProperty(opts?: Object): boolean; + isObjectTypeIndexer(opts?: Object): boolean; + isObjectTypeProperty(opts?: Object): boolean; + isQualifiedTypeIdentifier(opts?: Object): boolean; + isUnionTypeAnnotation(opts?: Object): boolean; + isVoidTypeAnnotation(opts?: Object): boolean; + isJSXAttribute(opts?: Object): boolean; + isJSXClosingElement(opts?: Object): boolean; + isJSXElement(opts?: Object): boolean; + isJSXEmptyExpression(opts?: Object): boolean; + isJSXExpressionContainer(opts?: Object): boolean; + isJSXIdentifier(opts?: Object): boolean; + isJSXMemberExpression(opts?: Object): boolean; + isJSXNamespacedName(opts?: Object): boolean; + isJSXOpeningElement(opts?: Object): boolean; + isJSXSpreadAttribute(opts?: Object): boolean; + isJSXText(opts?: Object): boolean; + isNoop(opts?: Object): boolean; + isParenthesizedExpression(opts?: Object): boolean; + isAwaitExpression(opts?: Object): boolean; + isBindExpression(opts?: Object): boolean; + isDecorator(opts?: Object): boolean; + isDoExpression(opts?: Object): boolean; + isExportDefaultSpecifier(opts?: Object): boolean; + isExportNamespaceSpecifier(opts?: Object): boolean; + isRestProperty(opts?: Object): boolean; + isSpreadProperty(opts?: Object): boolean; + isExpression(opts?: Object): boolean; + isBinary(opts?: Object): boolean; + isScopable(opts?: Object): boolean; + isBlockParent(opts?: Object): boolean; + isBlock(opts?: Object): boolean; + isStatement(opts?: Object): boolean; + isTerminatorless(opts?: Object): boolean; + isCompletionStatement(opts?: Object): boolean; + isConditional(opts?: Object): boolean; + isLoop(opts?: Object): boolean; + isWhile(opts?: Object): boolean; + isExpressionWrapper(opts?: Object): boolean; + isFor(opts?: Object): boolean; + isForXStatement(opts?: Object): boolean; + isFunction(opts?: Object): boolean; + isFunctionParent(opts?: Object): boolean; + isPureish(opts?: Object): boolean; + isDeclaration(opts?: Object): boolean; + isLVal(opts?: Object): boolean; + isLiteral(opts?: Object): boolean; + isImmutable(opts?: Object): boolean; + isUserWhitespacable(opts?: Object): boolean; + isMethod(opts?: Object): boolean; + isObjectMember(opts?: Object): boolean; + isProperty(opts?: Object): boolean; + isUnaryLike(opts?: Object): boolean; + isPattern(opts?: Object): boolean; + isClass(opts?: Object): boolean; + isModuleDeclaration(opts?: Object): boolean; + isExportDeclaration(opts?: Object): boolean; + isModuleSpecifier(opts?: Object): boolean; + isFlow(opts?: Object): boolean; + isFlowBaseAnnotation(opts?: Object): boolean; + isFlowDeclaration(opts?: Object): boolean; + isJSX(opts?: Object): boolean; + isNumberLiteral(opts?: Object): boolean; + isRegexLiteral(opts?: Object): boolean; + isReferencedIdentifier(opts?: Object): boolean; + isReferencedMemberExpression(opts?: Object): boolean; + isBindingIdentifier(opts?: Object): boolean; + isScope(opts?: Object): boolean; + isReferenced(opts?: Object): boolean; + isBlockScoped(opts?: Object): boolean; + isVar(opts?: Object): boolean; + isUser(opts?: Object): boolean; + isGenerated(opts?: Object): boolean; + isPure(opts?: Object): boolean; + + // ------------------------- assertXXX ------------------------- + assertArrayExpression(opts?: Object): void; + assertAssignmentExpression(opts?: Object): void; + assertBinaryExpression(opts?: Object): void; + assertDirective(opts?: Object): void; + assertDirectiveLiteral(opts?: Object): void; + assertBlockStatement(opts?: Object): void; + assertBreakStatement(opts?: Object): void; + assertCallExpression(opts?: Object): void; + assertCatchClause(opts?: Object): void; + assertConditionalExpression(opts?: Object): void; + assertContinueStatement(opts?: Object): void; + assertDebuggerStatement(opts?: Object): void; + assertDoWhileStatement(opts?: Object): void; + assertEmptyStatement(opts?: Object): void; + assertExpressionStatement(opts?: Object): void; + assertFile(opts?: Object): void; + assertForInStatement(opts?: Object): void; + assertForStatement(opts?: Object): void; + assertFunctionDeclaration(opts?: Object): void; + assertFunctionExpression(opts?: Object): void; + assertIdentifier(opts?: Object): void; + assertIfStatement(opts?: Object): void; + assertLabeledStatement(opts?: Object): void; + assertStringLiteral(opts?: Object): void; + assertNumericLiteral(opts?: Object): void; + assertNullLiteral(opts?: Object): void; + assertBooleanLiteral(opts?: Object): void; + assertRegExpLiteral(opts?: Object): void; + assertLogicalExpression(opts?: Object): void; + assertMemberExpression(opts?: Object): void; + assertNewExpression(opts?: Object): void; + assertProgram(opts?: Object): void; + assertObjectExpression(opts?: Object): void; + assertObjectMethod(opts?: Object): void; + assertObjectProperty(opts?: Object): void; + assertRestElement(opts?: Object): void; + assertReturnStatement(opts?: Object): void; + assertSequenceExpression(opts?: Object): void; + assertSwitchCase(opts?: Object): void; + assertSwitchStatement(opts?: Object): void; + assertThisExpression(opts?: Object): void; + assertThrowStatement(opts?: Object): void; + assertTryStatement(opts?: Object): void; + assertUnaryExpression(opts?: Object): void; + assertUpdateExpression(opts?: Object): void; + assertVariableDeclaration(opts?: Object): void; + assertVariableDeclarator(opts?: Object): void; + assertWhileStatement(opts?: Object): void; + assertWithStatement(opts?: Object): void; + assertAssignmentPattern(opts?: Object): void; + assertArrayPattern(opts?: Object): void; + assertArrowFunctionExpression(opts?: Object): void; + assertClassBody(opts?: Object): void; + assertClassDeclaration(opts?: Object): void; + assertClassExpression(opts?: Object): void; + assertExportAllDeclaration(opts?: Object): void; + assertExportDefaultDeclaration(opts?: Object): void; + assertExportNamedDeclaration(opts?: Object): void; + assertExportSpecifier(opts?: Object): void; + assertForOfStatement(opts?: Object): void; + assertImportDeclaration(opts?: Object): void; + assertImportDefaultSpecifier(opts?: Object): void; + assertImportNamespaceSpecifier(opts?: Object): void; + assertImportSpecifier(opts?: Object): void; + assertMetaProperty(opts?: Object): void; + assertClassMethod(opts?: Object): void; + assertObjectPattern(opts?: Object): void; + assertSpreadElement(opts?: Object): void; + assertSuper(opts?: Object): void; + assertTaggedTemplateExpression(opts?: Object): void; + assertTemplateElement(opts?: Object): void; + assertTemplateLiteral(opts?: Object): void; + assertYieldExpression(opts?: Object): void; + assertAnyTypeAnnotation(opts?: Object): void; + assertArrayTypeAnnotation(opts?: Object): void; + assertBooleanTypeAnnotation(opts?: Object): void; + assertBooleanLiteralTypeAnnotation(opts?: Object): void; + assertNullLiteralTypeAnnotation(opts?: Object): void; + assertClassImplements(opts?: Object): void; + assertClassProperty(opts?: Object): void; + assertDeclareClass(opts?: Object): void; + assertDeclareFunction(opts?: Object): void; + assertDeclareInterface(opts?: Object): void; + assertDeclareModule(opts?: Object): void; + assertDeclareTypeAlias(opts?: Object): void; + assertDeclareVariable(opts?: Object): void; + assertExistentialTypeParam(opts?: Object): void; + assertFunctionTypeAnnotation(opts?: Object): void; + assertFunctionTypeParam(opts?: Object): void; + assertGenericTypeAnnotation(opts?: Object): void; + assertInterfaceExtends(opts?: Object): void; + assertInterfaceDeclaration(opts?: Object): void; + assertIntersectionTypeAnnotation(opts?: Object): void; + assertMixedTypeAnnotation(opts?: Object): void; + assertNullableTypeAnnotation(opts?: Object): void; + assertNumericLiteralTypeAnnotation(opts?: Object): void; + assertNumberTypeAnnotation(opts?: Object): void; + assertStringLiteralTypeAnnotation(opts?: Object): void; + assertStringTypeAnnotation(opts?: Object): void; + assertThisTypeAnnotation(opts?: Object): void; + assertTupleTypeAnnotation(opts?: Object): void; + assertTypeofTypeAnnotation(opts?: Object): void; + assertTypeAlias(opts?: Object): void; + assertTypeAnnotation(opts?: Object): void; + assertTypeCastExpression(opts?: Object): void; + assertTypeParameterDeclaration(opts?: Object): void; + assertTypeParameterInstantiation(opts?: Object): void; + assertObjectTypeAnnotation(opts?: Object): void; + assertObjectTypeCallProperty(opts?: Object): void; + assertObjectTypeIndexer(opts?: Object): void; + assertObjectTypeProperty(opts?: Object): void; + assertQualifiedTypeIdentifier(opts?: Object): void; + assertUnionTypeAnnotation(opts?: Object): void; + assertVoidTypeAnnotation(opts?: Object): void; + assertJSXAttribute(opts?: Object): void; + assertJSXClosingElement(opts?: Object): void; + assertJSXElement(opts?: Object): void; + assertJSXEmptyExpression(opts?: Object): void; + assertJSXExpressionContainer(opts?: Object): void; + assertJSXIdentifier(opts?: Object): void; + assertJSXMemberExpression(opts?: Object): void; + assertJSXNamespacedName(opts?: Object): void; + assertJSXOpeningElement(opts?: Object): void; + assertJSXSpreadAttribute(opts?: Object): void; + assertJSXText(opts?: Object): void; + assertNoop(opts?: Object): void; + assertParenthesizedExpression(opts?: Object): void; + assertAwaitExpression(opts?: Object): void; + assertBindExpression(opts?: Object): void; + assertDecorator(opts?: Object): void; + assertDoExpression(opts?: Object): void; + assertExportDefaultSpecifier(opts?: Object): void; + assertExportNamespaceSpecifier(opts?: Object): void; + assertRestProperty(opts?: Object): void; + assertSpreadProperty(opts?: Object): void; + assertExpression(opts?: Object): void; + assertBinary(opts?: Object): void; + assertScopable(opts?: Object): void; + assertBlockParent(opts?: Object): void; + assertBlock(opts?: Object): void; + assertStatement(opts?: Object): void; + assertTerminatorless(opts?: Object): void; + assertCompletionStatement(opts?: Object): void; + assertConditional(opts?: Object): void; + assertLoop(opts?: Object): void; + assertWhile(opts?: Object): void; + assertExpressionWrapper(opts?: Object): void; + assertFor(opts?: Object): void; + assertForXStatement(opts?: Object): void; + assertFunction(opts?: Object): void; + assertFunctionParent(opts?: Object): void; + assertPureish(opts?: Object): void; + assertDeclaration(opts?: Object): void; + assertLVal(opts?: Object): void; + assertLiteral(opts?: Object): void; + assertImmutable(opts?: Object): void; + assertUserWhitespacable(opts?: Object): void; + assertMethod(opts?: Object): void; + assertObjectMember(opts?: Object): void; + assertProperty(opts?: Object): void; + assertUnaryLike(opts?: Object): void; + assertPattern(opts?: Object): void; + assertClass(opts?: Object): void; + assertModuleDeclaration(opts?: Object): void; + assertExportDeclaration(opts?: Object): void; + assertModuleSpecifier(opts?: Object): void; + assertFlow(opts?: Object): void; + assertFlowBaseAnnotation(opts?: Object): void; + assertFlowDeclaration(opts?: Object): void; + assertJSX(opts?: Object): void; + assertNumberLiteral(opts?: Object): void; + assertRegexLiteral(opts?: Object): void; +} + +export class Hub { + constructor(file: any, options: any); + file: any; + options: any; +} + +interface TraversalContext { + parentPath: NodePath; + scope: Scope; + state: any; + opts: any; +} + diff --git a/babel-traverse/tsconfig.json b/babel-traverse/tsconfig.json new file mode 100644 index 0000000000..5afbcffaad --- /dev/null +++ b/babel-traverse/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "babel-traverse-tests.ts" + ] +} \ No newline at end of file diff --git a/babel-types/babel-types-tests.ts b/babel-types/babel-types-tests.ts new file mode 100644 index 0000000000..cb02d11ee1 --- /dev/null +++ b/babel-types/babel-types-tests.ts @@ -0,0 +1,26 @@ + +/// + + +// Examples from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-types +import traverse from "babel-traverse"; +import * as t from "babel-types"; + +let ast: t.Node; + +traverse(ast, { + enter(path) { + let node = path.node; + if (t.isIdentifier(node, { name: "n" })) { + node.name = "x"; + } + } +}); + +if (t.isBinaryExpression(ast)) { + ast.left; + ast.right; + ast.operator; +} +t.assertBinaryExpression(ast); +t.assertBinaryExpression(ast, { operator: "*" }); diff --git a/babel-types/index.d.ts b/babel-types/index.d.ts new file mode 100644 index 0000000000..b3b0f966c6 --- /dev/null +++ b/babel-types/index.d.ts @@ -0,0 +1,1401 @@ +// Type definitions for babel-types v6.7 +// Project: https://github.com/babel/babel/tree/master/packages/babel-types +// Definitions by: Troy Gerwien +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Comment { + value: string; + start: number; + end: number; + loc: SourceLocation; +} + +export interface CommentBlock extends Comment { + type: "CommentBlock"; +} + +export interface CommentLine extends Comment { + type: "CommentLine"; +} + +export interface SourceLocation { + start: { + line: number; + column: number; + }; + + end: { + line: number; + column: number; + }; +} + +export interface Node { + type: string; + leadingComments?: Array; + innerComments?: Array; + trailingComments?: Array; + start: number; + end: number; + loc: SourceLocation; +} + +export interface ArrayExpression extends Node { + type: "ArrayExpression"; + elements: Array; +} + +export interface AssignmentExpression extends Node { + type: "AssignmentExpression"; + operator: "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&="; + left: LVal; + right: Expression; +} + +export interface BinaryExpression extends Node { + type: "BinaryExpression"; + operator: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<="; + left: Expression; + right: Expression; +} + +export interface Directive extends Node { + type: "Directive"; + value: DirectiveLiteral; +} + +export interface DirectiveLiteral extends Node { + type: "DirectiveLiteral"; + value: string; +} + +export interface BlockStatement extends Node { + type: "BlockStatement"; + directives?: Directive[]; + body: Statement[]; +} + +export interface BreakStatement extends Node { + type: "BreakStatement"; + label: Identifier; +} + +export interface CallExpression extends Node { + type: "CallExpression"; + callee: Expression | Super; + arguments: Array; +} + +export interface CatchClause extends Node { + type: "CatchClause"; + param: Pattern; + body: BlockStatement; +} + +export interface ConditionalExpression extends Node { + type: "ConditionalExpression"; + test: Expression; + consequent: Expression; + alternate: Expression; +} + +export interface ContinueStatement extends Node { + type: "ContinueStatement"; + label: Identifier; +} + +export interface DebuggerStatement extends Node { + type: "DebuggerStatement"; +} + +export interface DoWhileStatement extends Node { + type: "DoWhileStatement"; + test: Expression; + body: Statement; +} + +export interface EmptyStatement extends Node { + type: "EmptyStatement"; +} + +export interface ExpressionStatement extends Node { + type: "ExpressionStatement"; + expression: Expression; +} + +export interface File extends Node { + type: "File"; + program: Program; + comments: Comment[]; + tokens: any[]; +} + +export interface ForInStatement extends Node { + type: "ForInStatement"; + left: VariableDeclaration | LVal; + right: Expression; + body: Statement; +} + +export interface ForStatement extends Node { + type: "ForStatement"; + init: VariableDeclaration | Expression; + test: Expression; + update: Expression; + body: Statement; +} + +export interface FunctionDeclaration extends Node { + type: "FunctionDeclaration"; + id: Identifier; + params: Pattern[]; + body: BlockStatement; + generator: boolean; + async: boolean; + returnType?: TypeAnnotation; + typeParameters?: TypeParameterDeclaration; +} + +export interface FunctionExpression extends Node { + type: "FunctionExpression"; + id: Identifier; + params: Pattern[]; + body: BlockStatement; + generator: boolean; + async: boolean; + returnType?: TypeAnnotation; + typeParameters?: TypeParameterDeclaration; +} + +export interface Identifier extends Node { + type: "Identifier"; + name: string; + typeAnnotation?: TypeAnnotation; +} + +export interface IfStatement extends Node { + type: "IfStatement"; + test: Expression; + consequent: Statement; + alternate: Statement; +} + +export interface LabeledStatement extends Node { + type: "LabeledStatement"; + label: Identifier; + body: Statement; +} + +export interface StringLiteral extends Node { + type: "StringLiteral"; + value: string; +} + +export interface NumericLiteral extends Node { + type: "NumericLiteral"; + value: number; +} + +export interface NullLiteral extends Node { + type: "NullLiteral"; +} + +export interface BooleanLiteral extends Node { + type: "BooleanLiteral"; + value: boolean; +} + +export interface RegExpLiteral extends Node { + type: "RegExpLiteral"; + pattern: string; + flags?: string; +} + +export interface LogicalExpression extends Node { + type: "LogicalExpression"; + operator: "||" | "&&"; + left: Expression; + right: Expression; +} + +export interface MemberExpression extends Node { + type: "MemberExpression"; + object: Expression | Super; + property: Expression; + computed: boolean; +} + +export interface NewExpression extends Node { + type: "NewExpression"; + callee: Expression | Super; + arguments: Array; +} + +export interface Program extends Node { + type: "Program"; + sourceType: "script" | "module"; + directives?: Directive[]; + body: Array; +} + +export interface ObjectExpression extends Node { + type: "ObjectExpression"; + properties: Array; +} + +export interface ObjectMethod extends Node { + type: "ObjectMethod"; + key: Expression; + kind: "get" | "set" | "method"; + shorthand: boolean; + computed: boolean; + value: Expression; + decorators?: Decorator[]; + id: Identifier; + params: Pattern[]; + body: BlockStatement; + generator: boolean; + async: boolean; + returnType?: TypeAnnotation; + typeParameters?: TypeParameterDeclaration; +} + +export interface ObjectProperty extends Node { + type: "ObjectProperty"; + key: Expression; + computed: boolean; + value: Expression; + decorators?: Decorator[]; + shorthand: boolean; +} + +export interface RestElement extends Node { + type: "RestElement"; + argument: LVal; + typeAnnotation?: TypeAnnotation; +} + +export interface ReturnStatement extends Node { + type: "ReturnStatement"; + argument: Expression; +} + +export interface SequenceExpression extends Node { + type: "SequenceExpression"; + expressions: Expression[]; +} + +export interface SwitchCase extends Node { + type: "SwitchCase"; + test: Expression; + consequent: Statement[]; +} + +export interface SwitchStatement extends Node { + type: "SwitchStatement"; + discriminant: Expression; + cases: SwitchCase[]; +} + +export interface ThisExpression extends Node { + type: "ThisExpression"; +} + +export interface ThrowStatement extends Node { + type: "ThrowStatement"; + argument: Expression; +} + +export interface TryStatement extends Node { + type: "TryStatement"; + block: BlockStatement; + handler: CatchClause; + finalizer: BlockStatement; +} + +export interface UnaryExpression extends Node { + type: "UnaryExpression"; + operator: "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; + prefix: boolean; + argument: Expression; +} + +export interface UpdateExpression extends Node { + type: "UpdateExpression"; + operator: "++" | "--"; + prefix: boolean; + argument: Expression; +} + +export interface VariableDeclaration extends Node { + type: "VariableDeclaration"; + declarations: VariableDeclarator[]; + kind: "var" | "let" | "const"; +} + +export interface VariableDeclarator extends Node { + type: "VariableDeclarator"; + id: LVal; + init: Expression; +} + +export interface WhileStatement extends Node { + type: "WhileStatement"; + test: Expression; + body: Statement; +} + +export interface WithStatement extends Node { + type: "WithStatement"; + object: Expression; + body: BlockStatement | Statement; +} + +export interface AssignmentPattern extends Node { + type: "AssignmentPattern"; + left: Pattern; + right: Expression; +} + +export interface ArrayPattern extends Node { + type: "ArrayPattern"; + elements: Array; + typeAnnotation?: TypeAnnotation; +} + +export interface ArrowFunctionExpression extends Node { + type: "ArrowFunctionExpression"; + id: Identifier; + params: Pattern[]; + body: BlockStatement | Expression; + generator: boolean; + async: boolean; + expression: boolean; + returnType?: TypeAnnotation; + typeParameters?: TypeParameterDeclaration; +} + +export interface ClassBody extends Node { + type: "ClassBody"; + body: Array; +} + +export interface ClassDeclaration extends Node { + type: "ClassDeclaration"; + id: Identifier; + superClass: Expression; + body: ClassBody; + decorators?: Decorator[]; + implements?: ClassImplements[]; + mixins?: any[]; + typeParameters?: TypeParameterDeclaration; + superTypeParameters?: TypeParameterInstantiation; +} + +export interface ClassExpression extends Node { + type: "ClassExpression"; + id: Identifier; + superClass: Expression; + body: ClassBody; + decorators?: Decorator[]; + implements?: ClassImplements[]; + mixins?: any[]; + typeParameters?: TypeParameterDeclaration; + superTypeParameters?: TypeParameterInstantiation; +} + +export interface ExportAllDeclaration extends Node { + type: "ExportAllDeclaration"; + source: StringLiteral; +} + +export interface ExportDefaultDeclaration extends Node { + type: "ExportDefaultDeclaration"; + declaration: Declaration | Expression; +} + +export interface ExportNamedDeclaration extends Node { + type: "ExportNamedDeclaration"; + declaration: Declaration; + specifiers: ExportSpecifier[]; + source: StringLiteral; +} + +export interface ExportSpecifier extends Node { + type: "ExportSpecifier"; + local: Identifier; + imported: Identifier; + exported: Identifier; +} + +export interface ForOfStatement extends Node { + type: "ForOfStatement"; + left: VariableDeclaration | LVal; + right: Expression; + body: Statement; +} + +export interface ImportDeclaration extends Node { + type: "ImportDeclaration"; + specifiers: Array; + source: StringLiteral; +} + +export interface ImportDefaultSpecifier extends Node { + type: "ImportDefaultSpecifier"; + local: Identifier; +} + +export interface ImportNamespaceSpecifier extends Node { + type: "ImportNamespaceSpecifier"; + local: Identifier; +} + +export interface ImportSpecifier extends Node { + type: "ImportSpecifier"; + local: Identifier; + imported: Identifier; +} + +export interface MetaProperty extends Node { + type: "MetaProperty"; + meta: Identifier; + property: Identifier; +} + +export interface ClassMethod extends Node { + type: "ClassMethod"; + key: Expression; + value?: FunctionExpression; + kind: "constructor" | "method" | "get" | "set"; + computed: boolean; + static: boolean; + decorators?: Decorator[]; + id: Identifier; + params: Pattern[]; + body: BlockStatement; + generator: boolean; + async: boolean; + expression: boolean; + returnType?: TypeAnnotation; + typeParameters?: TypeParameterDeclaration; +} + +// See: https://github.com/babel/babel/blob/master/doc/ast/spec.md#objectpattern +export interface AssignmentProperty extends Node { + type: "ObjectProperty"; + key: Expression; + computed: boolean; + value: Pattern; + decorators?: Decorator[]; + shorthand: boolean; +} + +export interface ObjectPattern extends Node { + type: "ObjectPattern"; + properties: Array; + typeAnnotation?: TypeAnnotation; +} + +export interface SpreadElement extends Node { + type: "SpreadElement"; + argument: Expression; +} + +export interface Super extends Node { + type: "Super"; +} + +export interface TaggedTemplateExpression extends Node { + type: "TaggedTemplateExpression"; + tag: Expression; + quasi: TemplateLiteral; +} + +export interface TemplateElement extends Node { + type: "TemplateElement"; + tail: boolean; + value: { + cooked: string; + raw: string; + }; +} + +export interface TemplateLiteral extends Node { + type: "TemplateLiteral"; + quasis: TemplateElement[]; + expressions: Expression[]; +} + +export interface YieldExpression extends Node { + type: "YieldExpression"; + argument: Expression; + delegate: boolean; +} + +export interface AnyTypeAnnotation extends Node { + type: "AnyTypeAnnotation"; +} + +export interface ArrayTypeAnnotation extends Node { + type: "ArrayTypeAnnotation"; + elementType: FlowTypeAnnotation; +} + +export interface BooleanTypeAnnotation extends Node { + type: "BooleanTypeAnnotation"; +} + +export interface BooleanLiteralTypeAnnotation extends Node { + type: "BooleanLiteralTypeAnnotation"; +} + +export interface NullLiteralTypeAnnotation extends Node { + type: "NullLiteralTypeAnnotation"; +} + +export interface ClassImplements extends Node { + type: "ClassImplements"; + id: Identifier; + typeParameters: TypeParameterInstantiation; +} + +export interface ClassProperty extends Node { + type: "ClassProperty"; + key: Identifier; + value: Expression; + decorators?: Decorator[]; + typeAnnotation?: TypeAnnotation; +} + +export interface DeclareClass extends Node { + type: "DeclareClass"; + id: Identifier; + typeParameters: TypeParameterDeclaration; + extends: InterfaceExtends[]; + body: ObjectTypeAnnotation; +} + +export interface DeclareFunction extends Node { + type: "DeclareFunction"; + id: Identifier; +} + +export interface DeclareInterface extends Node { + type: "DeclareInterface"; + id: Identifier; + typeParameters: TypeParameterDeclaration; + extends: InterfaceExtends[]; + body: ObjectTypeAnnotation; +} + +export interface DeclareModule extends Node { + type: "DeclareModule"; + id: StringLiteral | Identifier; + body: BlockStatement; +} + +export interface DeclareTypeAlias extends Node { + type: "DeclareTypeAlias"; + id: Identifier; + typeParameters: TypeParameterDeclaration; + right: FlowTypeAnnotation; +} + +export interface DeclareVariable extends Node { + type: "DeclareVariable"; + id: Identifier; +} + +export interface ExistentialTypeParam extends Node { + type: "ExistentialTypeParam"; +} + +export interface FunctionTypeAnnotation extends Node { + type: "FunctionTypeAnnotation"; + typeParameters: TypeParameterDeclaration; + params: FunctionTypeParam[]; + rest: FunctionTypeParam; + returnType: FlowTypeAnnotation; +} + +export interface FunctionTypeParam extends Node { + type: "FunctionTypeParam"; + name: Identifier; + typeAnnotation: FlowTypeAnnotation; +} + +export interface GenericTypeAnnotation extends Node { + type: "GenericTypeAnnotation"; + id: Identifier; + typeParameters: TypeParameterInstantiation; +} + +export interface InterfaceExtends extends Node { + type: "InterfaceExtends"; + id: Identifier; + typeParameters: TypeParameterInstantiation; +} + +export interface InterfaceDeclaration extends Node { + type: "InterfaceDeclaration"; + id: Identifier; + typeParameters: TypeParameterDeclaration; + extends: InterfaceExtends[]; + mixins?: any[]; + body: ObjectTypeAnnotation; +} + +export interface IntersectionTypeAnnotation extends Node { + type: "IntersectionTypeAnnotation"; + types: FlowTypeAnnotation[]; +} + +export interface MixedTypeAnnotation extends Node { + type: "MixedTypeAnnotation"; +} + +export interface NullableTypeAnnotation extends Node { + type: "NullableTypeAnnotation"; + typeAnnotation: FlowTypeAnnotation; +} + +export interface NumericLiteralTypeAnnotation extends Node { + type: "NumericLiteralTypeAnnotation"; +} + +export interface NumberTypeAnnotation extends Node { + type: "NumberTypeAnnotation"; +} + +export interface StringLiteralTypeAnnotation extends Node { + type: "StringLiteralTypeAnnotation"; +} + +export interface StringTypeAnnotation extends Node { + type: "StringTypeAnnotation"; +} + +export interface ThisTypeAnnotation extends Node { + type: "ThisTypeAnnotation"; +} + +export interface TupleTypeAnnotation extends Node { + type: "TupleTypeAnnotation"; + types: FlowTypeAnnotation[]; +} + +export interface TypeofTypeAnnotation extends Node { + type: "TypeofTypeAnnotation"; + argument: FlowTypeAnnotation; +} + +export interface TypeAlias extends Node { + type: "TypeAlias"; + id: Identifier; + typeParameters: TypeParameterDeclaration; + right: FlowTypeAnnotation; +} + +export interface TypeAnnotation extends Node { + type: "TypeAnnotation"; + typeAnnotation: FlowTypeAnnotation; +} + +export interface TypeCastExpression extends Node { + type: "TypeCastExpression"; + expression: Expression; + typeAnnotation: FlowTypeAnnotation; +} + +export interface TypeParameterDeclaration extends Node { + type: "TypeParameterDeclaration"; + params: Identifier[]; +} + +export interface TypeParameterInstantiation extends Node { + type: "TypeParameterInstantiation"; + params: FlowTypeAnnotation[]; +} + +export interface ObjectTypeAnnotation extends Node { + type: "ObjectTypeAnnotation"; + properties: ObjectTypeProperty[]; + indexers: ObjectTypeIndexer[]; + callProperties: ObjectTypeCallProperty[]; +} + +export interface ObjectTypeCallProperty extends Node { + type: "ObjectTypeCallProperty"; + value: FlowTypeAnnotation; +} + +export interface ObjectTypeIndexer extends Node { + type: "ObjectTypeIndexer"; + id: Expression; + key: FlowTypeAnnotation; + value: FlowTypeAnnotation; +} + +export interface ObjectTypeProperty extends Node { + type: "ObjectTypeProperty"; + key: Expression; + value: FlowTypeAnnotation; +} + +export interface QualifiedTypeIdentifier extends Node { + type: "QualifiedTypeIdentifier"; + id: Identifier; + qualification: Identifier | QualifiedTypeIdentifier; +} + +export interface UnionTypeAnnotation extends Node { + type: "UnionTypeAnnotation"; + types: FlowTypeAnnotation[]; +} + +export interface VoidTypeAnnotation extends Node { + type: "VoidTypeAnnotation"; +} + +export interface JSXAttribute extends Node { + type: "JSXAttribute"; + name: JSXIdentifier | JSXNamespacedName; + value: JSXElement | StringLiteral | JSXExpressionContainer; +} + +export interface JSXClosingElement extends Node { + type: "JSXClosingElement"; + name: JSXIdentifier | JSXMemberExpression; +} + +export interface JSXElement extends Node { + type: "JSXElement"; + openingElement: JSXOpeningElement; + closingElement: JSXClosingElement; + children: Array; + selfClosing?: boolean; +} + +export interface JSXEmptyExpression extends Node { + type: "JSXEmptyExpression"; +} + +export interface JSXExpressionContainer extends Node { + type: "JSXExpressionContainer"; + expression: Expression; +} + +export interface JSXIdentifier extends Node { + type: "JSXIdentifier"; + name: string; +} + +export interface JSXMemberExpression extends Node { + type: "JSXMemberExpression"; + object: JSXMemberExpression | JSXIdentifier; + property: JSXIdentifier; +} + +export interface JSXNamespacedName extends Node { + type: "JSXNamespacedName"; + namespace: JSXIdentifier; + name: JSXIdentifier; +} + +export interface JSXOpeningElement extends Node { + type: "JSXOpeningElement"; + name: JSXIdentifier | JSXMemberExpression; + selfClosing: boolean; + attributes: JSXAttribute[]; +} + +export interface JSXSpreadAttribute extends Node { + type: "JSXSpreadAttribute"; + argument: Expression; +} + +export interface JSXText extends Node { + type: "JSXText"; + value: string; +} + +export interface Noop extends Node { + type: "Noop"; +} + +export interface ParenthesizedExpression extends Node { + type: "ParenthesizedExpression"; + expression: Expression; +} + +export interface AwaitExpression extends Node { + type: "AwaitExpression"; + argument: Expression; +} + +export interface BindExpression extends Node { + type: "BindExpression"; + object: Expression; + callee: Expression; +} + +export interface Decorator extends Node { + type: "Decorator"; + expression: Expression; +} + +export interface DoExpression extends Node { + type: "DoExpression"; + body: BlockStatement; +} + +export interface ExportDefaultSpecifier extends Node { + type: "ExportDefaultSpecifier"; + exported: Identifier; +} + +export interface ExportNamespaceSpecifier extends Node { + type: "ExportNamespaceSpecifier"; + exported: Identifier; +} + +export interface RestProperty extends Node { + type: "RestProperty"; + argument: LVal; +} + +export interface SpreadProperty extends Node { + type: "SpreadProperty"; + argument: Expression; +} + +export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression; +export type Binary = BinaryExpression | LogicalExpression; +export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ClassDeclaration | ClassExpression | ForOfStatement | ClassMethod; +export type BlockParent = BlockStatement | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ForOfStatement | ClassMethod; +export type Block = BlockStatement | Program; +export type Statement = BlockStatement | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement | EmptyStatement | ExpressionStatement | ForInStatement | ForStatement | FunctionDeclaration | IfStatement | LabeledStatement | ReturnStatement | SwitchStatement | ThrowStatement | TryStatement | VariableDeclaration | WhileStatement | WithStatement | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ForOfStatement | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; +export type Terminatorless = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement | YieldExpression | AwaitExpression; +export type CompletionStatement = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement; +export type Conditional = ConditionalExpression | IfStatement; +export type Loop = DoWhileStatement | ForInStatement | ForStatement | WhileStatement | ForOfStatement; +export type While = DoWhileStatement | WhileStatement; +export type ExpressionWrapper = ExpressionStatement | TypeCastExpression | ParenthesizedExpression; +export type For = ForInStatement | ForStatement | ForOfStatement; +export type ForXStatement = ForInStatement | ForOfStatement; +export type Function = FunctionDeclaration | FunctionExpression | ObjectMethod | ArrowFunctionExpression | ClassMethod; +export type FunctionParent = FunctionDeclaration | FunctionExpression | Program | ObjectMethod | ArrowFunctionExpression | ClassMethod; +export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | BooleanLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression; +export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; +export type LVal = Identifier | MemberExpression | RestElement | AssignmentPattern | ArrayPattern | ObjectPattern; +export type Literal = StringLiteral | NumericLiteral | BooleanLiteral | RegExpLiteral | TemplateLiteral; +export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement; +export type UserWhitespacable = ObjectMethod | ObjectProperty | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty; +export type Method = ObjectMethod | ClassMethod; +export type ObjectMember = ObjectMethod | ObjectProperty; +export type Property = ObjectProperty | ClassProperty; +export type UnaryLike = UnaryExpression | SpreadElement | RestProperty | SpreadProperty; +export type Pattern = AssignmentPattern | ArrayPattern | ObjectPattern; +export type Class = ClassDeclaration | ClassExpression; +export type ModuleDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration; +export type ExportDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration; +export type ModuleSpecifier = ExportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ImportSpecifier | ExportDefaultSpecifier | ExportNamespaceSpecifier; +export type Flow = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | ClassImplements | ClassProperty | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | ExistentialTypeParam | FunctionTypeAnnotation | FunctionTypeParam | GenericTypeAnnotation | InterfaceExtends | InterfaceDeclaration | IntersectionTypeAnnotation | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAlias | TypeAnnotation | TypeCastExpression | TypeParameterDeclaration | TypeParameterInstantiation | ObjectTypeAnnotation | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty | QualifiedTypeIdentifier | UnionTypeAnnotation | VoidTypeAnnotation; +export type FlowTypeAnnotation = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | FunctionTypeAnnotation | GenericTypeAnnotation | IntersectionTypeAnnotation | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAnnotation | ObjectTypeAnnotation | UnionTypeAnnotation | VoidTypeAnnotation; +export type FlowBaseAnnotation = AnyTypeAnnotation | BooleanTypeAnnotation | MixedTypeAnnotation | NumberTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | VoidTypeAnnotation; +export type FlowDeclaration = DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; +export type JSX = JSXAttribute | JSXClosingElement | JSXElement | JSXEmptyExpression | JSXExpressionContainer | JSXIdentifier | JSXMemberExpression | JSXNamespacedName | JSXOpeningElement | JSXSpreadAttribute | JSXText; + +export function arrayExpression(elements?: Array): ArrayExpression; +export function assignmentExpression(operator?: string, left?: LVal, right?: Expression): AssignmentExpression; +export function binaryExpression(operator?: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<=", left?: Expression, right?: Expression): BinaryExpression; +export function directive(value?: DirectiveLiteral): Directive; +export function directiveLiteral(value?: string): DirectiveLiteral; +export function blockStatement(body?: Statement[], directives?: Directive[]): BlockStatement; +export function breakStatement(label?: Identifier): BreakStatement; +export function callExpression(callee?: Expression, _arguments?: Array): CallExpression; +export function catchClause(param?: Identifier, body?: BlockStatement): CatchClause; +export function conditionalExpression(test?: Expression, consequent?: Expression, alternate?: Expression): ConditionalExpression; +export function continueStatement(label?: Identifier): ContinueStatement; +export function debuggerStatement(): DebuggerStatement; +export function doWhileStatement(test?: Expression, body?: Statement): DoWhileStatement; +export function emptyStatement(): EmptyStatement; +export function expressionStatement(expression?: Expression): ExpressionStatement; +export function file(program?: Program, comments?: Comment[], tokens?: any[]): File; +export function forInStatement(left?: VariableDeclaration | LVal, right?: Expression, body?: Statement): ForInStatement; +export function forStatement(init?: VariableDeclaration | Expression, test?: Expression, update?: Expression, body?: Statement): ForStatement; +export function functionDeclaration(id?: Identifier, params?: Pattern[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; +export function functionExpression(id?: Identifier, params?: Pattern[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression; +export function identifier(name?: string): Identifier; +export function ifStatement(test?: Expression, consequent?: Statement, alternate?: Statement): IfStatement; +export function labeledStatement(label?: Identifier, body?: Statement): LabeledStatement; +export function stringLiteral(value?: string): StringLiteral; +export function numericLiteral(value?: number): NumericLiteral; +export function nullLiteral(): NullLiteral; +export function booleanLiteral(value?: boolean): BooleanLiteral; +export function regExpLiteral(pattern?: string, flags?: string): RegExpLiteral; +export function logicalExpression(operator?: "||" | "&&", left?: Expression, right?: Expression): LogicalExpression; +export function memberExpression(object?: Expression | Super, property?: Expression, computed?: boolean): MemberExpression; +export function newExpression(callee?: Expression | Super, _arguments?: Array): NewExpression; +export function program(body?: Array, directives?: Directive[]): Program; +export function objectExpression(properties?: Array): ObjectExpression; +export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: Pattern[], body?: BlockStatement, computed?: boolean): ObjectMethod; +export function objectProperty(key?: Expression, value?: Expression, computed?: boolean, shorthand?: boolean, decorators?: Decorator[]): ObjectProperty; +export function restElement(argument?: LVal, typeAnnotation?: TypeAnnotation): RestElement; +export function returnStatement(argument?: Expression): ReturnStatement; +export function sequenceExpression(expressions?: Expression[]): SequenceExpression; +export function switchCase(test?: Expression, consequent?: Statement[]): SwitchCase; +export function switchStatement(discriminant?: Expression, cases?: SwitchCase[]): SwitchStatement; +export function thisExpression(): ThisExpression; +export function throwStatement(argument?: Expression): ThrowStatement; +export function tryStatement(block?: BlockStatement, handler?: CatchClause, finalizer?: BlockStatement): TryStatement; +export function unaryExpression(operator?: "void" | "delete" | "!" | "+" | "-" | "++" | "--" | "~" | "typeof", argument?: Expression, prefix?: boolean): UnaryExpression; +export function updateExpression(operator?: "++" | "--", argument?: Expression, prefix?: boolean): UpdateExpression; +export function variableDeclaration(kind?: "var" | "let" | "const", declarations?: VariableDeclarator[]): VariableDeclaration; +export function variableDeclarator(id?: LVal, init?: Expression): VariableDeclarator; +export function whileStatement(test?: Expression, body?: BlockStatement | Statement): WhileStatement; +export function withStatement(object?: Expression, body?: BlockStatement | Statement): WithStatement; +export function assignmentPattern(left?: Identifier, right?: Expression): AssignmentPattern; +export function arrayPattern(elements?: Array, typeAnnotation?: TypeAnnotation): ArrayPattern; +export function arrowFunctionExpression(params?: Pattern[], body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression; +export function classBody(body?: Array): ClassBody; +export function classDeclaration(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassDeclaration; +export function classExpression(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassExpression; +export function exportAllDeclaration(source?: StringLiteral): ExportAllDeclaration; +export function exportDefaultDeclaration(declaration?: FunctionDeclaration | ClassDeclaration | Expression): ExportDefaultDeclaration; +export function exportNamedDeclaration(declaration?: Declaration, specifiers?: ExportSpecifier[], source?: StringLiteral): ExportNamedDeclaration; +export function exportSpecifier(local?: Identifier, exported?: Identifier): ExportSpecifier; +export function forOfStatement(left?: VariableDeclaration | LVal, right?: Expression, body?: Statement): ForOfStatement; +export function importDeclaration(specifiers?: Array, source?: StringLiteral): ImportDeclaration; +export function importDefaultSpecifier(local?: Identifier): ImportDefaultSpecifier; +export function importNamespaceSpecifier(local?: Identifier): ImportNamespaceSpecifier; +export function importSpecifier(local?: Identifier, imported?: Identifier): ImportSpecifier; +export function metaProperty(meta?: string, property?: string): MetaProperty; +export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: Pattern[], body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod; +export function objectPattern(properties?: Array, typeAnnotation?: TypeAnnotation): ObjectPattern; +export function spreadElement(argument?: Expression): SpreadElement; +export function taggedTemplateExpression(tag?: Expression, quasi?: TemplateLiteral): TaggedTemplateExpression; +export function templateElement(value?: {cooked?: string; raw?: string;}, tail?: boolean): TemplateElement; +export function templateLiteral(quasis?: TemplateElement[], expressions?: Expression[]): TemplateLiteral; +export function yieldExpression(argument?: Expression, delegate?: boolean): YieldExpression; +export function anyTypeAnnotation(): AnyTypeAnnotation; +export function arrayTypeAnnotation(elementType?: FlowTypeAnnotation): ArrayTypeAnnotation; +export function booleanTypeAnnotation(): BooleanTypeAnnotation; +export function booleanLiteralTypeAnnotation(): BooleanLiteralTypeAnnotation; +export function nullLiteralTypeAnnotation(): NullLiteralTypeAnnotation; +export function classImplements(id?: Identifier, typeParameters?: TypeParameterInstantiation): ClassImplements; +export function classProperty(key?: Identifier, value?: Expression, typeAnnotation?: TypeAnnotation, decorators?: Decorator[]): ClassProperty; +export function declareClass(id?: Identifier, typeParameters?: TypeParameterDeclaration, _extends?: InterfaceExtends[], body?: ObjectTypeAnnotation): DeclareClass; +export function declareFunction(id?: Identifier): DeclareFunction; +export function declareInterface(id?: Identifier, typeParameters?: TypeParameterDeclaration, _extends?: InterfaceExtends[], body?: ObjectTypeAnnotation): DeclareInterface; +export function declareModule(id?: StringLiteral | Identifier, body?: BlockStatement): DeclareModule; +export function declareTypeAlias(id?: Identifier, typeParameters?: TypeParameterDeclaration, right?: FlowTypeAnnotation): DeclareTypeAlias; +export function declareVariable(id?: Identifier): DeclareVariable; +export function existentialTypeParam(): ExistentialTypeParam; +export function functionTypeAnnotation(typeParameters?: TypeParameterDeclaration, params?: FunctionTypeParam[], rest?: FunctionTypeParam, returnType?: FlowTypeAnnotation): FunctionTypeAnnotation; +export function functionTypeParam(name?: Identifier, typeAnnotation?: FlowTypeAnnotation): FunctionTypeParam; +export function genericTypeAnnotation(id?: Identifier, typeParameters?: TypeParameterInstantiation): GenericTypeAnnotation; +export function interfaceExtends(id?: Identifier, typeParameters?: TypeParameterInstantiation): InterfaceExtends; +export function interfaceDeclaration(id?: Identifier, typeParameters?: TypeParameterDeclaration, _extends?: InterfaceExtends[], body?: ObjectTypeAnnotation): InterfaceDeclaration; +export function intersectionTypeAnnotation(types?: FlowTypeAnnotation[]): IntersectionTypeAnnotation; +export function mixedTypeAnnotation(): MixedTypeAnnotation; +export function nullableTypeAnnotation(typeAnnotation?: FlowTypeAnnotation): NullableTypeAnnotation; +export function numericLiteralTypeAnnotation(): NumericLiteralTypeAnnotation; +export function numberTypeAnnotation(): NumberTypeAnnotation; +export function stringLiteralTypeAnnotation(): StringLiteralTypeAnnotation; +export function stringTypeAnnotation(): StringTypeAnnotation; +export function thisTypeAnnotation(): ThisTypeAnnotation; +export function tupleTypeAnnotation(types?: FlowTypeAnnotation[]): TupleTypeAnnotation; +export function typeofTypeAnnotation(argument?: FlowTypeAnnotation): TypeofTypeAnnotation; +export function typeAlias(id?: Identifier, typeParameters?: TypeParameterDeclaration, right?: FlowTypeAnnotation): TypeAlias; +export function typeAnnotation(typeAnnotation?: FlowTypeAnnotation): TypeAnnotation; +export function typeCastExpression(expression?: Expression, typeAnnotation?: FlowTypeAnnotation): TypeCastExpression; +export function typeParameterDeclaration(params?: Identifier[]): TypeParameterDeclaration; +export function typeParameterInstantiation(params?: FlowTypeAnnotation[]): TypeParameterInstantiation; +export function objectTypeAnnotation(properties?: ObjectTypeProperty[], indexers?: ObjectTypeIndexer[], callProperties?: ObjectTypeCallProperty[]): ObjectTypeAnnotation; +export function objectTypeCallProperty(value?: FlowTypeAnnotation): ObjectTypeCallProperty; +export function objectTypeIndexer(id?: Expression, key?: FlowTypeAnnotation, value?: FlowTypeAnnotation): ObjectTypeIndexer; +export function objectTypeProperty(key?: Expression, value?: FlowTypeAnnotation): ObjectTypeProperty; +export function qualifiedTypeIdentifier(id?: Identifier, qualification?: Identifier | QualifiedTypeIdentifier): QualifiedTypeIdentifier; +export function unionTypeAnnotation(types?: FlowTypeAnnotation[]): UnionTypeAnnotation; +export function voidTypeAnnotation(): VoidTypeAnnotation; +export function jSXAttribute(name?: JSXIdentifier | JSXNamespacedName, value?: JSXElement | StringLiteral | JSXExpressionContainer): JSXAttribute; +export function jSXClosingElement(name?: JSXIdentifier | JSXMemberExpression): JSXClosingElement; +export function jSXElement(openingElement?: JSXOpeningElement, closingElement?: JSXClosingElement, children?: Array, selfClosing?: boolean): JSXElement; +export function jSXEmptyExpression(): JSXEmptyExpression; +export function jSXExpressionContainer(expression?: Expression): JSXExpressionContainer; +export function jSXIdentifier(name?: string): JSXIdentifier; +export function jSXMemberExpression(object?: JSXMemberExpression | JSXIdentifier, property?: JSXIdentifier): JSXMemberExpression; +export function jSXNamespacedName(namespace?: JSXIdentifier, name?: JSXIdentifier): JSXNamespacedName; +export function jSXOpeningElement(name?: JSXIdentifier | JSXMemberExpression, attributes?: JSXAttribute[], selfClosing?: boolean): JSXOpeningElement; +export function jSXSpreadAttribute(argument?: Expression): JSXSpreadAttribute; +export function jSXText(value?: string): JSXText; +export function noop(): Noop; +export function parenthesizedExpression(expression?: Expression): ParenthesizedExpression; +export function awaitExpression(argument?: Expression): AwaitExpression; +export function bindExpression(object?: Expression, callee?: Expression): BindExpression; +export function decorator(expression?: Expression): Decorator; +export function doExpression(body?: BlockStatement): DoExpression; +export function exportDefaultSpecifier(exported?: Identifier): ExportDefaultSpecifier; +export function exportNamespaceSpecifier(exported?: Identifier): ExportNamespaceSpecifier; +export function restProperty(argument?: LVal): RestProperty; +export function spreadProperty(argument?: Expression): SpreadProperty; + +export function isArrayExpression(node: Object, opts?: Object): node is ArrayExpression; +export function isAssignmentExpression(node: Object, opts?: Object): node is AssignmentExpression; +export function isBinaryExpression(node: Object, opts?: Object): node is BinaryExpression; +export function isDirective(node: Object, opts?: Object): node is Directive; +export function isDirectiveLiteral(node: Object, opts?: Object): node is DirectiveLiteral; +export function isBlockStatement(node: Object, opts?: Object): node is BlockStatement; +export function isBreakStatement(node: Object, opts?: Object): node is BreakStatement; +export function isCallExpression(node: Object, opts?: Object): node is CallExpression; +export function isCatchClause(node: Object, opts?: Object): node is CatchClause; +export function isConditionalExpression(node: Object, opts?: Object): node is ConditionalExpression; +export function isContinueStatement(node: Object, opts?: Object): node is ContinueStatement; +export function isDebuggerStatement(node: Object, opts?: Object): node is DebuggerStatement; +export function isDoWhileStatement(node: Object, opts?: Object): node is DoWhileStatement; +export function isEmptyStatement(node: Object, opts?: Object): node is EmptyStatement; +export function isExpressionStatement(node: Object, opts?: Object): node is ExpressionStatement; +export function isFile(node: Object, opts?: Object): node is File; +export function isForInStatement(node: Object, opts?: Object): node is ForInStatement; +export function isForStatement(node: Object, opts?: Object): node is ForStatement; +export function isFunctionDeclaration(node: Object, opts?: Object): node is FunctionDeclaration; +export function isFunctionExpression(node: Object, opts?: Object): node is FunctionExpression; +export function isIdentifier(node: Object, opts?: Object): node is Identifier; +export function isIfStatement(node: Object, opts?: Object): node is IfStatement; +export function isLabeledStatement(node: Object, opts?: Object): node is LabeledStatement; +export function isStringLiteral(node: Object, opts?: Object): node is StringLiteral; +export function isNumericLiteral(node: Object, opts?: Object): node is NumericLiteral; +export function isNullLiteral(node: Object, opts?: Object): node is NullLiteral; +export function isBooleanLiteral(node: Object, opts?: Object): node is BooleanLiteral; +export function isRegExpLiteral(node: Object, opts?: Object): node is RegExpLiteral; +export function isLogicalExpression(node: Object, opts?: Object): node is LogicalExpression; +export function isMemberExpression(node: Object, opts?: Object): node is MemberExpression; +export function isNewExpression(node: Object, opts?: Object): node is NewExpression; +export function isProgram(node: Object, opts?: Object): node is Program; +export function isObjectExpression(node: Object, opts?: Object): node is ObjectExpression; +export function isObjectMethod(node: Object, opts?: Object): node is ObjectMethod; +export function isObjectProperty(node: Object, opts?: Object): node is ObjectProperty; +export function isRestElement(node: Object, opts?: Object): node is RestElement; +export function isReturnStatement(node: Object, opts?: Object): node is ReturnStatement; +export function isSequenceExpression(node: Object, opts?: Object): node is SequenceExpression; +export function isSwitchCase(node: Object, opts?: Object): node is SwitchCase; +export function isSwitchStatement(node: Object, opts?: Object): node is SwitchStatement; +export function isThisExpression(node: Object, opts?: Object): node is ThisExpression; +export function isThrowStatement(node: Object, opts?: Object): node is ThrowStatement; +export function isTryStatement(node: Object, opts?: Object): node is TryStatement; +export function isUnaryExpression(node: Object, opts?: Object): node is UnaryExpression; +export function isUpdateExpression(node: Object, opts?: Object): node is UpdateExpression; +export function isVariableDeclaration(node: Object, opts?: Object): node is VariableDeclaration; +export function isVariableDeclarator(node: Object, opts?: Object): node is VariableDeclarator; +export function isWhileStatement(node: Object, opts?: Object): node is WhileStatement; +export function isWithStatement(node: Object, opts?: Object): node is WithStatement; +export function isAssignmentPattern(node: Object, opts?: Object): node is AssignmentPattern; +export function isArrayPattern(node: Object, opts?: Object): node is ArrayPattern; +export function isArrowFunctionExpression(node: Object, opts?: Object): node is ArrowFunctionExpression; +export function isClassBody(node: Object, opts?: Object): node is ClassBody; +export function isClassDeclaration(node: Object, opts?: Object): node is ClassDeclaration; +export function isClassExpression(node: Object, opts?: Object): node is ClassExpression; +export function isExportAllDeclaration(node: Object, opts?: Object): node is ExportAllDeclaration; +export function isExportDefaultDeclaration(node: Object, opts?: Object): node is ExportDefaultDeclaration; +export function isExportNamedDeclaration(node: Object, opts?: Object): node is ExportNamedDeclaration; +export function isExportSpecifier(node: Object, opts?: Object): node is ExportSpecifier; +export function isForOfStatement(node: Object, opts?: Object): node is ForOfStatement; +export function isImportDeclaration(node: Object, opts?: Object): node is ImportDeclaration; +export function isImportDefaultSpecifier(node: Object, opts?: Object): node is ImportDefaultSpecifier; +export function isImportNamespaceSpecifier(node: Object, opts?: Object): node is ImportNamespaceSpecifier; +export function isImportSpecifier(node: Object, opts?: Object): node is ImportSpecifier; +export function isMetaProperty(node: Object, opts?: Object): node is MetaProperty; +export function isClassMethod(node: Object, opts?: Object): node is ClassMethod; +export function isObjectPattern(node: Object, opts?: Object): node is ObjectPattern; +export function isSpreadElement(node: Object, opts?: Object): node is SpreadElement; +export function isSuper(node: Object, opts?: Object): node is Super; +export function isTaggedTemplateExpression(node: Object, opts?: Object): node is TaggedTemplateExpression; +export function isTemplateElement(node: Object, opts?: Object): node is TemplateElement; +export function isTemplateLiteral(node: Object, opts?: Object): node is TemplateLiteral; +export function isYieldExpression(node: Object, opts?: Object): node is YieldExpression; +export function isAnyTypeAnnotation(node: Object, opts?: Object): node is AnyTypeAnnotation; +export function isArrayTypeAnnotation(node: Object, opts?: Object): node is ArrayTypeAnnotation; +export function isBooleanTypeAnnotation(node: Object, opts?: Object): node is BooleanTypeAnnotation; +export function isBooleanLiteralTypeAnnotation(node: Object, opts?: Object): node is BooleanLiteralTypeAnnotation; +export function isNullLiteralTypeAnnotation(node: Object, opts?: Object): node is NullLiteralTypeAnnotation; +export function isClassImplements(node: Object, opts?: Object): node is ClassImplements; +export function isClassProperty(node: Object, opts?: Object): node is ClassProperty; +export function isDeclareClass(node: Object, opts?: Object): node is DeclareClass; +export function isDeclareFunction(node: Object, opts?: Object): node is DeclareFunction; +export function isDeclareInterface(node: Object, opts?: Object): node is DeclareInterface; +export function isDeclareModule(node: Object, opts?: Object): node is DeclareModule; +export function isDeclareTypeAlias(node: Object, opts?: Object): node is DeclareTypeAlias; +export function isDeclareVariable(node: Object, opts?: Object): node is DeclareVariable; +export function isExistentialTypeParam(node: Object, opts?: Object): node is ExistentialTypeParam; +export function isFunctionTypeAnnotation(node: Object, opts?: Object): node is FunctionTypeAnnotation; +export function isFunctionTypeParam(node: Object, opts?: Object): node is FunctionTypeParam; +export function isGenericTypeAnnotation(node: Object, opts?: Object): node is GenericTypeAnnotation; +export function isInterfaceExtends(node: Object, opts?: Object): node is InterfaceExtends; +export function isInterfaceDeclaration(node: Object, opts?: Object): node is InterfaceDeclaration; +export function isIntersectionTypeAnnotation(node: Object, opts?: Object): node is IntersectionTypeAnnotation; +export function isMixedTypeAnnotation(node: Object, opts?: Object): node is MixedTypeAnnotation; +export function isNullableTypeAnnotation(node: Object, opts?: Object): node is NullableTypeAnnotation; +export function isNumericLiteralTypeAnnotation(node: Object, opts?: Object): node is NumericLiteralTypeAnnotation; +export function isNumberTypeAnnotation(node: Object, opts?: Object): node is NumberTypeAnnotation; +export function isStringLiteralTypeAnnotation(node: Object, opts?: Object): node is StringLiteralTypeAnnotation; +export function isStringTypeAnnotation(node: Object, opts?: Object): node is StringTypeAnnotation; +export function isThisTypeAnnotation(node: Object, opts?: Object): node is ThisTypeAnnotation; +export function isTupleTypeAnnotation(node: Object, opts?: Object): node is TupleTypeAnnotation; +export function isTypeofTypeAnnotation(node: Object, opts?: Object): node is TypeofTypeAnnotation; +export function isTypeAlias(node: Object, opts?: Object): node is TypeAlias; +export function isTypeAnnotation(node: Object, opts?: Object): node is TypeAnnotation; +export function isTypeCastExpression(node: Object, opts?: Object): node is TypeCastExpression; +export function isTypeParameterDeclaration(node: Object, opts?: Object): node is TypeParameterDeclaration; +export function isTypeParameterInstantiation(node: Object, opts?: Object): node is TypeParameterInstantiation; +export function isObjectTypeAnnotation(node: Object, opts?: Object): node is ObjectTypeAnnotation; +export function isObjectTypeCallProperty(node: Object, opts?: Object): node is ObjectTypeCallProperty; +export function isObjectTypeIndexer(node: Object, opts?: Object): node is ObjectTypeIndexer; +export function isObjectTypeProperty(node: Object, opts?: Object): node is ObjectTypeProperty; +export function isQualifiedTypeIdentifier(node: Object, opts?: Object): node is QualifiedTypeIdentifier; +export function isUnionTypeAnnotation(node: Object, opts?: Object): node is UnionTypeAnnotation; +export function isVoidTypeAnnotation(node: Object, opts?: Object): node is VoidTypeAnnotation; +export function isJSXAttribute(node: Object, opts?: Object): node is JSXAttribute; +export function isJSXClosingElement(node: Object, opts?: Object): node is JSXClosingElement; +export function isJSXElement(node: Object, opts?: Object): node is JSXElement; +export function isJSXEmptyExpression(node: Object, opts?: Object): node is JSXEmptyExpression; +export function isJSXExpressionContainer(node: Object, opts?: Object): node is JSXExpressionContainer; +export function isJSXIdentifier(node: Object, opts?: Object): node is JSXIdentifier; +export function isJSXMemberExpression(node: Object, opts?: Object): node is JSXMemberExpression; +export function isJSXNamespacedName(node: Object, opts?: Object): node is JSXNamespacedName; +export function isJSXOpeningElement(node: Object, opts?: Object): node is JSXOpeningElement; +export function isJSXSpreadAttribute(node: Object, opts?: Object): node is JSXSpreadAttribute; +export function isJSXText(node: Object, opts?: Object): node is JSXText; +export function isNoop(node: Object, opts?: Object): node is Noop; +export function isParenthesizedExpression(node: Object, opts?: Object): node is ParenthesizedExpression; +export function isAwaitExpression(node: Object, opts?: Object): node is AwaitExpression; +export function isBindExpression(node: Object, opts?: Object): node is BindExpression; +export function isDecorator(node: Object, opts?: Object): node is Decorator; +export function isDoExpression(node: Object, opts?: Object): node is DoExpression; +export function isExportDefaultSpecifier(node: Object, opts?: Object): node is ExportDefaultSpecifier; +export function isExportNamespaceSpecifier(node: Object, opts?: Object): node is ExportNamespaceSpecifier; +export function isRestProperty(node: Object, opts?: Object): node is RestProperty; +export function isSpreadProperty(node: Object, opts?: Object): node is SpreadProperty; +export function isExpression(node: Object, opts?: Object): node is Expression; +export function isBinary(node: Object, opts?: Object): node is Binary; +export function isScopable(node: Object, opts?: Object): node is Scopable; +export function isBlockParent(node: Object, opts?: Object): node is BlockParent; +export function isBlock(node: Object, opts?: Object): node is Block; +export function isStatement(node: Object, opts?: Object): node is Statement; +export function isTerminatorless(node: Object, opts?: Object): node is Terminatorless; +export function isCompletionStatement(node: Object, opts?: Object): node is CompletionStatement; +export function isConditional(node: Object, opts?: Object): node is Conditional; +export function isLoop(node: Object, opts?: Object): node is Loop; +export function isWhile(node: Object, opts?: Object): node is While; +export function isExpressionWrapper(node: Object, opts?: Object): node is ExpressionWrapper; +export function isFor(node: Object, opts?: Object): node is For; +export function isForXStatement(node: Object, opts?: Object): node is ForXStatement; +export function isFunction(node: Object, opts?: Object): node is Function; +export function isFunctionParent(node: Object, opts?: Object): node is FunctionParent; +export function isPureish(node: Object, opts?: Object): node is Pureish; +export function isDeclaration(node: Object, opts?: Object): node is Declaration; +export function isLVal(node: Object, opts?: Object): node is LVal; +export function isLiteral(node: Object, opts?: Object): node is Literal; +export function isImmutable(node: Object, opts?: Object): node is Immutable; +export function isUserWhitespacable(node: Object, opts?: Object): node is UserWhitespacable; +export function isMethod(node: Object, opts?: Object): node is Method; +export function isObjectMember(node: Object, opts?: Object): node is ObjectMember; +export function isProperty(node: Object, opts?: Object): node is Property; +export function isUnaryLike(node: Object, opts?: Object): node is UnaryLike; +export function isPattern(node: Object, opts?: Object): node is Pattern; +export function isClass(node: Object, opts?: Object): node is Class; +export function isModuleDeclaration(node: Object, opts?: Object): node is ModuleDeclaration; +export function isExportDeclaration(node: Object, opts?: Object): node is ExportDeclaration; +export function isModuleSpecifier(node: Object, opts?: Object): node is ModuleSpecifier; +export function isFlow(node: Object, opts?: Object): node is Flow; +export function isFlowBaseAnnotation(node: Object, opts?: Object): node is FlowBaseAnnotation; +export function isFlowDeclaration(node: Object, opts?: Object): node is FlowDeclaration; +export function isJSX(node: Object, opts?: Object): node is JSX; +export function isNumberLiteral(node: Object, opts?: Object): node is NumericLiteral; +export function isRegexLiteral(node: Object, opts?: Object): node is RegExpLiteral; + +export function isReferencedIdentifier(node: Object, opts?: Object): boolean; +export function isReferencedMemberExpression(node: Object, opts?: Object): boolean; +export function isBindingIdentifier(node: Object, opts?: Object): boolean; +export function isScope(node: Object, opts?: Object): boolean; +export function isReferenced(node: Object, opts?: Object): boolean; +export function isBlockScoped(node: Object, opts?: Object): boolean; +export function isVar(node: Object, opts?: Object): boolean; +export function isUser(node: Object, opts?: Object): boolean; +export function isGenerated(node: Object, opts?: Object): boolean; +export function isPure(node: Object, opts?: Object): boolean; + +export function assertArrayExpression(node: Object, opts?: Object): void; +export function assertAssignmentExpression(node: Object, opts?: Object): void; +export function assertBinaryExpression(node: Object, opts?: Object): void; +export function assertDirective(node: Object, opts?: Object): void; +export function assertDirectiveLiteral(node: Object, opts?: Object): void; +export function assertBlockStatement(node: Object, opts?: Object): void; +export function assertBreakStatement(node: Object, opts?: Object): void; +export function assertCallExpression(node: Object, opts?: Object): void; +export function assertCatchClause(node: Object, opts?: Object): void; +export function assertConditionalExpression(node: Object, opts?: Object): void; +export function assertContinueStatement(node: Object, opts?: Object): void; +export function assertDebuggerStatement(node: Object, opts?: Object): void; +export function assertDoWhileStatement(node: Object, opts?: Object): void; +export function assertEmptyStatement(node: Object, opts?: Object): void; +export function assertExpressionStatement(node: Object, opts?: Object): void; +export function assertFile(node: Object, opts?: Object): void; +export function assertForInStatement(node: Object, opts?: Object): void; +export function assertForStatement(node: Object, opts?: Object): void; +export function assertFunctionDeclaration(node: Object, opts?: Object): void; +export function assertFunctionExpression(node: Object, opts?: Object): void; +export function assertIdentifier(node: Object, opts?: Object): void; +export function assertIfStatement(node: Object, opts?: Object): void; +export function assertLabeledStatement(node: Object, opts?: Object): void; +export function assertStringLiteral(node: Object, opts?: Object): void; +export function assertNumericLiteral(node: Object, opts?: Object): void; +export function assertNullLiteral(node: Object, opts?: Object): void; +export function assertBooleanLiteral(node: Object, opts?: Object): void; +export function assertRegExpLiteral(node: Object, opts?: Object): void; +export function assertLogicalExpression(node: Object, opts?: Object): void; +export function assertMemberExpression(node: Object, opts?: Object): void; +export function assertNewExpression(node: Object, opts?: Object): void; +export function assertProgram(node: Object, opts?: Object): void; +export function assertObjectExpression(node: Object, opts?: Object): void; +export function assertObjectMethod(node: Object, opts?: Object): void; +export function assertObjectProperty(node: Object, opts?: Object): void; +export function assertRestElement(node: Object, opts?: Object): void; +export function assertReturnStatement(node: Object, opts?: Object): void; +export function assertSequenceExpression(node: Object, opts?: Object): void; +export function assertSwitchCase(node: Object, opts?: Object): void; +export function assertSwitchStatement(node: Object, opts?: Object): void; +export function assertThisExpression(node: Object, opts?: Object): void; +export function assertThrowStatement(node: Object, opts?: Object): void; +export function assertTryStatement(node: Object, opts?: Object): void; +export function assertUnaryExpression(node: Object, opts?: Object): void; +export function assertUpdateExpression(node: Object, opts?: Object): void; +export function assertVariableDeclaration(node: Object, opts?: Object): void; +export function assertVariableDeclarator(node: Object, opts?: Object): void; +export function assertWhileStatement(node: Object, opts?: Object): void; +export function assertWithStatement(node: Object, opts?: Object): void; +export function assertAssignmentPattern(node: Object, opts?: Object): void; +export function assertArrayPattern(node: Object, opts?: Object): void; +export function assertArrowFunctionExpression(node: Object, opts?: Object): void; +export function assertClassBody(node: Object, opts?: Object): void; +export function assertClassDeclaration(node: Object, opts?: Object): void; +export function assertClassExpression(node: Object, opts?: Object): void; +export function assertExportAllDeclaration(node: Object, opts?: Object): void; +export function assertExportDefaultDeclaration(node: Object, opts?: Object): void; +export function assertExportNamedDeclaration(node: Object, opts?: Object): void; +export function assertExportSpecifier(node: Object, opts?: Object): void; +export function assertForOfStatement(node: Object, opts?: Object): void; +export function assertImportDeclaration(node: Object, opts?: Object): void; +export function assertImportDefaultSpecifier(node: Object, opts?: Object): void; +export function assertImportNamespaceSpecifier(node: Object, opts?: Object): void; +export function assertImportSpecifier(node: Object, opts?: Object): void; +export function assertMetaProperty(node: Object, opts?: Object): void; +export function assertClassMethod(node: Object, opts?: Object): void; +export function assertObjectPattern(node: Object, opts?: Object): void; +export function assertSpreadElement(node: Object, opts?: Object): void; +export function assertSuper(node: Object, opts?: Object): void; +export function assertTaggedTemplateExpression(node: Object, opts?: Object): void; +export function assertTemplateElement(node: Object, opts?: Object): void; +export function assertTemplateLiteral(node: Object, opts?: Object): void; +export function assertYieldExpression(node: Object, opts?: Object): void; +export function assertAnyTypeAnnotation(node: Object, opts?: Object): void; +export function assertArrayTypeAnnotation(node: Object, opts?: Object): void; +export function assertBooleanTypeAnnotation(node: Object, opts?: Object): void; +export function assertBooleanLiteralTypeAnnotation(node: Object, opts?: Object): void; +export function assertNullLiteralTypeAnnotation(node: Object, opts?: Object): void; +export function assertClassImplements(node: Object, opts?: Object): void; +export function assertClassProperty(node: Object, opts?: Object): void; +export function assertDeclareClass(node: Object, opts?: Object): void; +export function assertDeclareFunction(node: Object, opts?: Object): void; +export function assertDeclareInterface(node: Object, opts?: Object): void; +export function assertDeclareModule(node: Object, opts?: Object): void; +export function assertDeclareTypeAlias(node: Object, opts?: Object): void; +export function assertDeclareVariable(node: Object, opts?: Object): void; +export function assertExistentialTypeParam(node: Object, opts?: Object): void; +export function assertFunctionTypeAnnotation(node: Object, opts?: Object): void; +export function assertFunctionTypeParam(node: Object, opts?: Object): void; +export function assertGenericTypeAnnotation(node: Object, opts?: Object): void; +export function assertInterfaceExtends(node: Object, opts?: Object): void; +export function assertInterfaceDeclaration(node: Object, opts?: Object): void; +export function assertIntersectionTypeAnnotation(node: Object, opts?: Object): void; +export function assertMixedTypeAnnotation(node: Object, opts?: Object): void; +export function assertNullableTypeAnnotation(node: Object, opts?: Object): void; +export function assertNumericLiteralTypeAnnotation(node: Object, opts?: Object): void; +export function assertNumberTypeAnnotation(node: Object, opts?: Object): void; +export function assertStringLiteralTypeAnnotation(node: Object, opts?: Object): void; +export function assertStringTypeAnnotation(node: Object, opts?: Object): void; +export function assertThisTypeAnnotation(node: Object, opts?: Object): void; +export function assertTupleTypeAnnotation(node: Object, opts?: Object): void; +export function assertTypeofTypeAnnotation(node: Object, opts?: Object): void; +export function assertTypeAlias(node: Object, opts?: Object): void; +export function assertTypeAnnotation(node: Object, opts?: Object): void; +export function assertTypeCastExpression(node: Object, opts?: Object): void; +export function assertTypeParameterDeclaration(node: Object, opts?: Object): void; +export function assertTypeParameterInstantiation(node: Object, opts?: Object): void; +export function assertObjectTypeAnnotation(node: Object, opts?: Object): void; +export function assertObjectTypeCallProperty(node: Object, opts?: Object): void; +export function assertObjectTypeIndexer(node: Object, opts?: Object): void; +export function assertObjectTypeProperty(node: Object, opts?: Object): void; +export function assertQualifiedTypeIdentifier(node: Object, opts?: Object): void; +export function assertUnionTypeAnnotation(node: Object, opts?: Object): void; +export function assertVoidTypeAnnotation(node: Object, opts?: Object): void; +export function assertJSXAttribute(node: Object, opts?: Object): void; +export function assertJSXClosingElement(node: Object, opts?: Object): void; +export function assertJSXElement(node: Object, opts?: Object): void; +export function assertJSXEmptyExpression(node: Object, opts?: Object): void; +export function assertJSXExpressionContainer(node: Object, opts?: Object): void; +export function assertJSXIdentifier(node: Object, opts?: Object): void; +export function assertJSXMemberExpression(node: Object, opts?: Object): void; +export function assertJSXNamespacedName(node: Object, opts?: Object): void; +export function assertJSXOpeningElement(node: Object, opts?: Object): void; +export function assertJSXSpreadAttribute(node: Object, opts?: Object): void; +export function assertJSXText(node: Object, opts?: Object): void; +export function assertNoop(node: Object, opts?: Object): void; +export function assertParenthesizedExpression(node: Object, opts?: Object): void; +export function assertAwaitExpression(node: Object, opts?: Object): void; +export function assertBindExpression(node: Object, opts?: Object): void; +export function assertDecorator(node: Object, opts?: Object): void; +export function assertDoExpression(node: Object, opts?: Object): void; +export function assertExportDefaultSpecifier(node: Object, opts?: Object): void; +export function assertExportNamespaceSpecifier(node: Object, opts?: Object): void; +export function assertRestProperty(node: Object, opts?: Object): void; +export function assertSpreadProperty(node: Object, opts?: Object): void; +export function assertExpression(node: Object, opts?: Object): void; +export function assertBinary(node: Object, opts?: Object): void; +export function assertScopable(node: Object, opts?: Object): void; +export function assertBlockParent(node: Object, opts?: Object): void; +export function assertBlock(node: Object, opts?: Object): void; +export function assertStatement(node: Object, opts?: Object): void; +export function assertTerminatorless(node: Object, opts?: Object): void; +export function assertCompletionStatement(node: Object, opts?: Object): void; +export function assertConditional(node: Object, opts?: Object): void; +export function assertLoop(node: Object, opts?: Object): void; +export function assertWhile(node: Object, opts?: Object): void; +export function assertExpressionWrapper(node: Object, opts?: Object): void; +export function assertFor(node: Object, opts?: Object): void; +export function assertForXStatement(node: Object, opts?: Object): void; +export function assertFunction(node: Object, opts?: Object): void; +export function assertFunctionParent(node: Object, opts?: Object): void; +export function assertPureish(node: Object, opts?: Object): void; +export function assertDeclaration(node: Object, opts?: Object): void; +export function assertLVal(node: Object, opts?: Object): void; +export function assertLiteral(node: Object, opts?: Object): void; +export function assertImmutable(node: Object, opts?: Object): void; +export function assertUserWhitespacable(node: Object, opts?: Object): void; +export function assertMethod(node: Object, opts?: Object): void; +export function assertObjectMember(node: Object, opts?: Object): void; +export function assertProperty(node: Object, opts?: Object): void; +export function assertUnaryLike(node: Object, opts?: Object): void; +export function assertPattern(node: Object, opts?: Object): void; +export function assertClass(node: Object, opts?: Object): void; +export function assertModuleDeclaration(node: Object, opts?: Object): void; +export function assertExportDeclaration(node: Object, opts?: Object): void; +export function assertModuleSpecifier(node: Object, opts?: Object): void; +export function assertFlow(node: Object, opts?: Object): void; +export function assertFlowBaseAnnotation(node: Object, opts?: Object): void; +export function assertFlowDeclaration(node: Object, opts?: Object): void; +export function assertJSX(node: Object, opts?: Object): void; +export function assertNumberLiteral(node: Object, opts?: Object): void; +export function assertRegexLiteral(node: Object, opts?: Object): void; + diff --git a/babel-types/tsconfig.json b/babel-types/tsconfig.json new file mode 100644 index 0000000000..11601b0c36 --- /dev/null +++ b/babel-types/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "babel-types-tests.ts" + ] +} \ No newline at end of file diff --git a/babylon/babylon-tests.ts b/babylon/babylon-tests.ts new file mode 100644 index 0000000000..bb95625935 --- /dev/null +++ b/babylon/babylon-tests.ts @@ -0,0 +1,24 @@ + +/// +/// + + +// Example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babylon +import * as babylon from "babylon"; +declare function assert(expr: boolean): void; + +const code = `function square(n) { + return n * n; +}`; + +let node = babylon.parse(code); +assert(node.type === "File"); +assert(node.start === 0); +assert(node.end === 38); +assert(node.loc.start > node.loc.end); + + +babylon.parse(code, { + sourceType: "module", // default: "script" + plugins: ["jsx"] // default: [] +}); diff --git a/babylon/index.d.ts b/babylon/index.d.ts new file mode 100644 index 0000000000..112e6be7be --- /dev/null +++ b/babylon/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for babylon v6.7 +// Project: https://github.com/babel/babylon +// Definitions by: Troy Gerwien +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as t from 'babel-types'; +type Node = t.Node; + +export function parse(code: string, opts?: BabylonOptions): Node; + +export interface BabylonOptions { + /** + * By default, import and export declarations can only appear at a program's top level. + * Setting this option to true allows them anywhere where a statement is allowed. + */ + allowImportExportEverywhere?: boolean; + + /** + * By default, a return statement at the top level raises an error. Set this to true to accept such code. + */ + allowReturnOutsideFunction?: boolean; + + allowSuperOutsideMethod?: boolean; + + /** + * Indicate the mode the code should be parsed in. Can be either "script" or "module". + */ + sourceType?: 'script' | 'module'; + + /** + * Correlate output AST nodes with their source filename. Useful when + * generating code and source maps from the ASTs of multiple input files. + */ + sourceFilename?: string; + + /** + * Array containing the plugins that you want to enable. + */ + plugins?: PluginName[]; +} + +export type PluginName = 'jsx' | 'flow' | 'asyncFunctions' | 'classConstructorCall' | 'doExpressions' + | 'trailingFunctionCommas' | 'objectRestSpread' | 'decorators' | 'classProperties' | 'exportExtensions' + | 'exponentiationOperator' | 'asyncGenerators' | 'functionBind' | 'functionSent'; + diff --git a/babylon/tsconfig.json b/babylon/tsconfig.json new file mode 100644 index 0000000000..c4a777d01c --- /dev/null +++ b/babylon/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "babylon-tests.ts" + ] +} \ No newline at end of file diff --git a/babylonjs/babylon-tests.ts b/babylonjs/babylon-tests.ts index 142d3840f5..8b13789179 100644 --- a/babylonjs/babylon-tests.ts +++ b/babylonjs/babylon-tests.ts @@ -1 +1 @@ -/// + diff --git a/babylonjs/babylon.d.ts b/babylonjs/babylon.d.ts deleted file mode 100644 index 7e129ee4a7..0000000000 --- a/babylonjs/babylon.d.ts +++ /dev/null @@ -1,7260 +0,0 @@ -// Type definitions for BabylonJS v2.3 -// Project: http://www.babylonjs.com/ -// Definitions by: David Catuhe -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace BABYLON { - class _DepthCullingState { - private _isDepthTestDirty; - private _isDepthMaskDirty; - private _isDepthFuncDirty; - private _isCullFaceDirty; - private _isCullDirty; - private _isZOffsetDirty; - private _depthTest; - private _depthMask; - private _depthFunc; - private _cull; - private _cullFace; - private _zOffset; - isDirty: boolean; - zOffset: number; - cullFace: number; - cull: boolean; - depthFunc: number; - depthMask: boolean; - depthTest: boolean; - reset(): void; - apply(gl: WebGLRenderingContext): void; - } - class _AlphaState { - private _isAlphaBlendDirty; - private _isBlendFunctionParametersDirty; - private _alphaBlend; - private _blendFunctionParameters; - isDirty: boolean; - alphaBlend: boolean; - setAlphaBlendFunctionParameters(value0: number, value1: number, value2: number, value3: number): void; - reset(): void; - apply(gl: WebGLRenderingContext): void; - } - class EngineCapabilities { - maxTexturesImageUnits: number; - maxTextureSize: number; - maxCubemapTextureSize: number; - maxRenderTextureSize: number; - standardDerivatives: boolean; - s3tc: any; - textureFloat: boolean; - textureAnisotropicFilterExtension: any; - maxAnisotropy: number; - instancedArrays: any; - uintIndices: boolean; - highPrecisionShaderSupported: boolean; - fragmentDepthSupported: boolean; - drawBuffersExtension: any; - } - /** - * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio. - */ - class Engine { - private static _ALPHA_DISABLE; - private static _ALPHA_ADD; - private static _ALPHA_COMBINE; - private static _ALPHA_SUBTRACT; - private static _ALPHA_MULTIPLY; - private static _ALPHA_MAXIMIZED; - private static _ALPHA_ONEONE; - private static _DELAYLOADSTATE_NONE; - private static _DELAYLOADSTATE_LOADED; - private static _DELAYLOADSTATE_LOADING; - private static _DELAYLOADSTATE_NOTLOADED; - private static _TEXTUREFORMAT_ALPHA; - private static _TEXTUREFORMAT_LUMINANCE; - private static _TEXTUREFORMAT_LUMINANCE_ALPHA; - private static _TEXTUREFORMAT_RGB; - private static _TEXTUREFORMAT_RGBA; - private static _TEXTURETYPE_UNSIGNED_INT; - private static _TEXTURETYPE_FLOAT; - static ALPHA_DISABLE: number; - static ALPHA_ONEONE: number; - static ALPHA_ADD: number; - static ALPHA_COMBINE: number; - static ALPHA_SUBTRACT: number; - static ALPHA_MULTIPLY: number; - static ALPHA_MAXIMIZED: number; - static DELAYLOADSTATE_NONE: number; - static DELAYLOADSTATE_LOADED: number; - static DELAYLOADSTATE_LOADING: number; - static DELAYLOADSTATE_NOTLOADED: number; - static TEXTUREFORMAT_ALPHA: number; - static TEXTUREFORMAT_LUMINANCE: number; - static TEXTUREFORMAT_LUMINANCE_ALPHA: number; - static TEXTUREFORMAT_RGB: number; - static TEXTUREFORMAT_RGBA: number; - static TEXTURETYPE_UNSIGNED_INT: number; - static TEXTURETYPE_FLOAT: number; - static Version: string; - static Epsilon: number; - static CollisionsEpsilon: number; - static CodeRepository: string; - static ShadersRepository: string; - isFullscreen: boolean; - isPointerLock: boolean; - cullBackFaces: boolean; - renderEvenInBackground: boolean; - enableOfflineSupport: boolean; - scenes: Scene[]; - _gl: WebGLRenderingContext; - private _renderingCanvas; - private _windowIsBackground; - private _webGLVersion; - static audioEngine: AudioEngine; - private _onBlur; - private _onFocus; - private _onFullscreenChange; - private _onPointerLockChange; - private _hardwareScalingLevel; - private _caps; - private _pointerLockRequested; - private _alphaTest; - private _loadingScreen; - private _drawCalls; - private _glVersion; - private _glRenderer; - private _glVendor; - private _videoTextureSupported; - private _renderingQueueLaunched; - private _activeRenderLoops; - private fpsRange; - private previousFramesDuration; - private fps; - private deltaTime; - private _depthCullingState; - private _alphaState; - private _alphaMode; - private _loadedTexturesCache; - private _maxTextureChannels; - private _activeTexturesCache; - private _currentEffect; - private _compiledEffects; - private _vertexAttribArrays; - private _cachedViewport; - private _cachedVertexBuffers; - private _cachedIndexBuffer; - private _cachedEffectForVertexBuffers; - private _currentRenderTarget; - private _uintIndicesCurrentlySet; - private _workingCanvas; - private _workingContext; - private _bindedRenderFunction; - /** - * @constructor - * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering - * @param {boolean} [antialias] - enable antialias - * @param options - further options to be sent to the getContext function - */ - constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?: { - antialias?: boolean; - preserveDrawingBuffer?: boolean; - }, adaptToDeviceRatio?: boolean); - webGLVersion: string; - private _prepareWorkingCanvas(); - resetTextureCache(): void; - getGlInfo(): { - vendor: string; - renderer: string; - version: string; - }; - getAspectRatio(camera: Camera, useScreen?: boolean): number; - getRenderWidth(useScreen?: boolean): number; - getRenderHeight(useScreen?: boolean): number; - getRenderingCanvas(): HTMLCanvasElement; - getRenderingCanvasClientRect(): ClientRect; - setHardwareScalingLevel(level: number): void; - getHardwareScalingLevel(): number; - getLoadedTexturesCache(): WebGLTexture[]; - getCaps(): EngineCapabilities; - drawCalls: number; - resetDrawCalls(): void; - setDepthFunctionToGreater(): void; - setDepthFunctionToGreaterOrEqual(): void; - setDepthFunctionToLess(): void; - setDepthFunctionToLessOrEqual(): void; - /** - * stop executing a render loop function and remove it from the execution array - * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed. - */ - stopRenderLoop(renderFunction?: () => void): void; - _renderLoop(): void; - /** - * Register and execute a render loop. The engine can have more than one render function. - * @param {Function} renderFunction - the function to continuesly execute starting the next render loop. - * @example - * engine.runRenderLoop(function () { - * scene.render() - * }) - */ - runRenderLoop(renderFunction: () => void): void; - /** - * Toggle full screen mode. - * @param {boolean} requestPointerLock - should a pointer lock be requested from the user - */ - switchFullscreen(requestPointerLock: boolean): void; - clear(color: any, backBuffer: boolean, depthStencil: boolean): void; - /** - * Set the WebGL's viewport - * @param {BABYLON.Viewport} viewport - the viewport element to be used. - * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used. - * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used. - */ - setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void; - setDirectViewport(x: number, y: number, width: number, height: number): void; - beginFrame(): void; - endFrame(): void; - /** - * resize the view according to the canvas' size. - * @example - * window.addEventListener("resize", function () { - * engine.resize(); - * }); - */ - resize(): void; - /** - * force a specific size of the canvas - * @param {number} width - the new canvas' width - * @param {number} height - the new canvas' height - */ - setSize(width: number, height: number): void; - bindFramebuffer(texture: WebGLTexture, faceIndex?: number): void; - unBindFramebuffer(texture: WebGLTexture, disableGenerateMipMaps?: boolean): void; - generateMipMapsForCubemap(texture: WebGLTexture): void; - flushFramebuffer(): void; - restoreDefaultFramebuffer(): void; - private _resetVertexBufferBinding(); - createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer; - createDynamicVertexBuffer(capacity: number): WebGLBuffer; - updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number): void; - private _resetIndexBufferBinding(); - createIndexBuffer(indices: number[] | Int32Array): WebGLBuffer; - bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void; - bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void; - _releaseBuffer(buffer: WebGLBuffer): boolean; - createInstancesBuffer(capacity: number): WebGLBuffer; - deleteInstancesBuffer(buffer: WebGLBuffer): void; - updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void; - unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void; - applyStates(): void; - draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void; - drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void; - drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void; - _releaseEffect(effect: Effect): void; - createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect; - createEffectForParticles(fragmentName: string, uniformsNames?: string[], samplers?: string[], defines?: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect; - createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram; - getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[]; - getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[]; - enableEffect(effect: Effect): void; - setArray(uniform: WebGLUniformLocation, array: number[]): void; - setArray2(uniform: WebGLUniformLocation, array: number[]): void; - setArray3(uniform: WebGLUniformLocation, array: number[]): void; - setArray4(uniform: WebGLUniformLocation, array: number[]): void; - setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void; - setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void; - setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void; - setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void; - setFloat(uniform: WebGLUniformLocation, value: number): void; - setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void; - setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void; - setBool(uniform: WebGLUniformLocation, bool: number): void; - setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; - setColor3(uniform: WebGLUniformLocation, color3: Color3): void; - setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void; - setState(culling: boolean, zOffset?: number, force?: boolean, reverseSide?: boolean): void; - setDepthBuffer(enable: boolean): void; - getDepthWrite(): boolean; - setDepthWrite(enable: boolean): void; - setColorWrite(enable: boolean): void; - setAlphaMode(mode: number): void; - getAlphaMode(): number; - setAlphaTesting(enable: boolean): void; - getAlphaTesting(): boolean; - wipeCaches(): void; - setSamplingMode(texture: WebGLTexture, samplingMode: number): void; - createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode?: number, onLoad?: () => void, onError?: () => void, buffer?: any): WebGLTexture; - updateRawTexture(texture: WebGLTexture, data: ArrayBufferView, format: number, invertY: boolean, compression?: string): void; - createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression?: string): WebGLTexture; - createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number, forceExponantOfTwo?: boolean): WebGLTexture; - updateTextureSamplingMode(samplingMode: number, texture: WebGLTexture): void; - updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void; - updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void; - createRenderTargetTexture(size: any, options: any): WebGLTexture; - createRenderTargetCubeTexture(size: number, options?: any): WebGLTexture; - createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean): WebGLTexture; - _releaseTexture(texture: WebGLTexture): void; - bindSamplers(effect: Effect): void; - _bindTexture(channel: number, texture: WebGLTexture): void; - setTextureFromPostProcess(channel: number, postProcess: PostProcess): void; - unbindAllTextures(): void; - setTexture(channel: number, texture: BaseTexture): void; - _setAnisotropicLevel(key: number, texture: BaseTexture): void; - readPixels(x: number, y: number, width: number, height: number): Uint8Array; - releaseInternalTexture(texture: WebGLTexture): void; - dispose(): void; - displayLoadingUI(): void; - hideLoadingUI(): void; - loadingScreen: ILoadingScreen; - loadingUIText: string; - loadingUIBackgroundColor: string; - getFps(): number; - getDeltaTime(): number; - private _measureFps(); - static isSupported(): boolean; - } -} - -interface Window { - mozIndexedDB(func: any): any; - webkitIndexedDB(func: any): any; - IDBTransaction(func: any): any; - webkitIDBTransaction(func: any): any; - msIDBTransaction(func: any): any; - IDBKeyRange(func: any): any; - webkitIDBKeyRange(func: any): any; - msIDBKeyRange(func: any): any; - webkitURL: HTMLURL; - webkitRequestAnimationFrame(func: any): any; - mozRequestAnimationFrame(func: any): any; - oRequestAnimationFrame(func: any): any; - WebGLRenderingContext: WebGLRenderingContext; - MSGesture: MSGesture; - CANNON: any; - SIMD: any; - AudioContext: AudioContext; - webkitAudioContext: AudioContext; - PointerEvent: any; -} -interface HTMLURL { - createObjectURL(param1: any, param2?: any): any; -} -interface Document { - exitFullscreen(): void; - webkitCancelFullScreen(): void; - mozCancelFullScreen(): void; - msCancelFullScreen(): void; - mozFullScreen: boolean; - msIsFullScreen: boolean; - fullscreen: boolean; - mozPointerLockElement: HTMLElement; - msPointerLockElement: HTMLElement; - webkitPointerLockElement: HTMLElement; -} -interface HTMLCanvasElement { - requestPointerLock(): void; - msRequestPointerLock(): void; - mozRequestPointerLock(): void; - webkitRequestPointerLock(): void; -} -interface CanvasRenderingContext2D { - imageSmoothingEnabled: boolean; - mozImageSmoothingEnabled: boolean; - oImageSmoothingEnabled: boolean; - webkitImageSmoothingEnabled: boolean; -} -interface WebGLTexture { - isReady: boolean; - isCube: boolean; - url: string; - noMipmap: boolean; - samplingMode: number; - references: number; - generateMipMaps: boolean; - _size: number; - _baseWidth: number; - _baseHeight: number; - _width: number; - _height: number; - _workingCanvas: HTMLCanvasElement; - _workingContext: CanvasRenderingContext2D; - _framebuffer: WebGLFramebuffer; - _depthBuffer: WebGLRenderbuffer; - _cachedCoordinatesMode: number; - _cachedWrapU: number; - _cachedWrapV: number; - _isDisabled: boolean; -} -interface WebGLBuffer { - references: number; - capacity: number; - is32Bits: boolean; -} -interface MouseEvent { - mozMovementX: number; - mozMovementY: number; - webkitMovementX: number; - webkitMovementY: number; - msMovementX: number; - msMovementY: number; -} -interface MSStyleCSSProperties { - webkitTransform: string; - webkitTransition: string; -} -interface Navigator { - getVRDevices: () => any; - mozGetVRDevices: (any: any) => any; - isCocoonJS: boolean; -} -interface Screen { - orientation: string; - mozOrientation: string; -} -interface HTMLMediaElement { - crossOrigin: string; -} - -declare namespace BABYLON { - /** - * Node is the basic class for all scene objects (Mesh, Light Camera). - */ - class Node { - parent: Node; - name: string; - id: string; - uniqueId: number; - state: string; - animations: Animation[]; - private _ranges; - onReady: (node: Node) => void; - private _childrenFlag; - private _isEnabled; - private _isReady; - _currentRenderId: number; - private _parentRenderId; - _waitingParentId: string; - private _scene; - _cache: any; - /** - * @constructor - * @param {string} name - the name and id to be given to this node - * @param {BABYLON.Scene} the scene this node will be added to - */ - constructor(name: string, scene: Scene); - getScene(): Scene; - getEngine(): Engine; - getWorldMatrix(): Matrix; - _initCache(): void; - updateCache(force?: boolean): void; - _updateCache(ignoreParentClass?: boolean): void; - _isSynchronized(): boolean; - _markSyncedWithParent(): void; - isSynchronizedWithParent(): boolean; - isSynchronized(updateCache?: boolean): boolean; - hasNewParent(update?: boolean): boolean; - /** - * Is this node ready to be used/rendered - * @return {boolean} is it ready - */ - isReady(): boolean; - /** - * Is this node enabled. - * If the node has a parent and is enabled, the parent will be inspected as well. - * @return {boolean} whether this node (and its parent) is enabled. - * @see setEnabled - */ - isEnabled(): boolean; - /** - * Set the enabled state of this node. - * @param {boolean} value - the new enabled state - * @see isEnabled - */ - setEnabled(value: boolean): void; - /** - * Is this node a descendant of the given node. - * The function will iterate up the hierarchy until the ancestor was found or no more parents defined. - * @param {BABYLON.Node} ancestor - The parent node to inspect - * @see parent - */ - isDescendantOf(ancestor: Node): boolean; - _getDescendants(list: Node[], results: Node[]): void; - /** - * Will return all nodes that have this node as parent. - * @return {BABYLON.Node[]} all children nodes of all types. - */ - getDescendants(): Node[]; - _setReady(state: boolean): void; - getAnimationByName(name: string): Animation; - createAnimationRange(name: string, from: number, to: number): void; - deleteAnimationRange(name: string, deleteFrames?: boolean): void; - getAnimationRange(name: string): AnimationRange; - beginAnimation(name: string, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): void; - serializeAnimationRanges(): any; - static ParseAnimationRanges(node: Node, parsedNode: any, scene: Scene): void; - } -} - -declare namespace BABYLON { - interface IDisposable { - dispose(): void; - } - /** - * Represents a scene to be rendered by the engine. - * @see http://doc.babylonjs.com/page.php?p=21911 - */ - class Scene { - private static _FOGMODE_NONE; - private static _FOGMODE_EXP; - private static _FOGMODE_EXP2; - private static _FOGMODE_LINEAR; - static MinDeltaTime: number; - static MaxDeltaTime: number; - static FOGMODE_NONE: number; - static FOGMODE_EXP: number; - static FOGMODE_EXP2: number; - static FOGMODE_LINEAR: number; - autoClear: boolean; - clearColor: any; - ambientColor: Color3; - /** - * A function to be executed before rendering this scene - * @type {Function} - */ - beforeRender: () => void; - /** - * A function to be executed after rendering this scene - * @type {Function} - */ - afterRender: () => void; - /** - * A function to be executed when this scene is disposed. - * @type {Function} - */ - onDispose: () => void; - beforeCameraRender: (camera: Camera) => void; - afterCameraRender: (camera: Camera) => void; - forceWireframe: boolean; - forcePointsCloud: boolean; - forceShowBoundingBoxes: boolean; - clipPlane: Plane; - animationsEnabled: boolean; - constantlyUpdateMeshUnderPointer: boolean; - private _onPointerMove; - private _onPointerDown; - private _onPointerUp; - onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo) => void; - onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void; - onPointerUp: (evt: PointerEvent, pickInfo: PickingInfo) => void; - onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void; - cameraToUseForPointers: Camera; - private _pointerX; - private _pointerY; - private _meshUnderPointer; - private _startingPointerPosition; - private _startingPointerTime; - _mirroredCameraPosition: Vector3; - private _onKeyDown; - private _onKeyUp; - /** - * is fog enabled on this scene. - * @type {boolean} - */ - fogEnabled: boolean; - fogMode: number; - fogColor: Color3; - fogDensity: number; - fogStart: number; - fogEnd: number; - /** - * is shadow enabled on this scene. - * @type {boolean} - */ - shadowsEnabled: boolean; - /** - * is light enabled on this scene. - * @type {boolean} - */ - lightsEnabled: boolean; - /** - * All of the lights added to this scene. - * @see BABYLON.Light - * @type {BABYLON.Light[]} - */ - lights: Light[]; - onNewLightAdded: (newLight?: Light, positionInArray?: number, scene?: Scene) => void; - onLightRemoved: (removedLight?: Light) => void; - /** - * All of the cameras added to this scene. - * @see BABYLON.Camera - * @type {BABYLON.Camera[]} - */ - cameras: Camera[]; - onNewCameraAdded: (newCamera?: Camera, positionInArray?: number, scene?: Scene) => void; - onCameraRemoved: (removedCamera?: Camera) => void; - activeCameras: Camera[]; - activeCamera: Camera; - /** - * All of the (abstract) meshes added to this scene. - * @see BABYLON.AbstractMesh - * @type {BABYLON.AbstractMesh[]} - */ - meshes: AbstractMesh[]; - onNewMeshAdded: (newMesh?: AbstractMesh, positionInArray?: number, scene?: Scene) => void; - onMeshRemoved: (removedMesh?: AbstractMesh) => void; - private _geometries; - onGeometryAdded: (newGeometry?: Geometry) => void; - onGeometryRemoved: (removedGeometry?: Geometry) => void; - materials: Material[]; - multiMaterials: MultiMaterial[]; - defaultMaterial: StandardMaterial; - texturesEnabled: boolean; - textures: BaseTexture[]; - particlesEnabled: boolean; - particleSystems: ParticleSystem[]; - spritesEnabled: boolean; - spriteManagers: SpriteManager[]; - layers: Layer[]; - skeletonsEnabled: boolean; - skeletons: Skeleton[]; - lensFlaresEnabled: boolean; - lensFlareSystems: LensFlareSystem[]; - collisionsEnabled: boolean; - private _workerCollisions; - collisionCoordinator: ICollisionCoordinator; - gravity: Vector3; - postProcessesEnabled: boolean; - postProcessManager: PostProcessManager; - postProcessRenderPipelineManager: PostProcessRenderPipelineManager; - renderTargetsEnabled: boolean; - dumpNextRenderTargets: boolean; - customRenderTargets: RenderTargetTexture[]; - useDelayedTextureLoading: boolean; - importedMeshesFiles: String[]; - probesEnabled: boolean; - reflectionProbes: ReflectionProbe[]; - database: any; - /** - * This scene's action manager - * @type {BABYLON.ActionManager} - */ - actionManager: ActionManager; - _actionManagers: ActionManager[]; - private _meshesForIntersections; - proceduralTexturesEnabled: boolean; - _proceduralTextures: ProceduralTexture[]; - mainSoundTrack: SoundTrack; - soundTracks: SoundTrack[]; - private _audioEnabled; - private _headphone; - simplificationQueue: SimplificationQueue; - private _engine; - private _totalVertices; - _activeIndices: number; - _activeParticles: number; - private _lastFrameDuration; - private _evaluateActiveMeshesDuration; - private _renderTargetsDuration; - _particlesDuration: number; - private _renderDuration; - _spritesDuration: number; - private _animationRatio; - private _animationStartDate; - _cachedMaterial: Material; - private _renderId; - private _executeWhenReadyTimeoutId; - _toBeDisposed: SmartArray; - private _onReadyCallbacks; - private _pendingData; - private _onBeforeRenderCallbacks; - private _onAfterRenderCallbacks; - private _activeMeshes; - private _processedMaterials; - private _renderTargets; - _activeParticleSystems: SmartArray; - private _activeSkeletons; - private _softwareSkinnedMeshes; - _activeBones: number; - private _renderingManager; - private _physicsEngine; - _activeAnimatables: Animatable[]; - private _transformMatrix; - private _pickWithRayInverseMatrix; - private _edgesRenderers; - private _boundingBoxRenderer; - private _outlineRenderer; - private _viewMatrix; - private _projectionMatrix; - private _frustumPlanes; - private _selectionOctree; - private _pointerOverMesh; - private _debugLayer; - private _depthRenderer; - private _uniqueIdCounter; - private _pickedMeshName; - /** - * @constructor - * @param {BABYLON.Engine} engine - the engine to be used to render this scene. - */ - constructor(engine: Engine); - debugLayer: DebugLayer; - workerCollisions: boolean; - SelectionOctree: Octree; - /** - * The mesh that is currently under the pointer. - * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none. - */ - meshUnderPointer: AbstractMesh; - /** - * Current on-screen X position of the pointer - * @return {number} X position of the pointer - */ - pointerX: number; - /** - * Current on-screen Y position of the pointer - * @return {number} Y position of the pointer - */ - pointerY: number; - getCachedMaterial(): Material; - getBoundingBoxRenderer(): BoundingBoxRenderer; - getOutlineRenderer(): OutlineRenderer; - getEngine(): Engine; - getTotalVertices(): number; - getActiveIndices(): number; - getActiveParticles(): number; - getActiveBones(): number; - getLastFrameDuration(): number; - getEvaluateActiveMeshesDuration(): number; - getActiveMeshes(): SmartArray; - getRenderTargetsDuration(): number; - getRenderDuration(): number; - getParticlesDuration(): number; - getSpritesDuration(): number; - getAnimationRatio(): number; - getRenderId(): number; - incrementRenderId(): void; - private _updatePointerPosition(evt); - attachControl(): void; - detachControl(): void; - isReady(): boolean; - resetCachedMaterial(): void; - registerBeforeRender(func: () => void): void; - unregisterBeforeRender(func: () => void): void; - registerAfterRender(func: () => void): void; - unregisterAfterRender(func: () => void): void; - _addPendingData(data: any): void; - _removePendingData(data: any): void; - getWaitingItemsCount(): number; - /** - * Registers a function to be executed when the scene is ready. - * @param {Function} func - the function to be executed. - */ - executeWhenReady(func: () => void): void; - _checkIsReady(): void; - /** - * Will start the animation sequence of a given target - * @param target - the target - * @param {number} from - from which frame should animation start - * @param {number} to - till which frame should animation run. - * @param {boolean} [loop] - should the animation loop - * @param {number} [speedRatio] - the speed in which to run the animation - * @param {Function} [onAnimationEnd] function to be executed when the animation ended. - * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params. - * @return {BABYLON.Animatable} the animatable object created for this animation - * @see BABYLON.Animatable - * @see http://doc.babylonjs.com/page.php?p=22081 - */ - beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void, animatable?: Animatable): Animatable; - beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable; - getAnimatableByTarget(target: any): Animatable; - Animatables: Animatable[]; - /** - * Will stop the animation of the given target - * @param target - the target - * @see beginAnimation - */ - stopAnimation(target: any): void; - private _animate(); - getViewMatrix(): Matrix; - getProjectionMatrix(): Matrix; - getTransformMatrix(): Matrix; - setTransformMatrix(view: Matrix, projection: Matrix): void; - addMesh(newMesh: AbstractMesh): void; - removeMesh(toRemove: AbstractMesh): number; - removeSkeleton(toRemove: Skeleton): number; - removeLight(toRemove: Light): number; - removeCamera(toRemove: Camera): number; - addLight(newLight: Light): void; - addCamera(newCamera: Camera): void; - /** - * Switch active camera - * @param {Camera} newCamera - new active camera - * @param {boolean} attachControl - call attachControl for the new active camera (default: true) - */ - swithActiveCamera(newCamera: Camera, attachControl?: boolean): void; - /** - * sets the active camera of the scene using its ID - * @param {string} id - the camera's ID - * @return {BABYLON.Camera|null} the new active camera or null if none found. - * @see activeCamera - */ - setActiveCameraByID(id: string): Camera; - /** - * sets the active camera of the scene using its name - * @param {string} name - the camera's name - * @return {BABYLON.Camera|null} the new active camera or null if none found. - * @see activeCamera - */ - setActiveCameraByName(name: string): Camera; - /** - * get a material using its id - * @param {string} the material's ID - * @return {BABYLON.Material|null} the material or null if none found. - */ - getMaterialByID(id: string): Material; - /** - * get a material using its name - * @param {string} the material's name - * @return {BABYLON.Material|null} the material or null if none found. - */ - getMaterialByName(name: string): Material; - getLensFlareSystemByName(name: string): LensFlareSystem; - getCameraByID(id: string): Camera; - getCameraByUniqueID(uniqueId: number): Camera; - /** - * get a camera using its name - * @param {string} the camera's name - * @return {BABYLON.Camera|null} the camera or null if none found. - */ - getCameraByName(name: string): Camera; - /** - * get a bone using its id - * @param {string} the bone's id - * @return {BABYLON.Bone|null} the bone or null if not found - */ - getBoneByID(id: string): Bone; - /** - * get a bone using its id - * @param {string} the bone's name - * @return {BABYLON.Bone|null} the bone or null if not found - */ - getBoneByName(name: string): Bone; - /** - * get a light node using its name - * @param {string} the light's name - * @return {BABYLON.Light|null} the light or null if none found. - */ - getLightByName(name: string): Light; - /** - * get a light node using its ID - * @param {string} the light's id - * @return {BABYLON.Light|null} the light or null if none found. - */ - getLightByID(id: string): Light; - /** - * get a light node using its scene-generated unique ID - * @param {number} the light's unique id - * @return {BABYLON.Light|null} the light or null if none found. - */ - getLightByUniqueID(uniqueId: number): Light; - /** - * get a particle system by id - * @param id {number} the particle system id - * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found. - */ - getParticleSystemByID(id: string): ParticleSystem; - /** - * get a geometry using its ID - * @param {string} the geometry's id - * @return {BABYLON.Geometry|null} the geometry or null if none found. - */ - getGeometryByID(id: string): Geometry; - /** - * add a new geometry to this scene. - * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene. - * @param {boolean} [force] - force addition, even if a geometry with this ID already exists - * @return {boolean} was the geometry added or not - */ - pushGeometry(geometry: Geometry, force?: boolean): boolean; - /** - * Removes an existing geometry - * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene. - * @return {boolean} was the geometry removed or not - */ - removeGeometry(geometry: Geometry): boolean; - getGeometries(): Geometry[]; - /** - * Get the first added mesh found of a given ID - * @param {string} id - the id to search for - * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all. - */ - getMeshByID(id: string): AbstractMesh; - /** - * Get a mesh with its auto-generated unique id - * @param {number} uniqueId - the unique id to search for - * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all. - */ - getMeshByUniqueID(uniqueId: number): AbstractMesh; - /** - * Get a the last added mesh found of a given ID - * @param {string} id - the id to search for - * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all. - */ - getLastMeshByID(id: string): AbstractMesh; - /** - * Get a the last added node (Mesh, Camera, Light) found of a given ID - * @param {string} id - the id to search for - * @return {BABYLON.Node|null} the node found or null if not found at all. - */ - getLastEntryByID(id: string): Node; - getNodeByID(id: string): Node; - getNodeByName(name: string): Node; - getMeshByName(name: string): AbstractMesh; - getSoundByName(name: string): Sound; - getLastSkeletonByID(id: string): Skeleton; - getSkeletonById(id: string): Skeleton; - getSkeletonByName(name: string): Skeleton; - isActiveMesh(mesh: Mesh): boolean; - private _evaluateSubMesh(subMesh, mesh); - private _evaluateActiveMeshes(); - private _activeMesh(mesh); - updateTransformMatrix(force?: boolean): void; - private _renderForCamera(camera); - private _processSubCameras(camera); - private _checkIntersections(); - render(): void; - private _updateAudioParameters(); - audioEnabled: boolean; - private _disableAudio(); - private _enableAudio(); - headphone: boolean; - private _switchAudioModeForHeadphones(); - private _switchAudioModeForNormalSpeakers(); - enableDepthRenderer(): DepthRenderer; - disableDepthRenderer(): void; - freezeMaterials(): void; - unfreezeMaterials(): void; - dispose(): void; - disposeSounds(): void; - getWorldExtends(): { - min: Vector3; - max: Vector3; - }; - createOrUpdateSelectionOctree(maxCapacity?: number, maxDepth?: number): Octree; - createPickingRay(x: number, y: number, world: Matrix, camera: Camera, cameraViewSpace?: boolean): Ray; - createPickingRayInCameraSpace(x: number, y: number, camera: Camera): Ray; - private _internalPick(rayFunction, predicate, fastCheck?); - private _internalPickSprites(ray, predicate?, fastCheck?, camera?); - pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo; - pickSprite(x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo; - pickWithRay(ray: Ray, predicate: (mesh: Mesh) => boolean, fastCheck?: boolean): PickingInfo; - setPointerOverMesh(mesh: AbstractMesh): void; - getPointerOverMesh(): AbstractMesh; - getPhysicsEngine(): PhysicsEngine; - /** - * Enables physics to the current scene - * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine - * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS. - * @return {boolean} was the physics engine initialized - */ - enablePhysics(gravity?: Vector3, plugin?: IPhysicsEnginePlugin): boolean; - disablePhysicsEngine(): void; - isPhysicsEnabled(): boolean; - /** - * Sets the gravity of the physics engine (and NOT of the scene) - * @param {BABYLON.Vector3} [gravity] - the new gravity to be used - */ - setGravity(gravity: Vector3): void; - createCompoundImpostor(parts: any, options: PhysicsBodyCreationOptions): any; - deleteCompoundImpostor(compound: any): void; - createDefaultCameraOrLight(): void; - private _getByTags(list, tagsQuery, forEach?); - getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[]; - getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[]; - getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[]; - getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[]; - } -} - -declare namespace BABYLON { - class Action { - triggerOptions: any; - trigger: number; - _actionManager: ActionManager; - private _nextActiveAction; - private _child; - private _condition; - private _triggerParameter; - constructor(triggerOptions: any, condition?: Condition); - _prepare(): void; - getTriggerParameter(): any; - _executeCurrent(evt: ActionEvent): void; - execute(evt: ActionEvent): void; - skipToNextActiveAction(): void; - then(action: Action): Action; - _getProperty(propertyPath: string): string; - _getEffectiveTarget(target: any, propertyPath: string): any; - } -} - -declare namespace BABYLON { - /** - * ActionEvent is the event beint sent when an action is triggered. - */ - class ActionEvent { - source: any; - pointerX: number; - pointerY: number; - meshUnderPointer: AbstractMesh; - sourceEvent: any; - additionalData: any; - /** - * @constructor - * @param source The mesh or sprite that triggered the action. - * @param pointerX The X mouse cursor position at the time of the event - * @param pointerY The Y mouse cursor position at the time of the event - * @param meshUnderPointer The mesh that is currently pointed at (can be null) - * @param sourceEvent the original (browser) event that triggered the ActionEvent - */ - constructor(source: any, pointerX: number, pointerY: number, meshUnderPointer: AbstractMesh, sourceEvent?: any, additionalData?: any); - /** - * Helper function to auto-create an ActionEvent from a source mesh. - * @param source The source mesh that triggered the event - * @param evt {Event} The original (browser) event - */ - static CreateNew(source: AbstractMesh, evt?: Event, additionalData?: any): ActionEvent; - /** - * Helper function to auto-create an ActionEvent from a source mesh. - * @param source The source sprite that triggered the event - * @param scene Scene associated with the sprite - * @param evt {Event} The original (browser) event - */ - static CreateNewFromSprite(source: Sprite, scene: Scene, evt?: Event, additionalData?: any): ActionEvent; - /** - * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew - * @param scene the scene where the event occurred - * @param evt {Event} The original (browser) event - */ - static CreateNewFromScene(scene: Scene, evt: Event): ActionEvent; - } - /** - * Action Manager manages all events to be triggered on a given mesh or the global scene. - * A single scene can have many Action Managers to handle predefined actions on specific meshes. - */ - class ActionManager { - private static _NothingTrigger; - private static _OnPickTrigger; - private static _OnLeftPickTrigger; - private static _OnRightPickTrigger; - private static _OnCenterPickTrigger; - private static _OnPickDownTrigger; - private static _OnPickUpTrigger; - private static _OnLongPressTrigger; - private static _OnPointerOverTrigger; - private static _OnPointerOutTrigger; - private static _OnEveryFrameTrigger; - private static _OnIntersectionEnterTrigger; - private static _OnIntersectionExitTrigger; - private static _OnKeyDownTrigger; - private static _OnKeyUpTrigger; - static NothingTrigger: number; - static OnPickTrigger: number; - static OnLeftPickTrigger: number; - static OnRightPickTrigger: number; - static OnCenterPickTrigger: number; - static OnPickDownTrigger: number; - static OnPickUpTrigger: number; - static OnLongPressTrigger: number; - static OnPointerOverTrigger: number; - static OnPointerOutTrigger: number; - static OnEveryFrameTrigger: number; - static OnIntersectionEnterTrigger: number; - static OnIntersectionExitTrigger: number; - static OnKeyDownTrigger: number; - static OnKeyUpTrigger: number; - static DragMovementThreshold: number; - static LongPressDelay: number; - actions: Action[]; - private _scene; - constructor(scene: Scene); - dispose(): void; - getScene(): Scene; - /** - * Does this action manager handles actions of any of the given triggers - * @param {number[]} triggers - the triggers to be tested - * @return {boolean} whether one (or more) of the triggers is handeled - */ - hasSpecificTriggers(triggers: number[]): boolean; - /** - * Does this action manager handles actions of a given trigger - * @param {number} trigger - the trigger to be tested - * @return {boolean} whether the trigger is handeled - */ - hasSpecificTrigger(trigger: number): boolean; - /** - * Does this action manager has pointer triggers - * @return {boolean} whether or not it has pointer triggers - */ - hasPointerTriggers: boolean; - /** - * Does this action manager has pick triggers - * @return {boolean} whether or not it has pick triggers - */ - hasPickTriggers: boolean; - /** - * Registers an action to this action manager - * @param {BABYLON.Action} action - the action to be registered - * @return {BABYLON.Action} the action amended (prepared) after registration - */ - registerAction(action: Action): Action; - /** - * Process a specific trigger - * @param {number} trigger - the trigger to process - * @param evt {BABYLON.ActionEvent} the event details to be processed - */ - processTrigger(trigger: number, evt: ActionEvent): void; - _getEffectiveTarget(target: any, propertyPath: string): any; - _getProperty(propertyPath: string): string; - static Parse(parsedActions: any, object: AbstractMesh, scene: Scene): void; - } -} - -declare namespace BABYLON { - class Condition { - _actionManager: ActionManager; - _evaluationId: number; - _currentResult: boolean; - constructor(actionManager: ActionManager); - isValid(): boolean; - _getProperty(propertyPath: string): string; - _getEffectiveTarget(target: any, propertyPath: string): any; - } - class ValueCondition extends Condition { - propertyPath: string; - value: any; - operator: number; - private static _IsEqual; - private static _IsDifferent; - private static _IsGreater; - private static _IsLesser; - static IsEqual: number; - static IsDifferent: number; - static IsGreater: number; - static IsLesser: number; - _actionManager: ActionManager; - private _target; - private _property; - constructor(actionManager: ActionManager, target: any, propertyPath: string, value: any, operator?: number); - isValid(): boolean; - } - class PredicateCondition extends Condition { - predicate: () => boolean; - _actionManager: ActionManager; - constructor(actionManager: ActionManager, predicate: () => boolean); - isValid(): boolean; - } - class StateCondition extends Condition { - value: string; - _actionManager: ActionManager; - private _target; - constructor(actionManager: ActionManager, target: any, value: string); - isValid(): boolean; - } -} - -declare namespace BABYLON { - class SwitchBooleanAction extends Action { - propertyPath: string; - private _target; - private _property; - constructor(triggerOptions: any, target: any, propertyPath: string, condition?: Condition); - _prepare(): void; - execute(): void; - } - class SetStateAction extends Action { - value: string; - private _target; - constructor(triggerOptions: any, target: any, value: string, condition?: Condition); - execute(): void; - } - class SetValueAction extends Action { - propertyPath: string; - value: any; - private _target; - private _property; - constructor(triggerOptions: any, target: any, propertyPath: string, value: any, condition?: Condition); - _prepare(): void; - execute(): void; - } - class IncrementValueAction extends Action { - propertyPath: string; - value: any; - private _target; - private _property; - constructor(triggerOptions: any, target: any, propertyPath: string, value: any, condition?: Condition); - _prepare(): void; - execute(): void; - } - class PlayAnimationAction extends Action { - from: number; - to: number; - loop: boolean; - private _target; - constructor(triggerOptions: any, target: any, from: number, to: number, loop?: boolean, condition?: Condition); - _prepare(): void; - execute(): void; - } - class StopAnimationAction extends Action { - private _target; - constructor(triggerOptions: any, target: any, condition?: Condition); - _prepare(): void; - execute(): void; - } - class DoNothingAction extends Action { - constructor(triggerOptions?: any, condition?: Condition); - execute(): void; - } - class CombineAction extends Action { - children: Action[]; - constructor(triggerOptions: any, children: Action[], condition?: Condition); - _prepare(): void; - execute(evt: ActionEvent): void; - } - class ExecuteCodeAction extends Action { - func: (evt: ActionEvent) => void; - constructor(triggerOptions: any, func: (evt: ActionEvent) => void, condition?: Condition); - execute(evt: ActionEvent): void; - } - class SetParentAction extends Action { - private _parent; - private _target; - constructor(triggerOptions: any, target: any, parent: any, condition?: Condition); - _prepare(): void; - execute(): void; - } - class PlaySoundAction extends Action { - private _sound; - constructor(triggerOptions: any, sound: Sound, condition?: Condition); - _prepare(): void; - execute(): void; - } - class StopSoundAction extends Action { - private _sound; - constructor(triggerOptions: any, sound: Sound, condition?: Condition); - _prepare(): void; - execute(): void; - } -} - -declare namespace BABYLON { - class InterpolateValueAction extends Action { - propertyPath: string; - value: any; - duration: number; - stopOtherAnimations: boolean; - onInterpolationDone: () => void; - private _target; - private _property; - constructor(triggerOptions: any, target: any, propertyPath: string, value: any, duration?: number, condition?: Condition, stopOtherAnimations?: boolean, onInterpolationDone?: () => void); - _prepare(): void; - execute(): void; - } -} - -declare namespace BABYLON { - class Animatable { - target: any; - fromFrame: number; - toFrame: number; - loopAnimation: boolean; - speedRatio: number; - onAnimationEnd: any; - private _localDelayOffset; - private _pausedDelay; - private _animations; - private _paused; - private _scene; - animationStarted: boolean; - constructor(scene: Scene, target: any, fromFrame?: number, toFrame?: number, loopAnimation?: boolean, speedRatio?: number, onAnimationEnd?: any, animations?: any); - getAnimations(): Animation[]; - appendAnimations(target: any, animations: Animation[]): void; - getAnimationByTargetProperty(property: string): Animation; - reset(): void; - goToFrame(frame: number): void; - pause(): void; - restart(): void; - stop(): void; - _animate(delay: number): boolean; - } -} - -declare namespace BABYLON { - class AnimationRange { - name: string; - from: number; - to: number; - constructor(name: string, from: number, to: number); - } - /** - * Composed of a frame, and an action function - */ - class AnimationEvent { - frame: number; - action: () => void; - onlyOnce: boolean; - isDone: boolean; - constructor(frame: number, action: () => void, onlyOnce?: boolean); - } - class Animation { - name: string; - targetProperty: string; - framePerSecond: number; - dataType: number; - loopMode: number; - private _keys; - private _offsetsCache; - private _highLimitsCache; - private _stopped; - _target: any; - private _easingFunction; - private _events; - targetPropertyPath: string[]; - currentFrame: number; - allowMatricesInterpolation: boolean; - private _ranges; - static _PrepareAnimation(name: string, targetProperty: string, framePerSecond: number, totalFrame: number, from: any, to: any, loopMode?: number, easingFunction?: EasingFunction): Animation; - static CreateAndStartAnimation(name: string, node: Node, targetProperty: string, framePerSecond: number, totalFrame: number, from: any, to: any, loopMode?: number, easingFunction?: EasingFunction, onAnimationEnd?: () => void): Animatable; - static CreateMergeAndStartAnimation(name: string, node: Node, targetProperty: string, framePerSecond: number, totalFrame: number, from: any, to: any, loopMode?: number, easingFunction?: EasingFunction, onAnimationEnd?: () => void): Animatable; - constructor(name: string, targetProperty: string, framePerSecond: number, dataType: number, loopMode?: number); - /** - * Add an event to this animation. - */ - addEvent(event: AnimationEvent): void; - /** - * Remove all events found at the given frame - * @param frame - */ - removeEvents(frame: number): void; - createRange(name: string, from: number, to: number): void; - deleteRange(name: string, deleteFrames?: boolean): void; - getRange(name: string): AnimationRange; - reset(): void; - isStopped(): boolean; - getKeys(): any[]; - getHighestFrame(): number; - getEasingFunction(): IEasingFunction; - setEasingFunction(easingFunction: EasingFunction): void; - floatInterpolateFunction(startValue: number, endValue: number, gradient: number): number; - quaternionInterpolateFunction(startValue: Quaternion, endValue: Quaternion, gradient: number): Quaternion; - vector3InterpolateFunction(startValue: Vector3, endValue: Vector3, gradient: number): Vector3; - vector2InterpolateFunction(startValue: Vector2, endValue: Vector2, gradient: number): Vector2; - color3InterpolateFunction(startValue: Color3, endValue: Color3, gradient: number): Color3; - matrixInterpolateFunction(startValue: Matrix, endValue: Matrix, gradient: number): Matrix; - clone(): Animation; - setKeys(values: Array): void; - private _getKeyValue(value); - private _interpolate(currentFrame, repeatCount, loopMode, offsetValue?, highLimitValue?); - setValue(currentValue: any): void; - goToFrame(frame: number): void; - animate(delay: number, from: number, to: number, loop: boolean, speedRatio: number): boolean; - serialize(): any; - private static _ANIMATIONTYPE_FLOAT; - private static _ANIMATIONTYPE_VECTOR3; - private static _ANIMATIONTYPE_QUATERNION; - private static _ANIMATIONTYPE_MATRIX; - private static _ANIMATIONTYPE_COLOR3; - private static _ANIMATIONTYPE_VECTOR2; - private static _ANIMATIONLOOPMODE_RELATIVE; - private static _ANIMATIONLOOPMODE_CYCLE; - private static _ANIMATIONLOOPMODE_CONSTANT; - static ANIMATIONTYPE_FLOAT: number; - static ANIMATIONTYPE_VECTOR3: number; - static ANIMATIONTYPE_VECTOR2: number; - static ANIMATIONTYPE_QUATERNION: number; - static ANIMATIONTYPE_MATRIX: number; - static ANIMATIONTYPE_COLOR3: number; - static ANIMATIONLOOPMODE_RELATIVE: number; - static ANIMATIONLOOPMODE_CYCLE: number; - static ANIMATIONLOOPMODE_CONSTANT: number; - static Parse(parsedAnimation: any): Animation; - static AppendSerializedAnimations(source: IAnimatable, destination: any): any; - } -} - -declare namespace BABYLON { - interface IEasingFunction { - ease(gradient: number): number; - } - class EasingFunction implements IEasingFunction { - private static _EASINGMODE_EASEIN; - private static _EASINGMODE_EASEOUT; - private static _EASINGMODE_EASEINOUT; - static EASINGMODE_EASEIN: number; - static EASINGMODE_EASEOUT: number; - static EASINGMODE_EASEINOUT: number; - private _easingMode; - setEasingMode(easingMode: number): void; - getEasingMode(): number; - easeInCore(gradient: number): number; - ease(gradient: number): number; - } - class CircleEase extends EasingFunction implements IEasingFunction { - easeInCore(gradient: number): number; - } - class BackEase extends EasingFunction implements IEasingFunction { - amplitude: number; - constructor(amplitude?: number); - easeInCore(gradient: number): number; - } - class BounceEase extends EasingFunction implements IEasingFunction { - bounces: number; - bounciness: number; - constructor(bounces?: number, bounciness?: number); - easeInCore(gradient: number): number; - } - class CubicEase extends EasingFunction implements IEasingFunction { - easeInCore(gradient: number): number; - } - class ElasticEase extends EasingFunction implements IEasingFunction { - oscillations: number; - springiness: number; - constructor(oscillations?: number, springiness?: number); - easeInCore(gradient: number): number; - } - class ExponentialEase extends EasingFunction implements IEasingFunction { - exponent: number; - constructor(exponent?: number); - easeInCore(gradient: number): number; - } - class PowerEase extends EasingFunction implements IEasingFunction { - power: number; - constructor(power?: number); - easeInCore(gradient: number): number; - } - class QuadraticEase extends EasingFunction implements IEasingFunction { - easeInCore(gradient: number): number; - } - class QuarticEase extends EasingFunction implements IEasingFunction { - easeInCore(gradient: number): number; - } - class QuinticEase extends EasingFunction implements IEasingFunction { - easeInCore(gradient: number): number; - } - class SineEase extends EasingFunction implements IEasingFunction { - easeInCore(gradient: number): number; - } - class BezierCurveEase extends EasingFunction implements IEasingFunction { - x1: number; - y1: number; - x2: number; - y2: number; - constructor(x1?: number, y1?: number, x2?: number, y2?: number); - easeInCore(gradient: number): number; - } -} - -declare namespace BABYLON { - class Analyser { - SMOOTHING: number; - FFT_SIZE: number; - BARGRAPHAMPLITUDE: number; - DEBUGCANVASPOS: { - x: number; - y: number; - }; - DEBUGCANVASSIZE: { - width: number; - height: number; - }; - private _byteFreqs; - private _byteTime; - private _floatFreqs; - private _webAudioAnalyser; - private _debugCanvas; - private _debugCanvasContext; - private _scene; - private _registerFunc; - private _audioEngine; - constructor(scene: Scene); - getFrequencyBinCount(): number; - getByteFrequencyData(): Uint8Array; - getByteTimeDomainData(): Uint8Array; - getFloatFrequencyData(): Uint8Array; - drawDebugCanvas(): void; - stopDebugCanvas(): void; - connectAudioNodes(inputAudioNode: AudioNode, outputAudioNode: AudioNode): void; - dispose(): void; - } -} - -declare namespace BABYLON { - class AudioEngine { - private _audioContext; - private _audioContextInitialized; - canUseWebAudio: boolean; - masterGain: GainNode; - private _connectedAnalyser; - WarnedWebAudioUnsupported: boolean; - unlocked: boolean; - onAudioUnlocked: () => any; - audioContext: AudioContext; - constructor(); - private _unlockiOSaudio(); - private _initializeAudioContext(); - dispose(): void; - getGlobalVolume(): number; - setGlobalVolume(newVolume: number): void; - connectToAnalyser(analyser: Analyser): void; - } -} - -declare namespace BABYLON { - class Sound { - name: string; - autoplay: boolean; - loop: boolean; - useCustomAttenuation: boolean; - soundTrackId: number; - spatialSound: boolean; - refDistance: number; - rolloffFactor: number; - maxDistance: number; - distanceModel: string; - private _panningModel; - onended: () => any; - private _playbackRate; - private _streaming; - private _startTime; - private _startOffset; - private _position; - private _localDirection; - private _volume; - private _isLoaded; - private _isReadyToPlay; - isPlaying: boolean; - isPaused: boolean; - private _isDirectional; - private _readyToPlayCallback; - private _audioBuffer; - private _soundSource; - private _streamingSource; - private _soundPanner; - private _soundGain; - private _inputAudioNode; - private _ouputAudioNode; - private _coneInnerAngle; - private _coneOuterAngle; - private _coneOuterGain; - private _scene; - private _connectedMesh; - private _customAttenuationFunction; - private _registerFunc; - private _isOutputConnected; - private _htmlAudioElement; - /** - * Create a sound and attach it to a scene - * @param name Name of your sound - * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer - * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played - * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming - */ - constructor(name: string, urlOrArrayBuffer: any, scene: Scene, readyToPlayCallback?: () => void, options?: any); - dispose(): void; - private _soundLoaded(audioData); - setAudioBuffer(audioBuffer: AudioBuffer): void; - updateOptions(options: any): void; - private _createSpatialParameters(); - private _updateSpatialParameters(); - switchPanningModelToHRTF(): void; - switchPanningModelToEqualPower(): void; - private _switchPanningModel(); - connectToSoundTrackAudioNode(soundTrackAudioNode: AudioNode): void; - /** - * Transform this sound into a directional source - * @param coneInnerAngle Size of the inner cone in degree - * @param coneOuterAngle Size of the outer cone in degree - * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0) - */ - setDirectionalCone(coneInnerAngle: number, coneOuterAngle: number, coneOuterGain: number): void; - setPosition(newPosition: Vector3): void; - setLocalDirectionToMesh(newLocalDirection: Vector3): void; - private _updateDirection(); - updateDistanceFromListener(): void; - setAttenuationFunction(callback: (currentVolume: number, currentDistance: number, maxDistance: number, refDistance: number, rolloffFactor: number) => number): void; - /** - * Play the sound - * @param time (optional) Start the sound after X seconds. Start immediately (0) by default. - */ - play(time?: number): void; - private _onended(); - /** - * Stop the sound - * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default. - */ - stop(time?: number): void; - pause(): void; - setVolume(newVolume: number, time?: number): void; - setPlaybackRate(newPlaybackRate: number): void; - getVolume(): number; - attachToMesh(meshToConnectTo: AbstractMesh): void; - private _onRegisterAfterWorldMatrixUpdate(connectedMesh); - clone(): Sound; - getAudioBuffer(): AudioBuffer; - static Parse(parsedSound: any, scene: Scene, rootUrl: string, sourceSound?: Sound): Sound; - } -} - -declare namespace BABYLON { - class SoundTrack { - private _outputAudioNode; - private _inputAudioNode; - private _trackConvolver; - private _scene; - id: number; - soundCollection: Array; - private _isMainTrack; - private _connectedAnalyser; - private _options; - private _isInitialized; - constructor(scene: Scene, options?: any); - private _initializeSoundTrackAudioGraph(); - dispose(): void; - AddSound(sound: Sound): void; - RemoveSound(sound: Sound): void; - setVolume(newVolume: number): void; - switchPanningModelToHRTF(): void; - switchPanningModelToEqualPower(): void; - connectToAnalyser(analyser: Analyser): void; - } -} - -declare namespace BABYLON { - class Bone extends Node { - name: string; - children: Bone[]; - animations: Animation[]; - length: number; - private _skeleton; - _matrix: Matrix; - private _restPose; - private _baseMatrix; - private _worldTransform; - private _absoluteTransform; - private _invertedAbsoluteTransform; - private _parent; - constructor(name: string, skeleton: Skeleton, parentBone: Bone, matrix: Matrix, restPose?: Matrix); - getParent(): Bone; - getLocalMatrix(): Matrix; - getBaseMatrix(): Matrix; - getRestPose(): Matrix; - returnToRest(): void; - getWorldMatrix(): Matrix; - getInvertedAbsoluteTransform(): Matrix; - getAbsoluteTransform(): Matrix; - updateMatrix(matrix: Matrix): void; - _updateDifferenceMatrix(rootMatrix?: Matrix): void; - markAsDirty(): void; - copyAnimationRange(source: Bone, rangeName: string, frameOffset: number, rescaleAsRequired?: boolean): boolean; - } -} - -declare namespace BABYLON { - class Skeleton { - name: string; - id: string; - bones: Bone[]; - needInitialSkinMatrix: boolean; - private _scene; - private _isDirty; - private _transformMatrices; - private _meshesWithPoseMatrix; - private _animatables; - private _identity; - private _ranges; - constructor(name: string, id: string, scene: Scene); - getTransformMatrices(mesh: AbstractMesh): Float32Array; - getScene(): Scene; - createAnimationRange(name: string, from: number, to: number): void; - deleteAnimationRange(name: string, deleteFrames?: boolean): void; - getAnimationRange(name: string): AnimationRange; - /** - * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences - */ - copyAnimationRange(source: Skeleton, name: string, rescaleAsRequired?: boolean): boolean; - returnToRest(): void; - private _getHighestAnimationFrame(); - beginAnimation(name: string, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): void; - _markAsDirty(): void; - _registerMeshWithPoseMatrix(mesh: AbstractMesh): void; - _unregisterMeshWithPoseMatrix(mesh: AbstractMesh): void; - _computeTransformMatrices(targetMatrix: Float32Array, initialSkinMatrix: Matrix): void; - prepare(): void; - getAnimatables(): IAnimatable[]; - clone(name: string, id: string): Skeleton; - dispose(): void; - serialize(): any; - static Parse(parsedSkeleton: any, scene: Scene): Skeleton; - } -} - -declare namespace BABYLON { - class ArcRotateCamera extends TargetCamera { - alpha: number; - beta: number; - radius: number; - target: any; - inertialAlphaOffset: number; - inertialBetaOffset: number; - inertialRadiusOffset: number; - lowerAlphaLimit: any; - upperAlphaLimit: any; - lowerBetaLimit: number; - upperBetaLimit: number; - lowerRadiusLimit: any; - upperRadiusLimit: any; - angularSensibilityX: number; - angularSensibilityY: number; - wheelPrecision: number; - pinchPrecision: number; - panningSensibility: number; - inertialPanningX: number; - inertialPanningY: number; - keysUp: number[]; - keysDown: number[]; - keysLeft: number[]; - keysRight: number[]; - zoomOnFactor: number; - targetScreenOffset: Vector2; - pinchInwards: boolean; - allowUpsideDown: boolean; - private _keys; - _viewMatrix: Matrix; - private _attachedElement; - private _onContextMenu; - private _onPointerDown; - private _onPointerUp; - private _onPointerMove; - private _wheel; - private _onMouseMove; - private _onKeyDown; - private _onKeyUp; - private _onLostFocus; - _reset: () => void; - private _onGestureStart; - private _onGesture; - private _MSGestureHandler; - panningAxis: Vector3; - private _localDirection; - private _transformedDirection; - private _isRightClick; - private _isCtrlPushed; - onCollide: (collidedMesh: AbstractMesh) => void; - checkCollisions: boolean; - collisionRadius: Vector3; - private _collider; - private _previousPosition; - private _collisionVelocity; - private _newPosition; - private _previousAlpha; - private _previousBeta; - private _previousRadius; - private _collisionTriggered; - angularSensibility: number; - constructor(name: string, alpha: number, beta: number, radius: number, target: any, scene: Scene); - _getTargetPosition(): Vector3; - _initCache(): void; - _updateCache(ignoreParentClass?: boolean): void; - _isSynchronizedViewMatrix(): boolean; - attachControl(element: HTMLElement, noPreventDefault?: boolean, useCtrlForPanning?: boolean): void; - detachControl(element: HTMLElement): void; - _checkInputs(): void; - private _checkLimits(); - setPosition(position: Vector3): void; - setTarget(target: Vector3): void; - _getViewMatrix(): Matrix; - private _onCollisionPositionChange; - zoomOn(meshes?: AbstractMesh[], doNotUpdateMaxZ?: boolean): void; - focusOn(meshesOrMinMaxVectorAndDistance: any, doNotUpdateMaxZ?: boolean): void; - /** - * @override - * Override Camera.createRigCamera - */ - createRigCamera(name: string, cameraIndex: number): Camera; - /** - * @override - * Override Camera._updateRigCameras - */ - _updateRigCameras(): void; - serialize(): any; - } -} - -declare namespace BABYLON { - class VRCameraMetrics { - hResolution: number; - vResolution: number; - hScreenSize: number; - vScreenSize: number; - vScreenCenter: number; - eyeToScreenDistance: number; - lensSeparationDistance: number; - interpupillaryDistance: number; - distortionK: number[]; - chromaAbCorrection: number[]; - postProcessScaleFactor: number; - lensCenterOffset: number; - compensateDistortion: boolean; - aspectRatio: number; - aspectRatioFov: number; - leftHMatrix: Matrix; - rightHMatrix: Matrix; - leftPreViewMatrix: Matrix; - rightPreViewMatrix: Matrix; - static GetDefault(): VRCameraMetrics; - } - class Camera extends Node { - position: Vector3; - private static _PERSPECTIVE_CAMERA; - private static _ORTHOGRAPHIC_CAMERA; - private static _FOVMODE_VERTICAL_FIXED; - private static _FOVMODE_HORIZONTAL_FIXED; - private static _RIG_MODE_NONE; - private static _RIG_MODE_STEREOSCOPIC_ANAGLYPH; - private static _RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL; - private static _RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; - private static _RIG_MODE_STEREOSCOPIC_OVERUNDER; - private static _RIG_MODE_VR; - static PERSPECTIVE_CAMERA: number; - static ORTHOGRAPHIC_CAMERA: number; - static FOVMODE_VERTICAL_FIXED: number; - static FOVMODE_HORIZONTAL_FIXED: number; - static RIG_MODE_NONE: number; - static RIG_MODE_STEREOSCOPIC_ANAGLYPH: number; - static RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: number; - static RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: number; - static RIG_MODE_STEREOSCOPIC_OVERUNDER: number; - static RIG_MODE_VR: number; - upVector: Vector3; - orthoLeft: any; - orthoRight: any; - orthoBottom: any; - orthoTop: any; - fov: number; - minZ: number; - maxZ: number; - inertia: number; - mode: number; - isIntermediate: boolean; - viewport: Viewport; - layerMask: number; - fovMode: number; - cameraRigMode: number; - _cameraRigParams: any; - _rigCameras: Camera[]; - private _computedViewMatrix; - _projectionMatrix: Matrix; - private _worldMatrix; - _postProcesses: PostProcess[]; - _postProcessesTakenIndices: any[]; - _activeMeshes: SmartArray; - private _globalPosition; - constructor(name: string, position: Vector3, scene: Scene); - globalPosition: Vector3; - getActiveMeshes(): SmartArray; - isActiveMesh(mesh: Mesh): boolean; - _initCache(): void; - _updateCache(ignoreParentClass?: boolean): void; - _updateFromScene(): void; - _isSynchronized(): boolean; - _isSynchronizedViewMatrix(): boolean; - _isSynchronizedProjectionMatrix(): boolean; - attachControl(element: HTMLElement): void; - detachControl(element: HTMLElement): void; - _update(): void; - _checkInputs(): void; - attachPostProcess(postProcess: PostProcess, insertAt?: number): number; - detachPostProcess(postProcess: PostProcess, atIndices?: any): number[]; - getWorldMatrix(): Matrix; - _getViewMatrix(): Matrix; - getViewMatrix(force?: boolean): Matrix; - _computeViewMatrix(force?: boolean): Matrix; - getProjectionMatrix(force?: boolean): Matrix; - dispose(): void; - setCameraRigMode(mode: number, rigParams: any): void; - private _getVRProjectionMatrix(); - setCameraRigParameter(name: string, value: any): void; - /** - * May needs to be overridden by children so sub has required properties to be copied - */ - createRigCamera(name: string, cameraIndex: number): Camera; - /** - * May needs to be overridden by children - */ - _updateRigCameras(): void; - serialize(): any; - static Parse(parsedCamera: any, scene: Scene): Camera; - } -} - -declare namespace BABYLON { - class DeviceOrientationCamera extends FreeCamera { - private _offsetX; - private _offsetY; - private _orientationGamma; - private _orientationBeta; - private _initialOrientationGamma; - private _initialOrientationBeta; - private _attachedCanvas; - private _orientationChanged; - angularSensibility: number; - moveSensibility: number; - constructor(name: string, position: Vector3, scene: Scene); - attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void; - detachControl(canvas: HTMLCanvasElement): void; - _checkInputs(): void; - } -} - -declare namespace BABYLON { - class FollowCamera extends TargetCamera { - radius: number; - rotationOffset: number; - heightOffset: number; - cameraAcceleration: number; - maxCameraSpeed: number; - target: AbstractMesh; - constructor(name: string, position: Vector3, scene: Scene); - private getRadians(degrees); - private follow(cameraTarget); - _checkInputs(): void; - serialize(): any; - } - class ArcFollowCamera extends TargetCamera { - alpha: number; - beta: number; - radius: number; - target: AbstractMesh; - private _cartesianCoordinates; - constructor(name: string, alpha: number, beta: number, radius: number, target: AbstractMesh, scene: Scene); - private follow(); - _checkInputs(): void; - serialize(): any; - } -} - -declare namespace BABYLON { - class FreeCamera extends TargetCamera { - ellipsoid: Vector3; - keysUp: number[]; - keysDown: number[]; - keysLeft: number[]; - keysRight: number[]; - checkCollisions: boolean; - applyGravity: boolean; - angularSensibility: number; - onCollide: (collidedMesh: AbstractMesh) => void; - private _keys; - private _collider; - private _needMoveForGravity; - private _oldPosition; - private _diffPosition; - private _newPosition; - private _attachedElement; - private _localDirection; - private _transformedDirection; - private _onMouseDown; - private _onMouseUp; - private _onMouseOut; - private _onMouseMove; - private _onKeyDown; - private _onKeyUp; - _waitingLockedTargetId: string; - constructor(name: string, position: Vector3, scene: Scene); - _onLostFocus(e: FocusEvent): void; - attachControl(element: HTMLElement, noPreventDefault?: boolean): void; - detachControl(element: HTMLElement): void; - _collideWithWorld(velocity: Vector3): void; - private _onCollisionPositionChange; - _checkInputs(): void; - _decideIfNeedsToMove(): boolean; - _updatePosition(): void; - serialize(): any; - } -} - -declare namespace BABYLON { - class GamepadCamera extends UniversalCamera { - constructor(name: string, position: Vector3, scene: Scene); - } -} - -declare namespace BABYLON { - class AnaglyphFreeCamera extends FreeCamera { - interaxialDistance: number; - constructor(name: string, position: Vector3, interaxialDistance: number, scene: Scene); - } - class AnaglyphArcRotateCamera extends ArcRotateCamera { - constructor(name: string, alpha: number, beta: number, radius: number, target: any, interaxialDistance: number, scene: Scene); - } - class AnaglyphGamepadCamera extends GamepadCamera { - constructor(name: string, position: Vector3, interaxialDistance: number, scene: Scene); - } - class StereoscopicFreeCamera extends FreeCamera { - constructor(name: string, position: Vector3, interaxialDistance: number, isSideBySide: boolean, scene: Scene); - } - class StereoscopicArcRotateCamera extends ArcRotateCamera { - constructor(name: string, alpha: number, beta: number, radius: number, target: any, interaxialDistance: number, isSideBySide: boolean, scene: Scene); - } - class StereoscopicGamepadCamera extends GamepadCamera { - constructor(name: string, position: Vector3, interaxialDistance: number, isSideBySide: boolean, scene: Scene); - } -} - -declare namespace BABYLON { - class TargetCamera extends Camera { - cameraDirection: Vector3; - cameraRotation: Vector2; - rotation: Vector3; - speed: number; - noRotationConstraint: boolean; - lockedTarget: any; - _currentTarget: Vector3; - _viewMatrix: Matrix; - _camMatrix: Matrix; - _cameraTransformMatrix: Matrix; - _cameraRotationMatrix: Matrix; - private _rigCamTransformMatrix; - _referencePoint: Vector3; - _transformedReferencePoint: Vector3; - _lookAtTemp: Matrix; - _tempMatrix: Matrix; - _reset: () => void; - _waitingLockedTargetId: string; - constructor(name: string, position: Vector3, scene: Scene); - getFrontPosition(distance: number): Vector3; - _getLockedTargetPosition(): Vector3; - _initCache(): void; - _updateCache(ignoreParentClass?: boolean): void; - _isSynchronizedViewMatrix(): boolean; - _computeLocalCameraSpeed(): number; - setTarget(target: Vector3): void; - getTarget(): Vector3; - _decideIfNeedsToMove(): boolean; - _updatePosition(): void; - _checkInputs(): void; - _getViewMatrix(): Matrix; - _getVRViewMatrix(): Matrix; - /** - * @override - * Override Camera.createRigCamera - */ - createRigCamera(name: string, cameraIndex: number): Camera; - /** - * @override - * Override Camera._updateRigCameras - */ - _updateRigCameras(): void; - private _getRigCamPosition(halfSpace, result); - serialize(): any; - } -} - -declare namespace BABYLON { - class TouchCamera extends FreeCamera { - private _offsetX; - private _offsetY; - private _pointerCount; - private _pointerPressed; - private _attachedCanvas; - private _onPointerDown; - private _onPointerUp; - private _onPointerMove; - touchAngularSensibility: number; - touchMoveSensibility: number; - constructor(name: string, position: Vector3, scene: Scene); - _onLostFocus(e: FocusEvent): void; - attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void; - detachControl(canvas: HTMLCanvasElement): void; - _checkInputs(): void; - } -} - -declare namespace BABYLON { - class UniversalCamera extends TouchCamera { - gamepad: Gamepad; - private _gamepads; - gamepadAngularSensibility: number; - gamepadMoveSensibility: number; - constructor(name: string, position: Vector3, scene: Scene); - private _onNewGameConnected(gamepad); - attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void; - detachControl(canvas: HTMLCanvasElement): void; - _checkInputs(): void; - dispose(): void; - } -} - -declare namespace BABYLON { - class VirtualJoysticksCamera extends FreeCamera { - private _leftjoystick; - private _rightjoystick; - constructor(name: string, position: Vector3, scene: Scene); - getLeftJoystick(): VirtualJoystick; - getRightJoystick(): VirtualJoystick; - _checkInputs(): void; - dispose(): void; - } -} - -declare namespace BABYLON { - class Collider { - radius: Vector3; - retry: number; - velocity: Vector3; - basePoint: Vector3; - epsilon: number; - collisionFound: boolean; - velocityWorldLength: number; - basePointWorld: Vector3; - velocityWorld: Vector3; - normalizedVelocity: Vector3; - initialVelocity: Vector3; - initialPosition: Vector3; - nearestDistance: number; - intersectionPoint: Vector3; - collidedMesh: AbstractMesh; - private _collisionPoint; - private _planeIntersectionPoint; - private _tempVector; - private _tempVector2; - private _tempVector3; - private _tempVector4; - private _edge; - private _baseToVertex; - private _destinationPoint; - private _slidePlaneNormal; - private _displacementVector; - _initialize(source: Vector3, dir: Vector3, e: number): void; - _checkPointInTriangle(point: Vector3, pa: Vector3, pb: Vector3, pc: Vector3, n: Vector3): boolean; - _canDoCollision(sphereCenter: Vector3, sphereRadius: number, vecMin: Vector3, vecMax: Vector3): boolean; - _testTriangle(faceIndex: number, trianglePlaneArray: Array, p1: Vector3, p2: Vector3, p3: Vector3, hasMaterial: boolean): void; - _collide(trianglePlaneArray: Array, pts: Vector3[], indices: number[] | Int32Array, indexStart: number, indexEnd: number, decal: number, hasMaterial: boolean): void; - _getResponse(pos: Vector3, vel: Vector3): void; - } -} - -declare namespace BABYLON { - var CollisionWorker: string; - interface ICollisionCoordinator { - getNewPosition(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh?: AbstractMesh) => void, collisionIndex: number): void; - init(scene: Scene): void; - destroy(): void; - onMeshAdded(mesh: AbstractMesh): any; - onMeshUpdated(mesh: AbstractMesh): any; - onMeshRemoved(mesh: AbstractMesh): any; - onGeometryAdded(geometry: Geometry): any; - onGeometryUpdated(geometry: Geometry): any; - onGeometryDeleted(geometry: Geometry): any; - } - interface SerializedMesh { - id: string; - name: string; - uniqueId: number; - geometryId: string; - sphereCenter: Array; - sphereRadius: number; - boxMinimum: Array; - boxMaximum: Array; - worldMatrixFromCache: any; - subMeshes: Array; - checkCollisions: boolean; - } - interface SerializedSubMesh { - position: number; - verticesStart: number; - verticesCount: number; - indexStart: number; - indexCount: number; - hasMaterial: boolean; - sphereCenter: Array; - sphereRadius: number; - boxMinimum: Array; - boxMaximum: Array; - } - interface SerializedGeometry { - id: string; - positions: Float32Array; - indices: Int32Array; - normals: Float32Array; - } - interface BabylonMessage { - taskType: WorkerTaskType; - payload: InitPayload | CollidePayload | UpdatePayload; - } - interface SerializedColliderToWorker { - position: Array; - velocity: Array; - radius: Array; - } - enum WorkerTaskType { - INIT = 0, - UPDATE = 1, - COLLIDE = 2, - } - interface WorkerReply { - error: WorkerReplyType; - taskType: WorkerTaskType; - payload?: any; - } - interface CollisionReplyPayload { - newPosition: Array; - collisionId: number; - collidedMeshUniqueId: number; - } - interface InitPayload { - } - interface CollidePayload { - collisionId: number; - collider: SerializedColliderToWorker; - maximumRetry: number; - excludedMeshUniqueId?: number; - } - interface UpdatePayload { - updatedMeshes: { - [n: number]: SerializedMesh; - }; - updatedGeometries: { - [s: string]: SerializedGeometry; - }; - removedMeshes: Array; - removedGeometries: Array; - } - enum WorkerReplyType { - SUCCESS = 0, - UNKNOWN_ERROR = 1, - } - class CollisionCoordinatorWorker implements ICollisionCoordinator { - private _scene; - private _scaledPosition; - private _scaledVelocity; - private _collisionsCallbackArray; - private _init; - private _runningUpdated; - private _runningCollisionTask; - private _worker; - private _addUpdateMeshesList; - private _addUpdateGeometriesList; - private _toRemoveMeshesArray; - private _toRemoveGeometryArray; - constructor(); - static SerializeMesh: (mesh: AbstractMesh) => SerializedMesh; - static SerializeGeometry: (geometry: Geometry) => SerializedGeometry; - getNewPosition(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh?: AbstractMesh) => void, collisionIndex: number): void; - init(scene: Scene): void; - destroy(): void; - onMeshAdded(mesh: AbstractMesh): void; - onMeshUpdated: (mesh: AbstractMesh) => void; - onMeshRemoved(mesh: AbstractMesh): void; - onGeometryAdded(geometry: Geometry): void; - onGeometryUpdated: (geometry: Geometry) => void; - onGeometryDeleted(geometry: Geometry): void; - private _afterRender; - private _onMessageFromWorker; - } - class CollisionCoordinatorLegacy implements ICollisionCoordinator { - private _scene; - private _scaledPosition; - private _scaledVelocity; - private _finalPosition; - getNewPosition(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh?: AbstractMesh) => void, collisionIndex: number): void; - init(scene: Scene): void; - destroy(): void; - onMeshAdded(mesh: AbstractMesh): void; - onMeshUpdated(mesh: AbstractMesh): void; - onMeshRemoved(mesh: AbstractMesh): void; - onGeometryAdded(geometry: Geometry): void; - onGeometryUpdated(geometry: Geometry): void; - onGeometryDeleted(geometry: Geometry): void; - private _collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh?); - } -} - -declare namespace BABYLON { - var WorkerIncluded: boolean; - class CollisionCache { - private _meshes; - private _geometries; - getMeshes(): { - [n: number]: SerializedMesh; - }; - getGeometries(): { - [s: number]: SerializedGeometry; - }; - getMesh(id: any): SerializedMesh; - addMesh(mesh: SerializedMesh): void; - removeMesh(uniqueId: number): void; - getGeometry(id: string): SerializedGeometry; - addGeometry(geometry: SerializedGeometry): void; - removeGeometry(id: string): void; - } - class CollideWorker { - collider: Collider; - private _collisionCache; - private finalPosition; - private collisionsScalingMatrix; - private collisionTranformationMatrix; - constructor(collider: Collider, _collisionCache: CollisionCache, finalPosition: Vector3); - collideWithWorld(position: Vector3, velocity: Vector3, maximumRetry: number, excludedMeshUniqueId?: number): void; - private checkCollision(mesh); - private processCollisionsForSubMeshes(transformMatrix, mesh); - private collideForSubMesh(subMesh, transformMatrix, meshGeometry); - private checkSubmeshCollision(subMesh); - } - interface ICollisionDetector { - onInit(payload: InitPayload): void; - onUpdate(payload: UpdatePayload): void; - onCollision(payload: CollidePayload): void; - } - class CollisionDetectorTransferable implements ICollisionDetector { - private _collisionCache; - onInit(payload: InitPayload): void; - onUpdate(payload: UpdatePayload): void; - onCollision(payload: CollidePayload): void; - } -} - -declare namespace BABYLON { - class IntersectionInfo { - bu: number; - bv: number; - distance: number; - faceId: number; - subMeshId: number; - constructor(bu: number, bv: number, distance: number); - } - class PickingInfo { - hit: boolean; - distance: number; - pickedPoint: Vector3; - pickedMesh: AbstractMesh; - bu: number; - bv: number; - faceId: number; - subMeshId: number; - pickedSprite: Sprite; - getNormal(useWorldCoordinates?: boolean, useVerticesNormals?: boolean): Vector3; - getTextureCoordinates(): Vector2; - } -} - -declare namespace BABYLON { - class DebugLayer { - private _scene; - private _camera; - private _transformationMatrix; - private _enabled; - private _labelsEnabled; - private _displayStatistics; - private _displayTree; - private _displayLogs; - private _globalDiv; - private _statsDiv; - private _statsSubsetDiv; - private _optionsDiv; - private _optionsSubsetDiv; - private _logDiv; - private _logSubsetDiv; - private _treeDiv; - private _treeSubsetDiv; - private _drawingCanvas; - private _drawingContext; - private _rootElement; - _syncPositions: () => void; - private _syncData; - private _syncUI; - private _onCanvasClick; - private _clickPosition; - private _ratio; - private _identityMatrix; - private _showUI; - private _needToRefreshMeshesTree; - shouldDisplayLabel: (node: Node) => boolean; - shouldDisplayAxis: (mesh: Mesh) => boolean; - axisRatio: number; - accentColor: string; - customStatsFunction: () => string; - constructor(scene: Scene); - private _refreshMeshesTreeContent(); - private _renderSingleAxis(zero, unit, unitText, label, color); - private _renderAxis(projectedPosition, mesh, globalViewport); - private _renderLabel(text, projectedPosition, labelOffset, onClick, getFillStyle); - private _isClickInsideRect(x, y, width, height); - isVisible(): boolean; - hide(): void; - show(showUI?: boolean, camera?: Camera, rootElement?: HTMLElement): void; - private _clearLabels(); - private _generateheader(root, text); - private _generateTexBox(root, title, color); - private _generateAdvancedCheckBox(root, leftTitle, rightTitle, initialState, task, tag?); - private _generateCheckBox(root, title, initialState, task, tag?); - private _generateButton(root, title, task, tag?); - private _generateRadio(root, title, name, initialState, task, tag?); - private _generateDOMelements(); - private _displayStats(); - } -} - -declare namespace BABYLON { - class BoundingBox { - minimum: Vector3; - maximum: Vector3; - vectors: Vector3[]; - center: Vector3; - extendSize: Vector3; - directions: Vector3[]; - vectorsWorld: Vector3[]; - minimumWorld: Vector3; - maximumWorld: Vector3; - private _worldMatrix; - constructor(minimum: Vector3, maximum: Vector3); - getWorldMatrix(): Matrix; - _update(world: Matrix): void; - isInFrustum(frustumPlanes: Plane[]): boolean; - isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; - intersectsPoint(point: Vector3): boolean; - intersectsSphere(sphere: BoundingSphere): boolean; - intersectsMinMax(min: Vector3, max: Vector3): boolean; - static Intersects(box0: BoundingBox, box1: BoundingBox): boolean; - static IntersectsSphere(minPoint: Vector3, maxPoint: Vector3, sphereCenter: Vector3, sphereRadius: number): boolean; - static IsCompletelyInFrustum(boundingVectors: Vector3[], frustumPlanes: Plane[]): boolean; - static IsInFrustum(boundingVectors: Vector3[], frustumPlanes: Plane[]): boolean; - } -} - -declare namespace BABYLON { - class BoundingInfo { - minimum: Vector3; - maximum: Vector3; - boundingBox: BoundingBox; - boundingSphere: BoundingSphere; - private _isLocked; - constructor(minimum: Vector3, maximum: Vector3); - isLocked: boolean; - update(world: Matrix): void; - isInFrustum(frustumPlanes: Plane[]): boolean; - isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; - _checkCollision(collider: Collider): boolean; - intersectsPoint(point: Vector3): boolean; - intersects(boundingInfo: BoundingInfo, precise: boolean): boolean; - } -} - -declare namespace BABYLON { - class BoundingSphere { - minimum: Vector3; - maximum: Vector3; - center: Vector3; - radius: number; - centerWorld: Vector3; - radiusWorld: number; - private _tempRadiusVector; - constructor(minimum: Vector3, maximum: Vector3); - _update(world: Matrix): void; - isInFrustum(frustumPlanes: Plane[]): boolean; - intersectsPoint(point: Vector3): boolean; - static Intersects(sphere0: BoundingSphere, sphere1: BoundingSphere): boolean; - } -} - -declare namespace BABYLON { - class Layer { - name: string; - texture: Texture; - isBackground: boolean; - color: Color4; - scale: Vector2; - offset: Vector2; - onDispose: () => void; - alphaBlendingMode: number; - private _scene; - private _vertexDeclaration; - private _vertexStrideSize; - private _vertexBuffer; - private _indexBuffer; - private _effect; - constructor(name: string, imgUrl: string, scene: Scene, isBackground?: boolean, color?: Color4); - render(): void; - dispose(): void; - } -} - -declare namespace BABYLON { - class LensFlare { - size: number; - position: number; - color: Color3; - texture: Texture; - private _system; - constructor(size: number, position: number, color: any, imgUrl: string, system: LensFlareSystem); - dispose: () => void; - } -} - -declare namespace BABYLON { - class LensFlareSystem { - name: string; - lensFlares: LensFlare[]; - borderLimit: number; - meshesSelectionPredicate: (mesh: Mesh) => boolean; - layerMask: number; - private _scene; - private _emitter; - private _vertexDeclaration; - private _vertexStrideSize; - private _vertexBuffer; - private _indexBuffer; - private _effect; - private _positionX; - private _positionY; - private _isEnabled; - constructor(name: string, emitter: any, scene: Scene); - isEnabled: boolean; - getScene(): Scene; - getEmitter(): any; - setEmitter(newEmitter: any): void; - getEmitterPosition(): Vector3; - computeEffectivePosition(globalViewport: Viewport): boolean; - _isVisible(): boolean; - render(): boolean; - dispose(): void; - static Parse(parsedLensFlareSystem: any, scene: Scene, rootUrl: string): LensFlareSystem; - serialize(): any; - } -} - -declare namespace BABYLON { - class DirectionalLight extends Light implements IShadowLight { - direction: Vector3; - position: Vector3; - private _transformedDirection; - transformedPosition: Vector3; - private _worldMatrix; - shadowOrthoScale: number; - autoUpdateExtends: boolean; - private _orthoLeft; - private _orthoRight; - private _orthoTop; - private _orthoBottom; - constructor(name: string, direction: Vector3, scene: Scene); - getAbsolutePosition(): Vector3; - setDirectionToTarget(target: Vector3): Vector3; - setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; - supportsVSM(): boolean; - needRefreshPerFrame(): boolean; - needCube(): boolean; - getShadowDirection(faceIndex?: number): Vector3; - computeTransformedPosition(): boolean; - transferToEffect(effect: Effect, directionUniformName: string): void; - _getWorldMatrix(): Matrix; - serialize(): any; - } -} - -declare namespace BABYLON { - class HemisphericLight extends Light { - direction: Vector3; - groundColor: Color3; - private _worldMatrix; - constructor(name: string, direction: Vector3, scene: Scene); - setDirectionToTarget(target: Vector3): Vector3; - getShadowGenerator(): ShadowGenerator; - transferToEffect(effect: Effect, directionUniformName: string, groundColorUniformName: string): void; - _getWorldMatrix(): Matrix; - serialize(): any; - } -} - -declare namespace BABYLON { - interface IShadowLight { - id: string; - position: Vector3; - transformedPosition: Vector3; - name: string; - computeTransformedPosition(): boolean; - getScene(): Scene; - setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; - supportsVSM(): boolean; - needRefreshPerFrame(): boolean; - needCube(): boolean; - getShadowDirection(faceIndex?: number): Vector3; - _shadowGenerator: ShadowGenerator; - } - class Light extends Node { - diffuse: Color3; - specular: Color3; - intensity: number; - range: number; - includeOnlyWithLayerMask: number; - includedOnlyMeshes: AbstractMesh[]; - excludedMeshes: AbstractMesh[]; - excludeWithLayerMask: number; - _shadowGenerator: ShadowGenerator; - private _parentedWorldMatrix; - _excludedMeshesIds: string[]; - _includedOnlyMeshesIds: string[]; - constructor(name: string, scene: Scene); - getShadowGenerator(): ShadowGenerator; - getAbsolutePosition(): Vector3; - transferToEffect(effect: Effect, uniformName0?: string, uniformName1?: string): void; - _getWorldMatrix(): Matrix; - canAffectMesh(mesh: AbstractMesh): boolean; - getWorldMatrix(): Matrix; - dispose(): void; - serialize(): any; - static Parse(parsedLight: any, scene: Scene): Light; - } -} - -declare namespace BABYLON { - class PointLight extends Light implements IShadowLight { - position: Vector3; - private _worldMatrix; - transformedPosition: Vector3; - constructor(name: string, position: Vector3, scene: Scene); - getAbsolutePosition(): Vector3; - computeTransformedPosition(): boolean; - transferToEffect(effect: Effect, positionUniformName: string): void; - needCube(): boolean; - supportsVSM(): boolean; - needRefreshPerFrame(): boolean; - getShadowDirection(faceIndex?: number): Vector3; - setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; - _getWorldMatrix(): Matrix; - serialize(): any; - } -} - -declare namespace BABYLON { - class SpotLight extends Light implements IShadowLight { - position: Vector3; - direction: Vector3; - angle: number; - exponent: number; - transformedPosition: Vector3; - private _transformedDirection; - private _worldMatrix; - constructor(name: string, position: Vector3, direction: Vector3, angle: number, exponent: number, scene: Scene); - getAbsolutePosition(): Vector3; - setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; - needCube(): boolean; - supportsVSM(): boolean; - needRefreshPerFrame(): boolean; - getShadowDirection(faceIndex?: number): Vector3; - setDirectionToTarget(target: Vector3): Vector3; - computeTransformedPosition(): boolean; - transferToEffect(effect: Effect, positionUniformName: string, directionUniformName: string): void; - _getWorldMatrix(): Matrix; - serialize(): any; - } -} - -declare namespace BABYLON { - interface ISceneLoaderPlugin { - extensions: string; - importMesh: (meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => boolean; - load: (scene: Scene, data: string, rootUrl: string) => boolean; - } - class SceneLoader { - private static _ForceFullSceneLoadingForIncremental; - private static _ShowLoadingScreen; - static ForceFullSceneLoadingForIncremental: boolean; - static ShowLoadingScreen: boolean; - private static _registeredPlugins; - private static _getPluginForFilename(sceneFilename); - static RegisterPlugin(plugin: ISceneLoaderPlugin): void; - static ImportMesh(meshesNames: any, rootUrl: string, sceneFilename: string, scene: Scene, onsuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, progressCallBack?: () => void, onerror?: (scene: Scene, e: any) => void): void; - /** - * Load a scene - * @param rootUrl a string that defines the root url for scene and resources - * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene - * @param engine is the instance of BABYLON.Engine to use to create the scene - */ - static Load(rootUrl: string, sceneFilename: any, engine: Engine, onsuccess?: (scene: Scene) => void, progressCallBack?: any, onerror?: (scene: Scene) => void): void; - /** - * Append a scene - * @param rootUrl a string that defines the root url for scene and resources - * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene - * @param scene is the instance of BABYLON.Scene to append to - */ - static Append(rootUrl: string, sceneFilename: any, scene: Scene, onsuccess?: (scene: Scene) => void, progressCallBack?: any, onerror?: (scene: Scene) => void): void; - } -} - -declare namespace BABYLON { - class SIMDVector3 { - static TransformCoordinatesToRefSIMD(vector: Vector3, transformation: Matrix, result: Vector3): void; - static TransformCoordinatesFromFloatsToRefSIMD(x: number, y: number, z: number, transformation: Matrix, result: Vector3): void; - } - class SIMDMatrix { - multiplyToArraySIMD(other: Matrix, result: Matrix, offset?: number): void; - invertToRefSIMD(other: Matrix): Matrix; - static LookAtLHToRefSIMD(eyeRef: Vector3, targetRef: Vector3, upRef: Vector3, result: Matrix): void; - } - class SIMDHelper { - private static _isEnabled; - static IsEnabled: boolean; - static DisableSIMD(): void; - static EnableSIMD(): void; - } -} - -declare namespace BABYLON { - class Color3 { - r: number; - g: number; - b: number; - constructor(r?: number, g?: number, b?: number); - toString(): string; - toArray(array: number[], index?: number): Color3; - toColor4(alpha?: number): Color4; - asArray(): number[]; - toLuminance(): number; - multiply(otherColor: Color3): Color3; - multiplyToRef(otherColor: Color3, result: Color3): Color3; - equals(otherColor: Color3): boolean; - equalsFloats(r: number, g: number, b: number): boolean; - scale(scale: number): Color3; - scaleToRef(scale: number, result: Color3): Color3; - add(otherColor: Color3): Color3; - addToRef(otherColor: Color3, result: Color3): Color3; - subtract(otherColor: Color3): Color3; - subtractToRef(otherColor: Color3, result: Color3): Color3; - clone(): Color3; - copyFrom(source: Color3): Color3; - copyFromFloats(r: number, g: number, b: number): Color3; - toHexString(): string; - toLinearSpace(): Color3; - toLinearSpaceToRef(convertedColor: Color3): Color3; - toGammaSpace(): Color3; - toGammaSpaceToRef(convertedColor: Color3): Color3; - static FromHexString(hex: string): Color3; - static FromArray(array: number[], offset?: number): Color3; - static FromInts(r: number, g: number, b: number): Color3; - static Lerp(start: Color3, end: Color3, amount: number): Color3; - static Red(): Color3; - static Green(): Color3; - static Blue(): Color3; - static Black(): Color3; - static White(): Color3; - static Purple(): Color3; - static Magenta(): Color3; - static Yellow(): Color3; - static Gray(): Color3; - } - class Color4 { - r: number; - g: number; - b: number; - a: number; - constructor(r: number, g: number, b: number, a: number); - addInPlace(right: any): Color4; - asArray(): number[]; - toArray(array: number[], index?: number): Color4; - add(right: Color4): Color4; - subtract(right: Color4): Color4; - subtractToRef(right: Color4, result: Color4): Color4; - scale(scale: number): Color4; - scaleToRef(scale: number, result: Color4): Color4; - toString(): string; - clone(): Color4; - copyFrom(source: Color4): Color4; - toHexString(): string; - static FromHexString(hex: string): Color4; - static Lerp(left: Color4, right: Color4, amount: number): Color4; - static LerpToRef(left: Color4, right: Color4, amount: number, result: Color4): void; - static FromArray(array: number[], offset?: number): Color4; - static FromInts(r: number, g: number, b: number, a: number): Color4; - static CheckColors4(colors: number[], count: number): number[]; - } - class Vector2 { - x: number; - y: number; - constructor(x: number, y: number); - toString(): string; - toArray(array: number[], index?: number): Vector2; - asArray(): number[]; - copyFrom(source: Vector2): Vector2; - copyFromFloats(x: number, y: number): Vector2; - add(otherVector: Vector2): Vector2; - addVector3(otherVector: Vector3): Vector2; - subtract(otherVector: Vector2): Vector2; - subtractInPlace(otherVector: Vector2): Vector2; - multiplyInPlace(otherVector: Vector2): Vector2; - multiply(otherVector: Vector2): Vector2; - multiplyToRef(otherVector: Vector2, result: Vector2): Vector2; - multiplyByFloats(x: number, y: number): Vector2; - divide(otherVector: Vector2): Vector2; - divideToRef(otherVector: Vector2, result: Vector2): Vector2; - negate(): Vector2; - scaleInPlace(scale: number): Vector2; - scale(scale: number): Vector2; - equals(otherVector: Vector2): boolean; - equalsWithEpsilon(otherVector: Vector2, epsilon?: number): boolean; - length(): number; - lengthSquared(): number; - normalize(): Vector2; - clone(): Vector2; - static Zero(): Vector2; - static FromArray(array: number[] | Float32Array, offset?: number): Vector2; - static FromArrayToRef(array: number[] | Float32Array, offset: number, result: Vector2): void; - static CatmullRom(value1: Vector2, value2: Vector2, value3: Vector2, value4: Vector2, amount: number): Vector2; - static Clamp(value: Vector2, min: Vector2, max: Vector2): Vector2; - static Hermite(value1: Vector2, tangent1: Vector2, value2: Vector2, tangent2: Vector2, amount: number): Vector2; - static Lerp(start: Vector2, end: Vector2, amount: number): Vector2; - static Dot(left: Vector2, right: Vector2): number; - static Normalize(vector: Vector2): Vector2; - static Minimize(left: Vector2, right: Vector2): Vector2; - static Maximize(left: Vector2, right: Vector2): Vector2; - static Transform(vector: Vector2, transformation: Matrix): Vector2; - static Distance(value1: Vector2, value2: Vector2): number; - static DistanceSquared(value1: Vector2, value2: Vector2): number; - } - class Vector3 { - x: number; - y: number; - z: number; - constructor(x: number, y: number, z: number); - toString(): string; - asArray(): number[]; - toArray(array: number[] | Float32Array, index?: number): Vector3; - toQuaternion(): Quaternion; - addInPlace(otherVector: Vector3): Vector3; - add(otherVector: Vector3): Vector3; - addToRef(otherVector: Vector3, result: Vector3): Vector3; - subtractInPlace(otherVector: Vector3): Vector3; - subtract(otherVector: Vector3): Vector3; - subtractToRef(otherVector: Vector3, result: Vector3): Vector3; - subtractFromFloats(x: number, y: number, z: number): Vector3; - subtractFromFloatsToRef(x: number, y: number, z: number, result: Vector3): Vector3; - negate(): Vector3; - scaleInPlace(scale: number): Vector3; - scale(scale: number): Vector3; - scaleToRef(scale: number, result: Vector3): void; - equals(otherVector: Vector3): boolean; - equalsWithEpsilon(otherVector: Vector3, epsilon?: number): boolean; - equalsToFloats(x: number, y: number, z: number): boolean; - multiplyInPlace(otherVector: Vector3): Vector3; - multiply(otherVector: Vector3): Vector3; - multiplyToRef(otherVector: Vector3, result: Vector3): Vector3; - multiplyByFloats(x: number, y: number, z: number): Vector3; - divide(otherVector: Vector3): Vector3; - divideToRef(otherVector: Vector3, result: Vector3): Vector3; - MinimizeInPlace(other: Vector3): Vector3; - MaximizeInPlace(other: Vector3): Vector3; - length(): number; - lengthSquared(): number; - normalize(): Vector3; - clone(): Vector3; - copyFrom(source: Vector3): Vector3; - copyFromFloats(x: number, y: number, z: number): Vector3; - static GetClipFactor(vector0: Vector3, vector1: Vector3, axis: Vector3, size: any): number; - static FromArray(array: number[] | Float32Array, offset?: number): Vector3; - static FromFloatArray(array: Float32Array, offset?: number): Vector3; - static FromArrayToRef(array: number[] | Float32Array, offset: number, result: Vector3): void; - static FromFloatArrayToRef(array: Float32Array, offset: number, result: Vector3): void; - static FromFloatsToRef(x: number, y: number, z: number, result: Vector3): void; - static Zero(): Vector3; - static Up(): Vector3; - static TransformCoordinates(vector: Vector3, transformation: Matrix): Vector3; - static TransformCoordinatesToRef(vector: Vector3, transformation: Matrix, result: Vector3): void; - static TransformCoordinatesFromFloatsToRef(x: number, y: number, z: number, transformation: Matrix, result: Vector3): void; - static TransformNormal(vector: Vector3, transformation: Matrix): Vector3; - static TransformNormalToRef(vector: Vector3, transformation: Matrix, result: Vector3): void; - static TransformNormalFromFloatsToRef(x: number, y: number, z: number, transformation: Matrix, result: Vector3): void; - static CatmullRom(value1: Vector3, value2: Vector3, value3: Vector3, value4: Vector3, amount: number): Vector3; - static Clamp(value: Vector3, min: Vector3, max: Vector3): Vector3; - static Hermite(value1: Vector3, tangent1: Vector3, value2: Vector3, tangent2: Vector3, amount: number): Vector3; - static Lerp(start: Vector3, end: Vector3, amount: number): Vector3; - static Dot(left: Vector3, right: Vector3): number; - static Cross(left: Vector3, right: Vector3): Vector3; - static CrossToRef(left: Vector3, right: Vector3, result: Vector3): void; - static Normalize(vector: Vector3): Vector3; - static NormalizeToRef(vector: Vector3, result: Vector3): void; - static Project(vector: Vector3, world: Matrix, transform: Matrix, viewport: Viewport): Vector3; - static UnprojectFromTransform(source: Vector3, viewportWidth: number, viewportHeight: number, world: Matrix, transform: Matrix): Vector3; - static Unproject(source: Vector3, viewportWidth: number, viewportHeight: number, world: Matrix, view: Matrix, projection: Matrix): Vector3; - static Minimize(left: Vector3, right: Vector3): Vector3; - static Maximize(left: Vector3, right: Vector3): Vector3; - static Distance(value1: Vector3, value2: Vector3): number; - static DistanceSquared(value1: Vector3, value2: Vector3): number; - static Center(value1: Vector3, value2: Vector3): Vector3; - /** - * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system), - * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply - * to something in order to rotate it from its local system to the given target system. - */ - static RotationFromAxis(axis1: Vector3, axis2: Vector3, axis3: Vector3): Vector3; - /** - * The same than RotationFromAxis but updates the passed ref Vector3 parameter. - */ - static RotationFromAxisToRef(axis1: Vector3, axis2: Vector3, axis3: Vector3, ref: Vector3): void; - } - class Vector4 { - x: number; - y: number; - z: number; - w: number; - constructor(x: number, y: number, z: number, w: number); - toString(): string; - asArray(): number[]; - toArray(array: number[], index?: number): Vector4; - addInPlace(otherVector: Vector4): Vector4; - add(otherVector: Vector4): Vector4; - addToRef(otherVector: Vector4, result: Vector4): Vector4; - subtractInPlace(otherVector: Vector4): Vector4; - subtract(otherVector: Vector4): Vector4; - subtractToRef(otherVector: Vector4, result: Vector4): Vector4; - subtractFromFloats(x: number, y: number, z: number, w: number): Vector4; - subtractFromFloatsToRef(x: number, y: number, z: number, w: number, result: Vector4): Vector4; - negate(): Vector4; - scaleInPlace(scale: number): Vector4; - scale(scale: number): Vector4; - scaleToRef(scale: number, result: Vector4): void; - equals(otherVector: Vector4): boolean; - equalsWithEpsilon(otherVector: Vector4, epsilon?: number): boolean; - equalsToFloats(x: number, y: number, z: number, w: number): boolean; - multiplyInPlace(otherVector: Vector4): Vector4; - multiply(otherVector: Vector4): Vector4; - multiplyToRef(otherVector: Vector4, result: Vector4): Vector4; - multiplyByFloats(x: number, y: number, z: number, w: number): Vector4; - divide(otherVector: Vector4): Vector4; - divideToRef(otherVector: Vector4, result: Vector4): Vector4; - MinimizeInPlace(other: Vector4): Vector4; - MaximizeInPlace(other: Vector4): Vector4; - length(): number; - lengthSquared(): number; - normalize(): Vector4; - clone(): Vector4; - copyFrom(source: Vector4): Vector4; - copyFromFloats(x: number, y: number, z: number, w: number): Vector4; - static FromArray(array: number[], offset?: number): Vector4; - static FromArrayToRef(array: number[], offset: number, result: Vector4): void; - static FromFloatArrayToRef(array: Float32Array, offset: number, result: Vector4): void; - static FromFloatsToRef(x: number, y: number, z: number, w: number, result: Vector4): void; - static Zero(): Vector4; - static Normalize(vector: Vector4): Vector4; - static NormalizeToRef(vector: Vector4, result: Vector4): void; - static Minimize(left: Vector4, right: Vector4): Vector4; - static Maximize(left: Vector4, right: Vector4): Vector4; - static Distance(value1: Vector4, value2: Vector4): number; - static DistanceSquared(value1: Vector4, value2: Vector4): number; - static Center(value1: Vector4, value2: Vector4): Vector4; - } - class Quaternion { - x: number; - y: number; - z: number; - w: number; - constructor(x?: number, y?: number, z?: number, w?: number); - toString(): string; - asArray(): number[]; - equals(otherQuaternion: Quaternion): boolean; - clone(): Quaternion; - copyFrom(other: Quaternion): Quaternion; - copyFromFloats(x: number, y: number, z: number, w: number): Quaternion; - add(other: Quaternion): Quaternion; - subtract(other: Quaternion): Quaternion; - scale(value: number): Quaternion; - multiply(q1: Quaternion): Quaternion; - multiplyToRef(q1: Quaternion, result: Quaternion): Quaternion; - multiplyInPlace(q1: Quaternion): Quaternion; - length(): number; - normalize(): Quaternion; - toEulerAngles(order?: string): Vector3; - toEulerAnglesToRef(result: Vector3, order?: string): Quaternion; - toRotationMatrix(result: Matrix): Quaternion; - fromRotationMatrix(matrix: Matrix): Quaternion; - static FromRotationMatrix(matrix: Matrix): Quaternion; - static FromRotationMatrixToRef(matrix: Matrix, result: Quaternion): void; - static Inverse(q: Quaternion): Quaternion; - static Identity(): Quaternion; - static RotationAxis(axis: Vector3, angle: number): Quaternion; - static FromArray(array: number[], offset?: number): Quaternion; - static RotationYawPitchRoll(yaw: number, pitch: number, roll: number): Quaternion; - static RotationYawPitchRollToRef(yaw: number, pitch: number, roll: number, result: Quaternion): void; - static RotationAlphaBetaGamma(alpha: number, beta: number, gamma: number): Quaternion; - static RotationAlphaBetaGammaToRef(alpha: number, beta: number, gamma: number, result: Quaternion): void; - static Slerp(left: Quaternion, right: Quaternion, amount: number): Quaternion; - } - class Matrix { - private static _tempQuaternion; - private static _xAxis; - private static _yAxis; - private static _zAxis; - m: Float32Array; - isIdentity(): boolean; - determinant(): number; - toArray(): Float32Array; - asArray(): Float32Array; - invert(): Matrix; - reset(): Matrix; - add(other: Matrix): Matrix; - addToRef(other: Matrix, result: Matrix): Matrix; - addToSelf(other: Matrix): Matrix; - invertToRef(other: Matrix): Matrix; - setTranslation(vector3: Vector3): Matrix; - multiply(other: Matrix): Matrix; - copyFrom(other: Matrix): Matrix; - copyToArray(array: Float32Array, offset?: number): Matrix; - multiplyToRef(other: Matrix, result: Matrix): Matrix; - multiplyToArray(other: Matrix, result: Float32Array, offset: number): Matrix; - equals(value: Matrix): boolean; - clone(): Matrix; - decompose(scale: Vector3, rotation: Quaternion, translation: Vector3): boolean; - static FromArray(array: number[], offset?: number): Matrix; - static FromArrayToRef(array: number[], offset: number, result: Matrix): void; - static FromFloat32ArrayToRefScaled(array: Float32Array, offset: number, scale: number, result: Matrix): void; - static FromValuesToRef(initialM11: number, initialM12: number, initialM13: number, initialM14: number, initialM21: number, initialM22: number, initialM23: number, initialM24: number, initialM31: number, initialM32: number, initialM33: number, initialM34: number, initialM41: number, initialM42: number, initialM43: number, initialM44: number, result: Matrix): void; - static FromValues(initialM11: number, initialM12: number, initialM13: number, initialM14: number, initialM21: number, initialM22: number, initialM23: number, initialM24: number, initialM31: number, initialM32: number, initialM33: number, initialM34: number, initialM41: number, initialM42: number, initialM43: number, initialM44: number): Matrix; - static Compose(scale: Vector3, rotation: Quaternion, translation: Vector3): Matrix; - static Identity(): Matrix; - static IdentityToRef(result: Matrix): void; - static Zero(): Matrix; - static RotationX(angle: number): Matrix; - static Invert(source: Matrix): Matrix; - static RotationXToRef(angle: number, result: Matrix): void; - static RotationY(angle: number): Matrix; - static RotationYToRef(angle: number, result: Matrix): void; - static RotationZ(angle: number): Matrix; - static RotationZToRef(angle: number, result: Matrix): void; - static RotationAxis(axis: Vector3, angle: number): Matrix; - static RotationAxisToRef(axis: Vector3, angle: number, result: Matrix): void; - static RotationYawPitchRoll(yaw: number, pitch: number, roll: number): Matrix; - static RotationYawPitchRollToRef(yaw: number, pitch: number, roll: number, result: Matrix): void; - static Scaling(x: number, y: number, z: number): Matrix; - static ScalingToRef(x: number, y: number, z: number, result: Matrix): void; - static Translation(x: number, y: number, z: number): Matrix; - static TranslationToRef(x: number, y: number, z: number, result: Matrix): void; - static Lerp(startValue: Matrix, endValue: Matrix, gradient: number): Matrix; - static LookAtLH(eye: Vector3, target: Vector3, up: Vector3): Matrix; - static LookAtLHToRef(eye: Vector3, target: Vector3, up: Vector3, result: Matrix): void; - static OrthoLH(width: number, height: number, znear: number, zfar: number): Matrix; - static OrthoLHToRef(width: number, height: number, znear: number, zfar: number, result: Matrix): void; - static OrthoOffCenterLH(left: number, right: number, bottom: number, top: number, znear: number, zfar: number): Matrix; - static OrthoOffCenterLHToRef(left: number, right: any, bottom: number, top: number, znear: number, zfar: number, result: Matrix): void; - static PerspectiveLH(width: number, height: number, znear: number, zfar: number): Matrix; - static PerspectiveFovLH(fov: number, aspect: number, znear: number, zfar: number): Matrix; - static PerspectiveFovLHToRef(fov: number, aspect: number, znear: number, zfar: number, result: Matrix, fovMode?: number): void; - static GetFinalMatrix(viewport: Viewport, world: Matrix, view: Matrix, projection: Matrix, zmin: number, zmax: number): Matrix; - static GetAsMatrix2x2(matrix: Matrix): Float32Array; - static GetAsMatrix3x3(matrix: Matrix): Float32Array; - static Transpose(matrix: Matrix): Matrix; - static Reflection(plane: Plane): Matrix; - static ReflectionToRef(plane: Plane, result: Matrix): void; - } - class Plane { - normal: Vector3; - d: number; - constructor(a: number, b: number, c: number, d: number); - asArray(): number[]; - clone(): Plane; - normalize(): Plane; - transform(transformation: Matrix): Plane; - dotCoordinate(point: any): number; - copyFromPoints(point1: Vector3, point2: Vector3, point3: Vector3): Plane; - isFrontFacingTo(direction: Vector3, epsilon: number): boolean; - signedDistanceTo(point: Vector3): number; - static FromArray(array: number[]): Plane; - static FromPoints(point1: any, point2: any, point3: any): Plane; - static FromPositionAndNormal(origin: Vector3, normal: Vector3): Plane; - static SignedDistanceToPlaneFromPositionAndNormal(origin: Vector3, normal: Vector3, point: Vector3): number; - } - class Viewport { - x: number; - y: number; - width: number; - height: number; - constructor(x: number, y: number, width: number, height: number); - toGlobal(engine: Engine): Viewport; - toScreenGlobal(engine: Engine): Viewport; - } - class Frustum { - static GetPlanes(transform: Matrix): Plane[]; - static GetPlanesToRef(transform: Matrix, frustumPlanes: Plane[]): void; - } - class Ray { - origin: Vector3; - direction: Vector3; - length: number; - private _edge1; - private _edge2; - private _pvec; - private _tvec; - private _qvec; - constructor(origin: Vector3, direction: Vector3, length?: number); - intersectsBoxMinMax(minimum: Vector3, maximum: Vector3): boolean; - intersectsBox(box: BoundingBox): boolean; - intersectsSphere(sphere: any): boolean; - intersectsTriangle(vertex0: Vector3, vertex1: Vector3, vertex2: Vector3): IntersectionInfo; - static CreateNew(x: number, y: number, viewportWidth: number, viewportHeight: number, world: Matrix, view: Matrix, projection: Matrix): Ray; - /** - * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be - * transformed to the given world matrix. - * @param origin The origin point - * @param end The end point - * @param world a matrix to transform the ray to. Default is the identity matrix. - */ - static CreateNewFromTo(origin: Vector3, end: Vector3, world?: Matrix): Ray; - static Transform(ray: Ray, matrix: Matrix): Ray; - } - enum Space { - LOCAL = 0, - WORLD = 1, - } - class Axis { - static X: Vector3; - static Y: Vector3; - static Z: Vector3; - } - class BezierCurve { - static interpolate(t: number, x1: number, y1: number, x2: number, y2: number): number; - } - enum Orientation { - CW = 0, - CCW = 1, - } - class Angle { - private _radians; - constructor(radians: number); - degrees: () => number; - radians: () => number; - static BetweenTwoPoints(a: Vector2, b: Vector2): Angle; - static FromRadians(radians: number): Angle; - static FromDegrees(degrees: number): Angle; - } - class Arc2 { - startPoint: Vector2; - midPoint: Vector2; - endPoint: Vector2; - centerPoint: Vector2; - radius: number; - angle: Angle; - startAngle: Angle; - orientation: Orientation; - constructor(startPoint: Vector2, midPoint: Vector2, endPoint: Vector2); - } - class PathCursor { - private path; - private _onchange; - value: number; - animations: Animation[]; - constructor(path: Path2); - getPoint(): Vector3; - moveAhead(step?: number): PathCursor; - moveBack(step?: number): PathCursor; - move(step: number): PathCursor; - private ensureLimits(); - private markAsDirty(propertyName); - private raiseOnChange(); - onchange(f: (cursor: PathCursor) => void): PathCursor; - } - class Path2 { - private _points; - private _length; - closed: boolean; - constructor(x: number, y: number); - addLineTo(x: number, y: number): Path2; - addArcTo(midX: number, midY: number, endX: number, endY: number, numberOfSegments?: number): Path2; - close(): Path2; - length(): number; - getPoints(): Vector2[]; - getPointAtLengthPosition(normalizedLengthPosition: number): Vector2; - static StartingAt(x: number, y: number): Path2; - } - class Path3D { - path: Vector3[]; - private _curve; - private _distances; - private _tangents; - private _normals; - private _binormals; - private _raw; - /** - * new Path3D(path, normal, raw) - * path : an array of Vector3, the curve axis of the Path3D - * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal. - * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed. - */ - constructor(path: Vector3[], firstNormal?: Vector3, raw?: boolean); - getCurve(): Vector3[]; - getTangents(): Vector3[]; - getNormals(): Vector3[]; - getBinormals(): Vector3[]; - getDistances(): number[]; - update(path: Vector3[], firstNormal?: Vector3): Path3D; - private _compute(firstNormal); - private _getFirstNonNullVector(index); - private _getLastNonNullVector(index); - private _normalVector(v0, vt, va); - } - class Curve3 { - private _points; - private _length; - static CreateQuadraticBezier(v0: Vector3, v1: Vector3, v2: Vector3, nbPoints: number): Curve3; - static CreateCubicBezier(v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3, nbPoints: number): Curve3; - static CreateHermiteSpline(p1: Vector3, t1: Vector3, p2: Vector3, t2: Vector3, nbPoints: number): Curve3; - constructor(points: Vector3[]); - getPoints(): Vector3[]; - length(): number; - continue(curve: Curve3): Curve3; - private _computeLength(path); - } - class PositionNormalVertex { - position: Vector3; - normal: Vector3; - constructor(position?: Vector3, normal?: Vector3); - clone(): PositionNormalVertex; - } - class PositionNormalTextureVertex { - position: Vector3; - normal: Vector3; - uv: Vector2; - constructor(position?: Vector3, normal?: Vector3, uv?: Vector2); - clone(): PositionNormalTextureVertex; - } - class Tmp { - static Vector2: Vector2[]; - static Vector3: Vector3[]; - static Vector4: Vector4[]; - static Quaternion: Quaternion[]; - static Matrix: Matrix[]; - } -} - -declare namespace BABYLON { - class EffectFallbacks { - private _defines; - private _currentRank; - private _maxRank; - private _mesh; - private _meshRank; - addFallback(rank: number, define: string): void; - addCPUSkinningFallback(rank: number, mesh: BABYLON.AbstractMesh): void; - isMoreFallbacks: boolean; - reduce(currentDefines: string): string; - } - class Effect { - name: any; - defines: string; - onCompiled: (effect: Effect) => void; - onError: (effect: Effect, errors: string) => void; - onBind: (effect: Effect) => void; - private _engine; - private _uniformsNames; - private _samplers; - private _isReady; - private _compilationError; - private _attributesNames; - private _attributes; - private _uniforms; - _key: string; - private _program; - private _valueCache; - constructor(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], engine: any, defines?: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void); - isReady(): boolean; - getProgram(): WebGLProgram; - getAttributesNames(): string[]; - getAttributeLocation(index: number): number; - getAttributeLocationByName(name: string): number; - getAttributesCount(): number; - getUniformIndex(uniformName: string): number; - getUniform(uniformName: string): WebGLUniformLocation; - getSamplers(): string[]; - getCompilationError(): string; - _loadVertexShader(vertex: any, callback: (data: any) => void): void; - _loadFragmentShader(fragment: any, callback: (data: any) => void): void; - private _dumpShadersName(); - private _prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks?); - isSupported: boolean; - _bindTexture(channel: string, texture: WebGLTexture): void; - setTexture(channel: string, texture: BaseTexture): void; - setTextureFromPostProcess(channel: string, postProcess: PostProcess): void; - _cacheMatrix(uniformName: any, matrix: any): void; - _cacheFloat2(uniformName: string, x: number, y: number): void; - _cacheFloat3(uniformName: string, x: number, y: number, z: number): void; - _cacheFloat4(uniformName: string, x: number, y: number, z: number, w: number): void; - setArray(uniformName: string, array: number[]): Effect; - setArray2(uniformName: string, array: number[]): Effect; - setArray3(uniformName: string, array: number[]): Effect; - setArray4(uniformName: string, array: number[]): Effect; - setMatrices(uniformName: string, matrices: Float32Array): Effect; - setMatrix(uniformName: string, matrix: Matrix): Effect; - setMatrix3x3(uniformName: string, matrix: Float32Array): Effect; - setMatrix2x2(uniformname: string, matrix: Float32Array): Effect; - setFloat(uniformName: string, value: number): Effect; - setBool(uniformName: string, bool: boolean): Effect; - setVector2(uniformName: string, vector2: Vector2): Effect; - setFloat2(uniformName: string, x: number, y: number): Effect; - setVector3(uniformName: string, vector3: Vector3): Effect; - setFloat3(uniformName: string, x: number, y: number, z: number): Effect; - setVector4(uniformName: string, vector4: Vector4): Effect; - setFloat4(uniformName: string, x: number, y: number, z: number, w: number): Effect; - setColor3(uniformName: string, color3: Color3): Effect; - setColor4(uniformName: string, color3: Color3, alpha: number): Effect; - static ShadersStore: {}; - } -} - -declare namespace BABYLON { - class MaterialDefines { - _keys: string[]; - isEqual(other: MaterialDefines): boolean; - cloneTo(other: MaterialDefines): void; - reset(): void; - toString(): string; - } - class Material { - name: string; - private static _TriangleFillMode; - private static _WireFrameFillMode; - private static _PointFillMode; - static TriangleFillMode: number; - static WireFrameFillMode: number; - static PointFillMode: number; - private static _ClockWiseSideOrientation; - private static _CounterClockWiseSideOrientation; - static ClockWiseSideOrientation: number; - static CounterClockWiseSideOrientation: number; - id: string; - checkReadyOnEveryCall: boolean; - checkReadyOnlyOnce: boolean; - state: string; - alpha: number; - backFaceCulling: boolean; - sideOrientation: number; - onCompiled: (effect: Effect) => void; - onError: (effect: Effect, errors: string) => void; - onDispose: () => void; - onBind: (material: Material, mesh: Mesh) => void; - getRenderTargetTextures: () => SmartArray; - alphaMode: number; - disableDepthWrite: boolean; - fogEnabled: boolean; - _effect: Effect; - _wasPreviouslyReady: boolean; - private _scene; - private _fillMode; - private _cachedDepthWriteState; - pointSize: number; - zOffset: number; - wireframe: boolean; - pointsCloud: boolean; - fillMode: number; - constructor(name: string, scene: Scene, doNotAdd?: boolean); - isFrozen: boolean; - freeze(): void; - unfreeze(): void; - isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean; - getEffect(): Effect; - getScene(): Scene; - needAlphaBlending(): boolean; - needAlphaTesting(): boolean; - getAlphaTestTexture(): BaseTexture; - trackCreation(onCompiled: (effect: Effect) => void, onError: (effect: Effect, errors: string) => void): void; - markDirty(): void; - _preBind(): void; - bind(world: Matrix, mesh?: Mesh): void; - bindOnlyWorldMatrix(world: Matrix): void; - unbind(): void; - clone(name: string): Material; - getBindedMeshes(): AbstractMesh[]; - dispose(forceDisposeEffect?: boolean): void; - copyTo(other: Material): void; - serialize(): any; - static ParseMultiMaterial(parsedMultiMaterial: any, scene: Scene): MultiMaterial; - static Parse(parsedMaterial: any, scene: Scene, rootUrl: string): any; - } -} - -declare namespace BABYLON { - class MultiMaterial extends Material { - subMaterials: Material[]; - constructor(name: string, scene: Scene); - getSubMaterial(index: any): Material; - isReady(mesh?: AbstractMesh): boolean; - clone(name: string, cloneChildren?: boolean): MultiMaterial; - serialize(): any; - } -} - -declare namespace BABYLON { - class ShaderMaterial extends Material { - private _shaderPath; - private _options; - private _textures; - private _floats; - private _floatsArrays; - private _colors3; - private _colors4; - private _vectors2; - private _vectors3; - private _vectors4; - private _matrices; - private _matrices3x3; - private _matrices2x2; - private _cachedWorldViewMatrix; - private _renderId; - constructor(name: string, scene: Scene, shaderPath: any, options: any); - needAlphaBlending(): boolean; - needAlphaTesting(): boolean; - private _checkUniform(uniformName); - setTexture(name: string, texture: Texture): ShaderMaterial; - setFloat(name: string, value: number): ShaderMaterial; - setFloats(name: string, value: number[]): ShaderMaterial; - setColor3(name: string, value: Color3): ShaderMaterial; - setColor4(name: string, value: Color4): ShaderMaterial; - setVector2(name: string, value: Vector2): ShaderMaterial; - setVector3(name: string, value: Vector3): ShaderMaterial; - setVector4(name: string, value: Vector4): ShaderMaterial; - setMatrix(name: string, value: Matrix): ShaderMaterial; - setMatrix3x3(name: string, value: Float32Array): ShaderMaterial; - setMatrix2x2(name: string, value: Float32Array): ShaderMaterial; - isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean; - bindOnlyWorldMatrix(world: Matrix): void; - bind(world: Matrix, mesh?: Mesh): void; - clone(name: string): ShaderMaterial; - dispose(forceDisposeEffect?: boolean): void; - serialize(): any; - static Parse(source: any, scene: Scene, rootUrl: string): ShaderMaterial; - } -} - -declare namespace BABYLON { - class FresnelParameters { - isEnabled: boolean; - leftColor: Color3; - rightColor: Color3; - bias: number; - power: number; - clone(): FresnelParameters; - serialize(): any; - static Parse(parsedFresnelParameters: any): FresnelParameters; - } - class StandardMaterial extends Material { - diffuseTexture: BaseTexture; - ambientTexture: BaseTexture; - opacityTexture: BaseTexture; - reflectionTexture: BaseTexture; - emissiveTexture: BaseTexture; - specularTexture: BaseTexture; - bumpTexture: BaseTexture; - lightmapTexture: BaseTexture; - ambientColor: Color3; - diffuseColor: Color3; - specularColor: Color3; - specularPower: number; - emissiveColor: Color3; - useAlphaFromDiffuseTexture: boolean; - useEmissiveAsIllumination: boolean; - linkEmissiveWithDiffuse: boolean; - useReflectionFresnelFromSpecular: boolean; - useSpecularOverAlpha: boolean; - disableLighting: boolean; - roughness: number; - useLightmapAsShadowmap: boolean; - diffuseFresnelParameters: FresnelParameters; - opacityFresnelParameters: FresnelParameters; - reflectionFresnelParameters: FresnelParameters; - emissiveFresnelParameters: FresnelParameters; - useGlossinessFromSpecularMapAlpha: boolean; - private _renderTargets; - private _worldViewProjectionMatrix; - private _globalAmbientColor; - private _renderId; - private _defines; - private _cachedDefines; - private _useLogarithmicDepth; - constructor(name: string, scene: Scene); - useLogarithmicDepth: boolean; - needAlphaBlending(): boolean; - needAlphaTesting(): boolean; - private _shouldUseAlphaFromDiffuseTexture(); - getAlphaTestTexture(): BaseTexture; - private _checkCache(scene, mesh?, useInstances?); - static PrepareDefinesForLights(scene: Scene, mesh: AbstractMesh, defines: MaterialDefines): boolean; - private static _scaledDiffuse; - private static _scaledSpecular; - static BindLights(scene: Scene, mesh: AbstractMesh, effect: Effect, defines: MaterialDefines): void; - isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean; - unbind(): void; - bindOnlyWorldMatrix(world: Matrix): void; - bind(world: Matrix, mesh?: Mesh): void; - getAnimatables(): IAnimatable[]; - dispose(forceDisposeEffect?: boolean): void; - clone(name: string): StandardMaterial; - serialize(): any; - static DiffuseTextureEnabled: boolean; - static AmbientTextureEnabled: boolean; - static OpacityTextureEnabled: boolean; - static ReflectionTextureEnabled: boolean; - static EmissiveTextureEnabled: boolean; - static SpecularTextureEnabled: boolean; - static BumpTextureEnabled: boolean; - static FresnelEnabled: boolean; - static LightmapEnabled: boolean; - static Parse(source: any, scene: Scene, rootUrl: string): StandardMaterial; - } -} - -declare namespace BABYLON { - class AbstractMesh extends Node implements IDisposable { - private static _BILLBOARDMODE_NONE; - private static _BILLBOARDMODE_X; - private static _BILLBOARDMODE_Y; - private static _BILLBOARDMODE_Z; - private static _BILLBOARDMODE_ALL; - static BILLBOARDMODE_NONE: number; - static BILLBOARDMODE_X: number; - static BILLBOARDMODE_Y: number; - static BILLBOARDMODE_Z: number; - static BILLBOARDMODE_ALL: number; - definedFacingForward: boolean; - position: Vector3; - rotation: Vector3; - rotationQuaternion: Quaternion; - scaling: Vector3; - billboardMode: number; - visibility: number; - alphaIndex: number; - infiniteDistance: boolean; - isVisible: boolean; - isPickable: boolean; - showBoundingBox: boolean; - showSubMeshesBoundingBox: boolean; - onDispose: any; - isBlocker: boolean; - renderingGroupId: number; - material: Material; - receiveShadows: boolean; - actionManager: ActionManager; - renderOutline: boolean; - outlineColor: Color3; - outlineWidth: number; - renderOverlay: boolean; - overlayColor: Color3; - overlayAlpha: number; - hasVertexAlpha: boolean; - useVertexColors: boolean; - applyFog: boolean; - computeBonesUsingShaders: boolean; - scalingDeterminant: number; - numBoneInfluencers: number; - useOctreeForRenderingSelection: boolean; - useOctreeForPicking: boolean; - useOctreeForCollisions: boolean; - layerMask: number; - alwaysSelectAsActiveMesh: boolean; - _physicImpostor: number; - _physicsMass: number; - _physicsFriction: number; - _physicRestitution: number; - onPhysicsCollide: (collidedMesh: AbstractMesh, contact: any) => void; - private _checkCollisions; - ellipsoid: Vector3; - ellipsoidOffset: Vector3; - private _collider; - private _oldPositionForCollisions; - private _diffPositionForCollisions; - private _newPositionForCollisions; - onCollide: (collidedMesh: AbstractMesh) => void; - onCollisionPositionChange: (newPosition: Vector3) => void; - private _meshToBoneReferal; - edgesWidth: number; - edgesColor: Color4; - _edgesRenderer: EdgesRenderer; - private _localWorld; - _worldMatrix: Matrix; - private _rotateYByPI; - private _absolutePosition; - private _collisionsTransformMatrix; - private _collisionsScalingMatrix; - _positions: Vector3[]; - private _isDirty; - _masterMesh: AbstractMesh; - _materialDefines: MaterialDefines; - _boundingInfo: BoundingInfo; - private _pivotMatrix; - _isDisposed: boolean; - _renderId: number; - subMeshes: SubMesh[]; - _submeshesOctree: Octree; - _intersectionsInProgress: AbstractMesh[]; - private _onAfterWorldMatrixUpdate; - private _isWorldMatrixFrozen; - _unIndexed: boolean; - _poseMatrix: Matrix; - _waitingActions: any; - _waitingFreezeWorldMatrix: boolean; - private _skeleton; - _bonesTransformMatrices: Float32Array; - skeleton: Skeleton; - constructor(name: string, scene: Scene); - updatePoseMatrix(matrix: Matrix): void; - getPoseMatrix(): Matrix; - disableEdgesRendering(): void; - enableEdgesRendering(epsilon?: number, checkVerticesInsteadOfIndices?: boolean): void; - isBlocked: boolean; - getLOD(camera: Camera): AbstractMesh; - getTotalVertices(): number; - getIndices(): number[] | Int32Array; - getVerticesData(kind: string): number[] | Float32Array; - isVerticesDataPresent(kind: string): boolean; - getBoundingInfo(): BoundingInfo; - useBones: boolean; - _preActivate(): void; - _activate(renderId: number): void; - getWorldMatrix(): Matrix; - worldMatrixFromCache: Matrix; - absolutePosition: Vector3; - freezeWorldMatrix(): void; - unfreezeWorldMatrix(): void; - isWorldMatrixFrozen: boolean; - rotate(axis: Vector3, amount: number, space?: Space): void; - translate(axis: Vector3, distance: number, space?: Space): void; - getAbsolutePosition(): Vector3; - setAbsolutePosition(absolutePosition: Vector3): void; - /** - * Perform relative position change from the point of view of behind the front of the mesh. - * This is performed taking into account the meshes current rotation, so you do not have to care. - * Supports definition of mesh facing forward or backward. - * @param {number} amountRight - * @param {number} amountUp - * @param {number} amountForward - */ - movePOV(amountRight: number, amountUp: number, amountForward: number): void; - /** - * Calculate relative position change from the point of view of behind the front of the mesh. - * This is performed taking into account the meshes current rotation, so you do not have to care. - * Supports definition of mesh facing forward or backward. - * @param {number} amountRight - * @param {number} amountUp - * @param {number} amountForward - */ - calcMovePOV(amountRight: number, amountUp: number, amountForward: number): Vector3; - /** - * Perform relative rotation change from the point of view of behind the front of the mesh. - * Supports definition of mesh facing forward or backward. - * @param {number} flipBack - * @param {number} twirlClockwise - * @param {number} tiltRight - */ - rotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): void; - /** - * Calculate relative rotation change from the point of view of behind the front of the mesh. - * Supports definition of mesh facing forward or backward. - * @param {number} flipBack - * @param {number} twirlClockwise - * @param {number} tiltRight - */ - calcRotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): Vector3; - setPivotMatrix(matrix: Matrix): void; - getPivotMatrix(): Matrix; - _isSynchronized(): boolean; - _initCache(): void; - markAsDirty(property: string): void; - _updateBoundingInfo(): void; - _updateSubMeshesBoundingInfo(matrix: Matrix): void; - computeWorldMatrix(force?: boolean): Matrix; - /** - * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated - * @param func: callback function to add - */ - registerAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): void; - unregisterAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): void; - setPositionWithLocalVector(vector3: Vector3): void; - getPositionExpressedInLocalSpace(): Vector3; - locallyTranslate(vector3: Vector3): void; - lookAt(targetPoint: Vector3, yawCor: number, pitchCor: number, rollCor: number): void; - attachToBone(bone: Bone, affectedMesh: AbstractMesh): void; - detachFromBone(): void; - isInFrustum(frustumPlanes: Plane[]): boolean; - isCompletelyInFrustum(camera?: Camera): boolean; - intersectsMesh(mesh: AbstractMesh, precise?: boolean): boolean; - intersectsPoint(point: Vector3): boolean; - setPhysicsState(impostor?: any, options?: PhysicsBodyCreationOptions): any; - getPhysicsImpostor(): number; - getPhysicsMass(): number; - getPhysicsFriction(): number; - getPhysicsRestitution(): number; - getPositionInCameraSpace(camera?: Camera): Vector3; - getDistanceToCamera(camera?: Camera): number; - applyImpulse(force: Vector3, contactPoint: Vector3): void; - setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3, options?: any): void; - updatePhysicsBodyPosition(): void; - checkCollisions: boolean; - moveWithCollisions(velocity: Vector3): void; - private _onCollisionPositionChange; - /** - * This function will create an octree to help select the right submeshes for rendering, picking and collisions - * Please note that you must have a decent number of submeshes to get performance improvements when using octree - */ - createOrUpdateSubmeshesOctree(maxCapacity?: number, maxDepth?: number): Octree; - _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): void; - _processCollisionsForSubMeshes(collider: Collider, transformMatrix: Matrix): void; - _checkCollision(collider: Collider): void; - _generatePointsArray(): boolean; - intersects(ray: Ray, fastCheck?: boolean): PickingInfo; - clone(name: string, newParent: Node, doNotCloneChildren?: boolean): AbstractMesh; - releaseSubMeshes(): void; - dispose(doNotRecurse?: boolean): void; - } -} - -declare namespace BABYLON { - class CSG { - private polygons; - matrix: Matrix; - position: Vector3; - rotation: Vector3; - rotationQuaternion: Quaternion; - scaling: Vector3; - static FromMesh(mesh: Mesh): CSG; - private static FromPolygons(polygons); - clone(): CSG; - private toPolygons(); - union(csg: CSG): CSG; - unionInPlace(csg: CSG): void; - subtract(csg: CSG): CSG; - subtractInPlace(csg: CSG): void; - intersect(csg: CSG): CSG; - intersectInPlace(csg: CSG): void; - inverse(): CSG; - inverseInPlace(): void; - copyTransformAttributes(csg: CSG): CSG; - buildMeshGeometry(name: string, scene: Scene, keepSubMeshes: boolean): Mesh; - toMesh(name: string, material: Material, scene: Scene, keepSubMeshes: boolean): Mesh; - } -} - -declare namespace BABYLON { - class Geometry implements IGetSetVerticesData { - id: string; - delayLoadState: number; - delayLoadingFile: string; - onGeometryUpdated: (geometry: Geometry, kind?: string) => void; - private _scene; - private _engine; - private _meshes; - private _totalVertices; - private _indices; - private _vertexBuffers; - private _isDisposed; - private _extend; - _delayInfo: any; - private _indexBuffer; - _boundingInfo: BoundingInfo; - _delayLoadingFunction: (any: any, geometry: Geometry) => void; - _softwareSkinningRenderId: number; - constructor(id: string, scene: Scene, vertexData?: VertexData, updatable?: boolean, mesh?: Mesh); - extend: { - minimum: Vector3; - maximum: Vector3; - }; - getScene(): Scene; - getEngine(): Engine; - isReady(): boolean; - setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; - setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean, stride?: number): void; - updateVerticesDataDirectly(kind: string, data: Float32Array, offset: number): void; - updateVerticesData(kind: string, data: number[] | Float32Array, updateExtends?: boolean): void; - getTotalVertices(): number; - getVerticesData(kind: string, copyWhenShared?: boolean): number[] | Float32Array; - getVertexBuffer(kind: string): VertexBuffer; - getVertexBuffers(): VertexBuffer[]; - isVerticesDataPresent(kind: string): boolean; - getVerticesDataKinds(): string[]; - setIndices(indices: number[] | Int32Array, totalVertices?: number): void; - getTotalIndices(): number; - getIndices(copyWhenShared?: boolean): number[] | Int32Array; - getIndexBuffer(): any; - releaseForMesh(mesh: Mesh, shouldDispose?: boolean): void; - applyToMesh(mesh: Mesh): void; - private _applyToMesh(mesh); - private notifyUpdate(kind?); - load(scene: Scene, onLoaded?: () => void): void; - isDisposed(): boolean; - dispose(): void; - copy(id: string): Geometry; - serialize(): any; - serializeVerticeData(): any; - static ExtractFromMesh(mesh: Mesh, id: string): Geometry; - static RandomId(): string; - static ImportGeometry(parsedGeometry: any, mesh: Mesh): void; - static Parse(parsedVertexData: any, scene: Scene, rootUrl: string): Geometry; - } - namespace Geometry.Primitives { - class _Primitive extends Geometry { - private _beingRegenerated; - private _canBeRegenerated; - constructor(id: string, scene: Scene, vertexData?: VertexData, canBeRegenerated?: boolean, mesh?: Mesh); - canBeRegenerated(): boolean; - regenerate(): void; - asNewGeometry(id: string): Geometry; - setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; - setVerticesData(kind: string, data: number[] | Int32Array | Float32Array, updatable?: boolean): void; - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - } - class Ribbon extends _Primitive { - pathArray: Vector3[][]; - closeArray: boolean; - closePath: boolean; - offset: number; - side: number; - constructor(id: string, scene: Scene, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - } - class Box extends _Primitive { - size: number; - side: number; - constructor(id: string, scene: Scene, size: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedBox: any, scene: Scene): Box; - } - class Sphere extends _Primitive { - segments: number; - diameter: number; - side: number; - constructor(id: string, scene: Scene, segments: number, diameter: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedSphere: any, scene: Scene): Geometry.Primitives.Sphere; - } - class Disc extends _Primitive { - radius: number; - tessellation: number; - side: number; - constructor(id: string, scene: Scene, radius: number, tessellation: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - } - class Cylinder extends _Primitive { - height: number; - diameterTop: number; - diameterBottom: number; - tessellation: number; - subdivisions: number; - side: number; - constructor(id: string, scene: Scene, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions?: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedCylinder: any, scene: Scene): Geometry.Primitives.Cylinder; - } - class Torus extends _Primitive { - diameter: number; - thickness: number; - tessellation: number; - side: number; - constructor(id: string, scene: Scene, diameter: number, thickness: number, tessellation: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedTorus: any, scene: Scene): Geometry.Primitives.Torus; - } - class Ground extends _Primitive { - width: number; - height: number; - subdivisions: number; - constructor(id: string, scene: Scene, width: number, height: number, subdivisions: number, canBeRegenerated?: boolean, mesh?: Mesh); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedGround: any, scene: Scene): Geometry.Primitives.Ground; - } - class TiledGround extends _Primitive { - xmin: number; - zmin: number; - xmax: number; - zmax: number; - subdivisions: { - w: number; - h: number; - }; - precision: { - w: number; - h: number; - }; - constructor(id: string, scene: Scene, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { - w: number; - h: number; - }, precision: { - w: number; - h: number; - }, canBeRegenerated?: boolean, mesh?: Mesh); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - } - class Plane extends _Primitive { - size: number; - side: number; - constructor(id: string, scene: Scene, size: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedPlane: any, scene: Scene): Geometry.Primitives.Plane; - } - class TorusKnot extends _Primitive { - radius: number; - tube: number; - radialSegments: number; - tubularSegments: number; - p: number; - q: number; - side: number; - constructor(id: string, scene: Scene, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); - _regenerateVertexData(): VertexData; - copy(id: string): Geometry; - serialize(): any; - static Parse(parsedTorusKnot: any, scene: Scene): Geometry.Primitives.TorusKnot; - } - } -} - -declare namespace BABYLON { - class GroundMesh extends Mesh { - generateOctree: boolean; - private _worldInverse; - private _heightQuads; - _subdivisions: number; - _width: number; - _height: number; - _minX: number; - _maxX: number; - _minZ: number; - _maxZ: number; - constructor(name: string, scene: Scene); - subdivisions: number; - optimize(chunksCount: number, octreeBlocksSize?: number): void; - /** - * Returns a height (y) value in the Worl system : - * the ground altitude at the coordinates (x, z) expressed in the World system. - * Returns the ground y position if (x, z) are outside the ground surface. - * Not pertinent if the ground is rotated. - */ - getHeightAtCoordinates(x: number, z: number): number; - /** - * Returns a normalized vector (Vector3) orthogonal to the ground - * at the ground coordinates (x, z) expressed in the World system. - * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface. - * Not pertinent if the ground is rotated. - */ - getNormalAtCoordinates(x: number, z: number): Vector3; - /** - * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground - * at the ground coordinates (x, z) expressed in the World system. - * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface. - * Not pertinent if the ground is rotated. - */ - getNormalAtCoordinatesToRef(x: number, z: number, ref: Vector3): void; - private _getFacetAt(x, z); - private _computeHeightQuads(); - } -} - -declare namespace BABYLON { - /** - * Creates an instance based on a source mesh. - */ - class InstancedMesh extends AbstractMesh { - private _sourceMesh; - private _currentLOD; - constructor(name: string, source: Mesh); - receiveShadows: boolean; - material: Material; - visibility: number; - skeleton: Skeleton; - renderingGroupId: number; - getTotalVertices(): number; - sourceMesh: Mesh; - getVerticesData(kind: string, copyWhenShared?: boolean): number[] | Float32Array; - isVerticesDataPresent(kind: string): boolean; - getIndices(): number[] | Int32Array; - _positions: Vector3[]; - refreshBoundingInfo(): void; - _preActivate(): void; - _activate(renderId: number): void; - getLOD(camera: Camera): AbstractMesh; - _syncSubMeshes(): void; - _generatePointsArray(): boolean; - clone(name: string, newParent: Node, doNotCloneChildren?: boolean): InstancedMesh; - dispose(doNotRecurse?: boolean): void; - } -} - -declare namespace BABYLON { - class LinesMesh extends Mesh { - color: Color3; - alpha: number; - private _colorShader; - constructor(name: string, scene: Scene, parent?: Node, source?: Mesh, doNotCloneChildren?: boolean); - material: Material; - isPickable: boolean; - checkCollisions: boolean; - _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void; - _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void; - intersects(ray: Ray, fastCheck?: boolean): any; - dispose(doNotRecurse?: boolean): void; - clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): LinesMesh; - } -} - -declare namespace BABYLON { - class _InstancesBatch { - mustReturn: boolean; - visibleInstances: InstancedMesh[][]; - renderSelf: boolean[]; - } - class Mesh extends AbstractMesh implements IGetSetVerticesData { - static _FRONTSIDE: number; - static _BACKSIDE: number; - static _DOUBLESIDE: number; - static _DEFAULTSIDE: number; - static _NO_CAP: number; - static _CAP_START: number; - static _CAP_END: number; - static _CAP_ALL: number; - static FRONTSIDE: number; - static BACKSIDE: number; - static DOUBLESIDE: number; - static DEFAULTSIDE: number; - static NO_CAP: number; - static CAP_START: number; - static CAP_END: number; - static CAP_ALL: number; - delayLoadState: number; - instances: InstancedMesh[]; - delayLoadingFile: string; - _binaryInfo: any; - private _LODLevels; - onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void; - onBeforeDraw: () => void; - _geometry: Geometry; - private _onBeforeRenderCallbacks; - private _onAfterRenderCallbacks; - _delayInfo: any; - _delayLoadingFunction: (any: any, mesh: Mesh) => void; - _visibleInstances: any; - private _renderIdForInstances; - private _batchCache; - private _worldMatricesInstancesBuffer; - private _worldMatricesInstancesArray; - private _instancesBufferSize; - _shouldGenerateFlatShading: boolean; - private _preActivateId; - private _sideOrientation; - private _areNormalsFrozen; - private _sourcePositions; - private _sourceNormals; - /** - * @constructor - * @param {string} name - The value used by scene.getMeshByName() to do a lookup. - * @param {Scene} scene - The scene to add this mesh to. - * @param {Node} parent - The parent of this mesh, if it has one - * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned. - * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False. - * When false, achieved by calling a clone(), also passing False. - * This will make creation of children, recursive. - */ - constructor(name: string, scene: Scene, parent?: Node, source?: Mesh, doNotCloneChildren?: boolean); - hasLODLevels: boolean; - private _sortLODLevels(); - /** - * Add a mesh as LOD level triggered at the given distance. - * @param {number} distance - the distance from the center of the object to show this level - * @param {Mesh} mesh - the mesh to be added as LOD level - * @return {Mesh} this mesh (for chaining) - */ - addLODLevel(distance: number, mesh: Mesh): Mesh; - getLODLevelAtDistance(distance: number): Mesh; - /** - * Remove a mesh from the LOD array - * @param {Mesh} mesh - the mesh to be removed. - * @return {Mesh} this mesh (for chaining) - */ - removeLODLevel(mesh: Mesh): Mesh; - getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh; - geometry: Geometry; - getTotalVertices(): number; - getVerticesData(kind: string, copyWhenShared?: boolean): number[] | Float32Array; - getVertexBuffer(kind: any): VertexBuffer; - isVerticesDataPresent(kind: string): boolean; - getVerticesDataKinds(): string[]; - getTotalIndices(): number; - getIndices(copyWhenShared?: boolean): number[] | Int32Array; - isBlocked: boolean; - isReady(): boolean; - isDisposed(): boolean; - sideOrientation: number; - areNormalsFrozen: boolean; - /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */ - freezeNormals(): void; - /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */ - unfreezeNormals(): void; - _preActivate(): void; - _registerInstanceForRenderId(instance: InstancedMesh, renderId: number): void; - refreshBoundingInfo(): void; - _createGlobalSubMesh(): SubMesh; - subdivide(count: number): void; - setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean, stride?: number): void; - updateVerticesData(kind: string, data: number[] | Float32Array, updateExtends?: boolean, makeItUnique?: boolean): void; - updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void; - updateMeshPositions(positionFunction: any, computeNormals?: boolean): void; - makeGeometryUnique(): void; - setIndices(indices: number[] | Int32Array, totalVertices?: number): void; - _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void; - _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void; - registerBeforeRender(func: (mesh: AbstractMesh) => void): void; - unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void; - registerAfterRender(func: (mesh: AbstractMesh) => void): void; - unregisterAfterRender(func: (mesh: AbstractMesh) => void): void; - _getInstancesRenderList(subMeshId: number): _InstancesBatch; - _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void; - _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean, onBeforeDraw: (isInstance: boolean, world: Matrix) => void): void; - render(subMesh: SubMesh, enableAlphaMode: boolean): void; - getEmittedParticleSystems(): ParticleSystem[]; - getHierarchyEmittedParticleSystems(): ParticleSystem[]; - getChildren(): Node[]; - _checkDelayState(): void; - isInFrustum(frustumPlanes: Plane[]): boolean; - setMaterialByID(id: string): void; - getAnimatables(): IAnimatable[]; - bakeTransformIntoVertices(transform: Matrix): void; - bakeCurrentTransformIntoVertices(): void; - _resetPointsArrayCache(): void; - _generatePointsArray(): boolean; - clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh; - dispose(doNotRecurse?: boolean): void; - applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void; - applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void; - convertToFlatShadedMesh(): void; - convertToUnIndexedMesh(): void; - flipFaces(flipNormals?: boolean): void; - createInstance(name: string): InstancedMesh; - synchronizeInstances(): void; - /** - * Simplify the mesh according to the given array of settings. - * Function will return immediately and will simplify async. - * @param settings a collection of simplification settings. - * @param parallelProcessing should all levels calculate parallel or one after the other. - * @param type the type of simplification to run. - * @param successCallback optional success callback to be called after the simplification finished processing all settings. - */ - simplify(settings: Array, parallelProcessing?: boolean, simplificationType?: SimplificationType, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void): void; - /** - * Optimization of the mesh's indices, in case a mesh has duplicated vertices. - * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes. - * This should be used together with the simplification to avoid disappearing triangles. - * @param successCallback an optional success callback to be called after the optimization finished. - */ - optimizeIndices(successCallback?: (mesh?: Mesh) => void): void; - static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh; - static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; - static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; - static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; - static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; - static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation?: number): Mesh; - static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; - static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; - static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh; - static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh; - static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; - static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction: any, rotationFunction: any, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; - static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; - static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; - static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh; - static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { - w: number; - h: number; - }, precision: { - w: number; - h: number; - }, scene: Scene, updatable?: boolean): Mesh; - static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void): GroundMesh; - static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { - (i: number, distance: number): number; - }, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; - static CreatePolyhedron(name: string, options: { - type?: number; - size?: number; - sizeX?: number; - sizeY?: number; - sizeZ?: number; - custom?: any; - faceUV?: Vector4[]; - faceColors?: Color4[]; - updatable?: boolean; - sideOrientation?: number; - }, scene: Scene): Mesh; - static CreateIcoSphere(name: string, options: { - radius?: number; - flat?: boolean; - subdivisions?: number; - sideOrientation?: number; - updatable?: boolean; - }, scene: Scene): Mesh; - static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh; - /** - * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. - */ - setPositionsForCPUSkinning(): Float32Array; - /** - * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. - */ - setNormalsForCPUSkinning(): Float32Array; - /** - * Update the vertex buffers by applying transformation from the bones - * @param {skeleton} skeleton to apply - */ - applySkeleton(skeleton: Skeleton): Mesh; - static MinMax(meshes: AbstractMesh[]): { - min: Vector3; - max: Vector3; - }; - static Center(meshesOrMinMaxVector: any): Vector3; - /** - * Merge the array of meshes into a single mesh for performance reasons. - * @param {Array} meshes - The vertices source. They should all be of the same material. Entries can empty - * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes - * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true. - * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class. - */ - static MergeMeshes(meshes: Array, disposeSource?: boolean, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh; - } -} - -declare namespace BABYLON { - interface IGetSetVerticesData { - isVerticesDataPresent(kind: string): boolean; - getVerticesData(kind: string, copyWhenShared?: boolean): number[] | Int32Array | Float32Array; - getIndices(copyWhenShared?: boolean): number[] | Int32Array; - setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean): void; - updateVerticesData(kind: string, data: number[] | Float32Array, updateExtends?: boolean, makeItUnique?: boolean): void; - setIndices(indices: number[] | Int32Array): void; - } - class VertexData { - positions: number[] | Float32Array; - normals: number[] | Float32Array; - uvs: number[] | Float32Array; - uvs2: number[] | Float32Array; - uvs3: number[] | Float32Array; - uvs4: number[] | Float32Array; - uvs5: number[] | Float32Array; - uvs6: number[] | Float32Array; - colors: number[] | Float32Array; - matricesIndices: number[] | Float32Array; - matricesWeights: number[] | Float32Array; - matricesIndicesExtra: number[] | Float32Array; - matricesWeightsExtra: number[] | Float32Array; - indices: number[] | Int32Array; - set(data: number[] | Float32Array, kind: string): void; - applyToMesh(mesh: Mesh, updatable?: boolean): void; - applyToGeometry(geometry: Geometry, updatable?: boolean): void; - updateMesh(mesh: Mesh, updateExtends?: boolean, makeItUnique?: boolean): void; - updateGeometry(geometry: Geometry, updateExtends?: boolean, makeItUnique?: boolean): void; - private _applyTo(meshOrGeometry, updatable?); - private _update(meshOrGeometry, updateExtends?, makeItUnique?); - transform(matrix: Matrix): void; - merge(other: VertexData): void; - private _mergeElement(source, other); - serialize(): any; - static ExtractFromMesh(mesh: Mesh, copyWhenShared?: boolean): VertexData; - static ExtractFromGeometry(geometry: Geometry, copyWhenShared?: boolean): VertexData; - private static _ExtractFrom(meshOrGeometry, copyWhenShared?); - static CreateRibbon(options: { - pathArray: Vector3[][]; - closeArray?: boolean; - closePath?: boolean; - offset?: number; - sideOrientation?: number; - }): VertexData; - static CreateBox(options: { - size?: number; - width?: number; - height?: number; - depth?: number; - faceUV?: Vector4[]; - faceColors?: Color4[]; - sideOrientation?: number; - }): VertexData; - static CreateSphere(options: { - segments?: number; - diameter?: number; - diameterX?: number; - diameterY?: number; - diameterZ?: number; - arc?: number; - slice?: number; - sideOrientation?: number; - }): VertexData; - static CreateCylinder(options: { - height?: number; - diameterTop?: number; - diameterBottom?: number; - diameter?: number; - tessellation?: number; - subdivisions?: number; - arc?: number; - faceColors?: Color4[]; - faceUV?: Vector4[]; - hasRings?: boolean; - enclose?: boolean; - sideOrientation?: number; - }): VertexData; - static CreateTorus(options: { - diameter?: number; - thickness?: number; - tessellation?: number; - sideOrientation?: number; - }): VertexData; - static CreateLines(options: { - points: Vector3[]; - }): VertexData; - static CreateDashedLines(options: { - points: Vector3[]; - dashSize?: number; - gapSize?: number; - dashNb?: number; - }): VertexData; - static CreateGround(options: { - width?: number; - height?: number; - subdivisions?: number; - }): VertexData; - static CreateTiledGround(options: { - xmin: number; - zmin: number; - xmax: number; - zmax: number; - subdivisions?: { - w: number; - h: number; - }; - precision?: { - w: number; - h: number; - }; - }): VertexData; - static CreateGroundFromHeightMap(options: { - width: number; - height: number; - subdivisions: number; - minHeight: number; - maxHeight: number; - buffer: Uint8Array; - bufferWidth: number; - bufferHeight: number; - }): VertexData; - static CreatePlane(options: { - size?: number; - width?: number; - height?: number; - sideOrientation?: number; - }): VertexData; - static CreateDisc(options: { - radius?: number; - tessellation?: number; - arc?: number; - sideOrientation?: number; - }): VertexData; - static CreateIcoSphere(options: { - radius?: number; - radiusX?: number; - radiusY?: number; - radiusZ?: number; - flat?: boolean; - subdivisions?: number; - sideOrientation?: number; - }): VertexData; - static CreatePolyhedron(options: { - type?: number; - size?: number; - sizeX?: number; - sizeY?: number; - sizeZ?: number; - custom?: any; - faceUV?: Vector4[]; - faceColors?: Color4[]; - flat?: boolean; - sideOrientation?: number; - }): VertexData; - static CreateTorusKnot(options: { - radius?: number; - tube?: number; - radialSegments?: number; - tubularSegments?: number; - p?: number; - q?: number; - sideOrientation?: number; - }): VertexData; - /** - * @param {any} - positions (number[] or Float32Array) - * @param {any} - indices (number[] or Uint16Array) - * @param {any} - normals (number[] or Float32Array) - */ - static ComputeNormals(positions: any, indices: any, normals: any): void; - private static _ComputeSides(sideOrientation, positions, indices, normals, uvs); - static ImportVertexData(parsedVertexData: any, geometry: Geometry): void; - } -} - -declare namespace BABYLON { - class MeshBuilder { - static CreateBox(name: string, options: { - width?: number; - height?: number; - depth?: number; - faceUV?: Vector4[]; - faceColors?: Color4[]; - sideOrientation?: number; - updatable?: boolean; - }, scene: Scene): Mesh; - static CreateSphere(name: string, options: { - segments?: number; - diameter?: number; - diameterX?: number; - diameterY?: number; - diameterZ?: number; - arc?: number; - slice?: number; - sideOrientation?: number; - updatable?: boolean; - }, scene: any): Mesh; - static CreateDisc(name: string, options: { - radius?: number; - tessellation?: number; - arc?: number; - updatable?: boolean; - sideOrientation?: number; - }, scene: Scene): Mesh; - static CreateIcoSphere(name: string, options: { - radius?: number; - radiusX?: number; - radiusY?: number; - radiusZ?: number; - flat?: boolean; - subdivisions?: number; - sideOrientation?: number; - updatable?: boolean; - }, scene: Scene): Mesh; - static CreateRibbon(name: string, options: { - pathArray: Vector3[][]; - closeArray?: boolean; - closePath?: boolean; - offset?: number; - updatable?: boolean; - sideOrientation?: number; - instance?: Mesh; - }, scene?: Scene): Mesh; - static CreateCylinder(name: string, options: { - height?: number; - diameterTop?: number; - diameterBottom?: number; - diameter?: number; - tessellation?: number; - subdivisions?: number; - arc?: number; - faceColors?: Color4[]; - faceUV?: Vector4[]; - updatable?: boolean; - hasRings?: boolean; - enclose?: boolean; - sideOrientation?: number; - }, scene: any): Mesh; - static CreateTorus(name: string, options: { - diameter?: number; - thickness?: number; - tessellation?: number; - updatable?: boolean; - sideOrientation?: number; - }, scene: any): Mesh; - static CreateTorusKnot(name: string, options: { - radius?: number; - tube?: number; - radialSegments?: number; - tubularSegments?: number; - p?: number; - q?: number; - updatable?: boolean; - sideOrientation?: number; - }, scene: any): Mesh; - static CreateLines(name: string, options: { - points: Vector3[]; - updatable?: boolean; - instance?: LinesMesh; - }, scene: Scene): LinesMesh; - static CreateDashedLines(name: string, options: { - points: Vector3[]; - dashSize?: number; - gapSize?: number; - dashNb?: number; - updatable?: boolean; - instance?: LinesMesh; - }, scene: Scene): LinesMesh; - static ExtrudeShape(name: string, options: { - shape: Vector3[]; - path: Vector3[]; - scale?: number; - rotation?: number; - cap?: number; - updatable?: boolean; - sideOrientation?: number; - instance?: Mesh; - }, scene: Scene): Mesh; - static ExtrudeShapeCustom(name: string, options: { - shape: Vector3[]; - path: Vector3[]; - scaleFunction?:any; - rotationFunction?:any; - ribbonCloseArray?: boolean; - ribbonClosePath?: boolean; - cap?: number; - updatable?: boolean; - sideOrientation?: number; - instance?: Mesh; - }, scene: Scene): Mesh; - static CreateLathe(name: string, options: { - shape: Vector3[]; - radius?: number; - tessellation?: number; - arc?: number; - closed?: boolean; - updatable?: boolean; - sideOrientation?: number; - cap?: number; - }, scene: Scene): Mesh; - static CreatePlane(name: string, options: { - size?: number; - width?: number; - height?: number; - sideOrientation?: number; - updatable?: boolean; - sourcePlane?: Plane; - }, scene: Scene): Mesh; - static CreateGround(name: string, options: { - width?: number; - height?: number; - subdivisions?: number; - updatable?: boolean; - }, scene: any): Mesh; - static CreateTiledGround(name: string, options: { - xmin: number; - zmin: number; - xmax: number; - zmax: number; - subdivisions?: { - w: number; - h: number; - }; - precision?: { - w: number; - h: number; - }; - updatable?: boolean; - }, scene: Scene): Mesh; - static CreateGroundFromHeightMap(name: string, url: string, options: { - width?: number; - height?: number; - subdivisions?: number; - minHeight?: number; - maxHeight?: number; - updatable?: boolean; - onReady?: (mesh: GroundMesh) => void; - }, scene: Scene): GroundMesh; - static CreateTube(name: string, options: { - path: Vector3[]; - radius?: number; - tessellation?: number; - radiusFunction?: { - (i: number, distance: number): number; - }; - cap?: number; - arc?: number; - updatable?: boolean; - sideOrientation?: number; - instance?: Mesh; - }, scene: Scene): Mesh; - static CreatePolyhedron(name: string, options: { - type?: number; - size?: number; - sizeX?: number; - sizeY?: number; - sizeZ?: number; - custom?: any; - faceUV?: Vector4[]; - faceColors?: Color4[]; - flat?: boolean; - updatable?: boolean; - sideOrientation?: number; - }, scene: Scene): Mesh; - static CreateDecal(name: string, sourceMesh: AbstractMesh, options: { - position?: Vector3; - normal?: Vector3; - size?: Vector3; - angle?: number; - }): Mesh; - private static _ExtrudeShapeGeneric(name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance); - } -} - -declare namespace BABYLON.Internals { - class MeshLODLevel { - distance: number; - mesh: Mesh; - constructor(distance: number, mesh: Mesh); - } -} - -declare namespace BABYLON { - /** - * A simplifier interface for future simplification implementations. - */ - interface ISimplifier { - /** - * Simplification of a given mesh according to the given settings. - * Since this requires computation, it is assumed that the function runs async. - * @param settings The settings of the simplification, including quality and distance - * @param successCallback A callback that will be called after the mesh was simplified. - * @param errorCallback in case of an error, this callback will be called. optional. - */ - simplify(settings: ISimplificationSettings, successCallback: (simplifiedMeshes: Mesh) => void, errorCallback?: () => void): void; - } - /** - * Expected simplification settings. - * Quality should be between 0 and 1 (1 being 100%, 0 being 0%); - */ - interface ISimplificationSettings { - quality: number; - distance: number; - optimizeMesh?: boolean; - } - class SimplificationSettings implements ISimplificationSettings { - quality: number; - distance: number; - optimizeMesh: boolean; - constructor(quality: number, distance: number, optimizeMesh?: boolean); - } - interface ISimplificationTask { - settings: Array; - simplificationType: SimplificationType; - mesh: Mesh; - successCallback?: () => void; - parallelProcessing: boolean; - } - class SimplificationQueue { - private _simplificationArray; - running: any; - constructor(); - addTask(task: ISimplificationTask): void; - executeNext(): void; - runSimplification(task: ISimplificationTask): void; - private getSimplifier(task); - } - /** - * The implemented types of simplification. - * At the moment only Quadratic Error Decimation is implemented. - */ - enum SimplificationType { - QUADRATIC = 0, - } - class DecimationTriangle { - vertices: Array; - normal: Vector3; - error: Array; - deleted: boolean; - isDirty: boolean; - borderFactor: number; - deletePending: boolean; - originalOffset: number; - constructor(vertices: Array); - } - class DecimationVertex { - position: Vector3; - id: any; - q: QuadraticMatrix; - isBorder: boolean; - triangleStart: number; - triangleCount: number; - originalOffsets: Array; - constructor(position: Vector3, id: any); - updatePosition(newPosition: Vector3): void; - } - class QuadraticMatrix { - data: Array; - constructor(data?: Array); - det(a11: any, a12: any, a13: any, a21: any, a22: any, a23: any, a31: any, a32: any, a33: any): number; - addInPlace(matrix: QuadraticMatrix): void; - addArrayInPlace(data: Array): void; - add(matrix: QuadraticMatrix): QuadraticMatrix; - static FromData(a: number, b: number, c: number, d: number): QuadraticMatrix; - static DataFromNumbers(a: number, b: number, c: number, d: number): number[]; - } - class Reference { - vertexId: number; - triangleId: number; - constructor(vertexId: number, triangleId: number); - } - /** - * An implementation of the Quadratic Error simplification algorithm. - * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf - * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS - * @author RaananW - */ - class QuadraticErrorSimplification implements ISimplifier { - private _mesh; - private triangles; - private vertices; - private references; - private initialized; - private _reconstructedMesh; - syncIterations: number; - aggressiveness: number; - decimationIterations: number; - boundingBoxEpsilon: number; - constructor(_mesh: Mesh); - simplify(settings: ISimplificationSettings, successCallback: (simplifiedMesh: Mesh) => void): void; - private isTriangleOnBoundingBox(triangle); - private runDecimation(settings, submeshIndex, successCallback); - private initWithMesh(submeshIndex, callback, optimizeMesh?); - private init(callback); - private reconstructMesh(submeshIndex); - private initDecimatedMesh(); - private isFlipped(vertex1, vertex2, point, deletedArray, borderFactor, delTr); - private updateTriangles(origVertex, vertex, deletedArray, deletedTriangles); - private identifyBorder(); - private updateMesh(identifyBorders?); - private vertexError(q, point); - private calculateError(vertex1, vertex2, pointResult?, normalResult?, uvResult?, colorResult?); - } -} - -declare namespace BABYLON { - class Polygon { - static Rectangle(xmin: number, ymin: number, xmax: number, ymax: number): Vector2[]; - static Circle(radius: number, cx?: number, cy?: number, numberOfSides?: number): Vector2[]; - static Parse(input: string): Vector2[]; - static StartingAt(x: number, y: number): Path2; - } - class PolygonMeshBuilder { - private _swctx; - private _points; - private _outlinepoints; - private _holes; - private _name; - private _scene; - constructor(name: string, contours: Path2, scene: Scene); - constructor(name: string, contours: Vector2[], scene: Scene); - addHole(hole: Vector2[]): PolygonMeshBuilder; - build(updatable?: boolean, depth?: number): Mesh; - private addSide(positions, normals, uvs, indices, bounds, points, depth, flip); - } -} - -declare namespace BABYLON { - class SubMesh { - materialIndex: number; - verticesStart: number; - verticesCount: number; - indexStart: any; - indexCount: number; - linesIndexCount: number; - private _mesh; - private _renderingMesh; - private _boundingInfo; - private _linesIndexBuffer; - _lastColliderWorldVertices: Vector3[]; - _trianglePlanes: Plane[]; - _lastColliderTransformMatrix: Matrix; - _renderId: number; - _alphaIndex: number; - _distanceToCamera: number; - _id: number; - constructor(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: any, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox?: boolean); - IsGlobal: boolean; - getBoundingInfo(): BoundingInfo; - getMesh(): AbstractMesh; - getRenderingMesh(): Mesh; - getMaterial(): Material; - refreshBoundingInfo(): void; - _checkCollision(collider: Collider): boolean; - updateBoundingInfo(world: Matrix): void; - isInFrustum(frustumPlanes: Plane[]): boolean; - render(enableAlphaMode: boolean): void; - getLinesIndexBuffer(indices: number[] | Int32Array, engine: any): WebGLBuffer; - canIntersects(ray: Ray): boolean; - intersects(ray: Ray, positions: Vector3[], indices: number[] | Int32Array, fastCheck?: boolean): IntersectionInfo; - clone(newMesh: AbstractMesh, newRenderingMesh?: Mesh): SubMesh; - dispose(): void; - static CreateFromIndices(materialIndex: number, startIndex: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh): SubMesh; - } -} - -declare namespace BABYLON { - class VertexBuffer { - private _mesh; - private _engine; - private _buffer; - private _data; - private _updatable; - private _kind; - private _strideSize; - constructor(engine: any, data: number[] | Float32Array, kind: string, updatable: boolean, postponeInternalCreation?: boolean, stride?: number); - isUpdatable(): boolean; - getData(): number[] | Float32Array; - getBuffer(): WebGLBuffer; - getStrideSize(): number; - create(data?: number[] | Float32Array): void; - update(data: number[] | Float32Array): void; - updateDirectly(data: Float32Array, offset: number): void; - dispose(): void; - private static _PositionKind; - private static _NormalKind; - private static _UVKind; - private static _UV2Kind; - private static _UV3Kind; - private static _UV4Kind; - private static _UV5Kind; - private static _UV6Kind; - private static _ColorKind; - private static _MatricesIndicesKind; - private static _MatricesWeightsKind; - private static _MatricesIndicesExtraKind; - private static _MatricesWeightsExtraKind; - static PositionKind: string; - static NormalKind: string; - static UVKind: string; - static UV2Kind: string; - static UV3Kind: string; - static UV4Kind: string; - static UV5Kind: string; - static UV6Kind: string; - static ColorKind: string; - static MatricesIndicesKind: string; - static MatricesWeightsKind: string; - static MatricesIndicesExtraKind: string; - static MatricesWeightsExtraKind: string; - } -} - -declare namespace BABYLON { - class Particle { - position: Vector3; - direction: Vector3; - color: Color4; - colorStep: Color4; - lifeTime: number; - age: number; - size: number; - angle: number; - angularSpeed: number; - copyTo(other: Particle): void; - } -} - -declare namespace BABYLON { - class ParticleSystem implements IDisposable { - name: string; - static BLENDMODE_ONEONE: number; - static BLENDMODE_STANDARD: number; - id: string; - renderingGroupId: number; - emitter: any; - emitRate: number; - manualEmitCount: number; - updateSpeed: number; - targetStopDuration: number; - disposeOnStop: boolean; - minEmitPower: number; - maxEmitPower: number; - minLifeTime: number; - maxLifeTime: number; - minSize: number; - maxSize: number; - minAngularSpeed: number; - maxAngularSpeed: number; - particleTexture: Texture; - layerMask: number; - onDispose: () => void; - updateFunction: (particles: Particle[]) => void; - blendMode: number; - forceDepthWrite: boolean; - gravity: Vector3; - direction1: Vector3; - direction2: Vector3; - minEmitBox: Vector3; - maxEmitBox: Vector3; - color1: Color4; - color2: Color4; - colorDead: Color4; - textureMask: Color4; - startDirectionFunction: (emitPower: number, worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void; - startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void; - private particles; - private _capacity; - private _scene; - private _vertexDeclaration; - private _vertexStrideSize; - private _stockParticles; - private _newPartsExcess; - private _vertexBuffer; - private _indexBuffer; - private _vertices; - private _effect; - private _customEffect; - private _cachedDefines; - private _scaledColorStep; - private _colorDiff; - private _scaledDirection; - private _scaledGravity; - private _currentRenderId; - private _alive; - private _started; - private _stopped; - private _actualFrame; - private _scaledUpdateSpeed; - constructor(name: string, capacity: number, scene: Scene, customEffect?: Effect); - recycleParticle(particle: Particle): void; - getCapacity(): number; - isAlive(): boolean; - isStarted(): boolean; - start(): void; - stop(): void; - _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void; - private _update(newParticles); - private _getEffect(); - animate(): void; - render(): number; - dispose(): void; - clone(name: string, newEmitter: any): ParticleSystem; - serialize(): any; - static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): ParticleSystem; - } -} - -declare namespace BABYLON { - class SolidParticle { - idx: number; - color: Color4; - position: Vector3; - rotation: Vector3; - quaternion: Vector4; - scale: Vector3; - uvs: Vector4; - velocity: Vector3; - alive: boolean; - _pos: number; - _model: ModelShape; - shapeId: number; - idxInShape: number; - constructor(particleIndex: number, positionIndex: number, model: ModelShape, shapeId: number, idxInShape: number); - } - class ModelShape { - shapeID: number; - _shape: Vector3[]; - _shapeUV: number[]; - _positionFunction: (particle: SolidParticle, i: number, s: number) => void; - _vertexFunction: (particle: SolidParticle, vertex: Vector3, i: number) => void; - constructor(id: number, shape: Vector3[], shapeUV: number[], posFunction: (particle: SolidParticle, i: number, s: number) => void, vtxFunction: (particle: SolidParticle, vertex: Vector3, i: number) => void); - } -} - -declare namespace BABYLON { - /** - * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System - */ - class SolidParticleSystem implements IDisposable { - particles: SolidParticle[]; - nbParticles: number; - billboard: boolean; - counter: number; - name: string; - mesh: Mesh; - vars: any; - pickedParticles: { - idx: number; - faceId: number; - }[]; - private _scene; - private _positions; - private _indices; - private _normals; - private _colors; - private _uvs; - private _positions32; - private _normals32; - private _fixedNormal32; - private _colors32; - private _uvs32; - private _index; - private _updatable; - private _pickable; - private _isVisibilityBoxLocked; - private _alwaysVisible; - private _shapeCounter; - private _copy; - private _shape; - private _shapeUV; - private _color; - private _computeParticleColor; - private _computeParticleTexture; - private _computeParticleRotation; - private _computeParticleVertex; - private _cam_axisZ; - private _cam_axisY; - private _cam_axisX; - private _axisX; - private _axisY; - private _axisZ; - private _camera; - private _particle; - private _fakeCamPos; - private _rotMatrix; - private _invertMatrix; - private _rotated; - private _quaternion; - private _vertex; - private _normal; - private _yaw; - private _pitch; - private _roll; - private _halfroll; - private _halfpitch; - private _halfyaw; - private _sinRoll; - private _cosRoll; - private _sinPitch; - private _cosPitch; - private _sinYaw; - private _cosYaw; - private _w; - /** - * Creates a SPS (Solid Particle System) object. - * @param name the SPS name, this will be the underlying mesh name - * @param updatable (default true) if the SPS must be updatable or immutable - * @param isPickable (default false) if the solid particles must be pickable - */ - constructor(name: string, scene: Scene, options?: { - updatable?: boolean; - isPickable?: boolean; - }); - /** - * Builds the SPS underlying mesh. Returns a standard Mesh. - * If no model shape was added to the SPS, the return mesh is only a single triangular plane. - */ - buildMesh(): Mesh; - private _resetCopy(); - private _meshBuilder(p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options); - private _posToShape(positions); - private _uvsToShapeUV(uvs); - private _addParticle(idx, idxpos, model, shapeId, idxInShape); - /** - * Adds some particles to the SPS from the model shape. - * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps - * @param mesh any Mesh object that will be used as a model for the solid particles. - * @param nb the number of particles to be created from this model - * @param positionFunction an optional javascript function to called for each particle on SPS creation - * @param vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation - */ - addShape(mesh: Mesh, nb: number, options?: { - positionFunction?: any; - vertexFunction?: any; - }): number; - private _rebuildParticle(particle); - /** - * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed. - */ - rebuildMesh(): void; - /** - * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc. - * This method calls updateParticle() for each particles of the SPS. - * For an animated SPS, it is usually called within the render loop. - * @param start (default 0) the particle index in the particle array where to start to compute the particle property values - * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values - * @param update (default true) if the mesh must be finally updated on this call after all the particle computations. - */ - setParticles(start?: number, end?: number, update?: boolean): void; - private _quaternionRotationYPR(); - private _quaternionToRotationMatrix(); - /** - * Disposes the SPS - */ - dispose(): void; - /** - * Visibilty helper : Recomputes the visible size according to the mesh bounding box - * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility - */ - refreshVisibleSize(): void; - /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box. - * @param size the size (float) of the visibility box - * note : this doesn't lock the SPS mesh bounding box. - * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility - */ - setVisibilityBox(size: number): void; - /** - * True if the SPS is set as always visible - */ - /** - * Sets the SPS as always visible or not - * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility - */ - isAlwaysVisible: boolean; - /** - * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more. - */ - /** - * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. - * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility - */ - isVisibilityBoxLocked: boolean; - /** - * Tells to setParticle() to compute the particle rotations or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate. - */ - computeParticleRotation: boolean; - /** - * Tells to setParticle() to compute the particle colors or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set. - */ - computeParticleColor: boolean; - /** - * Tells to setParticle() to compute the particle textures or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set. - */ - computeParticleTexture: boolean; - /** - * Tells to setParticle() to call the vertex function for each vertex of each particle, or not. - * Default value : false. The SPS is faster when it's set to false. - * Note : the particle custom vertex positions aren't stored values. - */ - computeParticleVertex: boolean; - /** - * This function does nothing. It may be overwritten to set all the particles first values. - * The SPS doesn't call this function, you may have to call it by your own. - * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management - */ - initParticles(): void; - /** - * This function does nothing. It may be overwritten to recycle a particle. - * The SPS doesn't call this function, you may have to call it by your own. - * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management - */ - recycleParticle(particle: SolidParticle): SolidParticle; - /** - * Updates a particle : this function should be overwritten by the user. - * It is called on each particle by setParticles(). This is the place to code each particle behavior. - * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management - * ex : just set a particle position or velocity and recycle conditions - */ - updateParticle(particle: SolidParticle): SolidParticle; - /** - * Updates a vertex of a particle : it can be overwritten by the user. - * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only. - * @param particle the current particle - * @param vertex the current index of the current particle - * @param pt the index of the current vertex in the particle shape - * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape - * ex : just set a vertex particle position - */ - updateParticleVertex(particle: SolidParticle, vertex: Vector3, pt: number): Vector3; - /** - * This will be called before any other treatment by setParticles() and will be passed three parameters. - * This does nothing and may be overwritten by the user. - * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param update the boolean update value actually passed to setParticles() - */ - beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void; - /** - * This will be called by setParticles() after all the other treatments and just before the actual mesh update. - * This will be passed three parameters. - * This does nothing and may be overwritten by the user. - * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param update the boolean update value actually passed to setParticles() - */ - afterUpdateParticles(start?: number, stop?: number, update?: boolean): void; - } -} - -declare namespace BABYLON { - interface IPhysicsEnginePlugin { - name: string; - initialize(iterations?: number): any; - setGravity(gravity: Vector3): void; - getGravity(): Vector3; - runOneStep(delta: number): void; - registerMesh(mesh: AbstractMesh, impostor: number, options: PhysicsBodyCreationOptions): any; - registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any; - unregisterMesh(mesh: AbstractMesh): any; - applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void; - createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3, options?: any): boolean; - dispose(): void; - isSupported(): boolean; - updateBodyPosition(mesh: AbstractMesh): void; - getWorldObject(): any; - getPhysicsBodyOfMesh(mesh: AbstractMesh): any; - } - interface PhysicsBodyCreationOptions { - mass: number; - friction: number; - restitution: number; - } - interface PhysicsCompoundBodyPart { - mesh: Mesh; - impostor: number; - } - class PhysicsEngine { - gravity: Vector3; - private _currentPlugin; - constructor(plugin?: IPhysicsEnginePlugin); - _initialize(gravity?: Vector3): void; - _runOneStep(delta: number): void; - _setGravity(gravity: Vector3): void; - _getGravity(): Vector3; - _registerMesh(mesh: AbstractMesh, impostor: number, options: PhysicsBodyCreationOptions): any; - _registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any; - _unregisterMesh(mesh: AbstractMesh): void; - _applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void; - _createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3, options?: any): boolean; - _updateBodyPosition(mesh: AbstractMesh): void; - dispose(): void; - isSupported(): boolean; - getPhysicsBodyOfMesh(mesh: AbstractMesh): any; - getPhysicsPluginName(): string; - static NoImpostor: number; - static SphereImpostor: number; - static BoxImpostor: number; - static PlaneImpostor: number; - static MeshImpostor: number; - static CapsuleImpostor: number; - static ConeImpostor: number; - static CylinderImpostor: number; - static ConvexHullImpostor: number; - static HeightmapImpostor: number; - static Epsilon: number; - } -} - -declare namespace BABYLON { - class AnaglyphPostProcess extends PostProcess { - constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); - } -} - -declare namespace BABYLON { - class BlackAndWhitePostProcess extends PostProcess { - constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); - } -} - -declare namespace BABYLON { - class BlurPostProcess extends PostProcess { - direction: Vector2; - blurWidth: number; - constructor(name: string, direction: Vector2, blurWidth: number, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); - } -} - -declare namespace BABYLON { - class ColorCorrectionPostProcess extends PostProcess { - private _colorTableTexture; - constructor(name: string, colorTableUrl: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); - } -} - -declare namespace BABYLON { - class ConvolutionPostProcess extends PostProcess { - kernel: number[]; - constructor(name: string, kernel: number[], ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); - static EdgeDetect0Kernel: number[]; - static EdgeDetect1Kernel: number[]; - static EdgeDetect2Kernel: number[]; - static SharpenKernel: number[]; - static EmbossKernel: number[]; - static GaussianKernel: number[]; - } -} - -declare namespace BABYLON { - class DisplayPassPostProcess extends PostProcess { - constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); - } -} - -declare namespace BABYLON { - class FilterPostProcess extends PostProcess { - kernelMatrix: Matrix; - constructor(name: string, kernelMatrix: Matrix, ratio: number, camera?: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); - } -} - -declare namespace BABYLON { - class FxaaPostProcess extends PostProcess { - texelWidth: number; - texelHeight: number; - constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); - } -} - -declare namespace BABYLON { - class HDRRenderingPipeline extends PostProcessRenderPipeline implements IDisposable { - /** - * Public members - */ - /** - * Gaussian blur coefficient - * @type {number} - */ - gaussCoeff: number; - /** - * Gaussian blur mean - * @type {number} - */ - gaussMean: number; - /** - * Gaussian blur standard deviation - * @type {number} - */ - gaussStandDev: number; - /** - * Gaussian blur multiplier. Multiplies the blur effect - * @type {number} - */ - gaussMultiplier: number; - /** - * Exposure, controls the overall intensity of the pipeline - * @type {number} - */ - exposure: number; - /** - * Minimum luminance that the post-process can output. Luminance is >= 0 - * @type {number} - */ - minimumLuminance: number; - /** - * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance - * @type {number} - */ - maximumLuminance: number; - /** - * Increase rate for luminance: eye adaptation speed to dark - * @type {number} - */ - luminanceIncreaserate: number; - /** - * Decrease rate for luminance: eye adaptation speed to bright - * @type {number} - */ - luminanceDecreaseRate: number; - /** - * Minimum luminance needed to compute HDR - * @type {number} - */ - brightThreshold: number; - /** - * Private members - */ - private _guassianBlurHPostProcess; - private _guassianBlurVPostProcess; - private _brightPassPostProcess; - private _textureAdderPostProcess; - private _downSampleX4PostProcess; - private _originalPostProcess; - private _hdrPostProcess; - private _hdrCurrentLuminance; - private _hdrOutputLuminance; - static LUM_STEPS: number; - private _downSamplePostProcesses; - private _scene; - private _needUpdate; - /** - * @constructor - * @param {string} name - The rendering pipeline name - * @param {BABYLON.Scene} scene - The scene linked to this pipeline - * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) - * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null. - * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to - */ - constructor(name: string, scene: Scene, ratio: number, originalPostProcess?: PostProcess, cameras?: Camera[]); - /** - * Tells the pipeline to update its post-processes - */ - update(): void; - /** - * Returns the current calculated luminance - */ - getCurrentLuminance(): number; - /** - * Returns the currently drawn luminance - */ - getOutputLuminance(): number; - /** - * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras - */ - dispose(): void; - /** - * Creates the HDR post-process and computes the luminance adaptation - */ - private _createHDRPostProcess(scene, ratio); - /** - * Texture Adder post-process - */ - private _createTextureAdderPostProcess(scene, ratio); - /** - * Down sample X4 post-process - */ - private _createDownSampleX4PostProcess(scene, ratio); - /** - * Bright pass post-process - */ - private _createBrightPassPostProcess(scene, ratio); - /** - * Luminance generator. Creates the luminance post-process and down sample post-processes - */ - private _createLuminanceGeneratorPostProcess(scene); - /** - * Gaussian blur post-processes. Horizontal and Vertical - */ - private _createGaussianBlurPostProcess(scene, ratio); - } -} - -declare namespace BABYLON { - class LensRenderingPipeline extends PostProcessRenderPipeline { - /** - * The chromatic aberration PostProcess id in the pipeline - * @type {string} - */ - LensChromaticAberrationEffect: string; - /** - * The highlights enhancing PostProcess id in the pipeline - * @type {string} - */ - HighlightsEnhancingEffect: string; - /** - * The depth-of-field PostProcess id in the pipeline - * @type {string} - */ - LensDepthOfFieldEffect: string; - private _scene; - private _depthTexture; - private _grainTexture; - private _chromaticAberrationPostProcess; - private _highlightsPostProcess; - private _depthOfFieldPostProcess; - private _edgeBlur; - private _grainAmount; - private _chromaticAberration; - private _distortion; - private _highlightsGain; - private _highlightsThreshold; - private _dofDistance; - private _dofAperture; - private _dofDarken; - private _dofPentagon; - private _blurNoise; - /** - * @constructor - * - * Effect parameters are as follow: - * { - * chromatic_aberration: number; // from 0 to x (1 for realism) - * edge_blur: number; // from 0 to x (1 for realism) - * distortion: number; // from 0 to x (1 for realism) - * grain_amount: number; // from 0 to 1 - * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise - * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default) - * dof_aperture: number; // depth-of-field: focus blur bias (default: 1) - * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default) - * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect - * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default) - * dof_threshold: number; // depth-of-field: highlights threshold (default: 1) - * blur_noise: boolean; // add a little bit of noise to the blur (default: true) - * } - * Note: if an effect parameter is unset, effect is disabled - * - * @param {string} name - The rendering pipeline name - * @param {object} parameters - An object containing all parameters (see above) - * @param {BABYLON.Scene} scene - The scene linked to this pipeline - * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) - * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to - */ - constructor(name: string, parameters: any, scene: Scene, ratio?: number, cameras?: Camera[]); - setEdgeBlur(amount: number): void; - disableEdgeBlur(): void; - setGrainAmount(amount: number): void; - disableGrain(): void; - setChromaticAberration(amount: number): void; - disableChromaticAberration(): void; - setEdgeDistortion(amount: number): void; - disableEdgeDistortion(): void; - setFocusDistance(amount: number): void; - disableDepthOfField(): void; - setAperture(amount: number): void; - setDarkenOutOfFocus(amount: number): void; - enablePentagonBokeh(): void; - disablePentagonBokeh(): void; - enableNoiseBlur(): void; - disableNoiseBlur(): void; - setHighlightsGain(amount: number): void; - setHighlightsThreshold(amount: number): void; - disableHighlights(): void; - /** - * Removes the internal pipeline assets and detaches the pipeline from the scene cameras - */ - dispose(disableDepthRender?: boolean): void; - private _createChromaticAberrationPostProcess(ratio); - private _createHighlightsPostProcess(ratio); - private _createDepthOfFieldPostProcess(ratio); - private _createGrainTexture(); - } -} - -declare namespace BABYLON { - class PassPostProcess extends PostProcess { - constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); - } -} - -declare namespace BABYLON { - class PostProcess { - name: string; - onApply: (effect: Effect) => void; - onBeforeRender: (effect: Effect) => void; - onAfterRender: (effect: Effect) => void; - onSizeChanged: () => void; - onActivate: (camera: Camera) => void; - width: number; - height: number; - renderTargetSamplingMode: number; - clearColor: Color4; - private _camera; - private _scene; - private _engine; - private _renderRatio; - private _reusable; - private _textureType; - _textures: SmartArray; - _currentRenderTextureInd: number; - private _effect; - private _samplers; - private _fragmentUrl; - private _parameters; - constructor(name: string, fragmentUrl: string, parameters: string[], samplers: string[], ratio: number | any, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean, defines?: string, textureType?: number); - updateEffect(defines?: string): void; - isReusable(): boolean; - activate(camera: Camera, sourceTexture?: WebGLTexture): void; - isSupported: boolean; - apply(): Effect; - dispose(camera?: Camera): void; - } -} - -declare namespace BABYLON { - class PostProcessManager { - private _scene; - private _indexBuffer; - private _vertexDeclaration; - private _vertexStrideSize; - private _vertexBuffer; - constructor(scene: Scene); - private _prepareBuffers(); - _prepareFrame(sourceTexture?: WebGLTexture): boolean; - directRender(postProcesses: PostProcess[], targetTexture?: WebGLTexture): void; - _finalizeFrame(doNotPresent?: boolean, targetTexture?: WebGLTexture, faceIndex?: number, postProcesses?: PostProcess[]): void; - dispose(): void; - } -} - -declare namespace BABYLON { - class RefractionPostProcess extends PostProcess { - color: Color3; - depth: number; - colorLevel: number; - private _refRexture; - constructor(name: string, refractionTextureUrl: string, color: Color3, depth: number, colorLevel: number, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); - dispose(camera: Camera): void; - } -} - -declare namespace BABYLON { - class SSAORenderingPipeline extends PostProcessRenderPipeline { - /** - * The PassPostProcess id in the pipeline that contains the original scene color - * @type {string} - */ - SSAOOriginalSceneColorEffect: string; - /** - * The SSAO PostProcess id in the pipeline - * @type {string} - */ - SSAORenderEffect: string; - /** - * The horizontal blur PostProcess id in the pipeline - * @type {string} - */ - SSAOBlurHRenderEffect: string; - /** - * The vertical blur PostProcess id in the pipeline - * @type {string} - */ - SSAOBlurVRenderEffect: string; - /** - * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect) - * @type {string} - */ - SSAOCombineRenderEffect: string; - /** - * The output strength of the SSAO post-process. Default value is 1.0. - * @type {number} - */ - totalStrength: number; - /** - * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006 - * @type {number} - */ - radius: number; - /** - * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel - * Must not be equal to fallOff and superior to fallOff. - * Default value is 0.975 - * @type {number} - */ - area: number; - /** - * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel - * Must not be equal to area and inferior to area. - * Default value is 0.0 - * @type {number} - */ - fallOff: number; - /** - * The base color of the SSAO post-process - * The final result is "base + ssao" between [0, 1] - * @type {number} - */ - base: number; - private _scene; - private _depthTexture; - private _randomTexture; - private _originalColorPostProcess; - private _ssaoPostProcess; - private _blurHPostProcess; - private _blurVPostProcess; - private _ssaoCombinePostProcess; - private _firstUpdate; - /** - * @constructor - * @param {string} name - The rendering pipeline name - * @param {BABYLON.Scene} scene - The scene linked to this pipeline - * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 } - * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to - */ - constructor(name: string, scene: Scene, ratio: any, cameras?: Camera[]); - /** - * Returns the horizontal blur PostProcess - * @return {BABYLON.BlurPostProcess} The horizontal blur post-process - */ - getBlurHPostProcess(): BlurPostProcess; - /** - * Returns the vertical blur PostProcess - * @return {BABYLON.BlurPostProcess} The vertical blur post-process - */ - getBlurVPostProcess(): BlurPostProcess; - /** - * Removes the internal pipeline assets and detatches the pipeline from the scene cameras - */ - dispose(disableDepthRender?: boolean): void; - private _createSSAOPostProcess(ratio); - private _createSSAOCombinePostProcess(ratio); - private _createRandomTexture(); - } -} - -declare namespace BABYLON { - class StereoscopicInterlacePostProcess extends PostProcess { - private _stepSize; - constructor(name: string, camB: Camera, postProcessA: PostProcess, isStereoscopicHoriz: boolean, samplingMode?: number); - } -} - -declare namespace BABYLON { - enum TonemappingOperator { - Hable = 0, - Reinhard = 1, - HejiDawson = 2, - Photographic = 3, - } - class TonemapPostProcess extends PostProcess { - private _operator; - private _exposureAdjustment; - constructor(name: string, operator: TonemappingOperator, exposureAdjustment: number, camera: Camera, samplingMode?: number, engine?: Engine, textureFormat?: number); - } -} - -declare namespace BABYLON { - class VolumetricLightScatteringPostProcess extends PostProcess { - private _volumetricLightScatteringPass; - private _volumetricLightScatteringRTT; - private _viewPort; - private _screenCoordinates; - private _cachedDefines; - private _customMeshPosition; - /** - * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false) - * @type {boolean} - */ - useCustomMeshPosition: boolean; - /** - * If the post-process should inverse the light scattering direction - * @type {boolean} - */ - invert: boolean; - /** - * The internal mesh used by the post-process - * @type {boolean} - */ - mesh: Mesh; - /** - * Set to true to use the diffuseColor instead of the diffuseTexture - * @type {boolean} - */ - useDiffuseColor: boolean; - /** - * Array containing the excluded meshes not rendered in the internal pass - */ - excludedMeshes: AbstractMesh[]; - /** - * Controls the overall intensity of the post-process - * @type {number} - */ - exposure: number; - /** - * Dissipates each sample's contribution in range [0, 1] - * @type {number} - */ - decay: number; - /** - * Controls the overall intensity of each sample - * @type {number} - */ - weight: number; - /** - * Controls the density of each sample - * @type {number} - */ - density: number; - /** - * @constructor - * @param {string} name - The post-process name - * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) - * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to - * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering - * @param {number} samples - The post-process quality, default 100 - * @param {number} samplingMode - The post-process filtering mode - * @param {BABYLON.Engine} engine - The babylon engine - * @param {boolean} reusable - If the post-process is reusable - * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided - */ - constructor(name: string, ratio: any, camera: Camera, mesh?: Mesh, samples?: number, samplingMode?: number, engine?: Engine, reusable?: boolean, scene?: Scene); - isReady(subMesh: SubMesh, useInstances: boolean): boolean; - /** - * Sets the new light position for light scattering effect - * @param {BABYLON.Vector3} The new custom light position - */ - setCustomMeshPosition(position: Vector3): void; - /** - * Returns the light position for light scattering effect - * @return {BABYLON.Vector3} The custom light position - */ - getCustomMeshPosition(): Vector3; - /** - * Disposes the internal assets and detaches the post-process from the camera - */ - dispose(camera: Camera): void; - /** - * Returns the render target texture used by the post-process - * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process - */ - getPass(): RenderTargetTexture; - private _meshExcluded(mesh); - private _createPass(scene, ratio); - private _updateMeshScreenCoordinates(scene); - /** - * Creates a default mesh for the Volumeric Light Scattering post-process - * @param {string} The mesh name - * @param {BABYLON.Scene} The scene where to create the mesh - * @return {BABYLON.Mesh} the default mesh - */ - static CreateDefaultMesh(name: string, scene: Scene): Mesh; - } -} - -declare namespace BABYLON { - class VRDistortionCorrectionPostProcess extends PostProcess { - aspectRatio: number; - private _isRightEye; - private _distortionFactors; - private _postProcessScaleFactor; - private _lensCenterOffset; - private _scaleIn; - private _scaleFactor; - private _lensCenter; - constructor(name: string, camera: Camera, isRightEye: boolean, vrMetrics: VRCameraMetrics); - } -} - -declare namespace BABYLON { - class ReflectionProbe { - name: string; - private _scene; - private _renderTargetTexture; - private _projectionMatrix; - private _viewMatrix; - private _target; - private _add; - private _attachedMesh; - position: Vector3; - constructor(name: string, size: number, scene: Scene, generateMipMaps?: boolean); - refreshRate: number; - getScene(): Scene; - cubeTexture: RenderTargetTexture; - renderList: AbstractMesh[]; - attachToMesh(mesh: AbstractMesh): void; - dispose(): void; - } -} - -declare namespace BABYLON { - class BoundingBoxRenderer { - frontColor: Color3; - backColor: Color3; - showBackLines: boolean; - renderList: SmartArray; - private _scene; - private _colorShader; - private _vb; - private _ib; - constructor(scene: Scene); - private _prepareRessources(); - reset(): void; - render(): void; - dispose(): void; - } -} - -declare namespace BABYLON { - class DepthRenderer { - private _scene; - private _depthMap; - private _effect; - private _viewMatrix; - private _projectionMatrix; - private _transformMatrix; - private _worldViewProjection; - private _cachedDefines; - constructor(scene: Scene, type?: number); - isReady(subMesh: SubMesh, useInstances: boolean): boolean; - getDepthMap(): RenderTargetTexture; - dispose(): void; - } -} - -declare namespace BABYLON { - class EdgesRenderer { - edgesWidthScalerForOrthographic: number; - edgesWidthScalerForPerspective: number; - private _source; - private _linesPositions; - private _linesNormals; - private _linesIndices; - private _epsilon; - private _indicesCount; - private _lineShader; - private _vb0; - private _vb1; - private _ib; - private _buffers; - private _checkVerticesInsteadOfIndices; - constructor(source: AbstractMesh, epsilon?: number, checkVerticesInsteadOfIndices?: boolean); - private _prepareRessources(); - dispose(): void; - private _processEdgeForAdjacencies(pa, pb, p0, p1, p2); - private _processEdgeForAdjacenciesWithVertices(pa, pb, p0, p1, p2); - private _checkEdge(faceIndex, edge, faceNormals, p0, p1); - _generateEdgesLines(): void; - render(): void; - } -} - -declare namespace BABYLON { - class OutlineRenderer { - private _scene; - private _effect; - private _cachedDefines; - constructor(scene: Scene); - render(subMesh: SubMesh, batch: _InstancesBatch, useOverlay?: boolean): void; - isReady(subMesh: SubMesh, useInstances: boolean): boolean; - } -} - -declare namespace BABYLON { - class RenderingGroup { - index: number; - private _scene; - private _opaqueSubMeshes; - private _transparentSubMeshes; - private _alphaTestSubMeshes; - private _activeVertices; - onBeforeTransparentRendering: () => void; - constructor(index: number, scene: Scene); - render(customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray) => void): boolean; - prepare(): void; - dispatch(subMesh: SubMesh): void; - } -} - -declare namespace BABYLON { - class RenderingManager { - static MAX_RENDERINGGROUPS: number; - private _scene; - private _renderingGroups; - private _depthBufferAlreadyCleaned; - private _currentIndex; - private _currentActiveMeshes; - private _currentRenderParticles; - private _currentRenderSprites; - constructor(scene: Scene); - private _renderParticles(index, activeMeshes); - private _renderSprites(index); - private _clearDepthBuffer(); - private _renderSpritesAndParticles(); - render(customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray) => void, activeMeshes: AbstractMesh[], renderParticles: boolean, renderSprites: boolean): void; - reset(): void; - dispatch(subMesh: SubMesh): void; - } -} - -declare namespace BABYLON { - class Sprite { - name: string; - position: Vector3; - color: Color4; - width: number; - height: number; - angle: number; - cellIndex: number; - invertU: number; - invertV: number; - disposeWhenFinishedAnimating: boolean; - animations: Animation[]; - isPickable: boolean; - actionManager: ActionManager; - private _animationStarted; - private _loopAnimation; - private _fromIndex; - private _toIndex; - private _delay; - private _direction; - private _frameCount; - private _manager; - private _time; - size: number; - constructor(name: string, manager: SpriteManager); - playAnimation(from: number, to: number, loop: boolean, delay: number): void; - stopAnimation(): void; - _animate(deltaTime: number): void; - dispose(): void; - } -} - -declare namespace BABYLON { - class SpriteManager { - name: string; - cellSize: number; - sprites: Sprite[]; - renderingGroupId: number; - layerMask: number; - onDispose: () => void; - fogEnabled: boolean; - isPickable: boolean; - private _capacity; - private _spriteTexture; - private _epsilon; - private _scene; - private _vertexDeclaration; - private _vertexStrideSize; - private _vertexBuffer; - private _indexBuffer; - private _vertices; - private _effectBase; - private _effectFog; - constructor(name: string, imgUrl: string, capacity: number, cellSize: number, scene: Scene, epsilon?: number, samplingMode?: number); - private _appendSpriteVertex(index, sprite, offsetX, offsetY, rowSize); - intersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean): PickingInfo; - render(): void; - dispose(): void; - } -} - -declare namespace BABYLON.Internals { - class AndOrNotEvaluator { - static Eval(query: string, evaluateCallback: (val: any) => boolean): boolean; - private static _HandleParenthesisContent(parenthesisContent, evaluateCallback); - private static _SimplifyNegation(booleanString); - } -} - -declare namespace BABYLON { - interface IAssetTask { - onSuccess: (task: IAssetTask) => void; - onError: (task: IAssetTask) => void; - isCompleted: boolean; - run(scene: Scene, onSuccess: () => void, onError: () => void): any; - } - class MeshAssetTask implements IAssetTask { - name: string; - meshesNames: any; - rootUrl: string; - sceneFilename: string; - loadedMeshes: Array; - loadedParticleSystems: Array; - loadedSkeletons: Array; - onSuccess: (task: IAssetTask) => void; - onError: (task: IAssetTask) => void; - isCompleted: boolean; - constructor(name: string, meshesNames: any, rootUrl: string, sceneFilename: string); - run(scene: Scene, onSuccess: () => void, onError: () => void): void; - } - class TextFileAssetTask implements IAssetTask { - name: string; - url: string; - onSuccess: (task: IAssetTask) => void; - onError: (task: IAssetTask) => void; - isCompleted: boolean; - text: string; - constructor(name: string, url: string); - run(scene: Scene, onSuccess: () => void, onError: () => void): void; - } - class BinaryFileAssetTask implements IAssetTask { - name: string; - url: string; - onSuccess: (task: IAssetTask) => void; - onError: (task: IAssetTask) => void; - isCompleted: boolean; - data: ArrayBuffer; - constructor(name: string, url: string); - run(scene: Scene, onSuccess: () => void, onError: () => void): void; - } - class ImageAssetTask implements IAssetTask { - name: string; - url: string; - onSuccess: (task: IAssetTask) => void; - onError: (task: IAssetTask) => void; - isCompleted: boolean; - image: HTMLImageElement; - constructor(name: string, url: string); - run(scene: Scene, onSuccess: () => void, onError: () => void): void; - } - class TextureAssetTask implements IAssetTask { - name: string; - url: string; - noMipmap: boolean; - invertY: boolean; - samplingMode: number; - onSuccess: (task: IAssetTask) => void; - onError: (task: IAssetTask) => void; - isCompleted: boolean; - texture: Texture; - constructor(name: string, url: string, noMipmap?: boolean, invertY?: boolean, samplingMode?: number); - run(scene: Scene, onSuccess: () => void, onError: () => void): void; - } - class AssetsManager { - private _tasks; - private _scene; - private _waitingTasksCount; - onFinish: (tasks: IAssetTask[]) => void; - onTaskSuccess: (task: IAssetTask) => void; - onTaskError: (task: IAssetTask) => void; - useDefaultLoadingScreen: boolean; - constructor(scene: Scene); - addMeshTask(taskName: string, meshesNames: any, rootUrl: string, sceneFilename: string): IAssetTask; - addTextFileTask(taskName: string, url: string): IAssetTask; - addBinaryFileTask(taskName: string, url: string): IAssetTask; - addImageTask(taskName: string, url: string): IAssetTask; - addTextureTask(taskName: string, url: string, noMipmap?: boolean, invertY?: boolean, samplingMode?: number): IAssetTask; - private _decreaseWaitingTasksCount(); - private _runTask(task); - reset(): AssetsManager; - load(): AssetsManager; - } -} - -declare namespace BABYLON { - class Database { - private callbackManifestChecked; - private currentSceneUrl; - private db; - private enableSceneOffline; - private enableTexturesOffline; - private manifestVersionFound; - private mustUpdateRessources; - private hasReachedQuota; - private isSupported; - private idbFactory; - static IsUASupportingBlobStorage: boolean; - static IDBStorageEnabled: boolean; - constructor(urlToScene: string, callbackManifestChecked: (checked: boolean) => any); - static parseURL: (url: string) => string; - static ReturnFullUrlLocation: (url: string) => string; - checkManifestFile(): void; - openAsync(successCallback: any, errorCallback: any): void; - loadImageFromDB(url: string, image: HTMLImageElement): void; - private _loadImageFromDBAsync(url, image, notInDBCallback); - private _saveImageIntoDBAsync(url, image); - private _checkVersionFromDB(url, versionLoaded); - private _loadVersionFromDBAsync(url, callback, updateInDBCallback); - private _saveVersionIntoDBAsync(url, callback); - private loadFileFromDB(url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer?); - private _loadFileFromDBAsync(url, callback, notInDBCallback, useArrayBuffer?); - private _saveFileIntoDBAsync(url, callback, progressCallback, useArrayBuffer?); - } -} - -declare namespace BABYLON { - class FilesInput { - private _engine; - private _currentScene; - private _canvas; - private _sceneLoadedCallback; - private _progressCallback; - private _additionnalRenderLoopLogicCallback; - private _textureLoadingCallback; - private _startingProcessingFilesCallback; - private _elementToMonitor; - static FilesTextures: any[]; - static FilesToLoad: any[]; - private _sceneFileToLoad; - private _filesToLoad; - constructor(p_engine: Engine, p_scene: Scene, p_canvas: HTMLCanvasElement, p_sceneLoadedCallback: any, p_progressCallback: any, p_additionnalRenderLoopLogicCallback: any, p_textureLoadingCallback: any, p_startingProcessingFilesCallback: any); - monitorElementForDragNDrop(p_elementToMonitor: HTMLElement): void; - private renderFunction(); - private drag(e); - private drop(eventDrop); - loadFiles(event: any): void; - reload(): void; - } -} - -declare namespace BABYLON { - class Gamepads { - private babylonGamepads; - private oneGamepadConnected; - private isMonitoring; - private gamepadEventSupported; - private gamepadSupportAvailable; - private _callbackGamepadConnected; - private static gamepadDOMInfo; - constructor(ongamedpadconnected: (gamepad: Gamepad) => void); - dispose(): void; - private _onGamepadConnected(evt); - private _addNewGamepad(gamepad); - private _onGamepadDisconnected(evt); - private _startMonitoringGamepads(); - private _stopMonitoringGamepads(); - private _checkGamepadsStatus(); - private _updateGamepadObjects(); - } - class StickValues { - x: any; - y: any; - constructor(x: any, y: any); - } - class Gamepad { - id: string; - index: number; - browserGamepad: any; - private _leftStick; - private _rightStick; - private _onleftstickchanged; - private _onrightstickchanged; - constructor(id: string, index: number, browserGamepad: any); - onleftstickchanged(callback: (values: StickValues) => void): void; - onrightstickchanged(callback: (values: StickValues) => void): void; - leftStick: StickValues; - rightStick: StickValues; - update(): void; - } - class GenericPad extends Gamepad { - id: string; - index: number; - gamepad: any; - private _buttons; - private _onbuttondown; - private _onbuttonup; - onbuttondown(callback: (buttonPressed: number) => void): void; - onbuttonup(callback: (buttonReleased: number) => void): void; - constructor(id: string, index: number, gamepad: any); - private _setButtonValue(newValue, currentValue, buttonIndex); - update(): void; - } - enum Xbox360Button { - A = 0, - B = 1, - X = 2, - Y = 3, - Start = 4, - Back = 5, - LB = 6, - RB = 7, - LeftStick = 8, - RightStick = 9, - } - enum Xbox360Dpad { - Up = 0, - Down = 1, - Left = 2, - Right = 3, - } - class Xbox360Pad extends Gamepad { - private _leftTrigger; - private _rightTrigger; - private _onlefttriggerchanged; - private _onrighttriggerchanged; - private _onbuttondown; - private _onbuttonup; - private _ondpaddown; - private _ondpadup; - private _buttonA; - private _buttonB; - private _buttonX; - private _buttonY; - private _buttonBack; - private _buttonStart; - private _buttonLB; - private _buttonRB; - private _buttonLeftStick; - private _buttonRightStick; - private _dPadUp; - private _dPadDown; - private _dPadLeft; - private _dPadRight; - onlefttriggerchanged(callback: (value: number) => void): void; - onrighttriggerchanged(callback: (value: number) => void): void; - leftTrigger: number; - rightTrigger: number; - onbuttondown(callback: (buttonPressed: Xbox360Button) => void): void; - onbuttonup(callback: (buttonReleased: Xbox360Button) => void): void; - ondpaddown(callback: (dPadPressed: Xbox360Dpad) => void): void; - ondpadup(callback: (dPadReleased: Xbox360Dpad) => void): void; - private _setButtonValue(newValue, currentValue, buttonType); - private _setDPadValue(newValue, currentValue, buttonType); - buttonA: number; - buttonB: number; - buttonX: number; - buttonY: number; - buttonStart: number; - buttonBack: number; - buttonLB: number; - buttonRB: number; - buttonLeftStick: number; - buttonRightStick: number; - dPadUp: number; - dPadDown: number; - dPadLeft: number; - dPadRight: number; - update(): void; - } -} -interface Navigator { - getGamepads(func?: any): any; - webkitGetGamepads(func?: any): any; - msGetGamepads(func?: any): any; - webkitGamepads(func?: any): any; -} - -declare namespace BABYLON { - interface ILoadingScreen { - displayLoadingUI: () => void; - hideLoadingUI: () => void; - loadingUIBackgroundColor: string; - loadingUIText: string; - } - class DefaultLoadingScreen implements ILoadingScreen { - private _renderingCanvas; - private _loadingText; - private _loadingDivBackgroundColor; - private _loadingDiv; - private _loadingTextDiv; - constructor(_renderingCanvas: HTMLCanvasElement, _loadingText?: string, _loadingDivBackgroundColor?: string); - displayLoadingUI(): void; - hideLoadingUI(): void; - loadingUIText: string; - loadingUIBackgroundColor: string; - private _resizeLoadingUI; - } -} - -declare namespace BABYLON { - class SceneOptimization { - priority: number; - apply: (scene: Scene) => boolean; - constructor(priority?: number); - } - class TextureOptimization extends SceneOptimization { - priority: number; - maximumSize: number; - constructor(priority?: number, maximumSize?: number); - apply: (scene: Scene) => boolean; - } - class HardwareScalingOptimization extends SceneOptimization { - priority: number; - maximumScale: number; - private _currentScale; - constructor(priority?: number, maximumScale?: number); - apply: (scene: Scene) => boolean; - } - class ShadowsOptimization extends SceneOptimization { - apply: (scene: Scene) => boolean; - } - class PostProcessesOptimization extends SceneOptimization { - apply: (scene: Scene) => boolean; - } - class LensFlaresOptimization extends SceneOptimization { - apply: (scene: Scene) => boolean; - } - class ParticlesOptimization extends SceneOptimization { - apply: (scene: Scene) => boolean; - } - class RenderTargetsOptimization extends SceneOptimization { - apply: (scene: Scene) => boolean; - } - class MergeMeshesOptimization extends SceneOptimization { - static _UpdateSelectionTree: boolean; - static UpdateSelectionTree: boolean; - private _canBeMerged; - apply: (scene: Scene, updateSelectionTree?: boolean) => boolean; - } - class SceneOptimizerOptions { - targetFrameRate: number; - trackerDuration: number; - optimizations: SceneOptimization[]; - constructor(targetFrameRate?: number, trackerDuration?: number); - static LowDegradationAllowed(targetFrameRate?: number): SceneOptimizerOptions; - static ModerateDegradationAllowed(targetFrameRate?: number): SceneOptimizerOptions; - static HighDegradationAllowed(targetFrameRate?: number): SceneOptimizerOptions; - } - class SceneOptimizer { - static _CheckCurrentState(scene: Scene, options: SceneOptimizerOptions, currentPriorityLevel: number, onSuccess?: () => void, onFailure?: () => void): void; - static OptimizeAsync(scene: Scene, options?: SceneOptimizerOptions, onSuccess?: () => void, onFailure?: () => void): void; - } -} - -declare namespace BABYLON { - class SceneSerializer { - static Serialize(scene: Scene): any; - static SerializeMesh(toSerialize: any, withParents?: boolean, withChildren?: boolean): any; - } -} - -declare namespace BABYLON { - class SmartArray { - data: Array; - length: number; - private _id; - private _duplicateId; - constructor(capacity: number); - push(value: any): void; - pushNoDuplicate(value: any): void; - sort(compareFn: any): void; - reset(): void; - concat(array: any): void; - concatWithNoDuplicate(array: any): void; - indexOf(value: any): number; - private static _GlobalId; - } -} - -declare namespace BABYLON { - class SmartCollection { - count: number; - items: any; - private _keys; - private _initialCapacity; - constructor(capacity?: number); - add(key: any, item: any): number; - remove(key: any): number; - removeItemOfIndex(index: number): number; - indexOf(key: any): number; - item(key: any): any; - getAllKeys(): any[]; - getKeyByIndex(index: number): any; - getItemByIndex(index: number): any; - empty(): void; - forEach(block: (item: any) => void): void; - } -} - -declare namespace BABYLON { - class Tags { - static EnableFor(obj: any): void; - static DisableFor(obj: any): void; - static HasTags(obj: any): boolean; - static GetTags(obj: any, asString?: boolean): any; - static AddTagsTo(obj: any, tagsString: string): void; - static _AddTagTo(obj: any, tag: string): void; - static RemoveTagsFrom(obj: any, tagsString: string): void; - static _RemoveTagFrom(obj: any, tag: string): void; - static MatchesQuery(obj: any, tagsQuery: string): boolean; - } -} - -declare namespace BABYLON.Internals { - interface DDSInfo { - width: number; - height: number; - mipmapCount: number; - isFourCC: boolean; - isRGB: boolean; - isLuminance: boolean; - isCube: boolean; - } - class DDSTools { - static GetDDSInfo(arrayBuffer: any): DDSInfo; - private static GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); - private static GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); - private static GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); - static UploadDDSLevels(gl: WebGLRenderingContext, ext: any, arrayBuffer: any, info: DDSInfo, loadMipmaps: boolean, faces: number): void; - } -} - -declare namespace BABYLON.Internals { - class TGATools { - private static _TYPE_NO_DATA; - private static _TYPE_INDEXED; - private static _TYPE_RGB; - private static _TYPE_GREY; - private static _TYPE_RLE_INDEXED; - private static _TYPE_RLE_RGB; - private static _TYPE_RLE_GREY; - private static _ORIGIN_MASK; - private static _ORIGIN_SHIFT; - private static _ORIGIN_BL; - private static _ORIGIN_BR; - private static _ORIGIN_UL; - private static _ORIGIN_UR; - static GetTGAHeader(data: Uint8Array): any; - static UploadContent(gl: WebGLRenderingContext, data: Uint8Array): void; - static _getImageData8bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; - static _getImageData16bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; - static _getImageData24bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; - static _getImageData32bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; - static _getImageDataGrey8bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; - static _getImageDataGrey16bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; - } -} - -declare namespace BABYLON { - interface IAnimatable { - animations: Array; - } - interface ISize { - width: number; - height: number; - } - class Tools { - static BaseUrl: string; - static CorsBehavior: any; - static UseFallbackTexture: boolean; - static Instantiate(className: string): any; - static GetConstructorName(obj: any): any; - static ToHex(i: number): string; - static SetImmediate(action: () => void): void; - static IsExponentOfTwo(value: number): boolean; - static GetExponentOfTwo(value: number, max: number): number; - static GetFilename(path: string): string; - static GetDOMTextContent(element: HTMLElement): string; - static ToDegrees(angle: number): number; - static ToRadians(angle: number): number; - static EncodeArrayBufferTobase64(buffer: ArrayBuffer): string; - static ExtractMinAndMaxIndexed(positions: number[] | Float32Array, indices: number[] | Int32Array, indexStart: number, indexCount: number): { - minimum: Vector3; - maximum: Vector3; - }; - static ExtractMinAndMax(positions: number[] | Float32Array, start: number, count: number): { - minimum: Vector3; - maximum: Vector3; - }; - static MakeArray(obj: any, allowsNullUndefined?: boolean): Array; - static GetPointerPrefix(): string; - static QueueNewFrame(func: any): void; - static RequestFullscreen(element: any): void; - static ExitFullscreen(): void; - static CleanUrl(url: string): string; - static LoadImage(url: any, onload: any, onerror: any, database: any): HTMLImageElement; - static LoadFile(url: string, callback: (data: any) => void, progressCallBack?: () => void, database?: any, useArrayBuffer?: boolean, onError?: () => void): void; - static ReadFileAsDataURL(fileToLoad: any, callback: any, progressCallback: any): void; - static ReadFile(fileToLoad: any, callback: any, progressCallBack: any, useArrayBuffer?: boolean): void; - static FileAsURL(content: string): string; - static Clamp(value: number, min?: number, max?: number): number; - static Sign(value: number): number; - static Format(value: number, decimals?: number): string; - static CheckExtends(v: Vector3, min: Vector3, max: Vector3): void; - static WithinEpsilon(a: number, b: number, epsilon?: number): boolean; - static DeepCopy(source: any, destination: any, doNotCopyList?: string[], mustCopyList?: string[]): void; - static IsEmpty(obj: any): boolean; - static RegisterTopRootEvents(events: { - name: string; - handler: EventListener; - }[]): void; - static UnregisterTopRootEvents(events: { - name: string; - handler: EventListener; - }[]): void; - static DumpFramebuffer(width: number, height: number, engine: Engine, successCallback?: (data: string) => void): void; - static CreateScreenshot(engine: Engine, camera: Camera, size: any, successCallback?: (data: string) => void): void; - static ValidateXHRData(xhr: XMLHttpRequest, dataType?: number): boolean; - private static _NoneLogLevel; - private static _MessageLogLevel; - private static _WarningLogLevel; - private static _ErrorLogLevel; - private static _LogCache; - static errorsCount: number; - static OnNewCacheEntry: (entry: string) => void; - static NoneLogLevel: number; - static MessageLogLevel: number; - static WarningLogLevel: number; - static ErrorLogLevel: number; - static AllLogLevel: number; - private static _AddLogEntry(entry); - private static _FormatMessage(message); - static Log: (message: string) => void; - private static _LogDisabled(message); - private static _LogEnabled(message); - static Warn: (message: string) => void; - private static _WarnDisabled(message); - private static _WarnEnabled(message); - static Error: (message: string) => void; - private static _ErrorDisabled(message); - private static _ErrorEnabled(message); - static LogCache: string; - static ClearLogCache(): void; - static LogLevels: number; - private static _PerformanceNoneLogLevel; - private static _PerformanceUserMarkLogLevel; - private static _PerformanceConsoleLogLevel; - private static _performance; - static PerformanceNoneLogLevel: number; - static PerformanceUserMarkLogLevel: number; - static PerformanceConsoleLogLevel: number; - static PerformanceLogLevel: number; - static _StartPerformanceCounterDisabled(counterName: string, condition?: boolean): void; - static _EndPerformanceCounterDisabled(counterName: string, condition?: boolean): void; - static _StartUserMark(counterName: string, condition?: boolean): void; - static _EndUserMark(counterName: string, condition?: boolean): void; - static _StartPerformanceConsole(counterName: string, condition?: boolean): void; - static _EndPerformanceConsole(counterName: string, condition?: boolean): void; - static StartPerformanceCounter: (counterName: string, condition?: boolean) => void; - static EndPerformanceCounter: (counterName: string, condition?: boolean) => void; - static Now: number; - } - /** - * An implementation of a loop for asynchronous functions. - */ - class AsyncLoop { - iterations: number; - private _fn; - private _successCallback; - index: number; - private _done; - /** - * Constroctor. - * @param iterations the number of iterations. - * @param _fn the function to run each iteration - * @param _successCallback the callback that will be called upon succesful execution - * @param offset starting offset. - */ - constructor(iterations: number, _fn: (asyncLoop: AsyncLoop) => void, _successCallback: () => void, offset?: number); - /** - * Execute the next iteration. Must be called after the last iteration was finished. - */ - executeNext(): void; - /** - * Break the loop and run the success callback. - */ - breakLoop(): void; - /** - * Helper function - */ - static Run(iterations: number, _fn: (asyncLoop: AsyncLoop) => void, _successCallback: () => void, offset?: number): AsyncLoop; - /** - * A for-loop that will run a given number of iterations synchronous and the rest async. - * @param iterations total number of iterations - * @param syncedIterations number of synchronous iterations in each async iteration. - * @param fn the function to call each iteration. - * @param callback a success call back that will be called when iterating stops. - * @param breakFunction a break condition (optional) - * @param timeout timeout settings for the setTimeout function. default - 0. - * @constructor - */ - static SyncAsyncForLoop(iterations: number, syncedIterations: number, fn: (iteration: number) => void, callback: () => void, breakFunction?: () => boolean, timeout?: number): void; - } -} - -declare namespace BABYLON { - enum JoystickAxis { - X = 0, - Y = 1, - Z = 2, - } - class VirtualJoystick { - reverseLeftRight: boolean; - reverseUpDown: boolean; - deltaPosition: Vector3; - pressed: boolean; - private static _globalJoystickIndex; - private static vjCanvas; - private static vjCanvasContext; - private static vjCanvasWidth; - private static vjCanvasHeight; - private static halfWidth; - private static halfHeight; - private _action; - private _axisTargetedByLeftAndRight; - private _axisTargetedByUpAndDown; - private _joystickSensibility; - private _inversedSensibility; - private _rotationSpeed; - private _inverseRotationSpeed; - private _rotateOnAxisRelativeToMesh; - private _joystickPointerID; - private _joystickColor; - private _joystickPointerPos; - private _joystickPreviousPointerPos; - private _joystickPointerStartPos; - private _deltaJoystickVector; - private _leftJoystick; - private _joystickIndex; - private _touches; - private _onPointerDownHandlerRef; - private _onPointerMoveHandlerRef; - private _onPointerUpHandlerRef; - private _onPointerOutHandlerRef; - private _onResize; - constructor(leftJoystick?: boolean); - setJoystickSensibility(newJoystickSensibility: number): void; - private _onPointerDown(e); - private _onPointerMove(e); - private _onPointerUp(e); - /** - * Change the color of the virtual joystick - * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000") - */ - setJoystickColor(newColor: string): void; - setActionOnTouch(action: () => any): void; - setAxisForLeftRight(axis: JoystickAxis): void; - setAxisForUpDown(axis: JoystickAxis): void; - private _clearCanvas(); - private _drawVirtualJoystick(); - releaseCanvas(): void; - } -} - -declare namespace BABYLON { - class VRDeviceOrientationFreeCamera extends FreeCamera { - _alpha: number; - _beta: number; - _gamma: number; - private _offsetOrientation; - private _deviceOrientationHandler; - constructor(name: string, position: Vector3, scene: Scene, compensateDistortion?: boolean); - _onOrientationEvent(evt: DeviceOrientationEvent): void; - attachControl(element: HTMLElement, noPreventDefault?: boolean): void; - detachControl(element: HTMLElement): void; - } -} - -declare var HMDVRDevice: any; -declare var PositionSensorVRDevice: any; -declare namespace BABYLON { - class WebVRFreeCamera extends FreeCamera { - _hmdDevice: any; - _sensorDevice: any; - _cacheState: any; - _cacheQuaternion: Quaternion; - _cacheRotation: Vector3; - _vrEnabled: boolean; - constructor(name: string, position: Vector3, scene: Scene, compensateDistortion?: boolean); - private _getWebVRDevices(devices); - _checkInputs(): void; - attachControl(element: HTMLElement, noPreventDefault?: boolean): void; - detachControl(element: HTMLElement): void; - } -} - -declare namespace BABYLON { - interface IOctreeContainer { - blocks: Array>; - } - class Octree { - maxDepth: number; - blocks: Array>; - dynamicContent: T[]; - private _maxBlockCapacity; - private _selectionContent; - private _creationFunc; - constructor(creationFunc: (entry: T, block: OctreeBlock) => void, maxBlockCapacity?: number, maxDepth?: number); - update(worldMin: Vector3, worldMax: Vector3, entries: T[]): void; - addMesh(entry: T): void; - select(frustumPlanes: Plane[], allowDuplicate?: boolean): SmartArray; - intersects(sphereCenter: Vector3, sphereRadius: number, allowDuplicate?: boolean): SmartArray; - intersectsRay(ray: Ray): SmartArray; - static _CreateBlocks(worldMin: Vector3, worldMax: Vector3, entries: T[], maxBlockCapacity: number, currentDepth: number, maxDepth: number, target: IOctreeContainer, creationFunc: (entry: T, block: OctreeBlock) => void): void; - static CreationFuncForMeshes: (entry: AbstractMesh, block: OctreeBlock) => void; - static CreationFuncForSubMeshes: (entry: SubMesh, block: OctreeBlock) => void; - } -} - -declare namespace BABYLON { - class OctreeBlock { - entries: T[]; - blocks: Array>; - private _depth; - private _maxDepth; - private _capacity; - private _minPoint; - private _maxPoint; - private _boundingVectors; - private _creationFunc; - constructor(minPoint: Vector3, maxPoint: Vector3, capacity: number, depth: number, maxDepth: number, creationFunc: (entry: T, block: OctreeBlock) => void); - capacity: number; - minPoint: Vector3; - maxPoint: Vector3; - addEntry(entry: T): void; - addEntries(entries: T[]): void; - select(frustumPlanes: Plane[], selection: SmartArray, allowDuplicate?: boolean): void; - intersects(sphereCenter: Vector3, sphereRadius: number, selection: SmartArray, allowDuplicate?: boolean): void; - intersectsRay(ray: Ray, selection: SmartArray): void; - createInnerBlocks(): void; - } -} - -declare namespace BABYLON { - class ShadowGenerator { - private static _FILTER_NONE; - private static _FILTER_VARIANCESHADOWMAP; - private static _FILTER_POISSONSAMPLING; - private static _FILTER_BLURVARIANCESHADOWMAP; - static FILTER_NONE: number; - static FILTER_VARIANCESHADOWMAP: number; - static FILTER_POISSONSAMPLING: number; - static FILTER_BLURVARIANCESHADOWMAP: number; - private _filter; - blurScale: number; - private _blurBoxOffset; - private _bias; - private _lightDirection; - forceBackFacesOnly: boolean; - bias: number; - blurBoxOffset: number; - filter: number; - useVarianceShadowMap: boolean; - usePoissonSampling: boolean; - useBlurVarianceShadowMap: boolean; - private _light; - private _scene; - private _shadowMap; - private _shadowMap2; - private _darkness; - private _transparencyShadow; - private _effect; - private _viewMatrix; - private _projectionMatrix; - private _transformMatrix; - private _worldViewProjection; - private _cachedPosition; - private _cachedDirection; - private _cachedDefines; - private _currentRenderID; - private _downSamplePostprocess; - private _boxBlurPostprocess; - private _mapSize; - private _currentFaceIndex; - private _currentFaceIndexCache; - constructor(mapSize: number, light: IShadowLight); - isReady(subMesh: SubMesh, useInstances: boolean): boolean; - getShadowMap(): RenderTargetTexture; - getShadowMapForRendering(): RenderTargetTexture; - getLight(): IShadowLight; - getTransformMatrix(): Matrix; - getDarkness(): number; - setDarkness(darkness: number): void; - setTransparencyShadow(hasShadow: boolean): void; - private _packHalf(depth); - dispose(): void; - serialize(): any; - static Parse(parsedShadowGenerator: any, scene: Scene): ShadowGenerator; - } -} - -declare namespace BABYLON.Internals { -} - -declare namespace BABYLON { - class BaseTexture { - name: string; - delayLoadState: number; - hasAlpha: boolean; - getAlphaFromRGB: boolean; - level: number; - isCube: boolean; - isRenderTarget: boolean; - animations: Animation[]; - onDispose: () => void; - coordinatesIndex: number; - coordinatesMode: number; - wrapU: number; - wrapV: number; - anisotropicFilteringLevel: number; - _cachedAnisotropicFilteringLevel: number; - private _scene; - _texture: WebGLTexture; - constructor(scene: Scene); - getScene(): Scene; - getTextureMatrix(): Matrix; - getReflectionTextureMatrix(): Matrix; - getInternalTexture(): WebGLTexture; - isReady(): boolean; - getSize(): ISize; - getBaseSize(): ISize; - scale(ratio: number): void; - canRescale: boolean; - _removeFromCache(url: string, noMipmap: boolean): void; - _getFromCache(url: string, noMipmap: boolean, sampling?: number): WebGLTexture; - delayLoad(): void; - clone(): BaseTexture; - releaseInternalTexture(): void; - dispose(): void; - serialize(): any; - } -} - -declare namespace BABYLON { - class CubeTexture extends BaseTexture { - url: string; - coordinatesMode: number; - private _noMipmap; - private _files; - private _extensions; - private _textureMatrix; - static CreateFromImages(files: string[], scene: Scene, noMipmap?: boolean): CubeTexture; - constructor(rootUrl: string, scene: Scene, extensions?: string[], noMipmap?: boolean, files?: string[]); - clone(): CubeTexture; - delayLoad(): void; - getReflectionTextureMatrix(): Matrix; - static Parse(parsedTexture: any, scene: Scene, rootUrl: string): CubeTexture; - serialize(): any; - } -} - -declare namespace BABYLON { - class DynamicTexture extends Texture { - private _generateMipMaps; - private _canvas; - private _context; - constructor(name: string, options: any, scene: Scene, generateMipMaps: boolean, samplingMode?: number); - canRescale: boolean; - scale(ratio: number): void; - getContext(): CanvasRenderingContext2D; - clear(): void; - update(invertY?: boolean): void; - drawText(text: string, x: number, y: number, font: string, color: string, clearColor: string, invertY?: boolean, update?: boolean): void; - clone(): DynamicTexture; - } -} - -declare namespace BABYLON { - class MirrorTexture extends RenderTargetTexture { - mirrorPlane: Plane; - private _transformMatrix; - private _mirrorMatrix; - private _savedViewMatrix; - constructor(name: string, size: number, scene: Scene, generateMipMaps?: boolean); - clone(): MirrorTexture; - serialize(): any; - } -} - -declare namespace BABYLON { - class RawTexture extends Texture { - format: number; - constructor(data: ArrayBufferView, width: number, height: number, format: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number); - update(data: ArrayBufferView): void; - static CreateLuminanceTexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; - static CreateLuminanceAlphaTexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; - static CreateAlphaTexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; - static CreateRGBTexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; - static CreateRGBATexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; - } -} - -declare namespace BABYLON { - class RenderTargetTexture extends Texture { - isCube: boolean; - static _REFRESHRATE_RENDER_ONCE: number; - static _REFRESHRATE_RENDER_ONEVERYFRAME: number; - static _REFRESHRATE_RENDER_ONEVERYTWOFRAMES: number; - static REFRESHRATE_RENDER_ONCE: number; - static REFRESHRATE_RENDER_ONEVERYFRAME: number; - static REFRESHRATE_RENDER_ONEVERYTWOFRAMES: number; - renderList: AbstractMesh[]; - renderParticles: boolean; - renderSprites: boolean; - coordinatesMode: number; - onBeforeRender: (faceIndex: number) => void; - onAfterRender: (faceIndex: number) => void; - onAfterUnbind: () => void; - onClear: (engine: Engine) => void; - activeCamera: Camera; - customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, beforeTransparents?: () => void) => void; - private _size; - _generateMipMaps: boolean; - private _renderingManager; - _waitingRenderList: string[]; - private _doNotChangeAspectRatio; - private _currentRefreshId; - private _refreshRate; - private _textureMatrix; - constructor(name: string, size: any, scene: Scene, generateMipMaps?: boolean, doNotChangeAspectRatio?: boolean, type?: number, isCube?: boolean); - resetRefreshCounter(): void; - refreshRate: number; - _shouldRender(): boolean; - isReady(): boolean; - getRenderSize(): number; - canRescale: boolean; - scale(ratio: number): void; - getReflectionTextureMatrix(): Matrix; - resize(size: any, generateMipMaps?: boolean): void; - render(useCameraPostProcess?: boolean, dumpForDebug?: boolean): void; - renderToTarget(faceIndex: number, currentRenderList: AbstractMesh[], useCameraPostProcess: boolean, dumpForDebug: boolean): void; - clone(): RenderTargetTexture; - serialize(): any; - } -} - -declare namespace BABYLON { - class Texture extends BaseTexture { - static NEAREST_SAMPLINGMODE: number; - static BILINEAR_SAMPLINGMODE: number; - static TRILINEAR_SAMPLINGMODE: number; - static EXPLICIT_MODE: number; - static SPHERICAL_MODE: number; - static PLANAR_MODE: number; - static CUBIC_MODE: number; - static PROJECTION_MODE: number; - static SKYBOX_MODE: number; - static INVCUBIC_MODE: number; - static EQUIRECTANGULAR_MODE: number; - static FIXED_EQUIRECTANGULAR_MODE: number; - static CLAMP_ADDRESSMODE: number; - static WRAP_ADDRESSMODE: number; - static MIRROR_ADDRESSMODE: number; - url: string; - uOffset: number; - vOffset: number; - uScale: number; - vScale: number; - uAng: number; - vAng: number; - wAng: number; - private _noMipmap; - _invertY: boolean; - private _rowGenerationMatrix; - private _cachedTextureMatrix; - private _projectionModeMatrix; - private _t0; - private _t1; - private _t2; - private _cachedUOffset; - private _cachedVOffset; - private _cachedUScale; - private _cachedVScale; - private _cachedUAng; - private _cachedVAng; - private _cachedWAng; - private _cachedCoordinatesMode; - _samplingMode: number; - private _buffer; - private _deleteBuffer; - constructor(url: string, scene: Scene, noMipmap?: boolean, invertY?: boolean, samplingMode?: number, onLoad?: () => void, onError?: () => void, buffer?: any, deleteBuffer?: boolean); - delayLoad(): void; - updateSamplingMode(samplingMode: number): void; - private _prepareRowForTextureGeneration(x, y, z, t); - getTextureMatrix(): Matrix; - getReflectionTextureMatrix(): Matrix; - clone(): Texture; - serialize(): any; - static CreateFromBase64String(data: string, name: string, scene: Scene, noMipmap?: boolean, invertY?: boolean, samplingMode?: number, onLoad?: () => void, onError?: () => void): Texture; - static Parse(parsedTexture: any, scene: Scene, rootUrl: string): BaseTexture; - } -} - -declare namespace BABYLON { - class VideoTexture extends Texture { - video: HTMLVideoElement; - private _autoLaunch; - private _lastUpdate; - constructor(name: string, urls: string[], scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number); - update(): boolean; - } -} - -declare namespace BABYLON { - class CannonJSPlugin implements IPhysicsEnginePlugin { - private _useDeltaForWorldStep; - private _world; - private _registeredMeshes; - private _physicsMaterials; - private _gravity; - private _fixedTimeStep; - name: string; - constructor(_useDeltaForWorldStep?: boolean); - initialize(iterations?: number): void; - private _checkWithEpsilon(value); - runOneStep(delta: number): void; - setGravity(gravity: Vector3): void; - getGravity(): Vector3; - registerMesh(mesh: AbstractMesh, impostor: number, options?: PhysicsBodyCreationOptions): any; - private _createShape(mesh, impostor); - private _createConvexPolyhedron(rawVerts, rawFaces, mesh); - private _createHeightmap(mesh, pointDepth?); - private _addMaterial(friction, restitution); - private _createRigidBodyFromShape(shape, mesh, options); - registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any; - private _unbindBody(body); - unregisterMesh(mesh: AbstractMesh): void; - applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void; - updateBodyPosition: (mesh: AbstractMesh) => void; - createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3): boolean; - dispose(): void; - isSupported(): boolean; - getWorldObject(): any; - getPhysicsBodyOfMesh(mesh: AbstractMesh): any; - } -} - -declare namespace BABYLON { - class OimoJSPlugin implements IPhysicsEnginePlugin { - private _world; - private _registeredMeshes; - name: string; - private _gravity; - private _checkWithEpsilon(value); - initialize(iterations?: number): void; - setGravity(gravity: Vector3): void; - getGravity(): Vector3; - registerMesh(mesh: AbstractMesh, impostor: number, options: PhysicsBodyCreationOptions): any; - registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any; - private _createBodyAsCompound(part, options, initialMesh); - unregisterMesh(mesh: AbstractMesh): void; - private _unbindBody(body); - /** - * Update the body position according to the mesh position - * @param mesh - */ - updateBodyPosition: (mesh: AbstractMesh) => void; - applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void; - createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3, options?: any): boolean; - dispose(): void; - isSupported(): boolean; - getWorldObject(): any; - getPhysicsBodyOfMesh(mesh: AbstractMesh): any; - private _getLastShape(body); - runOneStep(time: number): void; - } -} - -declare namespace BABYLON { - class PostProcessRenderEffect { - private _engine; - private _postProcesses; - private _getPostProcess; - private _singleInstance; - private _cameras; - private _indicesForCamera; - private _renderPasses; - private _renderEffectAsPasses; - _name: string; - applyParameters: (postProcess: PostProcess) => void; - constructor(engine: Engine, name: string, getPostProcess: () => PostProcess, singleInstance?: boolean); - isSupported: boolean; - _update(): void; - addPass(renderPass: PostProcessRenderPass): void; - removePass(renderPass: PostProcessRenderPass): void; - addRenderEffectAsPass(renderEffect: PostProcessRenderEffect): void; - getPass(passName: string): void; - emptyPasses(): void; - _attachCameras(cameras: Camera): any; - _attachCameras(cameras: Camera[]): any; - _detachCameras(cameras: Camera): any; - _detachCameras(cameras: Camera[]): any; - _enable(cameras: Camera): any; - _enable(cameras: Camera[]): any; - _disable(cameras: Camera): any; - _disable(cameras: Camera[]): any; - getPostProcess(camera?: Camera): PostProcess; - private _linkParameters(); - private _linkTextures(effect); - } -} - -declare namespace BABYLON { - class PostProcessRenderPass { - private _enabled; - private _renderList; - private _renderTexture; - private _scene; - private _refCount; - _name: string; - constructor(scene: Scene, name: string, size: number, renderList: Mesh[], beforeRender: () => void, afterRender: () => void); - _incRefCount(): number; - _decRefCount(): number; - _update(): void; - setRenderList(renderList: Mesh[]): void; - getRenderTexture(): RenderTargetTexture; - } -} - -declare namespace BABYLON { - class PostProcessRenderPipeline { - private _engine; - private _renderEffects; - private _renderEffectsForIsolatedPass; - private _cameras; - _name: string; - private static PASS_EFFECT_NAME; - private static PASS_SAMPLER_NAME; - constructor(engine: Engine, name: string); - isSupported: boolean; - addEffect(renderEffect: PostProcessRenderEffect): void; - _enableEffect(renderEffectName: string, cameras: Camera): any; - _enableEffect(renderEffectName: string, cameras: Camera[]): any; - _disableEffect(renderEffectName: string, cameras: Camera): any; - _disableEffect(renderEffectName: string, cameras: Camera[]): any; - _attachCameras(cameras: Camera, unique: boolean): any; - _attachCameras(cameras: Camera[], unique: boolean): any; - _detachCameras(cameras: Camera): any; - _detachCameras(cameras: Camera[]): any; - _enableDisplayOnlyPass(passName: any, cameras: Camera): any; - _enableDisplayOnlyPass(passName: any, cameras: Camera[]): any; - _disableDisplayOnlyPass(cameras: Camera): any; - _disableDisplayOnlyPass(cameras: Camera[]): any; - _update(): void; - dispose(): void; - } -} - -declare namespace BABYLON { - class PostProcessRenderPipelineManager { - private _renderPipelines; - constructor(); - addPipeline(renderPipeline: PostProcessRenderPipeline): void; - attachCamerasToRenderPipeline(renderPipelineName: string, cameras: Camera, unique?: boolean): any; - attachCamerasToRenderPipeline(renderPipelineName: string, cameras: Camera[], unique?: boolean): any; - detachCamerasFromRenderPipeline(renderPipelineName: string, cameras: Camera): any; - detachCamerasFromRenderPipeline(renderPipelineName: string, cameras: Camera[]): any; - enableEffectInPipeline(renderPipelineName: string, renderEffectName: string, cameras: Camera): any; - enableEffectInPipeline(renderPipelineName: string, renderEffectName: string, cameras: Camera[]): any; - disableEffectInPipeline(renderPipelineName: string, renderEffectName: string, cameras: Camera): any; - disableEffectInPipeline(renderPipelineName: string, renderEffectName: string, cameras: Camera[]): any; - enableDisplayOnlyPassInPipeline(renderPipelineName: string, passName: string, cameras: Camera): any; - enableDisplayOnlyPassInPipeline(renderPipelineName: string, passName: string, cameras: Camera[]): any; - disableDisplayOnlyPassInPipeline(renderPipelineName: string, cameras: Camera): any; - disableDisplayOnlyPassInPipeline(renderPipelineName: string, cameras: Camera[]): any; - update(): void; - } -} - -declare namespace BABYLON { - class CustomProceduralTexture extends ProceduralTexture { - private _animate; - private _time; - private _config; - private _texturePath; - constructor(name: string, texturePath: any, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); - private loadJson(jsonUrl); - isReady(): boolean; - render(useCameraPostProcess?: boolean): void; - updateTextures(): void; - updateShaderUniforms(): void; - animate: boolean; - } -} - -declare namespace BABYLON { - class ProceduralTexture extends Texture { - isCube: boolean; - private _size; - _generateMipMaps: boolean; - isEnabled: boolean; - private _doNotChangeAspectRatio; - private _currentRefreshId; - private _refreshRate; - onGenerated: () => void; - private _vertexBuffer; - private _indexBuffer; - private _effect; - private _vertexDeclaration; - private _vertexStrideSize; - private _uniforms; - private _samplers; - private _fragment; - _textures: Texture[]; - private _floats; - private _floatsArrays; - private _colors3; - private _colors4; - private _vectors2; - private _vectors3; - private _matrices; - private _fallbackTexture; - private _fallbackTextureUsed; - constructor(name: string, size: any, fragment: any, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean, isCube?: boolean); - reset(): void; - isReady(): boolean; - resetRefreshCounter(): void; - setFragment(fragment: any): void; - refreshRate: number; - _shouldRender(): boolean; - getRenderSize(): number; - resize(size: any, generateMipMaps: any): void; - private _checkUniform(uniformName); - setTexture(name: string, texture: Texture): ProceduralTexture; - setFloat(name: string, value: number): ProceduralTexture; - setFloats(name: string, value: number[]): ProceduralTexture; - setColor3(name: string, value: Color3): ProceduralTexture; - setColor4(name: string, value: Color4): ProceduralTexture; - setVector2(name: string, value: Vector2): ProceduralTexture; - setVector3(name: string, value: Vector3): ProceduralTexture; - setMatrix(name: string, value: Matrix): ProceduralTexture; - render(useCameraPostProcess?: boolean): void; - clone(): ProceduralTexture; - dispose(): void; - } -} diff --git a/babylonjs/index.d.ts b/babylonjs/index.d.ts new file mode 100644 index 0000000000..ad6d1a242f --- /dev/null +++ b/babylonjs/index.d.ts @@ -0,0 +1,7260 @@ +// Type definitions for BabylonJS v2.3 +// Project: http://www.babylonjs.com/ +// Definitions by: David Catuhe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace BABYLON { + class _DepthCullingState { + private _isDepthTestDirty; + private _isDepthMaskDirty; + private _isDepthFuncDirty; + private _isCullFaceDirty; + private _isCullDirty; + private _isZOffsetDirty; + private _depthTest; + private _depthMask; + private _depthFunc; + private _cull; + private _cullFace; + private _zOffset; + isDirty: boolean; + zOffset: number; + cullFace: number; + cull: boolean; + depthFunc: number; + depthMask: boolean; + depthTest: boolean; + reset(): void; + apply(gl: WebGLRenderingContext): void; + } + class _AlphaState { + private _isAlphaBlendDirty; + private _isBlendFunctionParametersDirty; + private _alphaBlend; + private _blendFunctionParameters; + isDirty: boolean; + alphaBlend: boolean; + setAlphaBlendFunctionParameters(value0: number, value1: number, value2: number, value3: number): void; + reset(): void; + apply(gl: WebGLRenderingContext): void; + } + class EngineCapabilities { + maxTexturesImageUnits: number; + maxTextureSize: number; + maxCubemapTextureSize: number; + maxRenderTextureSize: number; + standardDerivatives: boolean; + s3tc: any; + textureFloat: boolean; + textureAnisotropicFilterExtension: any; + maxAnisotropy: number; + instancedArrays: any; + uintIndices: boolean; + highPrecisionShaderSupported: boolean; + fragmentDepthSupported: boolean; + drawBuffersExtension: any; + } + /** + * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio. + */ + class Engine { + private static _ALPHA_DISABLE; + private static _ALPHA_ADD; + private static _ALPHA_COMBINE; + private static _ALPHA_SUBTRACT; + private static _ALPHA_MULTIPLY; + private static _ALPHA_MAXIMIZED; + private static _ALPHA_ONEONE; + private static _DELAYLOADSTATE_NONE; + private static _DELAYLOADSTATE_LOADED; + private static _DELAYLOADSTATE_LOADING; + private static _DELAYLOADSTATE_NOTLOADED; + private static _TEXTUREFORMAT_ALPHA; + private static _TEXTUREFORMAT_LUMINANCE; + private static _TEXTUREFORMAT_LUMINANCE_ALPHA; + private static _TEXTUREFORMAT_RGB; + private static _TEXTUREFORMAT_RGBA; + private static _TEXTURETYPE_UNSIGNED_INT; + private static _TEXTURETYPE_FLOAT; + static ALPHA_DISABLE: number; + static ALPHA_ONEONE: number; + static ALPHA_ADD: number; + static ALPHA_COMBINE: number; + static ALPHA_SUBTRACT: number; + static ALPHA_MULTIPLY: number; + static ALPHA_MAXIMIZED: number; + static DELAYLOADSTATE_NONE: number; + static DELAYLOADSTATE_LOADED: number; + static DELAYLOADSTATE_LOADING: number; + static DELAYLOADSTATE_NOTLOADED: number; + static TEXTUREFORMAT_ALPHA: number; + static TEXTUREFORMAT_LUMINANCE: number; + static TEXTUREFORMAT_LUMINANCE_ALPHA: number; + static TEXTUREFORMAT_RGB: number; + static TEXTUREFORMAT_RGBA: number; + static TEXTURETYPE_UNSIGNED_INT: number; + static TEXTURETYPE_FLOAT: number; + static Version: string; + static Epsilon: number; + static CollisionsEpsilon: number; + static CodeRepository: string; + static ShadersRepository: string; + isFullscreen: boolean; + isPointerLock: boolean; + cullBackFaces: boolean; + renderEvenInBackground: boolean; + enableOfflineSupport: boolean; + scenes: Scene[]; + _gl: WebGLRenderingContext; + private _renderingCanvas; + private _windowIsBackground; + private _webGLVersion; + static audioEngine: AudioEngine; + private _onBlur; + private _onFocus; + private _onFullscreenChange; + private _onPointerLockChange; + private _hardwareScalingLevel; + private _caps; + private _pointerLockRequested; + private _alphaTest; + private _loadingScreen; + private _drawCalls; + private _glVersion; + private _glRenderer; + private _glVendor; + private _videoTextureSupported; + private _renderingQueueLaunched; + private _activeRenderLoops; + private fpsRange; + private previousFramesDuration; + private fps; + private deltaTime; + private _depthCullingState; + private _alphaState; + private _alphaMode; + private _loadedTexturesCache; + private _maxTextureChannels; + private _activeTexturesCache; + private _currentEffect; + private _compiledEffects; + private _vertexAttribArrays; + private _cachedViewport; + private _cachedVertexBuffers; + private _cachedIndexBuffer; + private _cachedEffectForVertexBuffers; + private _currentRenderTarget; + private _uintIndicesCurrentlySet; + private _workingCanvas; + private _workingContext; + private _bindedRenderFunction; + /** + * @constructor + * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering + * @param {boolean} [antialias] - enable antialias + * @param options - further options to be sent to the getContext function + */ + constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?: { + antialias?: boolean; + preserveDrawingBuffer?: boolean; + }, adaptToDeviceRatio?: boolean); + webGLVersion: string; + private _prepareWorkingCanvas(); + resetTextureCache(): void; + getGlInfo(): { + vendor: string; + renderer: string; + version: string; + }; + getAspectRatio(camera: Camera, useScreen?: boolean): number; + getRenderWidth(useScreen?: boolean): number; + getRenderHeight(useScreen?: boolean): number; + getRenderingCanvas(): HTMLCanvasElement; + getRenderingCanvasClientRect(): ClientRect; + setHardwareScalingLevel(level: number): void; + getHardwareScalingLevel(): number; + getLoadedTexturesCache(): WebGLTexture[]; + getCaps(): EngineCapabilities; + drawCalls: number; + resetDrawCalls(): void; + setDepthFunctionToGreater(): void; + setDepthFunctionToGreaterOrEqual(): void; + setDepthFunctionToLess(): void; + setDepthFunctionToLessOrEqual(): void; + /** + * stop executing a render loop function and remove it from the execution array + * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed. + */ + stopRenderLoop(renderFunction?: () => void): void; + _renderLoop(): void; + /** + * Register and execute a render loop. The engine can have more than one render function. + * @param {Function} renderFunction - the function to continuesly execute starting the next render loop. + * @example + * engine.runRenderLoop(function () { + * scene.render() + * }) + */ + runRenderLoop(renderFunction: () => void): void; + /** + * Toggle full screen mode. + * @param {boolean} requestPointerLock - should a pointer lock be requested from the user + */ + switchFullscreen(requestPointerLock: boolean): void; + clear(color: any, backBuffer: boolean, depthStencil: boolean): void; + /** + * Set the WebGL's viewport + * @param {BABYLON.Viewport} viewport - the viewport element to be used. + * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used. + * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used. + */ + setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void; + setDirectViewport(x: number, y: number, width: number, height: number): void; + beginFrame(): void; + endFrame(): void; + /** + * resize the view according to the canvas' size. + * @example + * window.addEventListener("resize", function () { + * engine.resize(); + * }); + */ + resize(): void; + /** + * force a specific size of the canvas + * @param {number} width - the new canvas' width + * @param {number} height - the new canvas' height + */ + setSize(width: number, height: number): void; + bindFramebuffer(texture: WebGLTexture, faceIndex?: number): void; + unBindFramebuffer(texture: WebGLTexture, disableGenerateMipMaps?: boolean): void; + generateMipMapsForCubemap(texture: WebGLTexture): void; + flushFramebuffer(): void; + restoreDefaultFramebuffer(): void; + private _resetVertexBufferBinding(); + createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer; + createDynamicVertexBuffer(capacity: number): WebGLBuffer; + updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number): void; + private _resetIndexBufferBinding(); + createIndexBuffer(indices: number[] | Int32Array): WebGLBuffer; + bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void; + bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void; + _releaseBuffer(buffer: WebGLBuffer): boolean; + createInstancesBuffer(capacity: number): WebGLBuffer; + deleteInstancesBuffer(buffer: WebGLBuffer): void; + updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void; + unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void; + applyStates(): void; + draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void; + drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void; + drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void; + _releaseEffect(effect: Effect): void; + createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect; + createEffectForParticles(fragmentName: string, uniformsNames?: string[], samplers?: string[], defines?: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect; + createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram; + getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[]; + getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[]; + enableEffect(effect: Effect): void; + setArray(uniform: WebGLUniformLocation, array: number[]): void; + setArray2(uniform: WebGLUniformLocation, array: number[]): void; + setArray3(uniform: WebGLUniformLocation, array: number[]): void; + setArray4(uniform: WebGLUniformLocation, array: number[]): void; + setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void; + setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void; + setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void; + setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void; + setFloat(uniform: WebGLUniformLocation, value: number): void; + setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void; + setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void; + setBool(uniform: WebGLUniformLocation, bool: number): void; + setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; + setColor3(uniform: WebGLUniformLocation, color3: Color3): void; + setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void; + setState(culling: boolean, zOffset?: number, force?: boolean, reverseSide?: boolean): void; + setDepthBuffer(enable: boolean): void; + getDepthWrite(): boolean; + setDepthWrite(enable: boolean): void; + setColorWrite(enable: boolean): void; + setAlphaMode(mode: number): void; + getAlphaMode(): number; + setAlphaTesting(enable: boolean): void; + getAlphaTesting(): boolean; + wipeCaches(): void; + setSamplingMode(texture: WebGLTexture, samplingMode: number): void; + createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode?: number, onLoad?: () => void, onError?: () => void, buffer?: any): WebGLTexture; + updateRawTexture(texture: WebGLTexture, data: ArrayBufferView, format: number, invertY: boolean, compression?: string): void; + createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression?: string): WebGLTexture; + createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number, forceExponantOfTwo?: boolean): WebGLTexture; + updateTextureSamplingMode(samplingMode: number, texture: WebGLTexture): void; + updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void; + updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void; + createRenderTargetTexture(size: any, options: any): WebGLTexture; + createRenderTargetCubeTexture(size: number, options?: any): WebGLTexture; + createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean): WebGLTexture; + _releaseTexture(texture: WebGLTexture): void; + bindSamplers(effect: Effect): void; + _bindTexture(channel: number, texture: WebGLTexture): void; + setTextureFromPostProcess(channel: number, postProcess: PostProcess): void; + unbindAllTextures(): void; + setTexture(channel: number, texture: BaseTexture): void; + _setAnisotropicLevel(key: number, texture: BaseTexture): void; + readPixels(x: number, y: number, width: number, height: number): Uint8Array; + releaseInternalTexture(texture: WebGLTexture): void; + dispose(): void; + displayLoadingUI(): void; + hideLoadingUI(): void; + loadingScreen: ILoadingScreen; + loadingUIText: string; + loadingUIBackgroundColor: string; + getFps(): number; + getDeltaTime(): number; + private _measureFps(); + static isSupported(): boolean; + } +} + +interface Window { + mozIndexedDB(func: any): any; + webkitIndexedDB(func: any): any; + IDBTransaction(func: any): any; + webkitIDBTransaction(func: any): any; + msIDBTransaction(func: any): any; + IDBKeyRange(func: any): any; + webkitIDBKeyRange(func: any): any; + msIDBKeyRange(func: any): any; + webkitURL: HTMLURL; + webkitRequestAnimationFrame(func: any): any; + mozRequestAnimationFrame(func: any): any; + oRequestAnimationFrame(func: any): any; + WebGLRenderingContext: WebGLRenderingContext; + MSGesture: MSGesture; + CANNON: any; + SIMD: any; + AudioContext: AudioContext; + webkitAudioContext: AudioContext; + PointerEvent: any; +} +interface HTMLURL { + createObjectURL(param1: any, param2?: any): any; +} +interface Document { + exitFullscreen(): void; + webkitCancelFullScreen(): void; + mozCancelFullScreen(): void; + msCancelFullScreen(): void; + mozFullScreen: boolean; + msIsFullScreen: boolean; + fullscreen: boolean; + mozPointerLockElement: HTMLElement; + msPointerLockElement: HTMLElement; + webkitPointerLockElement: HTMLElement; +} +interface HTMLCanvasElement { + requestPointerLock(): void; + msRequestPointerLock(): void; + mozRequestPointerLock(): void; + webkitRequestPointerLock(): void; +} +interface CanvasRenderingContext2D { + imageSmoothingEnabled: boolean; + // mozImageSmoothingEnabled: boolean; + // oImageSmoothingEnabled: boolean; + // webkitImageSmoothingEnabled: boolean; +} +interface WebGLTexture { + isReady: boolean; + isCube: boolean; + url: string; + noMipmap: boolean; + samplingMode: number; + references: number; + generateMipMaps: boolean; + _size: number; + _baseWidth: number; + _baseHeight: number; + _width: number; + _height: number; + _workingCanvas: HTMLCanvasElement; + _workingContext: CanvasRenderingContext2D; + _framebuffer: WebGLFramebuffer; + _depthBuffer: WebGLRenderbuffer; + _cachedCoordinatesMode: number; + _cachedWrapU: number; + _cachedWrapV: number; + _isDisabled: boolean; +} +interface WebGLBuffer { + references: number; + capacity: number; + is32Bits: boolean; +} +interface MouseEvent { + mozMovementX: number; + mozMovementY: number; + webkitMovementX: number; + webkitMovementY: number; + msMovementX: number; + msMovementY: number; +} +interface MSStyleCSSProperties { + webkitTransform: string; + webkitTransition: string; +} +interface Navigator { + getVRDevices: () => any; + mozGetVRDevices: (any: any) => any; + isCocoonJS: boolean; +} +interface Screen { + orientation: string; + mozOrientation: string; +} +interface HTMLMediaElement { + // crossOrigin: string; +} + +declare namespace BABYLON { + /** + * Node is the basic class for all scene objects (Mesh, Light Camera). + */ + class Node { + parent: Node; + name: string; + id: string; + uniqueId: number; + state: string; + animations: Animation[]; + private _ranges; + onReady: (node: Node) => void; + private _childrenFlag; + private _isEnabled; + private _isReady; + _currentRenderId: number; + private _parentRenderId; + _waitingParentId: string; + private _scene; + _cache: any; + /** + * @constructor + * @param {string} name - the name and id to be given to this node + * @param {BABYLON.Scene} the scene this node will be added to + */ + constructor(name: string, scene: Scene); + getScene(): Scene; + getEngine(): Engine; + getWorldMatrix(): Matrix; + _initCache(): void; + updateCache(force?: boolean): void; + _updateCache(ignoreParentClass?: boolean): void; + _isSynchronized(): boolean; + _markSyncedWithParent(): void; + isSynchronizedWithParent(): boolean; + isSynchronized(updateCache?: boolean): boolean; + hasNewParent(update?: boolean): boolean; + /** + * Is this node ready to be used/rendered + * @return {boolean} is it ready + */ + isReady(): boolean; + /** + * Is this node enabled. + * If the node has a parent and is enabled, the parent will be inspected as well. + * @return {boolean} whether this node (and its parent) is enabled. + * @see setEnabled + */ + isEnabled(): boolean; + /** + * Set the enabled state of this node. + * @param {boolean} value - the new enabled state + * @see isEnabled + */ + setEnabled(value: boolean): void; + /** + * Is this node a descendant of the given node. + * The function will iterate up the hierarchy until the ancestor was found or no more parents defined. + * @param {BABYLON.Node} ancestor - The parent node to inspect + * @see parent + */ + isDescendantOf(ancestor: Node): boolean; + _getDescendants(list: Node[], results: Node[]): void; + /** + * Will return all nodes that have this node as parent. + * @return {BABYLON.Node[]} all children nodes of all types. + */ + getDescendants(): Node[]; + _setReady(state: boolean): void; + getAnimationByName(name: string): Animation; + createAnimationRange(name: string, from: number, to: number): void; + deleteAnimationRange(name: string, deleteFrames?: boolean): void; + getAnimationRange(name: string): AnimationRange; + beginAnimation(name: string, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): void; + serializeAnimationRanges(): any; + static ParseAnimationRanges(node: Node, parsedNode: any, scene: Scene): void; + } +} + +declare namespace BABYLON { + interface IDisposable { + dispose(): void; + } + /** + * Represents a scene to be rendered by the engine. + * @see http://doc.babylonjs.com/page.php?p=21911 + */ + class Scene { + private static _FOGMODE_NONE; + private static _FOGMODE_EXP; + private static _FOGMODE_EXP2; + private static _FOGMODE_LINEAR; + static MinDeltaTime: number; + static MaxDeltaTime: number; + static FOGMODE_NONE: number; + static FOGMODE_EXP: number; + static FOGMODE_EXP2: number; + static FOGMODE_LINEAR: number; + autoClear: boolean; + clearColor: any; + ambientColor: Color3; + /** + * A function to be executed before rendering this scene + * @type {Function} + */ + beforeRender: () => void; + /** + * A function to be executed after rendering this scene + * @type {Function} + */ + afterRender: () => void; + /** + * A function to be executed when this scene is disposed. + * @type {Function} + */ + onDispose: () => void; + beforeCameraRender: (camera: Camera) => void; + afterCameraRender: (camera: Camera) => void; + forceWireframe: boolean; + forcePointsCloud: boolean; + forceShowBoundingBoxes: boolean; + clipPlane: Plane; + animationsEnabled: boolean; + constantlyUpdateMeshUnderPointer: boolean; + private _onPointerMove; + private _onPointerDown; + private _onPointerUp; + onPointerMove: (evt: PointerEvent, pickInfo: PickingInfo) => void; + onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void; + onPointerUp: (evt: PointerEvent, pickInfo: PickingInfo) => void; + onPointerPick: (evt: PointerEvent, pickInfo: PickingInfo) => void; + cameraToUseForPointers: Camera; + private _pointerX; + private _pointerY; + private _meshUnderPointer; + private _startingPointerPosition; + private _startingPointerTime; + _mirroredCameraPosition: Vector3; + private _onKeyDown; + private _onKeyUp; + /** + * is fog enabled on this scene. + * @type {boolean} + */ + fogEnabled: boolean; + fogMode: number; + fogColor: Color3; + fogDensity: number; + fogStart: number; + fogEnd: number; + /** + * is shadow enabled on this scene. + * @type {boolean} + */ + shadowsEnabled: boolean; + /** + * is light enabled on this scene. + * @type {boolean} + */ + lightsEnabled: boolean; + /** + * All of the lights added to this scene. + * @see BABYLON.Light + * @type {BABYLON.Light[]} + */ + lights: Light[]; + onNewLightAdded: (newLight?: Light, positionInArray?: number, scene?: Scene) => void; + onLightRemoved: (removedLight?: Light) => void; + /** + * All of the cameras added to this scene. + * @see BABYLON.Camera + * @type {BABYLON.Camera[]} + */ + cameras: Camera[]; + onNewCameraAdded: (newCamera?: Camera, positionInArray?: number, scene?: Scene) => void; + onCameraRemoved: (removedCamera?: Camera) => void; + activeCameras: Camera[]; + activeCamera: Camera; + /** + * All of the (abstract) meshes added to this scene. + * @see BABYLON.AbstractMesh + * @type {BABYLON.AbstractMesh[]} + */ + meshes: AbstractMesh[]; + onNewMeshAdded: (newMesh?: AbstractMesh, positionInArray?: number, scene?: Scene) => void; + onMeshRemoved: (removedMesh?: AbstractMesh) => void; + private _geometries; + onGeometryAdded: (newGeometry?: Geometry) => void; + onGeometryRemoved: (removedGeometry?: Geometry) => void; + materials: Material[]; + multiMaterials: MultiMaterial[]; + defaultMaterial: StandardMaterial; + texturesEnabled: boolean; + textures: BaseTexture[]; + particlesEnabled: boolean; + particleSystems: ParticleSystem[]; + spritesEnabled: boolean; + spriteManagers: SpriteManager[]; + layers: Layer[]; + skeletonsEnabled: boolean; + skeletons: Skeleton[]; + lensFlaresEnabled: boolean; + lensFlareSystems: LensFlareSystem[]; + collisionsEnabled: boolean; + private _workerCollisions; + collisionCoordinator: ICollisionCoordinator; + gravity: Vector3; + postProcessesEnabled: boolean; + postProcessManager: PostProcessManager; + postProcessRenderPipelineManager: PostProcessRenderPipelineManager; + renderTargetsEnabled: boolean; + dumpNextRenderTargets: boolean; + customRenderTargets: RenderTargetTexture[]; + useDelayedTextureLoading: boolean; + importedMeshesFiles: String[]; + probesEnabled: boolean; + reflectionProbes: ReflectionProbe[]; + database: any; + /** + * This scene's action manager + * @type {BABYLON.ActionManager} + */ + actionManager: ActionManager; + _actionManagers: ActionManager[]; + private _meshesForIntersections; + proceduralTexturesEnabled: boolean; + _proceduralTextures: ProceduralTexture[]; + mainSoundTrack: SoundTrack; + soundTracks: SoundTrack[]; + private _audioEnabled; + private _headphone; + simplificationQueue: SimplificationQueue; + private _engine; + private _totalVertices; + _activeIndices: number; + _activeParticles: number; + private _lastFrameDuration; + private _evaluateActiveMeshesDuration; + private _renderTargetsDuration; + _particlesDuration: number; + private _renderDuration; + _spritesDuration: number; + private _animationRatio; + private _animationStartDate; + _cachedMaterial: Material; + private _renderId; + private _executeWhenReadyTimeoutId; + _toBeDisposed: SmartArray; + private _onReadyCallbacks; + private _pendingData; + private _onBeforeRenderCallbacks; + private _onAfterRenderCallbacks; + private _activeMeshes; + private _processedMaterials; + private _renderTargets; + _activeParticleSystems: SmartArray; + private _activeSkeletons; + private _softwareSkinnedMeshes; + _activeBones: number; + private _renderingManager; + private _physicsEngine; + _activeAnimatables: Animatable[]; + private _transformMatrix; + private _pickWithRayInverseMatrix; + private _edgesRenderers; + private _boundingBoxRenderer; + private _outlineRenderer; + private _viewMatrix; + private _projectionMatrix; + private _frustumPlanes; + private _selectionOctree; + private _pointerOverMesh; + private _debugLayer; + private _depthRenderer; + private _uniqueIdCounter; + private _pickedMeshName; + /** + * @constructor + * @param {BABYLON.Engine} engine - the engine to be used to render this scene. + */ + constructor(engine: Engine); + debugLayer: DebugLayer; + workerCollisions: boolean; + SelectionOctree: Octree; + /** + * The mesh that is currently under the pointer. + * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none. + */ + meshUnderPointer: AbstractMesh; + /** + * Current on-screen X position of the pointer + * @return {number} X position of the pointer + */ + pointerX: number; + /** + * Current on-screen Y position of the pointer + * @return {number} Y position of the pointer + */ + pointerY: number; + getCachedMaterial(): Material; + getBoundingBoxRenderer(): BoundingBoxRenderer; + getOutlineRenderer(): OutlineRenderer; + getEngine(): Engine; + getTotalVertices(): number; + getActiveIndices(): number; + getActiveParticles(): number; + getActiveBones(): number; + getLastFrameDuration(): number; + getEvaluateActiveMeshesDuration(): number; + getActiveMeshes(): SmartArray; + getRenderTargetsDuration(): number; + getRenderDuration(): number; + getParticlesDuration(): number; + getSpritesDuration(): number; + getAnimationRatio(): number; + getRenderId(): number; + incrementRenderId(): void; + private _updatePointerPosition(evt); + attachControl(): void; + detachControl(): void; + isReady(): boolean; + resetCachedMaterial(): void; + registerBeforeRender(func: () => void): void; + unregisterBeforeRender(func: () => void): void; + registerAfterRender(func: () => void): void; + unregisterAfterRender(func: () => void): void; + _addPendingData(data: any): void; + _removePendingData(data: any): void; + getWaitingItemsCount(): number; + /** + * Registers a function to be executed when the scene is ready. + * @param {Function} func - the function to be executed. + */ + executeWhenReady(func: () => void): void; + _checkIsReady(): void; + /** + * Will start the animation sequence of a given target + * @param target - the target + * @param {number} from - from which frame should animation start + * @param {number} to - till which frame should animation run. + * @param {boolean} [loop] - should the animation loop + * @param {number} [speedRatio] - the speed in which to run the animation + * @param {Function} [onAnimationEnd] function to be executed when the animation ended. + * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params. + * @return {BABYLON.Animatable} the animatable object created for this animation + * @see BABYLON.Animatable + * @see http://doc.babylonjs.com/page.php?p=22081 + */ + beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void, animatable?: Animatable): Animatable; + beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable; + getAnimatableByTarget(target: any): Animatable; + Animatables: Animatable[]; + /** + * Will stop the animation of the given target + * @param target - the target + * @see beginAnimation + */ + stopAnimation(target: any): void; + private _animate(); + getViewMatrix(): Matrix; + getProjectionMatrix(): Matrix; + getTransformMatrix(): Matrix; + setTransformMatrix(view: Matrix, projection: Matrix): void; + addMesh(newMesh: AbstractMesh): void; + removeMesh(toRemove: AbstractMesh): number; + removeSkeleton(toRemove: Skeleton): number; + removeLight(toRemove: Light): number; + removeCamera(toRemove: Camera): number; + addLight(newLight: Light): void; + addCamera(newCamera: Camera): void; + /** + * Switch active camera + * @param {Camera} newCamera - new active camera + * @param {boolean} attachControl - call attachControl for the new active camera (default: true) + */ + swithActiveCamera(newCamera: Camera, attachControl?: boolean): void; + /** + * sets the active camera of the scene using its ID + * @param {string} id - the camera's ID + * @return {BABYLON.Camera|null} the new active camera or null if none found. + * @see activeCamera + */ + setActiveCameraByID(id: string): Camera; + /** + * sets the active camera of the scene using its name + * @param {string} name - the camera's name + * @return {BABYLON.Camera|null} the new active camera or null if none found. + * @see activeCamera + */ + setActiveCameraByName(name: string): Camera; + /** + * get a material using its id + * @param {string} the material's ID + * @return {BABYLON.Material|null} the material or null if none found. + */ + getMaterialByID(id: string): Material; + /** + * get a material using its name + * @param {string} the material's name + * @return {BABYLON.Material|null} the material or null if none found. + */ + getMaterialByName(name: string): Material; + getLensFlareSystemByName(name: string): LensFlareSystem; + getCameraByID(id: string): Camera; + getCameraByUniqueID(uniqueId: number): Camera; + /** + * get a camera using its name + * @param {string} the camera's name + * @return {BABYLON.Camera|null} the camera or null if none found. + */ + getCameraByName(name: string): Camera; + /** + * get a bone using its id + * @param {string} the bone's id + * @return {BABYLON.Bone|null} the bone or null if not found + */ + getBoneByID(id: string): Bone; + /** + * get a bone using its id + * @param {string} the bone's name + * @return {BABYLON.Bone|null} the bone or null if not found + */ + getBoneByName(name: string): Bone; + /** + * get a light node using its name + * @param {string} the light's name + * @return {BABYLON.Light|null} the light or null if none found. + */ + getLightByName(name: string): Light; + /** + * get a light node using its ID + * @param {string} the light's id + * @return {BABYLON.Light|null} the light or null if none found. + */ + getLightByID(id: string): Light; + /** + * get a light node using its scene-generated unique ID + * @param {number} the light's unique id + * @return {BABYLON.Light|null} the light or null if none found. + */ + getLightByUniqueID(uniqueId: number): Light; + /** + * get a particle system by id + * @param id {number} the particle system id + * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found. + */ + getParticleSystemByID(id: string): ParticleSystem; + /** + * get a geometry using its ID + * @param {string} the geometry's id + * @return {BABYLON.Geometry|null} the geometry or null if none found. + */ + getGeometryByID(id: string): Geometry; + /** + * add a new geometry to this scene. + * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene. + * @param {boolean} [force] - force addition, even if a geometry with this ID already exists + * @return {boolean} was the geometry added or not + */ + pushGeometry(geometry: Geometry, force?: boolean): boolean; + /** + * Removes an existing geometry + * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene. + * @return {boolean} was the geometry removed or not + */ + removeGeometry(geometry: Geometry): boolean; + getGeometries(): Geometry[]; + /** + * Get the first added mesh found of a given ID + * @param {string} id - the id to search for + * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all. + */ + getMeshByID(id: string): AbstractMesh; + /** + * Get a mesh with its auto-generated unique id + * @param {number} uniqueId - the unique id to search for + * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all. + */ + getMeshByUniqueID(uniqueId: number): AbstractMesh; + /** + * Get a the last added mesh found of a given ID + * @param {string} id - the id to search for + * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all. + */ + getLastMeshByID(id: string): AbstractMesh; + /** + * Get a the last added node (Mesh, Camera, Light) found of a given ID + * @param {string} id - the id to search for + * @return {BABYLON.Node|null} the node found or null if not found at all. + */ + getLastEntryByID(id: string): Node; + getNodeByID(id: string): Node; + getNodeByName(name: string): Node; + getMeshByName(name: string): AbstractMesh; + getSoundByName(name: string): Sound; + getLastSkeletonByID(id: string): Skeleton; + getSkeletonById(id: string): Skeleton; + getSkeletonByName(name: string): Skeleton; + isActiveMesh(mesh: Mesh): boolean; + private _evaluateSubMesh(subMesh, mesh); + private _evaluateActiveMeshes(); + private _activeMesh(mesh); + updateTransformMatrix(force?: boolean): void; + private _renderForCamera(camera); + private _processSubCameras(camera); + private _checkIntersections(); + render(): void; + private _updateAudioParameters(); + audioEnabled: boolean; + private _disableAudio(); + private _enableAudio(); + headphone: boolean; + private _switchAudioModeForHeadphones(); + private _switchAudioModeForNormalSpeakers(); + enableDepthRenderer(): DepthRenderer; + disableDepthRenderer(): void; + freezeMaterials(): void; + unfreezeMaterials(): void; + dispose(): void; + disposeSounds(): void; + getWorldExtends(): { + min: Vector3; + max: Vector3; + }; + createOrUpdateSelectionOctree(maxCapacity?: number, maxDepth?: number): Octree; + createPickingRay(x: number, y: number, world: Matrix, camera: Camera, cameraViewSpace?: boolean): Ray; + createPickingRayInCameraSpace(x: number, y: number, camera: Camera): Ray; + private _internalPick(rayFunction, predicate, fastCheck?); + private _internalPickSprites(ray, predicate?, fastCheck?, camera?); + pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo; + pickSprite(x: number, y: number, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo; + pickWithRay(ray: Ray, predicate: (mesh: Mesh) => boolean, fastCheck?: boolean): PickingInfo; + setPointerOverMesh(mesh: AbstractMesh): void; + getPointerOverMesh(): AbstractMesh; + getPhysicsEngine(): PhysicsEngine; + /** + * Enables physics to the current scene + * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine + * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS. + * @return {boolean} was the physics engine initialized + */ + enablePhysics(gravity?: Vector3, plugin?: IPhysicsEnginePlugin): boolean; + disablePhysicsEngine(): void; + isPhysicsEnabled(): boolean; + /** + * Sets the gravity of the physics engine (and NOT of the scene) + * @param {BABYLON.Vector3} [gravity] - the new gravity to be used + */ + setGravity(gravity: Vector3): void; + createCompoundImpostor(parts: any, options: PhysicsBodyCreationOptions): any; + deleteCompoundImpostor(compound: any): void; + createDefaultCameraOrLight(): void; + private _getByTags(list, tagsQuery, forEach?); + getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[]; + getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[]; + getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[]; + getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[]; + } +} + +declare namespace BABYLON { + class Action { + triggerOptions: any; + trigger: number; + _actionManager: ActionManager; + private _nextActiveAction; + private _child; + private _condition; + private _triggerParameter; + constructor(triggerOptions: any, condition?: Condition); + _prepare(): void; + getTriggerParameter(): any; + _executeCurrent(evt: ActionEvent): void; + execute(evt: ActionEvent): void; + skipToNextActiveAction(): void; + then(action: Action): Action; + _getProperty(propertyPath: string): string; + _getEffectiveTarget(target: any, propertyPath: string): any; + } +} + +declare namespace BABYLON { + /** + * ActionEvent is the event beint sent when an action is triggered. + */ + class ActionEvent { + source: any; + pointerX: number; + pointerY: number; + meshUnderPointer: AbstractMesh; + sourceEvent: any; + additionalData: any; + /** + * @constructor + * @param source The mesh or sprite that triggered the action. + * @param pointerX The X mouse cursor position at the time of the event + * @param pointerY The Y mouse cursor position at the time of the event + * @param meshUnderPointer The mesh that is currently pointed at (can be null) + * @param sourceEvent the original (browser) event that triggered the ActionEvent + */ + constructor(source: any, pointerX: number, pointerY: number, meshUnderPointer: AbstractMesh, sourceEvent?: any, additionalData?: any); + /** + * Helper function to auto-create an ActionEvent from a source mesh. + * @param source The source mesh that triggered the event + * @param evt {Event} The original (browser) event + */ + static CreateNew(source: AbstractMesh, evt?: Event, additionalData?: any): ActionEvent; + /** + * Helper function to auto-create an ActionEvent from a source mesh. + * @param source The source sprite that triggered the event + * @param scene Scene associated with the sprite + * @param evt {Event} The original (browser) event + */ + static CreateNewFromSprite(source: Sprite, scene: Scene, evt?: Event, additionalData?: any): ActionEvent; + /** + * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew + * @param scene the scene where the event occurred + * @param evt {Event} The original (browser) event + */ + static CreateNewFromScene(scene: Scene, evt: Event): ActionEvent; + } + /** + * Action Manager manages all events to be triggered on a given mesh or the global scene. + * A single scene can have many Action Managers to handle predefined actions on specific meshes. + */ + class ActionManager { + private static _NothingTrigger; + private static _OnPickTrigger; + private static _OnLeftPickTrigger; + private static _OnRightPickTrigger; + private static _OnCenterPickTrigger; + private static _OnPickDownTrigger; + private static _OnPickUpTrigger; + private static _OnLongPressTrigger; + private static _OnPointerOverTrigger; + private static _OnPointerOutTrigger; + private static _OnEveryFrameTrigger; + private static _OnIntersectionEnterTrigger; + private static _OnIntersectionExitTrigger; + private static _OnKeyDownTrigger; + private static _OnKeyUpTrigger; + static NothingTrigger: number; + static OnPickTrigger: number; + static OnLeftPickTrigger: number; + static OnRightPickTrigger: number; + static OnCenterPickTrigger: number; + static OnPickDownTrigger: number; + static OnPickUpTrigger: number; + static OnLongPressTrigger: number; + static OnPointerOverTrigger: number; + static OnPointerOutTrigger: number; + static OnEveryFrameTrigger: number; + static OnIntersectionEnterTrigger: number; + static OnIntersectionExitTrigger: number; + static OnKeyDownTrigger: number; + static OnKeyUpTrigger: number; + static DragMovementThreshold: number; + static LongPressDelay: number; + actions: Action[]; + private _scene; + constructor(scene: Scene); + dispose(): void; + getScene(): Scene; + /** + * Does this action manager handles actions of any of the given triggers + * @param {number[]} triggers - the triggers to be tested + * @return {boolean} whether one (or more) of the triggers is handeled + */ + hasSpecificTriggers(triggers: number[]): boolean; + /** + * Does this action manager handles actions of a given trigger + * @param {number} trigger - the trigger to be tested + * @return {boolean} whether the trigger is handeled + */ + hasSpecificTrigger(trigger: number): boolean; + /** + * Does this action manager has pointer triggers + * @return {boolean} whether or not it has pointer triggers + */ + hasPointerTriggers: boolean; + /** + * Does this action manager has pick triggers + * @return {boolean} whether or not it has pick triggers + */ + hasPickTriggers: boolean; + /** + * Registers an action to this action manager + * @param {BABYLON.Action} action - the action to be registered + * @return {BABYLON.Action} the action amended (prepared) after registration + */ + registerAction(action: Action): Action; + /** + * Process a specific trigger + * @param {number} trigger - the trigger to process + * @param evt {BABYLON.ActionEvent} the event details to be processed + */ + processTrigger(trigger: number, evt: ActionEvent): void; + _getEffectiveTarget(target: any, propertyPath: string): any; + _getProperty(propertyPath: string): string; + static Parse(parsedActions: any, object: AbstractMesh, scene: Scene): void; + } +} + +declare namespace BABYLON { + class Condition { + _actionManager: ActionManager; + _evaluationId: number; + _currentResult: boolean; + constructor(actionManager: ActionManager); + isValid(): boolean; + _getProperty(propertyPath: string): string; + _getEffectiveTarget(target: any, propertyPath: string): any; + } + class ValueCondition extends Condition { + propertyPath: string; + value: any; + operator: number; + private static _IsEqual; + private static _IsDifferent; + private static _IsGreater; + private static _IsLesser; + static IsEqual: number; + static IsDifferent: number; + static IsGreater: number; + static IsLesser: number; + _actionManager: ActionManager; + private _target; + private _property; + constructor(actionManager: ActionManager, target: any, propertyPath: string, value: any, operator?: number); + isValid(): boolean; + } + class PredicateCondition extends Condition { + predicate: () => boolean; + _actionManager: ActionManager; + constructor(actionManager: ActionManager, predicate: () => boolean); + isValid(): boolean; + } + class StateCondition extends Condition { + value: string; + _actionManager: ActionManager; + private _target; + constructor(actionManager: ActionManager, target: any, value: string); + isValid(): boolean; + } +} + +declare namespace BABYLON { + class SwitchBooleanAction extends Action { + propertyPath: string; + private _target; + private _property; + constructor(triggerOptions: any, target: any, propertyPath: string, condition?: Condition); + _prepare(): void; + execute(): void; + } + class SetStateAction extends Action { + value: string; + private _target; + constructor(triggerOptions: any, target: any, value: string, condition?: Condition); + execute(): void; + } + class SetValueAction extends Action { + propertyPath: string; + value: any; + private _target; + private _property; + constructor(triggerOptions: any, target: any, propertyPath: string, value: any, condition?: Condition); + _prepare(): void; + execute(): void; + } + class IncrementValueAction extends Action { + propertyPath: string; + value: any; + private _target; + private _property; + constructor(triggerOptions: any, target: any, propertyPath: string, value: any, condition?: Condition); + _prepare(): void; + execute(): void; + } + class PlayAnimationAction extends Action { + from: number; + to: number; + loop: boolean; + private _target; + constructor(triggerOptions: any, target: any, from: number, to: number, loop?: boolean, condition?: Condition); + _prepare(): void; + execute(): void; + } + class StopAnimationAction extends Action { + private _target; + constructor(triggerOptions: any, target: any, condition?: Condition); + _prepare(): void; + execute(): void; + } + class DoNothingAction extends Action { + constructor(triggerOptions?: any, condition?: Condition); + execute(): void; + } + class CombineAction extends Action { + children: Action[]; + constructor(triggerOptions: any, children: Action[], condition?: Condition); + _prepare(): void; + execute(evt: ActionEvent): void; + } + class ExecuteCodeAction extends Action { + func: (evt: ActionEvent) => void; + constructor(triggerOptions: any, func: (evt: ActionEvent) => void, condition?: Condition); + execute(evt: ActionEvent): void; + } + class SetParentAction extends Action { + private _parent; + private _target; + constructor(triggerOptions: any, target: any, parent: any, condition?: Condition); + _prepare(): void; + execute(): void; + } + class PlaySoundAction extends Action { + private _sound; + constructor(triggerOptions: any, sound: Sound, condition?: Condition); + _prepare(): void; + execute(): void; + } + class StopSoundAction extends Action { + private _sound; + constructor(triggerOptions: any, sound: Sound, condition?: Condition); + _prepare(): void; + execute(): void; + } +} + +declare namespace BABYLON { + class InterpolateValueAction extends Action { + propertyPath: string; + value: any; + duration: number; + stopOtherAnimations: boolean; + onInterpolationDone: () => void; + private _target; + private _property; + constructor(triggerOptions: any, target: any, propertyPath: string, value: any, duration?: number, condition?: Condition, stopOtherAnimations?: boolean, onInterpolationDone?: () => void); + _prepare(): void; + execute(): void; + } +} + +declare namespace BABYLON { + class Animatable { + target: any; + fromFrame: number; + toFrame: number; + loopAnimation: boolean; + speedRatio: number; + onAnimationEnd: any; + private _localDelayOffset; + private _pausedDelay; + private _animations; + private _paused; + private _scene; + animationStarted: boolean; + constructor(scene: Scene, target: any, fromFrame?: number, toFrame?: number, loopAnimation?: boolean, speedRatio?: number, onAnimationEnd?: any, animations?: any); + getAnimations(): Animation[]; + appendAnimations(target: any, animations: Animation[]): void; + getAnimationByTargetProperty(property: string): Animation; + reset(): void; + goToFrame(frame: number): void; + pause(): void; + restart(): void; + stop(): void; + _animate(delay: number): boolean; + } +} + +declare namespace BABYLON { + class AnimationRange { + name: string; + from: number; + to: number; + constructor(name: string, from: number, to: number); + } + /** + * Composed of a frame, and an action function + */ + class AnimationEvent { + frame: number; + action: () => void; + onlyOnce: boolean; + isDone: boolean; + constructor(frame: number, action: () => void, onlyOnce?: boolean); + } + class Animation { + name: string; + targetProperty: string; + framePerSecond: number; + dataType: number; + loopMode: number; + private _keys; + private _offsetsCache; + private _highLimitsCache; + private _stopped; + _target: any; + private _easingFunction; + private _events; + targetPropertyPath: string[]; + currentFrame: number; + allowMatricesInterpolation: boolean; + private _ranges; + static _PrepareAnimation(name: string, targetProperty: string, framePerSecond: number, totalFrame: number, from: any, to: any, loopMode?: number, easingFunction?: EasingFunction): Animation; + static CreateAndStartAnimation(name: string, node: Node, targetProperty: string, framePerSecond: number, totalFrame: number, from: any, to: any, loopMode?: number, easingFunction?: EasingFunction, onAnimationEnd?: () => void): Animatable; + static CreateMergeAndStartAnimation(name: string, node: Node, targetProperty: string, framePerSecond: number, totalFrame: number, from: any, to: any, loopMode?: number, easingFunction?: EasingFunction, onAnimationEnd?: () => void): Animatable; + constructor(name: string, targetProperty: string, framePerSecond: number, dataType: number, loopMode?: number); + /** + * Add an event to this animation. + */ + addEvent(event: AnimationEvent): void; + /** + * Remove all events found at the given frame + * @param frame + */ + removeEvents(frame: number): void; + createRange(name: string, from: number, to: number): void; + deleteRange(name: string, deleteFrames?: boolean): void; + getRange(name: string): AnimationRange; + reset(): void; + isStopped(): boolean; + getKeys(): any[]; + getHighestFrame(): number; + getEasingFunction(): IEasingFunction; + setEasingFunction(easingFunction: EasingFunction): void; + floatInterpolateFunction(startValue: number, endValue: number, gradient: number): number; + quaternionInterpolateFunction(startValue: Quaternion, endValue: Quaternion, gradient: number): Quaternion; + vector3InterpolateFunction(startValue: Vector3, endValue: Vector3, gradient: number): Vector3; + vector2InterpolateFunction(startValue: Vector2, endValue: Vector2, gradient: number): Vector2; + color3InterpolateFunction(startValue: Color3, endValue: Color3, gradient: number): Color3; + matrixInterpolateFunction(startValue: Matrix, endValue: Matrix, gradient: number): Matrix; + clone(): Animation; + setKeys(values: Array): void; + private _getKeyValue(value); + private _interpolate(currentFrame, repeatCount, loopMode, offsetValue?, highLimitValue?); + setValue(currentValue: any): void; + goToFrame(frame: number): void; + animate(delay: number, from: number, to: number, loop: boolean, speedRatio: number): boolean; + serialize(): any; + private static _ANIMATIONTYPE_FLOAT; + private static _ANIMATIONTYPE_VECTOR3; + private static _ANIMATIONTYPE_QUATERNION; + private static _ANIMATIONTYPE_MATRIX; + private static _ANIMATIONTYPE_COLOR3; + private static _ANIMATIONTYPE_VECTOR2; + private static _ANIMATIONLOOPMODE_RELATIVE; + private static _ANIMATIONLOOPMODE_CYCLE; + private static _ANIMATIONLOOPMODE_CONSTANT; + static ANIMATIONTYPE_FLOAT: number; + static ANIMATIONTYPE_VECTOR3: number; + static ANIMATIONTYPE_VECTOR2: number; + static ANIMATIONTYPE_QUATERNION: number; + static ANIMATIONTYPE_MATRIX: number; + static ANIMATIONTYPE_COLOR3: number; + static ANIMATIONLOOPMODE_RELATIVE: number; + static ANIMATIONLOOPMODE_CYCLE: number; + static ANIMATIONLOOPMODE_CONSTANT: number; + static Parse(parsedAnimation: any): Animation; + static AppendSerializedAnimations(source: IAnimatable, destination: any): any; + } +} + +declare namespace BABYLON { + interface IEasingFunction { + ease(gradient: number): number; + } + class EasingFunction implements IEasingFunction { + private static _EASINGMODE_EASEIN; + private static _EASINGMODE_EASEOUT; + private static _EASINGMODE_EASEINOUT; + static EASINGMODE_EASEIN: number; + static EASINGMODE_EASEOUT: number; + static EASINGMODE_EASEINOUT: number; + private _easingMode; + setEasingMode(easingMode: number): void; + getEasingMode(): number; + easeInCore(gradient: number): number; + ease(gradient: number): number; + } + class CircleEase extends EasingFunction implements IEasingFunction { + easeInCore(gradient: number): number; + } + class BackEase extends EasingFunction implements IEasingFunction { + amplitude: number; + constructor(amplitude?: number); + easeInCore(gradient: number): number; + } + class BounceEase extends EasingFunction implements IEasingFunction { + bounces: number; + bounciness: number; + constructor(bounces?: number, bounciness?: number); + easeInCore(gradient: number): number; + } + class CubicEase extends EasingFunction implements IEasingFunction { + easeInCore(gradient: number): number; + } + class ElasticEase extends EasingFunction implements IEasingFunction { + oscillations: number; + springiness: number; + constructor(oscillations?: number, springiness?: number); + easeInCore(gradient: number): number; + } + class ExponentialEase extends EasingFunction implements IEasingFunction { + exponent: number; + constructor(exponent?: number); + easeInCore(gradient: number): number; + } + class PowerEase extends EasingFunction implements IEasingFunction { + power: number; + constructor(power?: number); + easeInCore(gradient: number): number; + } + class QuadraticEase extends EasingFunction implements IEasingFunction { + easeInCore(gradient: number): number; + } + class QuarticEase extends EasingFunction implements IEasingFunction { + easeInCore(gradient: number): number; + } + class QuinticEase extends EasingFunction implements IEasingFunction { + easeInCore(gradient: number): number; + } + class SineEase extends EasingFunction implements IEasingFunction { + easeInCore(gradient: number): number; + } + class BezierCurveEase extends EasingFunction implements IEasingFunction { + x1: number; + y1: number; + x2: number; + y2: number; + constructor(x1?: number, y1?: number, x2?: number, y2?: number); + easeInCore(gradient: number): number; + } +} + +declare namespace BABYLON { + class Analyser { + SMOOTHING: number; + FFT_SIZE: number; + BARGRAPHAMPLITUDE: number; + DEBUGCANVASPOS: { + x: number; + y: number; + }; + DEBUGCANVASSIZE: { + width: number; + height: number; + }; + private _byteFreqs; + private _byteTime; + private _floatFreqs; + private _webAudioAnalyser; + private _debugCanvas; + private _debugCanvasContext; + private _scene; + private _registerFunc; + private _audioEngine; + constructor(scene: Scene); + getFrequencyBinCount(): number; + getByteFrequencyData(): Uint8Array; + getByteTimeDomainData(): Uint8Array; + getFloatFrequencyData(): Uint8Array; + drawDebugCanvas(): void; + stopDebugCanvas(): void; + connectAudioNodes(inputAudioNode: AudioNode, outputAudioNode: AudioNode): void; + dispose(): void; + } +} + +declare namespace BABYLON { + class AudioEngine { + private _audioContext; + private _audioContextInitialized; + canUseWebAudio: boolean; + masterGain: GainNode; + private _connectedAnalyser; + WarnedWebAudioUnsupported: boolean; + unlocked: boolean; + onAudioUnlocked: () => any; + audioContext: AudioContext; + constructor(); + private _unlockiOSaudio(); + private _initializeAudioContext(); + dispose(): void; + getGlobalVolume(): number; + setGlobalVolume(newVolume: number): void; + connectToAnalyser(analyser: Analyser): void; + } +} + +declare namespace BABYLON { + class Sound { + name: string; + autoplay: boolean; + loop: boolean; + useCustomAttenuation: boolean; + soundTrackId: number; + spatialSound: boolean; + refDistance: number; + rolloffFactor: number; + maxDistance: number; + distanceModel: string; + private _panningModel; + onended: () => any; + private _playbackRate; + private _streaming; + private _startTime; + private _startOffset; + private _position; + private _localDirection; + private _volume; + private _isLoaded; + private _isReadyToPlay; + isPlaying: boolean; + isPaused: boolean; + private _isDirectional; + private _readyToPlayCallback; + private _audioBuffer; + private _soundSource; + private _streamingSource; + private _soundPanner; + private _soundGain; + private _inputAudioNode; + private _ouputAudioNode; + private _coneInnerAngle; + private _coneOuterAngle; + private _coneOuterGain; + private _scene; + private _connectedMesh; + private _customAttenuationFunction; + private _registerFunc; + private _isOutputConnected; + private _htmlAudioElement; + /** + * Create a sound and attach it to a scene + * @param name Name of your sound + * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer + * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played + * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming + */ + constructor(name: string, urlOrArrayBuffer: any, scene: Scene, readyToPlayCallback?: () => void, options?: any); + dispose(): void; + private _soundLoaded(audioData); + setAudioBuffer(audioBuffer: AudioBuffer): void; + updateOptions(options: any): void; + private _createSpatialParameters(); + private _updateSpatialParameters(); + switchPanningModelToHRTF(): void; + switchPanningModelToEqualPower(): void; + private _switchPanningModel(); + connectToSoundTrackAudioNode(soundTrackAudioNode: AudioNode): void; + /** + * Transform this sound into a directional source + * @param coneInnerAngle Size of the inner cone in degree + * @param coneOuterAngle Size of the outer cone in degree + * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0) + */ + setDirectionalCone(coneInnerAngle: number, coneOuterAngle: number, coneOuterGain: number): void; + setPosition(newPosition: Vector3): void; + setLocalDirectionToMesh(newLocalDirection: Vector3): void; + private _updateDirection(); + updateDistanceFromListener(): void; + setAttenuationFunction(callback: (currentVolume: number, currentDistance: number, maxDistance: number, refDistance: number, rolloffFactor: number) => number): void; + /** + * Play the sound + * @param time (optional) Start the sound after X seconds. Start immediately (0) by default. + */ + play(time?: number): void; + private _onended(); + /** + * Stop the sound + * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default. + */ + stop(time?: number): void; + pause(): void; + setVolume(newVolume: number, time?: number): void; + setPlaybackRate(newPlaybackRate: number): void; + getVolume(): number; + attachToMesh(meshToConnectTo: AbstractMesh): void; + private _onRegisterAfterWorldMatrixUpdate(connectedMesh); + clone(): Sound; + getAudioBuffer(): AudioBuffer; + static Parse(parsedSound: any, scene: Scene, rootUrl: string, sourceSound?: Sound): Sound; + } +} + +declare namespace BABYLON { + class SoundTrack { + private _outputAudioNode; + private _inputAudioNode; + private _trackConvolver; + private _scene; + id: number; + soundCollection: Array; + private _isMainTrack; + private _connectedAnalyser; + private _options; + private _isInitialized; + constructor(scene: Scene, options?: any); + private _initializeSoundTrackAudioGraph(); + dispose(): void; + AddSound(sound: Sound): void; + RemoveSound(sound: Sound): void; + setVolume(newVolume: number): void; + switchPanningModelToHRTF(): void; + switchPanningModelToEqualPower(): void; + connectToAnalyser(analyser: Analyser): void; + } +} + +declare namespace BABYLON { + class Bone extends Node { + name: string; + children: Bone[]; + animations: Animation[]; + length: number; + private _skeleton; + _matrix: Matrix; + private _restPose; + private _baseMatrix; + private _worldTransform; + private _absoluteTransform; + private _invertedAbsoluteTransform; + private _parent; + constructor(name: string, skeleton: Skeleton, parentBone: Bone, matrix: Matrix, restPose?: Matrix); + getParent(): Bone; + getLocalMatrix(): Matrix; + getBaseMatrix(): Matrix; + getRestPose(): Matrix; + returnToRest(): void; + getWorldMatrix(): Matrix; + getInvertedAbsoluteTransform(): Matrix; + getAbsoluteTransform(): Matrix; + updateMatrix(matrix: Matrix): void; + _updateDifferenceMatrix(rootMatrix?: Matrix): void; + markAsDirty(): void; + copyAnimationRange(source: Bone, rangeName: string, frameOffset: number, rescaleAsRequired?: boolean): boolean; + } +} + +declare namespace BABYLON { + class Skeleton { + name: string; + id: string; + bones: Bone[]; + needInitialSkinMatrix: boolean; + private _scene; + private _isDirty; + private _transformMatrices; + private _meshesWithPoseMatrix; + private _animatables; + private _identity; + private _ranges; + constructor(name: string, id: string, scene: Scene); + getTransformMatrices(mesh: AbstractMesh): Float32Array; + getScene(): Scene; + createAnimationRange(name: string, from: number, to: number): void; + deleteAnimationRange(name: string, deleteFrames?: boolean): void; + getAnimationRange(name: string): AnimationRange; + /** + * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences + */ + copyAnimationRange(source: Skeleton, name: string, rescaleAsRequired?: boolean): boolean; + returnToRest(): void; + private _getHighestAnimationFrame(); + beginAnimation(name: string, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): void; + _markAsDirty(): void; + _registerMeshWithPoseMatrix(mesh: AbstractMesh): void; + _unregisterMeshWithPoseMatrix(mesh: AbstractMesh): void; + _computeTransformMatrices(targetMatrix: Float32Array, initialSkinMatrix: Matrix): void; + prepare(): void; + getAnimatables(): IAnimatable[]; + clone(name: string, id: string): Skeleton; + dispose(): void; + serialize(): any; + static Parse(parsedSkeleton: any, scene: Scene): Skeleton; + } +} + +declare namespace BABYLON { + class ArcRotateCamera extends TargetCamera { + alpha: number; + beta: number; + radius: number; + target: any; + inertialAlphaOffset: number; + inertialBetaOffset: number; + inertialRadiusOffset: number; + lowerAlphaLimit: any; + upperAlphaLimit: any; + lowerBetaLimit: number; + upperBetaLimit: number; + lowerRadiusLimit: any; + upperRadiusLimit: any; + angularSensibilityX: number; + angularSensibilityY: number; + wheelPrecision: number; + pinchPrecision: number; + panningSensibility: number; + inertialPanningX: number; + inertialPanningY: number; + keysUp: number[]; + keysDown: number[]; + keysLeft: number[]; + keysRight: number[]; + zoomOnFactor: number; + targetScreenOffset: Vector2; + pinchInwards: boolean; + allowUpsideDown: boolean; + private _keys; + _viewMatrix: Matrix; + private _attachedElement; + private _onContextMenu; + private _onPointerDown; + private _onPointerUp; + private _onPointerMove; + private _wheel; + private _onMouseMove; + private _onKeyDown; + private _onKeyUp; + private _onLostFocus; + _reset: () => void; + private _onGestureStart; + private _onGesture; + private _MSGestureHandler; + panningAxis: Vector3; + private _localDirection; + private _transformedDirection; + private _isRightClick; + private _isCtrlPushed; + onCollide: (collidedMesh: AbstractMesh) => void; + checkCollisions: boolean; + collisionRadius: Vector3; + private _collider; + private _previousPosition; + private _collisionVelocity; + private _newPosition; + private _previousAlpha; + private _previousBeta; + private _previousRadius; + private _collisionTriggered; + angularSensibility: number; + constructor(name: string, alpha: number, beta: number, radius: number, target: any, scene: Scene); + _getTargetPosition(): Vector3; + _initCache(): void; + _updateCache(ignoreParentClass?: boolean): void; + _isSynchronizedViewMatrix(): boolean; + attachControl(element: HTMLElement, noPreventDefault?: boolean, useCtrlForPanning?: boolean): void; + detachControl(element: HTMLElement): void; + _checkInputs(): void; + private _checkLimits(); + setPosition(position: Vector3): void; + setTarget(target: Vector3): void; + _getViewMatrix(): Matrix; + private _onCollisionPositionChange; + zoomOn(meshes?: AbstractMesh[], doNotUpdateMaxZ?: boolean): void; + focusOn(meshesOrMinMaxVectorAndDistance: any, doNotUpdateMaxZ?: boolean): void; + /** + * @override + * Override Camera.createRigCamera + */ + createRigCamera(name: string, cameraIndex: number): Camera; + /** + * @override + * Override Camera._updateRigCameras + */ + _updateRigCameras(): void; + serialize(): any; + } +} + +declare namespace BABYLON { + class VRCameraMetrics { + hResolution: number; + vResolution: number; + hScreenSize: number; + vScreenSize: number; + vScreenCenter: number; + eyeToScreenDistance: number; + lensSeparationDistance: number; + interpupillaryDistance: number; + distortionK: number[]; + chromaAbCorrection: number[]; + postProcessScaleFactor: number; + lensCenterOffset: number; + compensateDistortion: boolean; + aspectRatio: number; + aspectRatioFov: number; + leftHMatrix: Matrix; + rightHMatrix: Matrix; + leftPreViewMatrix: Matrix; + rightPreViewMatrix: Matrix; + static GetDefault(): VRCameraMetrics; + } + class Camera extends Node { + position: Vector3; + private static _PERSPECTIVE_CAMERA; + private static _ORTHOGRAPHIC_CAMERA; + private static _FOVMODE_VERTICAL_FIXED; + private static _FOVMODE_HORIZONTAL_FIXED; + private static _RIG_MODE_NONE; + private static _RIG_MODE_STEREOSCOPIC_ANAGLYPH; + private static _RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL; + private static _RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; + private static _RIG_MODE_STEREOSCOPIC_OVERUNDER; + private static _RIG_MODE_VR; + static PERSPECTIVE_CAMERA: number; + static ORTHOGRAPHIC_CAMERA: number; + static FOVMODE_VERTICAL_FIXED: number; + static FOVMODE_HORIZONTAL_FIXED: number; + static RIG_MODE_NONE: number; + static RIG_MODE_STEREOSCOPIC_ANAGLYPH: number; + static RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: number; + static RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: number; + static RIG_MODE_STEREOSCOPIC_OVERUNDER: number; + static RIG_MODE_VR: number; + upVector: Vector3; + orthoLeft: any; + orthoRight: any; + orthoBottom: any; + orthoTop: any; + fov: number; + minZ: number; + maxZ: number; + inertia: number; + mode: number; + isIntermediate: boolean; + viewport: Viewport; + layerMask: number; + fovMode: number; + cameraRigMode: number; + _cameraRigParams: any; + _rigCameras: Camera[]; + private _computedViewMatrix; + _projectionMatrix: Matrix; + private _worldMatrix; + _postProcesses: PostProcess[]; + _postProcessesTakenIndices: any[]; + _activeMeshes: SmartArray; + private _globalPosition; + constructor(name: string, position: Vector3, scene: Scene); + globalPosition: Vector3; + getActiveMeshes(): SmartArray; + isActiveMesh(mesh: Mesh): boolean; + _initCache(): void; + _updateCache(ignoreParentClass?: boolean): void; + _updateFromScene(): void; + _isSynchronized(): boolean; + _isSynchronizedViewMatrix(): boolean; + _isSynchronizedProjectionMatrix(): boolean; + attachControl(element: HTMLElement): void; + detachControl(element: HTMLElement): void; + _update(): void; + _checkInputs(): void; + attachPostProcess(postProcess: PostProcess, insertAt?: number): number; + detachPostProcess(postProcess: PostProcess, atIndices?: any): number[]; + getWorldMatrix(): Matrix; + _getViewMatrix(): Matrix; + getViewMatrix(force?: boolean): Matrix; + _computeViewMatrix(force?: boolean): Matrix; + getProjectionMatrix(force?: boolean): Matrix; + dispose(): void; + setCameraRigMode(mode: number, rigParams: any): void; + private _getVRProjectionMatrix(); + setCameraRigParameter(name: string, value: any): void; + /** + * May needs to be overridden by children so sub has required properties to be copied + */ + createRigCamera(name: string, cameraIndex: number): Camera; + /** + * May needs to be overridden by children + */ + _updateRigCameras(): void; + serialize(): any; + static Parse(parsedCamera: any, scene: Scene): Camera; + } +} + +declare namespace BABYLON { + class DeviceOrientationCamera extends FreeCamera { + private _offsetX; + private _offsetY; + private _orientationGamma; + private _orientationBeta; + private _initialOrientationGamma; + private _initialOrientationBeta; + private _attachedCanvas; + private _orientationChanged; + angularSensibility: number; + moveSensibility: number; + constructor(name: string, position: Vector3, scene: Scene); + attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void; + detachControl(canvas: HTMLCanvasElement): void; + _checkInputs(): void; + } +} + +declare namespace BABYLON { + class FollowCamera extends TargetCamera { + radius: number; + rotationOffset: number; + heightOffset: number; + cameraAcceleration: number; + maxCameraSpeed: number; + target: AbstractMesh; + constructor(name: string, position: Vector3, scene: Scene); + private getRadians(degrees); + private follow(cameraTarget); + _checkInputs(): void; + serialize(): any; + } + class ArcFollowCamera extends TargetCamera { + alpha: number; + beta: number; + radius: number; + target: AbstractMesh; + private _cartesianCoordinates; + constructor(name: string, alpha: number, beta: number, radius: number, target: AbstractMesh, scene: Scene); + private follow(); + _checkInputs(): void; + serialize(): any; + } +} + +declare namespace BABYLON { + class FreeCamera extends TargetCamera { + ellipsoid: Vector3; + keysUp: number[]; + keysDown: number[]; + keysLeft: number[]; + keysRight: number[]; + checkCollisions: boolean; + applyGravity: boolean; + angularSensibility: number; + onCollide: (collidedMesh: AbstractMesh) => void; + private _keys; + private _collider; + private _needMoveForGravity; + private _oldPosition; + private _diffPosition; + private _newPosition; + private _attachedElement; + private _localDirection; + private _transformedDirection; + private _onMouseDown; + private _onMouseUp; + private _onMouseOut; + private _onMouseMove; + private _onKeyDown; + private _onKeyUp; + _waitingLockedTargetId: string; + constructor(name: string, position: Vector3, scene: Scene); + _onLostFocus(e: FocusEvent): void; + attachControl(element: HTMLElement, noPreventDefault?: boolean): void; + detachControl(element: HTMLElement): void; + _collideWithWorld(velocity: Vector3): void; + private _onCollisionPositionChange; + _checkInputs(): void; + _decideIfNeedsToMove(): boolean; + _updatePosition(): void; + serialize(): any; + } +} + +declare namespace BABYLON { + class GamepadCamera extends UniversalCamera { + constructor(name: string, position: Vector3, scene: Scene); + } +} + +declare namespace BABYLON { + class AnaglyphFreeCamera extends FreeCamera { + interaxialDistance: number; + constructor(name: string, position: Vector3, interaxialDistance: number, scene: Scene); + } + class AnaglyphArcRotateCamera extends ArcRotateCamera { + constructor(name: string, alpha: number, beta: number, radius: number, target: any, interaxialDistance: number, scene: Scene); + } + class AnaglyphGamepadCamera extends GamepadCamera { + constructor(name: string, position: Vector3, interaxialDistance: number, scene: Scene); + } + class StereoscopicFreeCamera extends FreeCamera { + constructor(name: string, position: Vector3, interaxialDistance: number, isSideBySide: boolean, scene: Scene); + } + class StereoscopicArcRotateCamera extends ArcRotateCamera { + constructor(name: string, alpha: number, beta: number, radius: number, target: any, interaxialDistance: number, isSideBySide: boolean, scene: Scene); + } + class StereoscopicGamepadCamera extends GamepadCamera { + constructor(name: string, position: Vector3, interaxialDistance: number, isSideBySide: boolean, scene: Scene); + } +} + +declare namespace BABYLON { + class TargetCamera extends Camera { + cameraDirection: Vector3; + cameraRotation: Vector2; + rotation: Vector3; + speed: number; + noRotationConstraint: boolean; + lockedTarget: any; + _currentTarget: Vector3; + _viewMatrix: Matrix; + _camMatrix: Matrix; + _cameraTransformMatrix: Matrix; + _cameraRotationMatrix: Matrix; + private _rigCamTransformMatrix; + _referencePoint: Vector3; + _transformedReferencePoint: Vector3; + _lookAtTemp: Matrix; + _tempMatrix: Matrix; + _reset: () => void; + _waitingLockedTargetId: string; + constructor(name: string, position: Vector3, scene: Scene); + getFrontPosition(distance: number): Vector3; + _getLockedTargetPosition(): Vector3; + _initCache(): void; + _updateCache(ignoreParentClass?: boolean): void; + _isSynchronizedViewMatrix(): boolean; + _computeLocalCameraSpeed(): number; + setTarget(target: Vector3): void; + getTarget(): Vector3; + _decideIfNeedsToMove(): boolean; + _updatePosition(): void; + _checkInputs(): void; + _getViewMatrix(): Matrix; + _getVRViewMatrix(): Matrix; + /** + * @override + * Override Camera.createRigCamera + */ + createRigCamera(name: string, cameraIndex: number): Camera; + /** + * @override + * Override Camera._updateRigCameras + */ + _updateRigCameras(): void; + private _getRigCamPosition(halfSpace, result); + serialize(): any; + } +} + +declare namespace BABYLON { + class TouchCamera extends FreeCamera { + private _offsetX; + private _offsetY; + private _pointerCount; + private _pointerPressed; + private _attachedCanvas; + private _onPointerDown; + private _onPointerUp; + private _onPointerMove; + touchAngularSensibility: number; + touchMoveSensibility: number; + constructor(name: string, position: Vector3, scene: Scene); + _onLostFocus(e: FocusEvent): void; + attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void; + detachControl(canvas: HTMLCanvasElement): void; + _checkInputs(): void; + } +} + +declare namespace BABYLON { + class UniversalCamera extends TouchCamera { + gamepad: Gamepad; + private _gamepads; + gamepadAngularSensibility: number; + gamepadMoveSensibility: number; + constructor(name: string, position: Vector3, scene: Scene); + private _onNewGameConnected(gamepad); + attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void; + detachControl(canvas: HTMLCanvasElement): void; + _checkInputs(): void; + dispose(): void; + } +} + +declare namespace BABYLON { + class VirtualJoysticksCamera extends FreeCamera { + private _leftjoystick; + private _rightjoystick; + constructor(name: string, position: Vector3, scene: Scene); + getLeftJoystick(): VirtualJoystick; + getRightJoystick(): VirtualJoystick; + _checkInputs(): void; + dispose(): void; + } +} + +declare namespace BABYLON { + class Collider { + radius: Vector3; + retry: number; + velocity: Vector3; + basePoint: Vector3; + epsilon: number; + collisionFound: boolean; + velocityWorldLength: number; + basePointWorld: Vector3; + velocityWorld: Vector3; + normalizedVelocity: Vector3; + initialVelocity: Vector3; + initialPosition: Vector3; + nearestDistance: number; + intersectionPoint: Vector3; + collidedMesh: AbstractMesh; + private _collisionPoint; + private _planeIntersectionPoint; + private _tempVector; + private _tempVector2; + private _tempVector3; + private _tempVector4; + private _edge; + private _baseToVertex; + private _destinationPoint; + private _slidePlaneNormal; + private _displacementVector; + _initialize(source: Vector3, dir: Vector3, e: number): void; + _checkPointInTriangle(point: Vector3, pa: Vector3, pb: Vector3, pc: Vector3, n: Vector3): boolean; + _canDoCollision(sphereCenter: Vector3, sphereRadius: number, vecMin: Vector3, vecMax: Vector3): boolean; + _testTriangle(faceIndex: number, trianglePlaneArray: Array, p1: Vector3, p2: Vector3, p3: Vector3, hasMaterial: boolean): void; + _collide(trianglePlaneArray: Array, pts: Vector3[], indices: number[] | Int32Array, indexStart: number, indexEnd: number, decal: number, hasMaterial: boolean): void; + _getResponse(pos: Vector3, vel: Vector3): void; + } +} + +declare namespace BABYLON { + var CollisionWorker: string; + interface ICollisionCoordinator { + getNewPosition(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh?: AbstractMesh) => void, collisionIndex: number): void; + init(scene: Scene): void; + destroy(): void; + onMeshAdded(mesh: AbstractMesh): any; + onMeshUpdated(mesh: AbstractMesh): any; + onMeshRemoved(mesh: AbstractMesh): any; + onGeometryAdded(geometry: Geometry): any; + onGeometryUpdated(geometry: Geometry): any; + onGeometryDeleted(geometry: Geometry): any; + } + interface SerializedMesh { + id: string; + name: string; + uniqueId: number; + geometryId: string; + sphereCenter: Array; + sphereRadius: number; + boxMinimum: Array; + boxMaximum: Array; + worldMatrixFromCache: any; + subMeshes: Array; + checkCollisions: boolean; + } + interface SerializedSubMesh { + position: number; + verticesStart: number; + verticesCount: number; + indexStart: number; + indexCount: number; + hasMaterial: boolean; + sphereCenter: Array; + sphereRadius: number; + boxMinimum: Array; + boxMaximum: Array; + } + interface SerializedGeometry { + id: string; + positions: Float32Array; + indices: Int32Array; + normals: Float32Array; + } + interface BabylonMessage { + taskType: WorkerTaskType; + payload: InitPayload | CollidePayload | UpdatePayload; + } + interface SerializedColliderToWorker { + position: Array; + velocity: Array; + radius: Array; + } + enum WorkerTaskType { + INIT = 0, + UPDATE = 1, + COLLIDE = 2, + } + interface WorkerReply { + error: WorkerReplyType; + taskType: WorkerTaskType; + payload?: any; + } + interface CollisionReplyPayload { + newPosition: Array; + collisionId: number; + collidedMeshUniqueId: number; + } + interface InitPayload { + } + interface CollidePayload { + collisionId: number; + collider: SerializedColliderToWorker; + maximumRetry: number; + excludedMeshUniqueId?: number; + } + interface UpdatePayload { + updatedMeshes: { + [n: number]: SerializedMesh; + }; + updatedGeometries: { + [s: string]: SerializedGeometry; + }; + removedMeshes: Array; + removedGeometries: Array; + } + enum WorkerReplyType { + SUCCESS = 0, + UNKNOWN_ERROR = 1, + } + class CollisionCoordinatorWorker implements ICollisionCoordinator { + private _scene; + private _scaledPosition; + private _scaledVelocity; + private _collisionsCallbackArray; + private _init; + private _runningUpdated; + private _runningCollisionTask; + private _worker; + private _addUpdateMeshesList; + private _addUpdateGeometriesList; + private _toRemoveMeshesArray; + private _toRemoveGeometryArray; + constructor(); + static SerializeMesh: (mesh: AbstractMesh) => SerializedMesh; + static SerializeGeometry: (geometry: Geometry) => SerializedGeometry; + getNewPosition(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh?: AbstractMesh) => void, collisionIndex: number): void; + init(scene: Scene): void; + destroy(): void; + onMeshAdded(mesh: AbstractMesh): void; + onMeshUpdated: (mesh: AbstractMesh) => void; + onMeshRemoved(mesh: AbstractMesh): void; + onGeometryAdded(geometry: Geometry): void; + onGeometryUpdated: (geometry: Geometry) => void; + onGeometryDeleted(geometry: Geometry): void; + private _afterRender; + private _onMessageFromWorker; + } + class CollisionCoordinatorLegacy implements ICollisionCoordinator { + private _scene; + private _scaledPosition; + private _scaledVelocity; + private _finalPosition; + getNewPosition(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh?: AbstractMesh) => void, collisionIndex: number): void; + init(scene: Scene): void; + destroy(): void; + onMeshAdded(mesh: AbstractMesh): void; + onMeshUpdated(mesh: AbstractMesh): void; + onMeshRemoved(mesh: AbstractMesh): void; + onGeometryAdded(geometry: Geometry): void; + onGeometryUpdated(geometry: Geometry): void; + onGeometryDeleted(geometry: Geometry): void; + private _collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh?); + } +} + +declare namespace BABYLON { + var WorkerIncluded: boolean; + class CollisionCache { + private _meshes; + private _geometries; + getMeshes(): { + [n: number]: SerializedMesh; + }; + getGeometries(): { + [s: number]: SerializedGeometry; + }; + getMesh(id: any): SerializedMesh; + addMesh(mesh: SerializedMesh): void; + removeMesh(uniqueId: number): void; + getGeometry(id: string): SerializedGeometry; + addGeometry(geometry: SerializedGeometry): void; + removeGeometry(id: string): void; + } + class CollideWorker { + collider: Collider; + private _collisionCache; + private finalPosition; + private collisionsScalingMatrix; + private collisionTranformationMatrix; + constructor(collider: Collider, _collisionCache: CollisionCache, finalPosition: Vector3); + collideWithWorld(position: Vector3, velocity: Vector3, maximumRetry: number, excludedMeshUniqueId?: number): void; + private checkCollision(mesh); + private processCollisionsForSubMeshes(transformMatrix, mesh); + private collideForSubMesh(subMesh, transformMatrix, meshGeometry); + private checkSubmeshCollision(subMesh); + } + interface ICollisionDetector { + onInit(payload: InitPayload): void; + onUpdate(payload: UpdatePayload): void; + onCollision(payload: CollidePayload): void; + } + class CollisionDetectorTransferable implements ICollisionDetector { + private _collisionCache; + onInit(payload: InitPayload): void; + onUpdate(payload: UpdatePayload): void; + onCollision(payload: CollidePayload): void; + } +} + +declare namespace BABYLON { + class IntersectionInfo { + bu: number; + bv: number; + distance: number; + faceId: number; + subMeshId: number; + constructor(bu: number, bv: number, distance: number); + } + class PickingInfo { + hit: boolean; + distance: number; + pickedPoint: Vector3; + pickedMesh: AbstractMesh; + bu: number; + bv: number; + faceId: number; + subMeshId: number; + pickedSprite: Sprite; + getNormal(useWorldCoordinates?: boolean, useVerticesNormals?: boolean): Vector3; + getTextureCoordinates(): Vector2; + } +} + +declare namespace BABYLON { + class DebugLayer { + private _scene; + private _camera; + private _transformationMatrix; + private _enabled; + private _labelsEnabled; + private _displayStatistics; + private _displayTree; + private _displayLogs; + private _globalDiv; + private _statsDiv; + private _statsSubsetDiv; + private _optionsDiv; + private _optionsSubsetDiv; + private _logDiv; + private _logSubsetDiv; + private _treeDiv; + private _treeSubsetDiv; + private _drawingCanvas; + private _drawingContext; + private _rootElement; + _syncPositions: () => void; + private _syncData; + private _syncUI; + private _onCanvasClick; + private _clickPosition; + private _ratio; + private _identityMatrix; + private _showUI; + private _needToRefreshMeshesTree; + shouldDisplayLabel: (node: Node) => boolean; + shouldDisplayAxis: (mesh: Mesh) => boolean; + axisRatio: number; + accentColor: string; + customStatsFunction: () => string; + constructor(scene: Scene); + private _refreshMeshesTreeContent(); + private _renderSingleAxis(zero, unit, unitText, label, color); + private _renderAxis(projectedPosition, mesh, globalViewport); + private _renderLabel(text, projectedPosition, labelOffset, onClick, getFillStyle); + private _isClickInsideRect(x, y, width, height); + isVisible(): boolean; + hide(): void; + show(showUI?: boolean, camera?: Camera, rootElement?: HTMLElement): void; + private _clearLabels(); + private _generateheader(root, text); + private _generateTexBox(root, title, color); + private _generateAdvancedCheckBox(root, leftTitle, rightTitle, initialState, task, tag?); + private _generateCheckBox(root, title, initialState, task, tag?); + private _generateButton(root, title, task, tag?); + private _generateRadio(root, title, name, initialState, task, tag?); + private _generateDOMelements(); + private _displayStats(); + } +} + +declare namespace BABYLON { + class BoundingBox { + minimum: Vector3; + maximum: Vector3; + vectors: Vector3[]; + center: Vector3; + extendSize: Vector3; + directions: Vector3[]; + vectorsWorld: Vector3[]; + minimumWorld: Vector3; + maximumWorld: Vector3; + private _worldMatrix; + constructor(minimum: Vector3, maximum: Vector3); + getWorldMatrix(): Matrix; + _update(world: Matrix): void; + isInFrustum(frustumPlanes: Plane[]): boolean; + isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; + intersectsPoint(point: Vector3): boolean; + intersectsSphere(sphere: BoundingSphere): boolean; + intersectsMinMax(min: Vector3, max: Vector3): boolean; + static Intersects(box0: BoundingBox, box1: BoundingBox): boolean; + static IntersectsSphere(minPoint: Vector3, maxPoint: Vector3, sphereCenter: Vector3, sphereRadius: number): boolean; + static IsCompletelyInFrustum(boundingVectors: Vector3[], frustumPlanes: Plane[]): boolean; + static IsInFrustum(boundingVectors: Vector3[], frustumPlanes: Plane[]): boolean; + } +} + +declare namespace BABYLON { + class BoundingInfo { + minimum: Vector3; + maximum: Vector3; + boundingBox: BoundingBox; + boundingSphere: BoundingSphere; + private _isLocked; + constructor(minimum: Vector3, maximum: Vector3); + isLocked: boolean; + update(world: Matrix): void; + isInFrustum(frustumPlanes: Plane[]): boolean; + isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; + _checkCollision(collider: Collider): boolean; + intersectsPoint(point: Vector3): boolean; + intersects(boundingInfo: BoundingInfo, precise: boolean): boolean; + } +} + +declare namespace BABYLON { + class BoundingSphere { + minimum: Vector3; + maximum: Vector3; + center: Vector3; + radius: number; + centerWorld: Vector3; + radiusWorld: number; + private _tempRadiusVector; + constructor(minimum: Vector3, maximum: Vector3); + _update(world: Matrix): void; + isInFrustum(frustumPlanes: Plane[]): boolean; + intersectsPoint(point: Vector3): boolean; + static Intersects(sphere0: BoundingSphere, sphere1: BoundingSphere): boolean; + } +} + +declare namespace BABYLON { + class Layer { + name: string; + texture: Texture; + isBackground: boolean; + color: Color4; + scale: Vector2; + offset: Vector2; + onDispose: () => void; + alphaBlendingMode: number; + private _scene; + private _vertexDeclaration; + private _vertexStrideSize; + private _vertexBuffer; + private _indexBuffer; + private _effect; + constructor(name: string, imgUrl: string, scene: Scene, isBackground?: boolean, color?: Color4); + render(): void; + dispose(): void; + } +} + +declare namespace BABYLON { + class LensFlare { + size: number; + position: number; + color: Color3; + texture: Texture; + private _system; + constructor(size: number, position: number, color: any, imgUrl: string, system: LensFlareSystem); + dispose: () => void; + } +} + +declare namespace BABYLON { + class LensFlareSystem { + name: string; + lensFlares: LensFlare[]; + borderLimit: number; + meshesSelectionPredicate: (mesh: Mesh) => boolean; + layerMask: number; + private _scene; + private _emitter; + private _vertexDeclaration; + private _vertexStrideSize; + private _vertexBuffer; + private _indexBuffer; + private _effect; + private _positionX; + private _positionY; + private _isEnabled; + constructor(name: string, emitter: any, scene: Scene); + isEnabled: boolean; + getScene(): Scene; + getEmitter(): any; + setEmitter(newEmitter: any): void; + getEmitterPosition(): Vector3; + computeEffectivePosition(globalViewport: Viewport): boolean; + _isVisible(): boolean; + render(): boolean; + dispose(): void; + static Parse(parsedLensFlareSystem: any, scene: Scene, rootUrl: string): LensFlareSystem; + serialize(): any; + } +} + +declare namespace BABYLON { + class DirectionalLight extends Light implements IShadowLight { + direction: Vector3; + position: Vector3; + private _transformedDirection; + transformedPosition: Vector3; + private _worldMatrix; + shadowOrthoScale: number; + autoUpdateExtends: boolean; + private _orthoLeft; + private _orthoRight; + private _orthoTop; + private _orthoBottom; + constructor(name: string, direction: Vector3, scene: Scene); + getAbsolutePosition(): Vector3; + setDirectionToTarget(target: Vector3): Vector3; + setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; + supportsVSM(): boolean; + needRefreshPerFrame(): boolean; + needCube(): boolean; + getShadowDirection(faceIndex?: number): Vector3; + computeTransformedPosition(): boolean; + transferToEffect(effect: Effect, directionUniformName: string): void; + _getWorldMatrix(): Matrix; + serialize(): any; + } +} + +declare namespace BABYLON { + class HemisphericLight extends Light { + direction: Vector3; + groundColor: Color3; + private _worldMatrix; + constructor(name: string, direction: Vector3, scene: Scene); + setDirectionToTarget(target: Vector3): Vector3; + getShadowGenerator(): ShadowGenerator; + transferToEffect(effect: Effect, directionUniformName: string, groundColorUniformName: string): void; + _getWorldMatrix(): Matrix; + serialize(): any; + } +} + +declare namespace BABYLON { + interface IShadowLight { + id: string; + position: Vector3; + transformedPosition: Vector3; + name: string; + computeTransformedPosition(): boolean; + getScene(): Scene; + setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; + supportsVSM(): boolean; + needRefreshPerFrame(): boolean; + needCube(): boolean; + getShadowDirection(faceIndex?: number): Vector3; + _shadowGenerator: ShadowGenerator; + } + class Light extends Node { + diffuse: Color3; + specular: Color3; + intensity: number; + range: number; + includeOnlyWithLayerMask: number; + includedOnlyMeshes: AbstractMesh[]; + excludedMeshes: AbstractMesh[]; + excludeWithLayerMask: number; + _shadowGenerator: ShadowGenerator; + private _parentedWorldMatrix; + _excludedMeshesIds: string[]; + _includedOnlyMeshesIds: string[]; + constructor(name: string, scene: Scene); + getShadowGenerator(): ShadowGenerator; + getAbsolutePosition(): Vector3; + transferToEffect(effect: Effect, uniformName0?: string, uniformName1?: string): void; + _getWorldMatrix(): Matrix; + canAffectMesh(mesh: AbstractMesh): boolean; + getWorldMatrix(): Matrix; + dispose(): void; + serialize(): any; + static Parse(parsedLight: any, scene: Scene): Light; + } +} + +declare namespace BABYLON { + class PointLight extends Light implements IShadowLight { + position: Vector3; + private _worldMatrix; + transformedPosition: Vector3; + constructor(name: string, position: Vector3, scene: Scene); + getAbsolutePosition(): Vector3; + computeTransformedPosition(): boolean; + transferToEffect(effect: Effect, positionUniformName: string): void; + needCube(): boolean; + supportsVSM(): boolean; + needRefreshPerFrame(): boolean; + getShadowDirection(faceIndex?: number): Vector3; + setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; + _getWorldMatrix(): Matrix; + serialize(): any; + } +} + +declare namespace BABYLON { + class SpotLight extends Light implements IShadowLight { + position: Vector3; + direction: Vector3; + angle: number; + exponent: number; + transformedPosition: Vector3; + private _transformedDirection; + private _worldMatrix; + constructor(name: string, position: Vector3, direction: Vector3, angle: number, exponent: number, scene: Scene); + getAbsolutePosition(): Vector3; + setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; + needCube(): boolean; + supportsVSM(): boolean; + needRefreshPerFrame(): boolean; + getShadowDirection(faceIndex?: number): Vector3; + setDirectionToTarget(target: Vector3): Vector3; + computeTransformedPosition(): boolean; + transferToEffect(effect: Effect, positionUniformName: string, directionUniformName: string): void; + _getWorldMatrix(): Matrix; + serialize(): any; + } +} + +declare namespace BABYLON { + interface ISceneLoaderPlugin { + extensions: string; + importMesh: (meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => boolean; + load: (scene: Scene, data: string, rootUrl: string) => boolean; + } + class SceneLoader { + private static _ForceFullSceneLoadingForIncremental; + private static _ShowLoadingScreen; + static ForceFullSceneLoadingForIncremental: boolean; + static ShowLoadingScreen: boolean; + private static _registeredPlugins; + private static _getPluginForFilename(sceneFilename); + static RegisterPlugin(plugin: ISceneLoaderPlugin): void; + static ImportMesh(meshesNames: any, rootUrl: string, sceneFilename: string, scene: Scene, onsuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, progressCallBack?: () => void, onerror?: (scene: Scene, e: any) => void): void; + /** + * Load a scene + * @param rootUrl a string that defines the root url for scene and resources + * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene + * @param engine is the instance of BABYLON.Engine to use to create the scene + */ + static Load(rootUrl: string, sceneFilename: any, engine: Engine, onsuccess?: (scene: Scene) => void, progressCallBack?: any, onerror?: (scene: Scene) => void): void; + /** + * Append a scene + * @param rootUrl a string that defines the root url for scene and resources + * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene + * @param scene is the instance of BABYLON.Scene to append to + */ + static Append(rootUrl: string, sceneFilename: any, scene: Scene, onsuccess?: (scene: Scene) => void, progressCallBack?: any, onerror?: (scene: Scene) => void): void; + } +} + +declare namespace BABYLON { + class SIMDVector3 { + static TransformCoordinatesToRefSIMD(vector: Vector3, transformation: Matrix, result: Vector3): void; + static TransformCoordinatesFromFloatsToRefSIMD(x: number, y: number, z: number, transformation: Matrix, result: Vector3): void; + } + class SIMDMatrix { + multiplyToArraySIMD(other: Matrix, result: Matrix, offset?: number): void; + invertToRefSIMD(other: Matrix): Matrix; + static LookAtLHToRefSIMD(eyeRef: Vector3, targetRef: Vector3, upRef: Vector3, result: Matrix): void; + } + class SIMDHelper { + private static _isEnabled; + static IsEnabled: boolean; + static DisableSIMD(): void; + static EnableSIMD(): void; + } +} + +declare namespace BABYLON { + class Color3 { + r: number; + g: number; + b: number; + constructor(r?: number, g?: number, b?: number); + toString(): string; + toArray(array: number[], index?: number): Color3; + toColor4(alpha?: number): Color4; + asArray(): number[]; + toLuminance(): number; + multiply(otherColor: Color3): Color3; + multiplyToRef(otherColor: Color3, result: Color3): Color3; + equals(otherColor: Color3): boolean; + equalsFloats(r: number, g: number, b: number): boolean; + scale(scale: number): Color3; + scaleToRef(scale: number, result: Color3): Color3; + add(otherColor: Color3): Color3; + addToRef(otherColor: Color3, result: Color3): Color3; + subtract(otherColor: Color3): Color3; + subtractToRef(otherColor: Color3, result: Color3): Color3; + clone(): Color3; + copyFrom(source: Color3): Color3; + copyFromFloats(r: number, g: number, b: number): Color3; + toHexString(): string; + toLinearSpace(): Color3; + toLinearSpaceToRef(convertedColor: Color3): Color3; + toGammaSpace(): Color3; + toGammaSpaceToRef(convertedColor: Color3): Color3; + static FromHexString(hex: string): Color3; + static FromArray(array: number[], offset?: number): Color3; + static FromInts(r: number, g: number, b: number): Color3; + static Lerp(start: Color3, end: Color3, amount: number): Color3; + static Red(): Color3; + static Green(): Color3; + static Blue(): Color3; + static Black(): Color3; + static White(): Color3; + static Purple(): Color3; + static Magenta(): Color3; + static Yellow(): Color3; + static Gray(): Color3; + } + class Color4 { + r: number; + g: number; + b: number; + a: number; + constructor(r: number, g: number, b: number, a: number); + addInPlace(right: any): Color4; + asArray(): number[]; + toArray(array: number[], index?: number): Color4; + add(right: Color4): Color4; + subtract(right: Color4): Color4; + subtractToRef(right: Color4, result: Color4): Color4; + scale(scale: number): Color4; + scaleToRef(scale: number, result: Color4): Color4; + toString(): string; + clone(): Color4; + copyFrom(source: Color4): Color4; + toHexString(): string; + static FromHexString(hex: string): Color4; + static Lerp(left: Color4, right: Color4, amount: number): Color4; + static LerpToRef(left: Color4, right: Color4, amount: number, result: Color4): void; + static FromArray(array: number[], offset?: number): Color4; + static FromInts(r: number, g: number, b: number, a: number): Color4; + static CheckColors4(colors: number[], count: number): number[]; + } + class Vector2 { + x: number; + y: number; + constructor(x: number, y: number); + toString(): string; + toArray(array: number[], index?: number): Vector2; + asArray(): number[]; + copyFrom(source: Vector2): Vector2; + copyFromFloats(x: number, y: number): Vector2; + add(otherVector: Vector2): Vector2; + addVector3(otherVector: Vector3): Vector2; + subtract(otherVector: Vector2): Vector2; + subtractInPlace(otherVector: Vector2): Vector2; + multiplyInPlace(otherVector: Vector2): Vector2; + multiply(otherVector: Vector2): Vector2; + multiplyToRef(otherVector: Vector2, result: Vector2): Vector2; + multiplyByFloats(x: number, y: number): Vector2; + divide(otherVector: Vector2): Vector2; + divideToRef(otherVector: Vector2, result: Vector2): Vector2; + negate(): Vector2; + scaleInPlace(scale: number): Vector2; + scale(scale: number): Vector2; + equals(otherVector: Vector2): boolean; + equalsWithEpsilon(otherVector: Vector2, epsilon?: number): boolean; + length(): number; + lengthSquared(): number; + normalize(): Vector2; + clone(): Vector2; + static Zero(): Vector2; + static FromArray(array: number[] | Float32Array, offset?: number): Vector2; + static FromArrayToRef(array: number[] | Float32Array, offset: number, result: Vector2): void; + static CatmullRom(value1: Vector2, value2: Vector2, value3: Vector2, value4: Vector2, amount: number): Vector2; + static Clamp(value: Vector2, min: Vector2, max: Vector2): Vector2; + static Hermite(value1: Vector2, tangent1: Vector2, value2: Vector2, tangent2: Vector2, amount: number): Vector2; + static Lerp(start: Vector2, end: Vector2, amount: number): Vector2; + static Dot(left: Vector2, right: Vector2): number; + static Normalize(vector: Vector2): Vector2; + static Minimize(left: Vector2, right: Vector2): Vector2; + static Maximize(left: Vector2, right: Vector2): Vector2; + static Transform(vector: Vector2, transformation: Matrix): Vector2; + static Distance(value1: Vector2, value2: Vector2): number; + static DistanceSquared(value1: Vector2, value2: Vector2): number; + } + class Vector3 { + x: number; + y: number; + z: number; + constructor(x: number, y: number, z: number); + toString(): string; + asArray(): number[]; + toArray(array: number[] | Float32Array, index?: number): Vector3; + toQuaternion(): Quaternion; + addInPlace(otherVector: Vector3): Vector3; + add(otherVector: Vector3): Vector3; + addToRef(otherVector: Vector3, result: Vector3): Vector3; + subtractInPlace(otherVector: Vector3): Vector3; + subtract(otherVector: Vector3): Vector3; + subtractToRef(otherVector: Vector3, result: Vector3): Vector3; + subtractFromFloats(x: number, y: number, z: number): Vector3; + subtractFromFloatsToRef(x: number, y: number, z: number, result: Vector3): Vector3; + negate(): Vector3; + scaleInPlace(scale: number): Vector3; + scale(scale: number): Vector3; + scaleToRef(scale: number, result: Vector3): void; + equals(otherVector: Vector3): boolean; + equalsWithEpsilon(otherVector: Vector3, epsilon?: number): boolean; + equalsToFloats(x: number, y: number, z: number): boolean; + multiplyInPlace(otherVector: Vector3): Vector3; + multiply(otherVector: Vector3): Vector3; + multiplyToRef(otherVector: Vector3, result: Vector3): Vector3; + multiplyByFloats(x: number, y: number, z: number): Vector3; + divide(otherVector: Vector3): Vector3; + divideToRef(otherVector: Vector3, result: Vector3): Vector3; + MinimizeInPlace(other: Vector3): Vector3; + MaximizeInPlace(other: Vector3): Vector3; + length(): number; + lengthSquared(): number; + normalize(): Vector3; + clone(): Vector3; + copyFrom(source: Vector3): Vector3; + copyFromFloats(x: number, y: number, z: number): Vector3; + static GetClipFactor(vector0: Vector3, vector1: Vector3, axis: Vector3, size: any): number; + static FromArray(array: number[] | Float32Array, offset?: number): Vector3; + static FromFloatArray(array: Float32Array, offset?: number): Vector3; + static FromArrayToRef(array: number[] | Float32Array, offset: number, result: Vector3): void; + static FromFloatArrayToRef(array: Float32Array, offset: number, result: Vector3): void; + static FromFloatsToRef(x: number, y: number, z: number, result: Vector3): void; + static Zero(): Vector3; + static Up(): Vector3; + static TransformCoordinates(vector: Vector3, transformation: Matrix): Vector3; + static TransformCoordinatesToRef(vector: Vector3, transformation: Matrix, result: Vector3): void; + static TransformCoordinatesFromFloatsToRef(x: number, y: number, z: number, transformation: Matrix, result: Vector3): void; + static TransformNormal(vector: Vector3, transformation: Matrix): Vector3; + static TransformNormalToRef(vector: Vector3, transformation: Matrix, result: Vector3): void; + static TransformNormalFromFloatsToRef(x: number, y: number, z: number, transformation: Matrix, result: Vector3): void; + static CatmullRom(value1: Vector3, value2: Vector3, value3: Vector3, value4: Vector3, amount: number): Vector3; + static Clamp(value: Vector3, min: Vector3, max: Vector3): Vector3; + static Hermite(value1: Vector3, tangent1: Vector3, value2: Vector3, tangent2: Vector3, amount: number): Vector3; + static Lerp(start: Vector3, end: Vector3, amount: number): Vector3; + static Dot(left: Vector3, right: Vector3): number; + static Cross(left: Vector3, right: Vector3): Vector3; + static CrossToRef(left: Vector3, right: Vector3, result: Vector3): void; + static Normalize(vector: Vector3): Vector3; + static NormalizeToRef(vector: Vector3, result: Vector3): void; + static Project(vector: Vector3, world: Matrix, transform: Matrix, viewport: Viewport): Vector3; + static UnprojectFromTransform(source: Vector3, viewportWidth: number, viewportHeight: number, world: Matrix, transform: Matrix): Vector3; + static Unproject(source: Vector3, viewportWidth: number, viewportHeight: number, world: Matrix, view: Matrix, projection: Matrix): Vector3; + static Minimize(left: Vector3, right: Vector3): Vector3; + static Maximize(left: Vector3, right: Vector3): Vector3; + static Distance(value1: Vector3, value2: Vector3): number; + static DistanceSquared(value1: Vector3, value2: Vector3): number; + static Center(value1: Vector3, value2: Vector3): Vector3; + /** + * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system), + * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply + * to something in order to rotate it from its local system to the given target system. + */ + static RotationFromAxis(axis1: Vector3, axis2: Vector3, axis3: Vector3): Vector3; + /** + * The same than RotationFromAxis but updates the passed ref Vector3 parameter. + */ + static RotationFromAxisToRef(axis1: Vector3, axis2: Vector3, axis3: Vector3, ref: Vector3): void; + } + class Vector4 { + x: number; + y: number; + z: number; + w: number; + constructor(x: number, y: number, z: number, w: number); + toString(): string; + asArray(): number[]; + toArray(array: number[], index?: number): Vector4; + addInPlace(otherVector: Vector4): Vector4; + add(otherVector: Vector4): Vector4; + addToRef(otherVector: Vector4, result: Vector4): Vector4; + subtractInPlace(otherVector: Vector4): Vector4; + subtract(otherVector: Vector4): Vector4; + subtractToRef(otherVector: Vector4, result: Vector4): Vector4; + subtractFromFloats(x: number, y: number, z: number, w: number): Vector4; + subtractFromFloatsToRef(x: number, y: number, z: number, w: number, result: Vector4): Vector4; + negate(): Vector4; + scaleInPlace(scale: number): Vector4; + scale(scale: number): Vector4; + scaleToRef(scale: number, result: Vector4): void; + equals(otherVector: Vector4): boolean; + equalsWithEpsilon(otherVector: Vector4, epsilon?: number): boolean; + equalsToFloats(x: number, y: number, z: number, w: number): boolean; + multiplyInPlace(otherVector: Vector4): Vector4; + multiply(otherVector: Vector4): Vector4; + multiplyToRef(otherVector: Vector4, result: Vector4): Vector4; + multiplyByFloats(x: number, y: number, z: number, w: number): Vector4; + divide(otherVector: Vector4): Vector4; + divideToRef(otherVector: Vector4, result: Vector4): Vector4; + MinimizeInPlace(other: Vector4): Vector4; + MaximizeInPlace(other: Vector4): Vector4; + length(): number; + lengthSquared(): number; + normalize(): Vector4; + clone(): Vector4; + copyFrom(source: Vector4): Vector4; + copyFromFloats(x: number, y: number, z: number, w: number): Vector4; + static FromArray(array: number[], offset?: number): Vector4; + static FromArrayToRef(array: number[], offset: number, result: Vector4): void; + static FromFloatArrayToRef(array: Float32Array, offset: number, result: Vector4): void; + static FromFloatsToRef(x: number, y: number, z: number, w: number, result: Vector4): void; + static Zero(): Vector4; + static Normalize(vector: Vector4): Vector4; + static NormalizeToRef(vector: Vector4, result: Vector4): void; + static Minimize(left: Vector4, right: Vector4): Vector4; + static Maximize(left: Vector4, right: Vector4): Vector4; + static Distance(value1: Vector4, value2: Vector4): number; + static DistanceSquared(value1: Vector4, value2: Vector4): number; + static Center(value1: Vector4, value2: Vector4): Vector4; + } + class Quaternion { + x: number; + y: number; + z: number; + w: number; + constructor(x?: number, y?: number, z?: number, w?: number); + toString(): string; + asArray(): number[]; + equals(otherQuaternion: Quaternion): boolean; + clone(): Quaternion; + copyFrom(other: Quaternion): Quaternion; + copyFromFloats(x: number, y: number, z: number, w: number): Quaternion; + add(other: Quaternion): Quaternion; + subtract(other: Quaternion): Quaternion; + scale(value: number): Quaternion; + multiply(q1: Quaternion): Quaternion; + multiplyToRef(q1: Quaternion, result: Quaternion): Quaternion; + multiplyInPlace(q1: Quaternion): Quaternion; + length(): number; + normalize(): Quaternion; + toEulerAngles(order?: string): Vector3; + toEulerAnglesToRef(result: Vector3, order?: string): Quaternion; + toRotationMatrix(result: Matrix): Quaternion; + fromRotationMatrix(matrix: Matrix): Quaternion; + static FromRotationMatrix(matrix: Matrix): Quaternion; + static FromRotationMatrixToRef(matrix: Matrix, result: Quaternion): void; + static Inverse(q: Quaternion): Quaternion; + static Identity(): Quaternion; + static RotationAxis(axis: Vector3, angle: number): Quaternion; + static FromArray(array: number[], offset?: number): Quaternion; + static RotationYawPitchRoll(yaw: number, pitch: number, roll: number): Quaternion; + static RotationYawPitchRollToRef(yaw: number, pitch: number, roll: number, result: Quaternion): void; + static RotationAlphaBetaGamma(alpha: number, beta: number, gamma: number): Quaternion; + static RotationAlphaBetaGammaToRef(alpha: number, beta: number, gamma: number, result: Quaternion): void; + static Slerp(left: Quaternion, right: Quaternion, amount: number): Quaternion; + } + class Matrix { + private static _tempQuaternion; + private static _xAxis; + private static _yAxis; + private static _zAxis; + m: Float32Array; + isIdentity(): boolean; + determinant(): number; + toArray(): Float32Array; + asArray(): Float32Array; + invert(): Matrix; + reset(): Matrix; + add(other: Matrix): Matrix; + addToRef(other: Matrix, result: Matrix): Matrix; + addToSelf(other: Matrix): Matrix; + invertToRef(other: Matrix): Matrix; + setTranslation(vector3: Vector3): Matrix; + multiply(other: Matrix): Matrix; + copyFrom(other: Matrix): Matrix; + copyToArray(array: Float32Array, offset?: number): Matrix; + multiplyToRef(other: Matrix, result: Matrix): Matrix; + multiplyToArray(other: Matrix, result: Float32Array, offset: number): Matrix; + equals(value: Matrix): boolean; + clone(): Matrix; + decompose(scale: Vector3, rotation: Quaternion, translation: Vector3): boolean; + static FromArray(array: number[], offset?: number): Matrix; + static FromArrayToRef(array: number[], offset: number, result: Matrix): void; + static FromFloat32ArrayToRefScaled(array: Float32Array, offset: number, scale: number, result: Matrix): void; + static FromValuesToRef(initialM11: number, initialM12: number, initialM13: number, initialM14: number, initialM21: number, initialM22: number, initialM23: number, initialM24: number, initialM31: number, initialM32: number, initialM33: number, initialM34: number, initialM41: number, initialM42: number, initialM43: number, initialM44: number, result: Matrix): void; + static FromValues(initialM11: number, initialM12: number, initialM13: number, initialM14: number, initialM21: number, initialM22: number, initialM23: number, initialM24: number, initialM31: number, initialM32: number, initialM33: number, initialM34: number, initialM41: number, initialM42: number, initialM43: number, initialM44: number): Matrix; + static Compose(scale: Vector3, rotation: Quaternion, translation: Vector3): Matrix; + static Identity(): Matrix; + static IdentityToRef(result: Matrix): void; + static Zero(): Matrix; + static RotationX(angle: number): Matrix; + static Invert(source: Matrix): Matrix; + static RotationXToRef(angle: number, result: Matrix): void; + static RotationY(angle: number): Matrix; + static RotationYToRef(angle: number, result: Matrix): void; + static RotationZ(angle: number): Matrix; + static RotationZToRef(angle: number, result: Matrix): void; + static RotationAxis(axis: Vector3, angle: number): Matrix; + static RotationAxisToRef(axis: Vector3, angle: number, result: Matrix): void; + static RotationYawPitchRoll(yaw: number, pitch: number, roll: number): Matrix; + static RotationYawPitchRollToRef(yaw: number, pitch: number, roll: number, result: Matrix): void; + static Scaling(x: number, y: number, z: number): Matrix; + static ScalingToRef(x: number, y: number, z: number, result: Matrix): void; + static Translation(x: number, y: number, z: number): Matrix; + static TranslationToRef(x: number, y: number, z: number, result: Matrix): void; + static Lerp(startValue: Matrix, endValue: Matrix, gradient: number): Matrix; + static LookAtLH(eye: Vector3, target: Vector3, up: Vector3): Matrix; + static LookAtLHToRef(eye: Vector3, target: Vector3, up: Vector3, result: Matrix): void; + static OrthoLH(width: number, height: number, znear: number, zfar: number): Matrix; + static OrthoLHToRef(width: number, height: number, znear: number, zfar: number, result: Matrix): void; + static OrthoOffCenterLH(left: number, right: number, bottom: number, top: number, znear: number, zfar: number): Matrix; + static OrthoOffCenterLHToRef(left: number, right: any, bottom: number, top: number, znear: number, zfar: number, result: Matrix): void; + static PerspectiveLH(width: number, height: number, znear: number, zfar: number): Matrix; + static PerspectiveFovLH(fov: number, aspect: number, znear: number, zfar: number): Matrix; + static PerspectiveFovLHToRef(fov: number, aspect: number, znear: number, zfar: number, result: Matrix, fovMode?: number): void; + static GetFinalMatrix(viewport: Viewport, world: Matrix, view: Matrix, projection: Matrix, zmin: number, zmax: number): Matrix; + static GetAsMatrix2x2(matrix: Matrix): Float32Array; + static GetAsMatrix3x3(matrix: Matrix): Float32Array; + static Transpose(matrix: Matrix): Matrix; + static Reflection(plane: Plane): Matrix; + static ReflectionToRef(plane: Plane, result: Matrix): void; + } + class Plane { + normal: Vector3; + d: number; + constructor(a: number, b: number, c: number, d: number); + asArray(): number[]; + clone(): Plane; + normalize(): Plane; + transform(transformation: Matrix): Plane; + dotCoordinate(point: any): number; + copyFromPoints(point1: Vector3, point2: Vector3, point3: Vector3): Plane; + isFrontFacingTo(direction: Vector3, epsilon: number): boolean; + signedDistanceTo(point: Vector3): number; + static FromArray(array: number[]): Plane; + static FromPoints(point1: any, point2: any, point3: any): Plane; + static FromPositionAndNormal(origin: Vector3, normal: Vector3): Plane; + static SignedDistanceToPlaneFromPositionAndNormal(origin: Vector3, normal: Vector3, point: Vector3): number; + } + class Viewport { + x: number; + y: number; + width: number; + height: number; + constructor(x: number, y: number, width: number, height: number); + toGlobal(engine: Engine): Viewport; + toScreenGlobal(engine: Engine): Viewport; + } + class Frustum { + static GetPlanes(transform: Matrix): Plane[]; + static GetPlanesToRef(transform: Matrix, frustumPlanes: Plane[]): void; + } + class Ray { + origin: Vector3; + direction: Vector3; + length: number; + private _edge1; + private _edge2; + private _pvec; + private _tvec; + private _qvec; + constructor(origin: Vector3, direction: Vector3, length?: number); + intersectsBoxMinMax(minimum: Vector3, maximum: Vector3): boolean; + intersectsBox(box: BoundingBox): boolean; + intersectsSphere(sphere: any): boolean; + intersectsTriangle(vertex0: Vector3, vertex1: Vector3, vertex2: Vector3): IntersectionInfo; + static CreateNew(x: number, y: number, viewportWidth: number, viewportHeight: number, world: Matrix, view: Matrix, projection: Matrix): Ray; + /** + * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be + * transformed to the given world matrix. + * @param origin The origin point + * @param end The end point + * @param world a matrix to transform the ray to. Default is the identity matrix. + */ + static CreateNewFromTo(origin: Vector3, end: Vector3, world?: Matrix): Ray; + static Transform(ray: Ray, matrix: Matrix): Ray; + } + enum Space { + LOCAL = 0, + WORLD = 1, + } + class Axis { + static X: Vector3; + static Y: Vector3; + static Z: Vector3; + } + class BezierCurve { + static interpolate(t: number, x1: number, y1: number, x2: number, y2: number): number; + } + enum Orientation { + CW = 0, + CCW = 1, + } + class Angle { + private _radians; + constructor(radians: number); + degrees: () => number; + radians: () => number; + static BetweenTwoPoints(a: Vector2, b: Vector2): Angle; + static FromRadians(radians: number): Angle; + static FromDegrees(degrees: number): Angle; + } + class Arc2 { + startPoint: Vector2; + midPoint: Vector2; + endPoint: Vector2; + centerPoint: Vector2; + radius: number; + angle: Angle; + startAngle: Angle; + orientation: Orientation; + constructor(startPoint: Vector2, midPoint: Vector2, endPoint: Vector2); + } + class PathCursor { + private path; + private _onchange; + value: number; + animations: Animation[]; + constructor(path: Path2); + getPoint(): Vector3; + moveAhead(step?: number): PathCursor; + moveBack(step?: number): PathCursor; + move(step: number): PathCursor; + private ensureLimits(); + private markAsDirty(propertyName); + private raiseOnChange(); + onchange(f: (cursor: PathCursor) => void): PathCursor; + } + class Path2 { + private _points; + private _length; + closed: boolean; + constructor(x: number, y: number); + addLineTo(x: number, y: number): Path2; + addArcTo(midX: number, midY: number, endX: number, endY: number, numberOfSegments?: number): Path2; + close(): Path2; + length(): number; + getPoints(): Vector2[]; + getPointAtLengthPosition(normalizedLengthPosition: number): Vector2; + static StartingAt(x: number, y: number): Path2; + } + class Path3D { + path: Vector3[]; + private _curve; + private _distances; + private _tangents; + private _normals; + private _binormals; + private _raw; + /** + * new Path3D(path, normal, raw) + * path : an array of Vector3, the curve axis of the Path3D + * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal. + * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed. + */ + constructor(path: Vector3[], firstNormal?: Vector3, raw?: boolean); + getCurve(): Vector3[]; + getTangents(): Vector3[]; + getNormals(): Vector3[]; + getBinormals(): Vector3[]; + getDistances(): number[]; + update(path: Vector3[], firstNormal?: Vector3): Path3D; + private _compute(firstNormal); + private _getFirstNonNullVector(index); + private _getLastNonNullVector(index); + private _normalVector(v0, vt, va); + } + class Curve3 { + private _points; + private _length; + static CreateQuadraticBezier(v0: Vector3, v1: Vector3, v2: Vector3, nbPoints: number): Curve3; + static CreateCubicBezier(v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3, nbPoints: number): Curve3; + static CreateHermiteSpline(p1: Vector3, t1: Vector3, p2: Vector3, t2: Vector3, nbPoints: number): Curve3; + constructor(points: Vector3[]); + getPoints(): Vector3[]; + length(): number; + continue(curve: Curve3): Curve3; + private _computeLength(path); + } + class PositionNormalVertex { + position: Vector3; + normal: Vector3; + constructor(position?: Vector3, normal?: Vector3); + clone(): PositionNormalVertex; + } + class PositionNormalTextureVertex { + position: Vector3; + normal: Vector3; + uv: Vector2; + constructor(position?: Vector3, normal?: Vector3, uv?: Vector2); + clone(): PositionNormalTextureVertex; + } + class Tmp { + static Vector2: Vector2[]; + static Vector3: Vector3[]; + static Vector4: Vector4[]; + static Quaternion: Quaternion[]; + static Matrix: Matrix[]; + } +} + +declare namespace BABYLON { + class EffectFallbacks { + private _defines; + private _currentRank; + private _maxRank; + private _mesh; + private _meshRank; + addFallback(rank: number, define: string): void; + addCPUSkinningFallback(rank: number, mesh: BABYLON.AbstractMesh): void; + isMoreFallbacks: boolean; + reduce(currentDefines: string): string; + } + class Effect { + name: any; + defines: string; + onCompiled: (effect: Effect) => void; + onError: (effect: Effect, errors: string) => void; + onBind: (effect: Effect) => void; + private _engine; + private _uniformsNames; + private _samplers; + private _isReady; + private _compilationError; + private _attributesNames; + private _attributes; + private _uniforms; + _key: string; + private _program; + private _valueCache; + constructor(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], engine: any, defines?: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void); + isReady(): boolean; + getProgram(): WebGLProgram; + getAttributesNames(): string[]; + getAttributeLocation(index: number): number; + getAttributeLocationByName(name: string): number; + getAttributesCount(): number; + getUniformIndex(uniformName: string): number; + getUniform(uniformName: string): WebGLUniformLocation; + getSamplers(): string[]; + getCompilationError(): string; + _loadVertexShader(vertex: any, callback: (data: any) => void): void; + _loadFragmentShader(fragment: any, callback: (data: any) => void): void; + private _dumpShadersName(); + private _prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks?); + isSupported: boolean; + _bindTexture(channel: string, texture: WebGLTexture): void; + setTexture(channel: string, texture: BaseTexture): void; + setTextureFromPostProcess(channel: string, postProcess: PostProcess): void; + _cacheMatrix(uniformName: any, matrix: any): void; + _cacheFloat2(uniformName: string, x: number, y: number): void; + _cacheFloat3(uniformName: string, x: number, y: number, z: number): void; + _cacheFloat4(uniformName: string, x: number, y: number, z: number, w: number): void; + setArray(uniformName: string, array: number[]): Effect; + setArray2(uniformName: string, array: number[]): Effect; + setArray3(uniformName: string, array: number[]): Effect; + setArray4(uniformName: string, array: number[]): Effect; + setMatrices(uniformName: string, matrices: Float32Array): Effect; + setMatrix(uniformName: string, matrix: Matrix): Effect; + setMatrix3x3(uniformName: string, matrix: Float32Array): Effect; + setMatrix2x2(uniformname: string, matrix: Float32Array): Effect; + setFloat(uniformName: string, value: number): Effect; + setBool(uniformName: string, bool: boolean): Effect; + setVector2(uniformName: string, vector2: Vector2): Effect; + setFloat2(uniformName: string, x: number, y: number): Effect; + setVector3(uniformName: string, vector3: Vector3): Effect; + setFloat3(uniformName: string, x: number, y: number, z: number): Effect; + setVector4(uniformName: string, vector4: Vector4): Effect; + setFloat4(uniformName: string, x: number, y: number, z: number, w: number): Effect; + setColor3(uniformName: string, color3: Color3): Effect; + setColor4(uniformName: string, color3: Color3, alpha: number): Effect; + static ShadersStore: {}; + } +} + +declare namespace BABYLON { + class MaterialDefines { + _keys: string[]; + isEqual(other: MaterialDefines): boolean; + cloneTo(other: MaterialDefines): void; + reset(): void; + toString(): string; + } + class Material { + name: string; + private static _TriangleFillMode; + private static _WireFrameFillMode; + private static _PointFillMode; + static TriangleFillMode: number; + static WireFrameFillMode: number; + static PointFillMode: number; + private static _ClockWiseSideOrientation; + private static _CounterClockWiseSideOrientation; + static ClockWiseSideOrientation: number; + static CounterClockWiseSideOrientation: number; + id: string; + checkReadyOnEveryCall: boolean; + checkReadyOnlyOnce: boolean; + state: string; + alpha: number; + backFaceCulling: boolean; + sideOrientation: number; + onCompiled: (effect: Effect) => void; + onError: (effect: Effect, errors: string) => void; + onDispose: () => void; + onBind: (material: Material, mesh: Mesh) => void; + getRenderTargetTextures: () => SmartArray; + alphaMode: number; + disableDepthWrite: boolean; + fogEnabled: boolean; + _effect: Effect; + _wasPreviouslyReady: boolean; + private _scene; + private _fillMode; + private _cachedDepthWriteState; + pointSize: number; + zOffset: number; + wireframe: boolean; + pointsCloud: boolean; + fillMode: number; + constructor(name: string, scene: Scene, doNotAdd?: boolean); + isFrozen: boolean; + freeze(): void; + unfreeze(): void; + isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean; + getEffect(): Effect; + getScene(): Scene; + needAlphaBlending(): boolean; + needAlphaTesting(): boolean; + getAlphaTestTexture(): BaseTexture; + trackCreation(onCompiled: (effect: Effect) => void, onError: (effect: Effect, errors: string) => void): void; + markDirty(): void; + _preBind(): void; + bind(world: Matrix, mesh?: Mesh): void; + bindOnlyWorldMatrix(world: Matrix): void; + unbind(): void; + clone(name: string): Material; + getBindedMeshes(): AbstractMesh[]; + dispose(forceDisposeEffect?: boolean): void; + copyTo(other: Material): void; + serialize(): any; + static ParseMultiMaterial(parsedMultiMaterial: any, scene: Scene): MultiMaterial; + static Parse(parsedMaterial: any, scene: Scene, rootUrl: string): any; + } +} + +declare namespace BABYLON { + class MultiMaterial extends Material { + subMaterials: Material[]; + constructor(name: string, scene: Scene); + getSubMaterial(index: any): Material; + isReady(mesh?: AbstractMesh): boolean; + clone(name: string, cloneChildren?: boolean): MultiMaterial; + serialize(): any; + } +} + +declare namespace BABYLON { + class ShaderMaterial extends Material { + private _shaderPath; + private _options; + private _textures; + private _floats; + private _floatsArrays; + private _colors3; + private _colors4; + private _vectors2; + private _vectors3; + private _vectors4; + private _matrices; + private _matrices3x3; + private _matrices2x2; + private _cachedWorldViewMatrix; + private _renderId; + constructor(name: string, scene: Scene, shaderPath: any, options: any); + needAlphaBlending(): boolean; + needAlphaTesting(): boolean; + private _checkUniform(uniformName); + setTexture(name: string, texture: Texture): ShaderMaterial; + setFloat(name: string, value: number): ShaderMaterial; + setFloats(name: string, value: number[]): ShaderMaterial; + setColor3(name: string, value: Color3): ShaderMaterial; + setColor4(name: string, value: Color4): ShaderMaterial; + setVector2(name: string, value: Vector2): ShaderMaterial; + setVector3(name: string, value: Vector3): ShaderMaterial; + setVector4(name: string, value: Vector4): ShaderMaterial; + setMatrix(name: string, value: Matrix): ShaderMaterial; + setMatrix3x3(name: string, value: Float32Array): ShaderMaterial; + setMatrix2x2(name: string, value: Float32Array): ShaderMaterial; + isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean; + bindOnlyWorldMatrix(world: Matrix): void; + bind(world: Matrix, mesh?: Mesh): void; + clone(name: string): ShaderMaterial; + dispose(forceDisposeEffect?: boolean): void; + serialize(): any; + static Parse(source: any, scene: Scene, rootUrl: string): ShaderMaterial; + } +} + +declare namespace BABYLON { + class FresnelParameters { + isEnabled: boolean; + leftColor: Color3; + rightColor: Color3; + bias: number; + power: number; + clone(): FresnelParameters; + serialize(): any; + static Parse(parsedFresnelParameters: any): FresnelParameters; + } + class StandardMaterial extends Material { + diffuseTexture: BaseTexture; + ambientTexture: BaseTexture; + opacityTexture: BaseTexture; + reflectionTexture: BaseTexture; + emissiveTexture: BaseTexture; + specularTexture: BaseTexture; + bumpTexture: BaseTexture; + lightmapTexture: BaseTexture; + ambientColor: Color3; + diffuseColor: Color3; + specularColor: Color3; + specularPower: number; + emissiveColor: Color3; + useAlphaFromDiffuseTexture: boolean; + useEmissiveAsIllumination: boolean; + linkEmissiveWithDiffuse: boolean; + useReflectionFresnelFromSpecular: boolean; + useSpecularOverAlpha: boolean; + disableLighting: boolean; + roughness: number; + useLightmapAsShadowmap: boolean; + diffuseFresnelParameters: FresnelParameters; + opacityFresnelParameters: FresnelParameters; + reflectionFresnelParameters: FresnelParameters; + emissiveFresnelParameters: FresnelParameters; + useGlossinessFromSpecularMapAlpha: boolean; + private _renderTargets; + private _worldViewProjectionMatrix; + private _globalAmbientColor; + private _renderId; + private _defines; + private _cachedDefines; + private _useLogarithmicDepth; + constructor(name: string, scene: Scene); + useLogarithmicDepth: boolean; + needAlphaBlending(): boolean; + needAlphaTesting(): boolean; + private _shouldUseAlphaFromDiffuseTexture(); + getAlphaTestTexture(): BaseTexture; + private _checkCache(scene, mesh?, useInstances?); + static PrepareDefinesForLights(scene: Scene, mesh: AbstractMesh, defines: MaterialDefines): boolean; + private static _scaledDiffuse; + private static _scaledSpecular; + static BindLights(scene: Scene, mesh: AbstractMesh, effect: Effect, defines: MaterialDefines): void; + isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean; + unbind(): void; + bindOnlyWorldMatrix(world: Matrix): void; + bind(world: Matrix, mesh?: Mesh): void; + getAnimatables(): IAnimatable[]; + dispose(forceDisposeEffect?: boolean): void; + clone(name: string): StandardMaterial; + serialize(): any; + static DiffuseTextureEnabled: boolean; + static AmbientTextureEnabled: boolean; + static OpacityTextureEnabled: boolean; + static ReflectionTextureEnabled: boolean; + static EmissiveTextureEnabled: boolean; + static SpecularTextureEnabled: boolean; + static BumpTextureEnabled: boolean; + static FresnelEnabled: boolean; + static LightmapEnabled: boolean; + static Parse(source: any, scene: Scene, rootUrl: string): StandardMaterial; + } +} + +declare namespace BABYLON { + class AbstractMesh extends Node implements IDisposable { + private static _BILLBOARDMODE_NONE; + private static _BILLBOARDMODE_X; + private static _BILLBOARDMODE_Y; + private static _BILLBOARDMODE_Z; + private static _BILLBOARDMODE_ALL; + static BILLBOARDMODE_NONE: number; + static BILLBOARDMODE_X: number; + static BILLBOARDMODE_Y: number; + static BILLBOARDMODE_Z: number; + static BILLBOARDMODE_ALL: number; + definedFacingForward: boolean; + position: Vector3; + rotation: Vector3; + rotationQuaternion: Quaternion; + scaling: Vector3; + billboardMode: number; + visibility: number; + alphaIndex: number; + infiniteDistance: boolean; + isVisible: boolean; + isPickable: boolean; + showBoundingBox: boolean; + showSubMeshesBoundingBox: boolean; + onDispose: any; + isBlocker: boolean; + renderingGroupId: number; + material: Material; + receiveShadows: boolean; + actionManager: ActionManager; + renderOutline: boolean; + outlineColor: Color3; + outlineWidth: number; + renderOverlay: boolean; + overlayColor: Color3; + overlayAlpha: number; + hasVertexAlpha: boolean; + useVertexColors: boolean; + applyFog: boolean; + computeBonesUsingShaders: boolean; + scalingDeterminant: number; + numBoneInfluencers: number; + useOctreeForRenderingSelection: boolean; + useOctreeForPicking: boolean; + useOctreeForCollisions: boolean; + layerMask: number; + alwaysSelectAsActiveMesh: boolean; + _physicImpostor: number; + _physicsMass: number; + _physicsFriction: number; + _physicRestitution: number; + onPhysicsCollide: (collidedMesh: AbstractMesh, contact: any) => void; + private _checkCollisions; + ellipsoid: Vector3; + ellipsoidOffset: Vector3; + private _collider; + private _oldPositionForCollisions; + private _diffPositionForCollisions; + private _newPositionForCollisions; + onCollide: (collidedMesh: AbstractMesh) => void; + onCollisionPositionChange: (newPosition: Vector3) => void; + private _meshToBoneReferal; + edgesWidth: number; + edgesColor: Color4; + _edgesRenderer: EdgesRenderer; + private _localWorld; + _worldMatrix: Matrix; + private _rotateYByPI; + private _absolutePosition; + private _collisionsTransformMatrix; + private _collisionsScalingMatrix; + _positions: Vector3[]; + private _isDirty; + _masterMesh: AbstractMesh; + _materialDefines: MaterialDefines; + _boundingInfo: BoundingInfo; + private _pivotMatrix; + _isDisposed: boolean; + _renderId: number; + subMeshes: SubMesh[]; + _submeshesOctree: Octree; + _intersectionsInProgress: AbstractMesh[]; + private _onAfterWorldMatrixUpdate; + private _isWorldMatrixFrozen; + _unIndexed: boolean; + _poseMatrix: Matrix; + _waitingActions: any; + _waitingFreezeWorldMatrix: boolean; + private _skeleton; + _bonesTransformMatrices: Float32Array; + skeleton: Skeleton; + constructor(name: string, scene: Scene); + updatePoseMatrix(matrix: Matrix): void; + getPoseMatrix(): Matrix; + disableEdgesRendering(): void; + enableEdgesRendering(epsilon?: number, checkVerticesInsteadOfIndices?: boolean): void; + isBlocked: boolean; + getLOD(camera: Camera): AbstractMesh; + getTotalVertices(): number; + getIndices(): number[] | Int32Array; + getVerticesData(kind: string): number[] | Float32Array; + isVerticesDataPresent(kind: string): boolean; + getBoundingInfo(): BoundingInfo; + useBones: boolean; + _preActivate(): void; + _activate(renderId: number): void; + getWorldMatrix(): Matrix; + worldMatrixFromCache: Matrix; + absolutePosition: Vector3; + freezeWorldMatrix(): void; + unfreezeWorldMatrix(): void; + isWorldMatrixFrozen: boolean; + rotate(axis: Vector3, amount: number, space?: Space): void; + translate(axis: Vector3, distance: number, space?: Space): void; + getAbsolutePosition(): Vector3; + setAbsolutePosition(absolutePosition: Vector3): void; + /** + * Perform relative position change from the point of view of behind the front of the mesh. + * This is performed taking into account the meshes current rotation, so you do not have to care. + * Supports definition of mesh facing forward or backward. + * @param {number} amountRight + * @param {number} amountUp + * @param {number} amountForward + */ + movePOV(amountRight: number, amountUp: number, amountForward: number): void; + /** + * Calculate relative position change from the point of view of behind the front of the mesh. + * This is performed taking into account the meshes current rotation, so you do not have to care. + * Supports definition of mesh facing forward or backward. + * @param {number} amountRight + * @param {number} amountUp + * @param {number} amountForward + */ + calcMovePOV(amountRight: number, amountUp: number, amountForward: number): Vector3; + /** + * Perform relative rotation change from the point of view of behind the front of the mesh. + * Supports definition of mesh facing forward or backward. + * @param {number} flipBack + * @param {number} twirlClockwise + * @param {number} tiltRight + */ + rotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): void; + /** + * Calculate relative rotation change from the point of view of behind the front of the mesh. + * Supports definition of mesh facing forward or backward. + * @param {number} flipBack + * @param {number} twirlClockwise + * @param {number} tiltRight + */ + calcRotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): Vector3; + setPivotMatrix(matrix: Matrix): void; + getPivotMatrix(): Matrix; + _isSynchronized(): boolean; + _initCache(): void; + markAsDirty(property: string): void; + _updateBoundingInfo(): void; + _updateSubMeshesBoundingInfo(matrix: Matrix): void; + computeWorldMatrix(force?: boolean): Matrix; + /** + * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated + * @param func: callback function to add + */ + registerAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): void; + unregisterAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): void; + setPositionWithLocalVector(vector3: Vector3): void; + getPositionExpressedInLocalSpace(): Vector3; + locallyTranslate(vector3: Vector3): void; + lookAt(targetPoint: Vector3, yawCor: number, pitchCor: number, rollCor: number): void; + attachToBone(bone: Bone, affectedMesh: AbstractMesh): void; + detachFromBone(): void; + isInFrustum(frustumPlanes: Plane[]): boolean; + isCompletelyInFrustum(camera?: Camera): boolean; + intersectsMesh(mesh: AbstractMesh, precise?: boolean): boolean; + intersectsPoint(point: Vector3): boolean; + setPhysicsState(impostor?: any, options?: PhysicsBodyCreationOptions): any; + getPhysicsImpostor(): number; + getPhysicsMass(): number; + getPhysicsFriction(): number; + getPhysicsRestitution(): number; + getPositionInCameraSpace(camera?: Camera): Vector3; + getDistanceToCamera(camera?: Camera): number; + applyImpulse(force: Vector3, contactPoint: Vector3): void; + setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3, options?: any): void; + updatePhysicsBodyPosition(): void; + checkCollisions: boolean; + moveWithCollisions(velocity: Vector3): void; + private _onCollisionPositionChange; + /** + * This function will create an octree to help select the right submeshes for rendering, picking and collisions + * Please note that you must have a decent number of submeshes to get performance improvements when using octree + */ + createOrUpdateSubmeshesOctree(maxCapacity?: number, maxDepth?: number): Octree; + _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): void; + _processCollisionsForSubMeshes(collider: Collider, transformMatrix: Matrix): void; + _checkCollision(collider: Collider): void; + _generatePointsArray(): boolean; + intersects(ray: Ray, fastCheck?: boolean): PickingInfo; + clone(name: string, newParent: Node, doNotCloneChildren?: boolean): AbstractMesh; + releaseSubMeshes(): void; + dispose(doNotRecurse?: boolean): void; + } +} + +declare namespace BABYLON { + class CSG { + private polygons; + matrix: Matrix; + position: Vector3; + rotation: Vector3; + rotationQuaternion: Quaternion; + scaling: Vector3; + static FromMesh(mesh: Mesh): CSG; + private static FromPolygons(polygons); + clone(): CSG; + private toPolygons(); + union(csg: CSG): CSG; + unionInPlace(csg: CSG): void; + subtract(csg: CSG): CSG; + subtractInPlace(csg: CSG): void; + intersect(csg: CSG): CSG; + intersectInPlace(csg: CSG): void; + inverse(): CSG; + inverseInPlace(): void; + copyTransformAttributes(csg: CSG): CSG; + buildMeshGeometry(name: string, scene: Scene, keepSubMeshes: boolean): Mesh; + toMesh(name: string, material: Material, scene: Scene, keepSubMeshes: boolean): Mesh; + } +} + +declare namespace BABYLON { + class Geometry implements IGetSetVerticesData { + id: string; + delayLoadState: number; + delayLoadingFile: string; + onGeometryUpdated: (geometry: Geometry, kind?: string) => void; + private _scene; + private _engine; + private _meshes; + private _totalVertices; + private _indices; + private _vertexBuffers; + private _isDisposed; + private _extend; + _delayInfo: any; + private _indexBuffer; + _boundingInfo: BoundingInfo; + _delayLoadingFunction: (any: any, geometry: Geometry) => void; + _softwareSkinningRenderId: number; + constructor(id: string, scene: Scene, vertexData?: VertexData, updatable?: boolean, mesh?: Mesh); + extend: { + minimum: Vector3; + maximum: Vector3; + }; + getScene(): Scene; + getEngine(): Engine; + isReady(): boolean; + setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; + setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean, stride?: number): void; + updateVerticesDataDirectly(kind: string, data: Float32Array, offset: number): void; + updateVerticesData(kind: string, data: number[] | Float32Array, updateExtends?: boolean): void; + getTotalVertices(): number; + getVerticesData(kind: string, copyWhenShared?: boolean): number[] | Float32Array; + getVertexBuffer(kind: string): VertexBuffer; + getVertexBuffers(): VertexBuffer[]; + isVerticesDataPresent(kind: string): boolean; + getVerticesDataKinds(): string[]; + setIndices(indices: number[] | Int32Array, totalVertices?: number): void; + getTotalIndices(): number; + getIndices(copyWhenShared?: boolean): number[] | Int32Array; + getIndexBuffer(): any; + releaseForMesh(mesh: Mesh, shouldDispose?: boolean): void; + applyToMesh(mesh: Mesh): void; + private _applyToMesh(mesh); + private notifyUpdate(kind?); + load(scene: Scene, onLoaded?: () => void): void; + isDisposed(): boolean; + dispose(): void; + copy(id: string): Geometry; + serialize(): any; + serializeVerticeData(): any; + static ExtractFromMesh(mesh: Mesh, id: string): Geometry; + static RandomId(): string; + static ImportGeometry(parsedGeometry: any, mesh: Mesh): void; + static Parse(parsedVertexData: any, scene: Scene, rootUrl: string): Geometry; + } + namespace Geometry.Primitives { + class _Primitive extends Geometry { + private _beingRegenerated; + private _canBeRegenerated; + constructor(id: string, scene: Scene, vertexData?: VertexData, canBeRegenerated?: boolean, mesh?: Mesh); + canBeRegenerated(): boolean; + regenerate(): void; + asNewGeometry(id: string): Geometry; + setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; + setVerticesData(kind: string, data: number[] | Int32Array | Float32Array, updatable?: boolean): void; + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + } + class Ribbon extends _Primitive { + pathArray: Vector3[][]; + closeArray: boolean; + closePath: boolean; + offset: number; + side: number; + constructor(id: string, scene: Scene, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + class Box extends _Primitive { + size: number; + side: number; + constructor(id: string, scene: Scene, size: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedBox: any, scene: Scene): Box; + } + class Sphere extends _Primitive { + segments: number; + diameter: number; + side: number; + constructor(id: string, scene: Scene, segments: number, diameter: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedSphere: any, scene: Scene): Geometry.Primitives.Sphere; + } + class Disc extends _Primitive { + radius: number; + tessellation: number; + side: number; + constructor(id: string, scene: Scene, radius: number, tessellation: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + class Cylinder extends _Primitive { + height: number; + diameterTop: number; + diameterBottom: number; + tessellation: number; + subdivisions: number; + side: number; + constructor(id: string, scene: Scene, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions?: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedCylinder: any, scene: Scene): Geometry.Primitives.Cylinder; + } + class Torus extends _Primitive { + diameter: number; + thickness: number; + tessellation: number; + side: number; + constructor(id: string, scene: Scene, diameter: number, thickness: number, tessellation: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedTorus: any, scene: Scene): Geometry.Primitives.Torus; + } + class Ground extends _Primitive { + width: number; + height: number; + subdivisions: number; + constructor(id: string, scene: Scene, width: number, height: number, subdivisions: number, canBeRegenerated?: boolean, mesh?: Mesh); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedGround: any, scene: Scene): Geometry.Primitives.Ground; + } + class TiledGround extends _Primitive { + xmin: number; + zmin: number; + xmax: number; + zmax: number; + subdivisions: { + w: number; + h: number; + }; + precision: { + w: number; + h: number; + }; + constructor(id: string, scene: Scene, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { + w: number; + h: number; + }, precision: { + w: number; + h: number; + }, canBeRegenerated?: boolean, mesh?: Mesh); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + class Plane extends _Primitive { + size: number; + side: number; + constructor(id: string, scene: Scene, size: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedPlane: any, scene: Scene): Geometry.Primitives.Plane; + } + class TorusKnot extends _Primitive { + radius: number; + tube: number; + radialSegments: number; + tubularSegments: number; + p: number; + q: number; + side: number; + constructor(id: string, scene: Scene, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + serialize(): any; + static Parse(parsedTorusKnot: any, scene: Scene): Geometry.Primitives.TorusKnot; + } + } +} + +declare namespace BABYLON { + class GroundMesh extends Mesh { + generateOctree: boolean; + private _worldInverse; + private _heightQuads; + _subdivisions: number; + _width: number; + _height: number; + _minX: number; + _maxX: number; + _minZ: number; + _maxZ: number; + constructor(name: string, scene: Scene); + subdivisions: number; + optimize(chunksCount: number, octreeBlocksSize?: number): void; + /** + * Returns a height (y) value in the Worl system : + * the ground altitude at the coordinates (x, z) expressed in the World system. + * Returns the ground y position if (x, z) are outside the ground surface. + * Not pertinent if the ground is rotated. + */ + getHeightAtCoordinates(x: number, z: number): number; + /** + * Returns a normalized vector (Vector3) orthogonal to the ground + * at the ground coordinates (x, z) expressed in the World system. + * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface. + * Not pertinent if the ground is rotated. + */ + getNormalAtCoordinates(x: number, z: number): Vector3; + /** + * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground + * at the ground coordinates (x, z) expressed in the World system. + * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface. + * Not pertinent if the ground is rotated. + */ + getNormalAtCoordinatesToRef(x: number, z: number, ref: Vector3): void; + private _getFacetAt(x, z); + private _computeHeightQuads(); + } +} + +declare namespace BABYLON { + /** + * Creates an instance based on a source mesh. + */ + class InstancedMesh extends AbstractMesh { + private _sourceMesh; + private _currentLOD; + constructor(name: string, source: Mesh); + receiveShadows: boolean; + material: Material; + visibility: number; + skeleton: Skeleton; + renderingGroupId: number; + getTotalVertices(): number; + sourceMesh: Mesh; + getVerticesData(kind: string, copyWhenShared?: boolean): number[] | Float32Array; + isVerticesDataPresent(kind: string): boolean; + getIndices(): number[] | Int32Array; + _positions: Vector3[]; + refreshBoundingInfo(): void; + _preActivate(): void; + _activate(renderId: number): void; + getLOD(camera: Camera): AbstractMesh; + _syncSubMeshes(): void; + _generatePointsArray(): boolean; + clone(name: string, newParent: Node, doNotCloneChildren?: boolean): InstancedMesh; + dispose(doNotRecurse?: boolean): void; + } +} + +declare namespace BABYLON { + class LinesMesh extends Mesh { + color: Color3; + alpha: number; + private _colorShader; + constructor(name: string, scene: Scene, parent?: Node, source?: Mesh, doNotCloneChildren?: boolean); + material: Material; + isPickable: boolean; + checkCollisions: boolean; + _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void; + _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void; + intersects(ray: Ray, fastCheck?: boolean): any; + dispose(doNotRecurse?: boolean): void; + clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): LinesMesh; + } +} + +declare namespace BABYLON { + class _InstancesBatch { + mustReturn: boolean; + visibleInstances: InstancedMesh[][]; + renderSelf: boolean[]; + } + class Mesh extends AbstractMesh implements IGetSetVerticesData { + static _FRONTSIDE: number; + static _BACKSIDE: number; + static _DOUBLESIDE: number; + static _DEFAULTSIDE: number; + static _NO_CAP: number; + static _CAP_START: number; + static _CAP_END: number; + static _CAP_ALL: number; + static FRONTSIDE: number; + static BACKSIDE: number; + static DOUBLESIDE: number; + static DEFAULTSIDE: number; + static NO_CAP: number; + static CAP_START: number; + static CAP_END: number; + static CAP_ALL: number; + delayLoadState: number; + instances: InstancedMesh[]; + delayLoadingFile: string; + _binaryInfo: any; + private _LODLevels; + onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void; + onBeforeDraw: () => void; + _geometry: Geometry; + private _onBeforeRenderCallbacks; + private _onAfterRenderCallbacks; + _delayInfo: any; + _delayLoadingFunction: (any: any, mesh: Mesh) => void; + _visibleInstances: any; + private _renderIdForInstances; + private _batchCache; + private _worldMatricesInstancesBuffer; + private _worldMatricesInstancesArray; + private _instancesBufferSize; + _shouldGenerateFlatShading: boolean; + private _preActivateId; + private _sideOrientation; + private _areNormalsFrozen; + private _sourcePositions; + private _sourceNormals; + /** + * @constructor + * @param {string} name - The value used by scene.getMeshByName() to do a lookup. + * @param {Scene} scene - The scene to add this mesh to. + * @param {Node} parent - The parent of this mesh, if it has one + * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned. + * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False. + * When false, achieved by calling a clone(), also passing False. + * This will make creation of children, recursive. + */ + constructor(name: string, scene: Scene, parent?: Node, source?: Mesh, doNotCloneChildren?: boolean); + hasLODLevels: boolean; + private _sortLODLevels(); + /** + * Add a mesh as LOD level triggered at the given distance. + * @param {number} distance - the distance from the center of the object to show this level + * @param {Mesh} mesh - the mesh to be added as LOD level + * @return {Mesh} this mesh (for chaining) + */ + addLODLevel(distance: number, mesh: Mesh): Mesh; + getLODLevelAtDistance(distance: number): Mesh; + /** + * Remove a mesh from the LOD array + * @param {Mesh} mesh - the mesh to be removed. + * @return {Mesh} this mesh (for chaining) + */ + removeLODLevel(mesh: Mesh): Mesh; + getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh; + geometry: Geometry; + getTotalVertices(): number; + getVerticesData(kind: string, copyWhenShared?: boolean): number[] | Float32Array; + getVertexBuffer(kind: any): VertexBuffer; + isVerticesDataPresent(kind: string): boolean; + getVerticesDataKinds(): string[]; + getTotalIndices(): number; + getIndices(copyWhenShared?: boolean): number[] | Int32Array; + isBlocked: boolean; + isReady(): boolean; + isDisposed(): boolean; + sideOrientation: number; + areNormalsFrozen: boolean; + /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */ + freezeNormals(): void; + /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */ + unfreezeNormals(): void; + _preActivate(): void; + _registerInstanceForRenderId(instance: InstancedMesh, renderId: number): void; + refreshBoundingInfo(): void; + _createGlobalSubMesh(): SubMesh; + subdivide(count: number): void; + setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean, stride?: number): void; + updateVerticesData(kind: string, data: number[] | Float32Array, updateExtends?: boolean, makeItUnique?: boolean): void; + updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void; + updateMeshPositions(positionFunction: any, computeNormals?: boolean): void; + makeGeometryUnique(): void; + setIndices(indices: number[] | Int32Array, totalVertices?: number): void; + _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void; + _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void; + registerBeforeRender(func: (mesh: AbstractMesh) => void): void; + unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void; + registerAfterRender(func: (mesh: AbstractMesh) => void): void; + unregisterAfterRender(func: (mesh: AbstractMesh) => void): void; + _getInstancesRenderList(subMeshId: number): _InstancesBatch; + _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void; + _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean, onBeforeDraw: (isInstance: boolean, world: Matrix) => void): void; + render(subMesh: SubMesh, enableAlphaMode: boolean): void; + getEmittedParticleSystems(): ParticleSystem[]; + getHierarchyEmittedParticleSystems(): ParticleSystem[]; + getChildren(): Node[]; + _checkDelayState(): void; + isInFrustum(frustumPlanes: Plane[]): boolean; + setMaterialByID(id: string): void; + getAnimatables(): IAnimatable[]; + bakeTransformIntoVertices(transform: Matrix): void; + bakeCurrentTransformIntoVertices(): void; + _resetPointsArrayCache(): void; + _generatePointsArray(): boolean; + clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh; + dispose(doNotRecurse?: boolean): void; + applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void; + applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void; + convertToFlatShadedMesh(): void; + convertToUnIndexedMesh(): void; + flipFaces(flipNormals?: boolean): void; + createInstance(name: string): InstancedMesh; + synchronizeInstances(): void; + /** + * Simplify the mesh according to the given array of settings. + * Function will return immediately and will simplify async. + * @param settings a collection of simplification settings. + * @param parallelProcessing should all levels calculate parallel or one after the other. + * @param type the type of simplification to run. + * @param successCallback optional success callback to be called after the simplification finished processing all settings. + */ + simplify(settings: Array, parallelProcessing?: boolean, simplificationType?: SimplificationType, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void): void; + /** + * Optimization of the mesh's indices, in case a mesh has duplicated vertices. + * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes. + * This should be used together with the simplification to avoid disappearing triangles. + * @param successCallback an optional success callback to be called after the optimization finished. + */ + optimizeIndices(successCallback?: (mesh?: Mesh) => void): void; + static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh; + static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; + static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation?: number): Mesh; + static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh; + static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Scene, updatable?: boolean, instance?: LinesMesh): LinesMesh; + static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; + static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction: any, rotationFunction: any, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; + static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh; + static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { + w: number; + h: number; + }, precision: { + w: number; + h: number; + }, scene: Scene, updatable?: boolean): Mesh; + static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void): GroundMesh; + static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { + (i: number, distance: number): number; + }, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh; + static CreatePolyhedron(name: string, options: { + type?: number; + size?: number; + sizeX?: number; + sizeY?: number; + sizeZ?: number; + custom?: any; + faceUV?: Vector4[]; + faceColors?: Color4[]; + updatable?: boolean; + sideOrientation?: number; + }, scene: Scene): Mesh; + static CreateIcoSphere(name: string, options: { + radius?: number; + flat?: boolean; + subdivisions?: number; + sideOrientation?: number; + updatable?: boolean; + }, scene: Scene): Mesh; + static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh; + /** + * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. + */ + setPositionsForCPUSkinning(): Float32Array; + /** + * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. + */ + setNormalsForCPUSkinning(): Float32Array; + /** + * Update the vertex buffers by applying transformation from the bones + * @param {skeleton} skeleton to apply + */ + applySkeleton(skeleton: Skeleton): Mesh; + static MinMax(meshes: AbstractMesh[]): { + min: Vector3; + max: Vector3; + }; + static Center(meshesOrMinMaxVector: any): Vector3; + /** + * Merge the array of meshes into a single mesh for performance reasons. + * @param {Array} meshes - The vertices source. They should all be of the same material. Entries can empty + * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes + * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true. + * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class. + */ + static MergeMeshes(meshes: Array, disposeSource?: boolean, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh; + } +} + +declare namespace BABYLON { + interface IGetSetVerticesData { + isVerticesDataPresent(kind: string): boolean; + getVerticesData(kind: string, copyWhenShared?: boolean): number[] | Int32Array | Float32Array; + getIndices(copyWhenShared?: boolean): number[] | Int32Array; + setVerticesData(kind: string, data: number[] | Float32Array, updatable?: boolean): void; + updateVerticesData(kind: string, data: number[] | Float32Array, updateExtends?: boolean, makeItUnique?: boolean): void; + setIndices(indices: number[] | Int32Array): void; + } + class VertexData { + positions: number[] | Float32Array; + normals: number[] | Float32Array; + uvs: number[] | Float32Array; + uvs2: number[] | Float32Array; + uvs3: number[] | Float32Array; + uvs4: number[] | Float32Array; + uvs5: number[] | Float32Array; + uvs6: number[] | Float32Array; + colors: number[] | Float32Array; + matricesIndices: number[] | Float32Array; + matricesWeights: number[] | Float32Array; + matricesIndicesExtra: number[] | Float32Array; + matricesWeightsExtra: number[] | Float32Array; + indices: number[] | Int32Array; + set(data: number[] | Float32Array, kind: string): void; + applyToMesh(mesh: Mesh, updatable?: boolean): void; + applyToGeometry(geometry: Geometry, updatable?: boolean): void; + updateMesh(mesh: Mesh, updateExtends?: boolean, makeItUnique?: boolean): void; + updateGeometry(geometry: Geometry, updateExtends?: boolean, makeItUnique?: boolean): void; + private _applyTo(meshOrGeometry, updatable?); + private _update(meshOrGeometry, updateExtends?, makeItUnique?); + transform(matrix: Matrix): void; + merge(other: VertexData): void; + private _mergeElement(source, other); + serialize(): any; + static ExtractFromMesh(mesh: Mesh, copyWhenShared?: boolean): VertexData; + static ExtractFromGeometry(geometry: Geometry, copyWhenShared?: boolean): VertexData; + private static _ExtractFrom(meshOrGeometry, copyWhenShared?); + static CreateRibbon(options: { + pathArray: Vector3[][]; + closeArray?: boolean; + closePath?: boolean; + offset?: number; + sideOrientation?: number; + }): VertexData; + static CreateBox(options: { + size?: number; + width?: number; + height?: number; + depth?: number; + faceUV?: Vector4[]; + faceColors?: Color4[]; + sideOrientation?: number; + }): VertexData; + static CreateSphere(options: { + segments?: number; + diameter?: number; + diameterX?: number; + diameterY?: number; + diameterZ?: number; + arc?: number; + slice?: number; + sideOrientation?: number; + }): VertexData; + static CreateCylinder(options: { + height?: number; + diameterTop?: number; + diameterBottom?: number; + diameter?: number; + tessellation?: number; + subdivisions?: number; + arc?: number; + faceColors?: Color4[]; + faceUV?: Vector4[]; + hasRings?: boolean; + enclose?: boolean; + sideOrientation?: number; + }): VertexData; + static CreateTorus(options: { + diameter?: number; + thickness?: number; + tessellation?: number; + sideOrientation?: number; + }): VertexData; + static CreateLines(options: { + points: Vector3[]; + }): VertexData; + static CreateDashedLines(options: { + points: Vector3[]; + dashSize?: number; + gapSize?: number; + dashNb?: number; + }): VertexData; + static CreateGround(options: { + width?: number; + height?: number; + subdivisions?: number; + }): VertexData; + static CreateTiledGround(options: { + xmin: number; + zmin: number; + xmax: number; + zmax: number; + subdivisions?: { + w: number; + h: number; + }; + precision?: { + w: number; + h: number; + }; + }): VertexData; + static CreateGroundFromHeightMap(options: { + width: number; + height: number; + subdivisions: number; + minHeight: number; + maxHeight: number; + buffer: Uint8Array; + bufferWidth: number; + bufferHeight: number; + }): VertexData; + static CreatePlane(options: { + size?: number; + width?: number; + height?: number; + sideOrientation?: number; + }): VertexData; + static CreateDisc(options: { + radius?: number; + tessellation?: number; + arc?: number; + sideOrientation?: number; + }): VertexData; + static CreateIcoSphere(options: { + radius?: number; + radiusX?: number; + radiusY?: number; + radiusZ?: number; + flat?: boolean; + subdivisions?: number; + sideOrientation?: number; + }): VertexData; + static CreatePolyhedron(options: { + type?: number; + size?: number; + sizeX?: number; + sizeY?: number; + sizeZ?: number; + custom?: any; + faceUV?: Vector4[]; + faceColors?: Color4[]; + flat?: boolean; + sideOrientation?: number; + }): VertexData; + static CreateTorusKnot(options: { + radius?: number; + tube?: number; + radialSegments?: number; + tubularSegments?: number; + p?: number; + q?: number; + sideOrientation?: number; + }): VertexData; + /** + * @param {any} - positions (number[] or Float32Array) + * @param {any} - indices (number[] or Uint16Array) + * @param {any} - normals (number[] or Float32Array) + */ + static ComputeNormals(positions: any, indices: any, normals: any): void; + private static _ComputeSides(sideOrientation, positions, indices, normals, uvs); + static ImportVertexData(parsedVertexData: any, geometry: Geometry): void; + } +} + +declare namespace BABYLON { + class MeshBuilder { + static CreateBox(name: string, options: { + width?: number; + height?: number; + depth?: number; + faceUV?: Vector4[]; + faceColors?: Color4[]; + sideOrientation?: number; + updatable?: boolean; + }, scene: Scene): Mesh; + static CreateSphere(name: string, options: { + segments?: number; + diameter?: number; + diameterX?: number; + diameterY?: number; + diameterZ?: number; + arc?: number; + slice?: number; + sideOrientation?: number; + updatable?: boolean; + }, scene: any): Mesh; + static CreateDisc(name: string, options: { + radius?: number; + tessellation?: number; + arc?: number; + updatable?: boolean; + sideOrientation?: number; + }, scene: Scene): Mesh; + static CreateIcoSphere(name: string, options: { + radius?: number; + radiusX?: number; + radiusY?: number; + radiusZ?: number; + flat?: boolean; + subdivisions?: number; + sideOrientation?: number; + updatable?: boolean; + }, scene: Scene): Mesh; + static CreateRibbon(name: string, options: { + pathArray: Vector3[][]; + closeArray?: boolean; + closePath?: boolean; + offset?: number; + updatable?: boolean; + sideOrientation?: number; + instance?: Mesh; + }, scene?: Scene): Mesh; + static CreateCylinder(name: string, options: { + height?: number; + diameterTop?: number; + diameterBottom?: number; + diameter?: number; + tessellation?: number; + subdivisions?: number; + arc?: number; + faceColors?: Color4[]; + faceUV?: Vector4[]; + updatable?: boolean; + hasRings?: boolean; + enclose?: boolean; + sideOrientation?: number; + }, scene: any): Mesh; + static CreateTorus(name: string, options: { + diameter?: number; + thickness?: number; + tessellation?: number; + updatable?: boolean; + sideOrientation?: number; + }, scene: any): Mesh; + static CreateTorusKnot(name: string, options: { + radius?: number; + tube?: number; + radialSegments?: number; + tubularSegments?: number; + p?: number; + q?: number; + updatable?: boolean; + sideOrientation?: number; + }, scene: any): Mesh; + static CreateLines(name: string, options: { + points: Vector3[]; + updatable?: boolean; + instance?: LinesMesh; + }, scene: Scene): LinesMesh; + static CreateDashedLines(name: string, options: { + points: Vector3[]; + dashSize?: number; + gapSize?: number; + dashNb?: number; + updatable?: boolean; + instance?: LinesMesh; + }, scene: Scene): LinesMesh; + static ExtrudeShape(name: string, options: { + shape: Vector3[]; + path: Vector3[]; + scale?: number; + rotation?: number; + cap?: number; + updatable?: boolean; + sideOrientation?: number; + instance?: Mesh; + }, scene: Scene): Mesh; + static ExtrudeShapeCustom(name: string, options: { + shape: Vector3[]; + path: Vector3[]; + scaleFunction?:any; + rotationFunction?:any; + ribbonCloseArray?: boolean; + ribbonClosePath?: boolean; + cap?: number; + updatable?: boolean; + sideOrientation?: number; + instance?: Mesh; + }, scene: Scene): Mesh; + static CreateLathe(name: string, options: { + shape: Vector3[]; + radius?: number; + tessellation?: number; + arc?: number; + closed?: boolean; + updatable?: boolean; + sideOrientation?: number; + cap?: number; + }, scene: Scene): Mesh; + static CreatePlane(name: string, options: { + size?: number; + width?: number; + height?: number; + sideOrientation?: number; + updatable?: boolean; + sourcePlane?: Plane; + }, scene: Scene): Mesh; + static CreateGround(name: string, options: { + width?: number; + height?: number; + subdivisions?: number; + updatable?: boolean; + }, scene: any): Mesh; + static CreateTiledGround(name: string, options: { + xmin: number; + zmin: number; + xmax: number; + zmax: number; + subdivisions?: { + w: number; + h: number; + }; + precision?: { + w: number; + h: number; + }; + updatable?: boolean; + }, scene: Scene): Mesh; + static CreateGroundFromHeightMap(name: string, url: string, options: { + width?: number; + height?: number; + subdivisions?: number; + minHeight?: number; + maxHeight?: number; + updatable?: boolean; + onReady?: (mesh: GroundMesh) => void; + }, scene: Scene): GroundMesh; + static CreateTube(name: string, options: { + path: Vector3[]; + radius?: number; + tessellation?: number; + radiusFunction?: { + (i: number, distance: number): number; + }; + cap?: number; + arc?: number; + updatable?: boolean; + sideOrientation?: number; + instance?: Mesh; + }, scene: Scene): Mesh; + static CreatePolyhedron(name: string, options: { + type?: number; + size?: number; + sizeX?: number; + sizeY?: number; + sizeZ?: number; + custom?: any; + faceUV?: Vector4[]; + faceColors?: Color4[]; + flat?: boolean; + updatable?: boolean; + sideOrientation?: number; + }, scene: Scene): Mesh; + static CreateDecal(name: string, sourceMesh: AbstractMesh, options: { + position?: Vector3; + normal?: Vector3; + size?: Vector3; + angle?: number; + }): Mesh; + private static _ExtrudeShapeGeneric(name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance); + } +} + +declare namespace BABYLON.Internals { + class MeshLODLevel { + distance: number; + mesh: Mesh; + constructor(distance: number, mesh: Mesh); + } +} + +declare namespace BABYLON { + /** + * A simplifier interface for future simplification implementations. + */ + interface ISimplifier { + /** + * Simplification of a given mesh according to the given settings. + * Since this requires computation, it is assumed that the function runs async. + * @param settings The settings of the simplification, including quality and distance + * @param successCallback A callback that will be called after the mesh was simplified. + * @param errorCallback in case of an error, this callback will be called. optional. + */ + simplify(settings: ISimplificationSettings, successCallback: (simplifiedMeshes: Mesh) => void, errorCallback?: () => void): void; + } + /** + * Expected simplification settings. + * Quality should be between 0 and 1 (1 being 100%, 0 being 0%); + */ + interface ISimplificationSettings { + quality: number; + distance: number; + optimizeMesh?: boolean; + } + class SimplificationSettings implements ISimplificationSettings { + quality: number; + distance: number; + optimizeMesh: boolean; + constructor(quality: number, distance: number, optimizeMesh?: boolean); + } + interface ISimplificationTask { + settings: Array; + simplificationType: SimplificationType; + mesh: Mesh; + successCallback?: () => void; + parallelProcessing: boolean; + } + class SimplificationQueue { + private _simplificationArray; + running: any; + constructor(); + addTask(task: ISimplificationTask): void; + executeNext(): void; + runSimplification(task: ISimplificationTask): void; + private getSimplifier(task); + } + /** + * The implemented types of simplification. + * At the moment only Quadratic Error Decimation is implemented. + */ + enum SimplificationType { + QUADRATIC = 0, + } + class DecimationTriangle { + vertices: Array; + normal: Vector3; + error: Array; + deleted: boolean; + isDirty: boolean; + borderFactor: number; + deletePending: boolean; + originalOffset: number; + constructor(vertices: Array); + } + class DecimationVertex { + position: Vector3; + id: any; + q: QuadraticMatrix; + isBorder: boolean; + triangleStart: number; + triangleCount: number; + originalOffsets: Array; + constructor(position: Vector3, id: any); + updatePosition(newPosition: Vector3): void; + } + class QuadraticMatrix { + data: Array; + constructor(data?: Array); + det(a11: any, a12: any, a13: any, a21: any, a22: any, a23: any, a31: any, a32: any, a33: any): number; + addInPlace(matrix: QuadraticMatrix): void; + addArrayInPlace(data: Array): void; + add(matrix: QuadraticMatrix): QuadraticMatrix; + static FromData(a: number, b: number, c: number, d: number): QuadraticMatrix; + static DataFromNumbers(a: number, b: number, c: number, d: number): number[]; + } + class Reference { + vertexId: number; + triangleId: number; + constructor(vertexId: number, triangleId: number); + } + /** + * An implementation of the Quadratic Error simplification algorithm. + * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf + * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS + * @author RaananW + */ + class QuadraticErrorSimplification implements ISimplifier { + private _mesh; + private triangles; + private vertices; + private references; + private initialized; + private _reconstructedMesh; + syncIterations: number; + aggressiveness: number; + decimationIterations: number; + boundingBoxEpsilon: number; + constructor(_mesh: Mesh); + simplify(settings: ISimplificationSettings, successCallback: (simplifiedMesh: Mesh) => void): void; + private isTriangleOnBoundingBox(triangle); + private runDecimation(settings, submeshIndex, successCallback); + private initWithMesh(submeshIndex, callback, optimizeMesh?); + private init(callback); + private reconstructMesh(submeshIndex); + private initDecimatedMesh(); + private isFlipped(vertex1, vertex2, point, deletedArray, borderFactor, delTr); + private updateTriangles(origVertex, vertex, deletedArray, deletedTriangles); + private identifyBorder(); + private updateMesh(identifyBorders?); + private vertexError(q, point); + private calculateError(vertex1, vertex2, pointResult?, normalResult?, uvResult?, colorResult?); + } +} + +declare namespace BABYLON { + class Polygon { + static Rectangle(xmin: number, ymin: number, xmax: number, ymax: number): Vector2[]; + static Circle(radius: number, cx?: number, cy?: number, numberOfSides?: number): Vector2[]; + static Parse(input: string): Vector2[]; + static StartingAt(x: number, y: number): Path2; + } + class PolygonMeshBuilder { + private _swctx; + private _points; + private _outlinepoints; + private _holes; + private _name; + private _scene; + constructor(name: string, contours: Path2, scene: Scene); + constructor(name: string, contours: Vector2[], scene: Scene); + addHole(hole: Vector2[]): PolygonMeshBuilder; + build(updatable?: boolean, depth?: number): Mesh; + private addSide(positions, normals, uvs, indices, bounds, points, depth, flip); + } +} + +declare namespace BABYLON { + class SubMesh { + materialIndex: number; + verticesStart: number; + verticesCount: number; + indexStart: any; + indexCount: number; + linesIndexCount: number; + private _mesh; + private _renderingMesh; + private _boundingInfo; + private _linesIndexBuffer; + _lastColliderWorldVertices: Vector3[]; + _trianglePlanes: Plane[]; + _lastColliderTransformMatrix: Matrix; + _renderId: number; + _alphaIndex: number; + _distanceToCamera: number; + _id: number; + constructor(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: any, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox?: boolean); + IsGlobal: boolean; + getBoundingInfo(): BoundingInfo; + getMesh(): AbstractMesh; + getRenderingMesh(): Mesh; + getMaterial(): Material; + refreshBoundingInfo(): void; + _checkCollision(collider: Collider): boolean; + updateBoundingInfo(world: Matrix): void; + isInFrustum(frustumPlanes: Plane[]): boolean; + render(enableAlphaMode: boolean): void; + getLinesIndexBuffer(indices: number[] | Int32Array, engine: any): WebGLBuffer; + canIntersects(ray: Ray): boolean; + intersects(ray: Ray, positions: Vector3[], indices: number[] | Int32Array, fastCheck?: boolean): IntersectionInfo; + clone(newMesh: AbstractMesh, newRenderingMesh?: Mesh): SubMesh; + dispose(): void; + static CreateFromIndices(materialIndex: number, startIndex: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh): SubMesh; + } +} + +declare namespace BABYLON { + class VertexBuffer { + private _mesh; + private _engine; + private _buffer; + private _data; + private _updatable; + private _kind; + private _strideSize; + constructor(engine: any, data: number[] | Float32Array, kind: string, updatable: boolean, postponeInternalCreation?: boolean, stride?: number); + isUpdatable(): boolean; + getData(): number[] | Float32Array; + getBuffer(): WebGLBuffer; + getStrideSize(): number; + create(data?: number[] | Float32Array): void; + update(data: number[] | Float32Array): void; + updateDirectly(data: Float32Array, offset: number): void; + dispose(): void; + private static _PositionKind; + private static _NormalKind; + private static _UVKind; + private static _UV2Kind; + private static _UV3Kind; + private static _UV4Kind; + private static _UV5Kind; + private static _UV6Kind; + private static _ColorKind; + private static _MatricesIndicesKind; + private static _MatricesWeightsKind; + private static _MatricesIndicesExtraKind; + private static _MatricesWeightsExtraKind; + static PositionKind: string; + static NormalKind: string; + static UVKind: string; + static UV2Kind: string; + static UV3Kind: string; + static UV4Kind: string; + static UV5Kind: string; + static UV6Kind: string; + static ColorKind: string; + static MatricesIndicesKind: string; + static MatricesWeightsKind: string; + static MatricesIndicesExtraKind: string; + static MatricesWeightsExtraKind: string; + } +} + +declare namespace BABYLON { + class Particle { + position: Vector3; + direction: Vector3; + color: Color4; + colorStep: Color4; + lifeTime: number; + age: number; + size: number; + angle: number; + angularSpeed: number; + copyTo(other: Particle): void; + } +} + +declare namespace BABYLON { + class ParticleSystem implements IDisposable { + name: string; + static BLENDMODE_ONEONE: number; + static BLENDMODE_STANDARD: number; + id: string; + renderingGroupId: number; + emitter: any; + emitRate: number; + manualEmitCount: number; + updateSpeed: number; + targetStopDuration: number; + disposeOnStop: boolean; + minEmitPower: number; + maxEmitPower: number; + minLifeTime: number; + maxLifeTime: number; + minSize: number; + maxSize: number; + minAngularSpeed: number; + maxAngularSpeed: number; + particleTexture: Texture; + layerMask: number; + onDispose: () => void; + updateFunction: (particles: Particle[]) => void; + blendMode: number; + forceDepthWrite: boolean; + gravity: Vector3; + direction1: Vector3; + direction2: Vector3; + minEmitBox: Vector3; + maxEmitBox: Vector3; + color1: Color4; + color2: Color4; + colorDead: Color4; + textureMask: Color4; + startDirectionFunction: (emitPower: number, worldMatrix: Matrix, directionToUpdate: Vector3, particle: Particle) => void; + startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3, particle: Particle) => void; + private particles; + private _capacity; + private _scene; + private _vertexDeclaration; + private _vertexStrideSize; + private _stockParticles; + private _newPartsExcess; + private _vertexBuffer; + private _indexBuffer; + private _vertices; + private _effect; + private _customEffect; + private _cachedDefines; + private _scaledColorStep; + private _colorDiff; + private _scaledDirection; + private _scaledGravity; + private _currentRenderId; + private _alive; + private _started; + private _stopped; + private _actualFrame; + private _scaledUpdateSpeed; + constructor(name: string, capacity: number, scene: Scene, customEffect?: Effect); + recycleParticle(particle: Particle): void; + getCapacity(): number; + isAlive(): boolean; + isStarted(): boolean; + start(): void; + stop(): void; + _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void; + private _update(newParticles); + private _getEffect(); + animate(): void; + render(): number; + dispose(): void; + clone(name: string, newEmitter: any): ParticleSystem; + serialize(): any; + static Parse(parsedParticleSystem: any, scene: Scene, rootUrl: string): ParticleSystem; + } +} + +declare namespace BABYLON { + class SolidParticle { + idx: number; + color: Color4; + position: Vector3; + rotation: Vector3; + quaternion: Vector4; + scale: Vector3; + uvs: Vector4; + velocity: Vector3; + alive: boolean; + _pos: number; + _model: ModelShape; + shapeId: number; + idxInShape: number; + constructor(particleIndex: number, positionIndex: number, model: ModelShape, shapeId: number, idxInShape: number); + } + class ModelShape { + shapeID: number; + _shape: Vector3[]; + _shapeUV: number[]; + _positionFunction: (particle: SolidParticle, i: number, s: number) => void; + _vertexFunction: (particle: SolidParticle, vertex: Vector3, i: number) => void; + constructor(id: number, shape: Vector3[], shapeUV: number[], posFunction: (particle: SolidParticle, i: number, s: number) => void, vtxFunction: (particle: SolidParticle, vertex: Vector3, i: number) => void); + } +} + +declare namespace BABYLON { + /** + * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System + */ + class SolidParticleSystem implements IDisposable { + particles: SolidParticle[]; + nbParticles: number; + billboard: boolean; + counter: number; + name: string; + mesh: Mesh; + vars: any; + pickedParticles: { + idx: number; + faceId: number; + }[]; + private _scene; + private _positions; + private _indices; + private _normals; + private _colors; + private _uvs; + private _positions32; + private _normals32; + private _fixedNormal32; + private _colors32; + private _uvs32; + private _index; + private _updatable; + private _pickable; + private _isVisibilityBoxLocked; + private _alwaysVisible; + private _shapeCounter; + private _copy; + private _shape; + private _shapeUV; + private _color; + private _computeParticleColor; + private _computeParticleTexture; + private _computeParticleRotation; + private _computeParticleVertex; + private _cam_axisZ; + private _cam_axisY; + private _cam_axisX; + private _axisX; + private _axisY; + private _axisZ; + private _camera; + private _particle; + private _fakeCamPos; + private _rotMatrix; + private _invertMatrix; + private _rotated; + private _quaternion; + private _vertex; + private _normal; + private _yaw; + private _pitch; + private _roll; + private _halfroll; + private _halfpitch; + private _halfyaw; + private _sinRoll; + private _cosRoll; + private _sinPitch; + private _cosPitch; + private _sinYaw; + private _cosYaw; + private _w; + /** + * Creates a SPS (Solid Particle System) object. + * @param name the SPS name, this will be the underlying mesh name + * @param updatable (default true) if the SPS must be updatable or immutable + * @param isPickable (default false) if the solid particles must be pickable + */ + constructor(name: string, scene: Scene, options?: { + updatable?: boolean; + isPickable?: boolean; + }); + /** + * Builds the SPS underlying mesh. Returns a standard Mesh. + * If no model shape was added to the SPS, the return mesh is only a single triangular plane. + */ + buildMesh(): Mesh; + private _resetCopy(); + private _meshBuilder(p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options); + private _posToShape(positions); + private _uvsToShapeUV(uvs); + private _addParticle(idx, idxpos, model, shapeId, idxInShape); + /** + * Adds some particles to the SPS from the model shape. + * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps + * @param mesh any Mesh object that will be used as a model for the solid particles. + * @param nb the number of particles to be created from this model + * @param positionFunction an optional javascript function to called for each particle on SPS creation + * @param vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation + */ + addShape(mesh: Mesh, nb: number, options?: { + positionFunction?: any; + vertexFunction?: any; + }): number; + private _rebuildParticle(particle); + /** + * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed. + */ + rebuildMesh(): void; + /** + * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc. + * This method calls updateParticle() for each particles of the SPS. + * For an animated SPS, it is usually called within the render loop. + * @param start (default 0) the particle index in the particle array where to start to compute the particle property values + * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values + * @param update (default true) if the mesh must be finally updated on this call after all the particle computations. + */ + setParticles(start?: number, end?: number, update?: boolean): void; + private _quaternionRotationYPR(); + private _quaternionToRotationMatrix(); + /** + * Disposes the SPS + */ + dispose(): void; + /** + * Visibilty helper : Recomputes the visible size according to the mesh bounding box + * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility + */ + refreshVisibleSize(): void; + /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box. + * @param size the size (float) of the visibility box + * note : this doesn't lock the SPS mesh bounding box. + * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility + */ + setVisibilityBox(size: number): void; + /** + * True if the SPS is set as always visible + */ + /** + * Sets the SPS as always visible or not + * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility + */ + isAlwaysVisible: boolean; + /** + * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more. + */ + /** + * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. + * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility + */ + isVisibilityBoxLocked: boolean; + /** + * Tells to setParticle() to compute the particle rotations or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate. + */ + computeParticleRotation: boolean; + /** + * Tells to setParticle() to compute the particle colors or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set. + */ + computeParticleColor: boolean; + /** + * Tells to setParticle() to compute the particle textures or not. + * Default value : true. The SPS is faster when it's set to false. + * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set. + */ + computeParticleTexture: boolean; + /** + * Tells to setParticle() to call the vertex function for each vertex of each particle, or not. + * Default value : false. The SPS is faster when it's set to false. + * Note : the particle custom vertex positions aren't stored values. + */ + computeParticleVertex: boolean; + /** + * This function does nothing. It may be overwritten to set all the particles first values. + * The SPS doesn't call this function, you may have to call it by your own. + * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management + */ + initParticles(): void; + /** + * This function does nothing. It may be overwritten to recycle a particle. + * The SPS doesn't call this function, you may have to call it by your own. + * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management + */ + recycleParticle(particle: SolidParticle): SolidParticle; + /** + * Updates a particle : this function should be overwritten by the user. + * It is called on each particle by setParticles(). This is the place to code each particle behavior. + * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management + * ex : just set a particle position or velocity and recycle conditions + */ + updateParticle(particle: SolidParticle): SolidParticle; + /** + * Updates a vertex of a particle : it can be overwritten by the user. + * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only. + * @param particle the current particle + * @param vertex the current index of the current particle + * @param pt the index of the current vertex in the particle shape + * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape + * ex : just set a vertex particle position + */ + updateParticleVertex(particle: SolidParticle, vertex: Vector3, pt: number): Vector3; + /** + * This will be called before any other treatment by setParticles() and will be passed three parameters. + * This does nothing and may be overwritten by the user. + * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() + * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() + * @param update the boolean update value actually passed to setParticles() + */ + beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void; + /** + * This will be called by setParticles() after all the other treatments and just before the actual mesh update. + * This will be passed three parameters. + * This does nothing and may be overwritten by the user. + * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() + * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() + * @param update the boolean update value actually passed to setParticles() + */ + afterUpdateParticles(start?: number, stop?: number, update?: boolean): void; + } +} + +declare namespace BABYLON { + interface IPhysicsEnginePlugin { + name: string; + initialize(iterations?: number): any; + setGravity(gravity: Vector3): void; + getGravity(): Vector3; + runOneStep(delta: number): void; + registerMesh(mesh: AbstractMesh, impostor: number, options: PhysicsBodyCreationOptions): any; + registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any; + unregisterMesh(mesh: AbstractMesh): any; + applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void; + createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3, options?: any): boolean; + dispose(): void; + isSupported(): boolean; + updateBodyPosition(mesh: AbstractMesh): void; + getWorldObject(): any; + getPhysicsBodyOfMesh(mesh: AbstractMesh): any; + } + interface PhysicsBodyCreationOptions { + mass: number; + friction: number; + restitution: number; + } + interface PhysicsCompoundBodyPart { + mesh: Mesh; + impostor: number; + } + class PhysicsEngine { + gravity: Vector3; + private _currentPlugin; + constructor(plugin?: IPhysicsEnginePlugin); + _initialize(gravity?: Vector3): void; + _runOneStep(delta: number): void; + _setGravity(gravity: Vector3): void; + _getGravity(): Vector3; + _registerMesh(mesh: AbstractMesh, impostor: number, options: PhysicsBodyCreationOptions): any; + _registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any; + _unregisterMesh(mesh: AbstractMesh): void; + _applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void; + _createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3, options?: any): boolean; + _updateBodyPosition(mesh: AbstractMesh): void; + dispose(): void; + isSupported(): boolean; + getPhysicsBodyOfMesh(mesh: AbstractMesh): any; + getPhysicsPluginName(): string; + static NoImpostor: number; + static SphereImpostor: number; + static BoxImpostor: number; + static PlaneImpostor: number; + static MeshImpostor: number; + static CapsuleImpostor: number; + static ConeImpostor: number; + static CylinderImpostor: number; + static ConvexHullImpostor: number; + static HeightmapImpostor: number; + static Epsilon: number; + } +} + +declare namespace BABYLON { + class AnaglyphPostProcess extends PostProcess { + constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare namespace BABYLON { + class BlackAndWhitePostProcess extends PostProcess { + constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare namespace BABYLON { + class BlurPostProcess extends PostProcess { + direction: Vector2; + blurWidth: number; + constructor(name: string, direction: Vector2, blurWidth: number, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare namespace BABYLON { + class ColorCorrectionPostProcess extends PostProcess { + private _colorTableTexture; + constructor(name: string, colorTableUrl: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare namespace BABYLON { + class ConvolutionPostProcess extends PostProcess { + kernel: number[]; + constructor(name: string, kernel: number[], ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + static EdgeDetect0Kernel: number[]; + static EdgeDetect1Kernel: number[]; + static EdgeDetect2Kernel: number[]; + static SharpenKernel: number[]; + static EmbossKernel: number[]; + static GaussianKernel: number[]; + } +} + +declare namespace BABYLON { + class DisplayPassPostProcess extends PostProcess { + constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare namespace BABYLON { + class FilterPostProcess extends PostProcess { + kernelMatrix: Matrix; + constructor(name: string, kernelMatrix: Matrix, ratio: number, camera?: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare namespace BABYLON { + class FxaaPostProcess extends PostProcess { + texelWidth: number; + texelHeight: number; + constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare namespace BABYLON { + class HDRRenderingPipeline extends PostProcessRenderPipeline implements IDisposable { + /** + * Public members + */ + /** + * Gaussian blur coefficient + * @type {number} + */ + gaussCoeff: number; + /** + * Gaussian blur mean + * @type {number} + */ + gaussMean: number; + /** + * Gaussian blur standard deviation + * @type {number} + */ + gaussStandDev: number; + /** + * Gaussian blur multiplier. Multiplies the blur effect + * @type {number} + */ + gaussMultiplier: number; + /** + * Exposure, controls the overall intensity of the pipeline + * @type {number} + */ + exposure: number; + /** + * Minimum luminance that the post-process can output. Luminance is >= 0 + * @type {number} + */ + minimumLuminance: number; + /** + * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance + * @type {number} + */ + maximumLuminance: number; + /** + * Increase rate for luminance: eye adaptation speed to dark + * @type {number} + */ + luminanceIncreaserate: number; + /** + * Decrease rate for luminance: eye adaptation speed to bright + * @type {number} + */ + luminanceDecreaseRate: number; + /** + * Minimum luminance needed to compute HDR + * @type {number} + */ + brightThreshold: number; + /** + * Private members + */ + private _guassianBlurHPostProcess; + private _guassianBlurVPostProcess; + private _brightPassPostProcess; + private _textureAdderPostProcess; + private _downSampleX4PostProcess; + private _originalPostProcess; + private _hdrPostProcess; + private _hdrCurrentLuminance; + private _hdrOutputLuminance; + static LUM_STEPS: number; + private _downSamplePostProcesses; + private _scene; + private _needUpdate; + /** + * @constructor + * @param {string} name - The rendering pipeline name + * @param {BABYLON.Scene} scene - The scene linked to this pipeline + * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) + * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null. + * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to + */ + constructor(name: string, scene: Scene, ratio: number, originalPostProcess?: PostProcess, cameras?: Camera[]); + /** + * Tells the pipeline to update its post-processes + */ + update(): void; + /** + * Returns the current calculated luminance + */ + getCurrentLuminance(): number; + /** + * Returns the currently drawn luminance + */ + getOutputLuminance(): number; + /** + * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras + */ + dispose(): void; + /** + * Creates the HDR post-process and computes the luminance adaptation + */ + private _createHDRPostProcess(scene, ratio); + /** + * Texture Adder post-process + */ + private _createTextureAdderPostProcess(scene, ratio); + /** + * Down sample X4 post-process + */ + private _createDownSampleX4PostProcess(scene, ratio); + /** + * Bright pass post-process + */ + private _createBrightPassPostProcess(scene, ratio); + /** + * Luminance generator. Creates the luminance post-process and down sample post-processes + */ + private _createLuminanceGeneratorPostProcess(scene); + /** + * Gaussian blur post-processes. Horizontal and Vertical + */ + private _createGaussianBlurPostProcess(scene, ratio); + } +} + +declare namespace BABYLON { + class LensRenderingPipeline extends PostProcessRenderPipeline { + /** + * The chromatic aberration PostProcess id in the pipeline + * @type {string} + */ + LensChromaticAberrationEffect: string; + /** + * The highlights enhancing PostProcess id in the pipeline + * @type {string} + */ + HighlightsEnhancingEffect: string; + /** + * The depth-of-field PostProcess id in the pipeline + * @type {string} + */ + LensDepthOfFieldEffect: string; + private _scene; + private _depthTexture; + private _grainTexture; + private _chromaticAberrationPostProcess; + private _highlightsPostProcess; + private _depthOfFieldPostProcess; + private _edgeBlur; + private _grainAmount; + private _chromaticAberration; + private _distortion; + private _highlightsGain; + private _highlightsThreshold; + private _dofDistance; + private _dofAperture; + private _dofDarken; + private _dofPentagon; + private _blurNoise; + /** + * @constructor + * + * Effect parameters are as follow: + * { + * chromatic_aberration: number; // from 0 to x (1 for realism) + * edge_blur: number; // from 0 to x (1 for realism) + * distortion: number; // from 0 to x (1 for realism) + * grain_amount: number; // from 0 to 1 + * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise + * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default) + * dof_aperture: number; // depth-of-field: focus blur bias (default: 1) + * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default) + * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect + * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default) + * dof_threshold: number; // depth-of-field: highlights threshold (default: 1) + * blur_noise: boolean; // add a little bit of noise to the blur (default: true) + * } + * Note: if an effect parameter is unset, effect is disabled + * + * @param {string} name - The rendering pipeline name + * @param {object} parameters - An object containing all parameters (see above) + * @param {BABYLON.Scene} scene - The scene linked to this pipeline + * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) + * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to + */ + constructor(name: string, parameters: any, scene: Scene, ratio?: number, cameras?: Camera[]); + setEdgeBlur(amount: number): void; + disableEdgeBlur(): void; + setGrainAmount(amount: number): void; + disableGrain(): void; + setChromaticAberration(amount: number): void; + disableChromaticAberration(): void; + setEdgeDistortion(amount: number): void; + disableEdgeDistortion(): void; + setFocusDistance(amount: number): void; + disableDepthOfField(): void; + setAperture(amount: number): void; + setDarkenOutOfFocus(amount: number): void; + enablePentagonBokeh(): void; + disablePentagonBokeh(): void; + enableNoiseBlur(): void; + disableNoiseBlur(): void; + setHighlightsGain(amount: number): void; + setHighlightsThreshold(amount: number): void; + disableHighlights(): void; + /** + * Removes the internal pipeline assets and detaches the pipeline from the scene cameras + */ + dispose(disableDepthRender?: boolean): void; + private _createChromaticAberrationPostProcess(ratio); + private _createHighlightsPostProcess(ratio); + private _createDepthOfFieldPostProcess(ratio); + private _createGrainTexture(); + } +} + +declare namespace BABYLON { + class PassPostProcess extends PostProcess { + constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare namespace BABYLON { + class PostProcess { + name: string; + onApply: (effect: Effect) => void; + onBeforeRender: (effect: Effect) => void; + onAfterRender: (effect: Effect) => void; + onSizeChanged: () => void; + onActivate: (camera: Camera) => void; + width: number; + height: number; + renderTargetSamplingMode: number; + clearColor: Color4; + private _camera; + private _scene; + private _engine; + private _renderRatio; + private _reusable; + private _textureType; + _textures: SmartArray; + _currentRenderTextureInd: number; + private _effect; + private _samplers; + private _fragmentUrl; + private _parameters; + constructor(name: string, fragmentUrl: string, parameters: string[], samplers: string[], ratio: number | any, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean, defines?: string, textureType?: number); + updateEffect(defines?: string): void; + isReusable(): boolean; + activate(camera: Camera, sourceTexture?: WebGLTexture): void; + isSupported: boolean; + apply(): Effect; + dispose(camera?: Camera): void; + } +} + +declare namespace BABYLON { + class PostProcessManager { + private _scene; + private _indexBuffer; + private _vertexDeclaration; + private _vertexStrideSize; + private _vertexBuffer; + constructor(scene: Scene); + private _prepareBuffers(); + _prepareFrame(sourceTexture?: WebGLTexture): boolean; + directRender(postProcesses: PostProcess[], targetTexture?: WebGLTexture): void; + _finalizeFrame(doNotPresent?: boolean, targetTexture?: WebGLTexture, faceIndex?: number, postProcesses?: PostProcess[]): void; + dispose(): void; + } +} + +declare namespace BABYLON { + class RefractionPostProcess extends PostProcess { + color: Color3; + depth: number; + colorLevel: number; + private _refRexture; + constructor(name: string, refractionTextureUrl: string, color: Color3, depth: number, colorLevel: number, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + dispose(camera: Camera): void; + } +} + +declare namespace BABYLON { + class SSAORenderingPipeline extends PostProcessRenderPipeline { + /** + * The PassPostProcess id in the pipeline that contains the original scene color + * @type {string} + */ + SSAOOriginalSceneColorEffect: string; + /** + * The SSAO PostProcess id in the pipeline + * @type {string} + */ + SSAORenderEffect: string; + /** + * The horizontal blur PostProcess id in the pipeline + * @type {string} + */ + SSAOBlurHRenderEffect: string; + /** + * The vertical blur PostProcess id in the pipeline + * @type {string} + */ + SSAOBlurVRenderEffect: string; + /** + * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect) + * @type {string} + */ + SSAOCombineRenderEffect: string; + /** + * The output strength of the SSAO post-process. Default value is 1.0. + * @type {number} + */ + totalStrength: number; + /** + * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006 + * @type {number} + */ + radius: number; + /** + * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel + * Must not be equal to fallOff and superior to fallOff. + * Default value is 0.975 + * @type {number} + */ + area: number; + /** + * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel + * Must not be equal to area and inferior to area. + * Default value is 0.0 + * @type {number} + */ + fallOff: number; + /** + * The base color of the SSAO post-process + * The final result is "base + ssao" between [0, 1] + * @type {number} + */ + base: number; + private _scene; + private _depthTexture; + private _randomTexture; + private _originalColorPostProcess; + private _ssaoPostProcess; + private _blurHPostProcess; + private _blurVPostProcess; + private _ssaoCombinePostProcess; + private _firstUpdate; + /** + * @constructor + * @param {string} name - The rendering pipeline name + * @param {BABYLON.Scene} scene - The scene linked to this pipeline + * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 } + * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to + */ + constructor(name: string, scene: Scene, ratio: any, cameras?: Camera[]); + /** + * Returns the horizontal blur PostProcess + * @return {BABYLON.BlurPostProcess} The horizontal blur post-process + */ + getBlurHPostProcess(): BlurPostProcess; + /** + * Returns the vertical blur PostProcess + * @return {BABYLON.BlurPostProcess} The vertical blur post-process + */ + getBlurVPostProcess(): BlurPostProcess; + /** + * Removes the internal pipeline assets and detatches the pipeline from the scene cameras + */ + dispose(disableDepthRender?: boolean): void; + private _createSSAOPostProcess(ratio); + private _createSSAOCombinePostProcess(ratio); + private _createRandomTexture(); + } +} + +declare namespace BABYLON { + class StereoscopicInterlacePostProcess extends PostProcess { + private _stepSize; + constructor(name: string, camB: Camera, postProcessA: PostProcess, isStereoscopicHoriz: boolean, samplingMode?: number); + } +} + +declare namespace BABYLON { + enum TonemappingOperator { + Hable = 0, + Reinhard = 1, + HejiDawson = 2, + Photographic = 3, + } + class TonemapPostProcess extends PostProcess { + private _operator; + private _exposureAdjustment; + constructor(name: string, operator: TonemappingOperator, exposureAdjustment: number, camera: Camera, samplingMode?: number, engine?: Engine, textureFormat?: number); + } +} + +declare namespace BABYLON { + class VolumetricLightScatteringPostProcess extends PostProcess { + private _volumetricLightScatteringPass; + private _volumetricLightScatteringRTT; + private _viewPort; + private _screenCoordinates; + private _cachedDefines; + private _customMeshPosition; + /** + * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false) + * @type {boolean} + */ + useCustomMeshPosition: boolean; + /** + * If the post-process should inverse the light scattering direction + * @type {boolean} + */ + invert: boolean; + /** + * The internal mesh used by the post-process + * @type {boolean} + */ + mesh: Mesh; + /** + * Set to true to use the diffuseColor instead of the diffuseTexture + * @type {boolean} + */ + useDiffuseColor: boolean; + /** + * Array containing the excluded meshes not rendered in the internal pass + */ + excludedMeshes: AbstractMesh[]; + /** + * Controls the overall intensity of the post-process + * @type {number} + */ + exposure: number; + /** + * Dissipates each sample's contribution in range [0, 1] + * @type {number} + */ + decay: number; + /** + * Controls the overall intensity of each sample + * @type {number} + */ + weight: number; + /** + * Controls the density of each sample + * @type {number} + */ + density: number; + /** + * @constructor + * @param {string} name - The post-process name + * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) + * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to + * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering + * @param {number} samples - The post-process quality, default 100 + * @param {number} samplingMode - The post-process filtering mode + * @param {BABYLON.Engine} engine - The babylon engine + * @param {boolean} reusable - If the post-process is reusable + * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided + */ + constructor(name: string, ratio: any, camera: Camera, mesh?: Mesh, samples?: number, samplingMode?: number, engine?: Engine, reusable?: boolean, scene?: Scene); + isReady(subMesh: SubMesh, useInstances: boolean): boolean; + /** + * Sets the new light position for light scattering effect + * @param {BABYLON.Vector3} The new custom light position + */ + setCustomMeshPosition(position: Vector3): void; + /** + * Returns the light position for light scattering effect + * @return {BABYLON.Vector3} The custom light position + */ + getCustomMeshPosition(): Vector3; + /** + * Disposes the internal assets and detaches the post-process from the camera + */ + dispose(camera: Camera): void; + /** + * Returns the render target texture used by the post-process + * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process + */ + getPass(): RenderTargetTexture; + private _meshExcluded(mesh); + private _createPass(scene, ratio); + private _updateMeshScreenCoordinates(scene); + /** + * Creates a default mesh for the Volumeric Light Scattering post-process + * @param {string} The mesh name + * @param {BABYLON.Scene} The scene where to create the mesh + * @return {BABYLON.Mesh} the default mesh + */ + static CreateDefaultMesh(name: string, scene: Scene): Mesh; + } +} + +declare namespace BABYLON { + class VRDistortionCorrectionPostProcess extends PostProcess { + aspectRatio: number; + private _isRightEye; + private _distortionFactors; + private _postProcessScaleFactor; + private _lensCenterOffset; + private _scaleIn; + private _scaleFactor; + private _lensCenter; + constructor(name: string, camera: Camera, isRightEye: boolean, vrMetrics: VRCameraMetrics); + } +} + +declare namespace BABYLON { + class ReflectionProbe { + name: string; + private _scene; + private _renderTargetTexture; + private _projectionMatrix; + private _viewMatrix; + private _target; + private _add; + private _attachedMesh; + position: Vector3; + constructor(name: string, size: number, scene: Scene, generateMipMaps?: boolean); + refreshRate: number; + getScene(): Scene; + cubeTexture: RenderTargetTexture; + renderList: AbstractMesh[]; + attachToMesh(mesh: AbstractMesh): void; + dispose(): void; + } +} + +declare namespace BABYLON { + class BoundingBoxRenderer { + frontColor: Color3; + backColor: Color3; + showBackLines: boolean; + renderList: SmartArray; + private _scene; + private _colorShader; + private _vb; + private _ib; + constructor(scene: Scene); + private _prepareRessources(); + reset(): void; + render(): void; + dispose(): void; + } +} + +declare namespace BABYLON { + class DepthRenderer { + private _scene; + private _depthMap; + private _effect; + private _viewMatrix; + private _projectionMatrix; + private _transformMatrix; + private _worldViewProjection; + private _cachedDefines; + constructor(scene: Scene, type?: number); + isReady(subMesh: SubMesh, useInstances: boolean): boolean; + getDepthMap(): RenderTargetTexture; + dispose(): void; + } +} + +declare namespace BABYLON { + class EdgesRenderer { + edgesWidthScalerForOrthographic: number; + edgesWidthScalerForPerspective: number; + private _source; + private _linesPositions; + private _linesNormals; + private _linesIndices; + private _epsilon; + private _indicesCount; + private _lineShader; + private _vb0; + private _vb1; + private _ib; + private _buffers; + private _checkVerticesInsteadOfIndices; + constructor(source: AbstractMesh, epsilon?: number, checkVerticesInsteadOfIndices?: boolean); + private _prepareRessources(); + dispose(): void; + private _processEdgeForAdjacencies(pa, pb, p0, p1, p2); + private _processEdgeForAdjacenciesWithVertices(pa, pb, p0, p1, p2); + private _checkEdge(faceIndex, edge, faceNormals, p0, p1); + _generateEdgesLines(): void; + render(): void; + } +} + +declare namespace BABYLON { + class OutlineRenderer { + private _scene; + private _effect; + private _cachedDefines; + constructor(scene: Scene); + render(subMesh: SubMesh, batch: _InstancesBatch, useOverlay?: boolean): void; + isReady(subMesh: SubMesh, useInstances: boolean): boolean; + } +} + +declare namespace BABYLON { + class RenderingGroup { + index: number; + private _scene; + private _opaqueSubMeshes; + private _transparentSubMeshes; + private _alphaTestSubMeshes; + private _activeVertices; + onBeforeTransparentRendering: () => void; + constructor(index: number, scene: Scene); + render(customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray) => void): boolean; + prepare(): void; + dispatch(subMesh: SubMesh): void; + } +} + +declare namespace BABYLON { + class RenderingManager { + static MAX_RENDERINGGROUPS: number; + private _scene; + private _renderingGroups; + private _depthBufferAlreadyCleaned; + private _currentIndex; + private _currentActiveMeshes; + private _currentRenderParticles; + private _currentRenderSprites; + constructor(scene: Scene); + private _renderParticles(index, activeMeshes); + private _renderSprites(index); + private _clearDepthBuffer(); + private _renderSpritesAndParticles(); + render(customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray) => void, activeMeshes: AbstractMesh[], renderParticles: boolean, renderSprites: boolean): void; + reset(): void; + dispatch(subMesh: SubMesh): void; + } +} + +declare namespace BABYLON { + class Sprite { + name: string; + position: Vector3; + color: Color4; + width: number; + height: number; + angle: number; + cellIndex: number; + invertU: number; + invertV: number; + disposeWhenFinishedAnimating: boolean; + animations: Animation[]; + isPickable: boolean; + actionManager: ActionManager; + private _animationStarted; + private _loopAnimation; + private _fromIndex; + private _toIndex; + private _delay; + private _direction; + private _frameCount; + private _manager; + private _time; + size: number; + constructor(name: string, manager: SpriteManager); + playAnimation(from: number, to: number, loop: boolean, delay: number): void; + stopAnimation(): void; + _animate(deltaTime: number): void; + dispose(): void; + } +} + +declare namespace BABYLON { + class SpriteManager { + name: string; + cellSize: number; + sprites: Sprite[]; + renderingGroupId: number; + layerMask: number; + onDispose: () => void; + fogEnabled: boolean; + isPickable: boolean; + private _capacity; + private _spriteTexture; + private _epsilon; + private _scene; + private _vertexDeclaration; + private _vertexStrideSize; + private _vertexBuffer; + private _indexBuffer; + private _vertices; + private _effectBase; + private _effectFog; + constructor(name: string, imgUrl: string, capacity: number, cellSize: number, scene: Scene, epsilon?: number, samplingMode?: number); + private _appendSpriteVertex(index, sprite, offsetX, offsetY, rowSize); + intersects(ray: Ray, camera: Camera, predicate?: (sprite: Sprite) => boolean, fastCheck?: boolean): PickingInfo; + render(): void; + dispose(): void; + } +} + +declare namespace BABYLON.Internals { + class AndOrNotEvaluator { + static Eval(query: string, evaluateCallback: (val: any) => boolean): boolean; + private static _HandleParenthesisContent(parenthesisContent, evaluateCallback); + private static _SimplifyNegation(booleanString); + } +} + +declare namespace BABYLON { + interface IAssetTask { + onSuccess: (task: IAssetTask) => void; + onError: (task: IAssetTask) => void; + isCompleted: boolean; + run(scene: Scene, onSuccess: () => void, onError: () => void): any; + } + class MeshAssetTask implements IAssetTask { + name: string; + meshesNames: any; + rootUrl: string; + sceneFilename: string; + loadedMeshes: Array; + loadedParticleSystems: Array; + loadedSkeletons: Array; + onSuccess: (task: IAssetTask) => void; + onError: (task: IAssetTask) => void; + isCompleted: boolean; + constructor(name: string, meshesNames: any, rootUrl: string, sceneFilename: string); + run(scene: Scene, onSuccess: () => void, onError: () => void): void; + } + class TextFileAssetTask implements IAssetTask { + name: string; + url: string; + onSuccess: (task: IAssetTask) => void; + onError: (task: IAssetTask) => void; + isCompleted: boolean; + text: string; + constructor(name: string, url: string); + run(scene: Scene, onSuccess: () => void, onError: () => void): void; + } + class BinaryFileAssetTask implements IAssetTask { + name: string; + url: string; + onSuccess: (task: IAssetTask) => void; + onError: (task: IAssetTask) => void; + isCompleted: boolean; + data: ArrayBuffer; + constructor(name: string, url: string); + run(scene: Scene, onSuccess: () => void, onError: () => void): void; + } + class ImageAssetTask implements IAssetTask { + name: string; + url: string; + onSuccess: (task: IAssetTask) => void; + onError: (task: IAssetTask) => void; + isCompleted: boolean; + image: HTMLImageElement; + constructor(name: string, url: string); + run(scene: Scene, onSuccess: () => void, onError: () => void): void; + } + class TextureAssetTask implements IAssetTask { + name: string; + url: string; + noMipmap: boolean; + invertY: boolean; + samplingMode: number; + onSuccess: (task: IAssetTask) => void; + onError: (task: IAssetTask) => void; + isCompleted: boolean; + texture: Texture; + constructor(name: string, url: string, noMipmap?: boolean, invertY?: boolean, samplingMode?: number); + run(scene: Scene, onSuccess: () => void, onError: () => void): void; + } + class AssetsManager { + private _tasks; + private _scene; + private _waitingTasksCount; + onFinish: (tasks: IAssetTask[]) => void; + onTaskSuccess: (task: IAssetTask) => void; + onTaskError: (task: IAssetTask) => void; + useDefaultLoadingScreen: boolean; + constructor(scene: Scene); + addMeshTask(taskName: string, meshesNames: any, rootUrl: string, sceneFilename: string): IAssetTask; + addTextFileTask(taskName: string, url: string): IAssetTask; + addBinaryFileTask(taskName: string, url: string): IAssetTask; + addImageTask(taskName: string, url: string): IAssetTask; + addTextureTask(taskName: string, url: string, noMipmap?: boolean, invertY?: boolean, samplingMode?: number): IAssetTask; + private _decreaseWaitingTasksCount(); + private _runTask(task); + reset(): AssetsManager; + load(): AssetsManager; + } +} + +declare namespace BABYLON { + class Database { + private callbackManifestChecked; + private currentSceneUrl; + private db; + private enableSceneOffline; + private enableTexturesOffline; + private manifestVersionFound; + private mustUpdateRessources; + private hasReachedQuota; + private isSupported; + private idbFactory; + static IsUASupportingBlobStorage: boolean; + static IDBStorageEnabled: boolean; + constructor(urlToScene: string, callbackManifestChecked: (checked: boolean) => any); + static parseURL: (url: string) => string; + static ReturnFullUrlLocation: (url: string) => string; + checkManifestFile(): void; + openAsync(successCallback: any, errorCallback: any): void; + loadImageFromDB(url: string, image: HTMLImageElement): void; + private _loadImageFromDBAsync(url, image, notInDBCallback); + private _saveImageIntoDBAsync(url, image); + private _checkVersionFromDB(url, versionLoaded); + private _loadVersionFromDBAsync(url, callback, updateInDBCallback); + private _saveVersionIntoDBAsync(url, callback); + private loadFileFromDB(url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer?); + private _loadFileFromDBAsync(url, callback, notInDBCallback, useArrayBuffer?); + private _saveFileIntoDBAsync(url, callback, progressCallback, useArrayBuffer?); + } +} + +declare namespace BABYLON { + class FilesInput { + private _engine; + private _currentScene; + private _canvas; + private _sceneLoadedCallback; + private _progressCallback; + private _additionnalRenderLoopLogicCallback; + private _textureLoadingCallback; + private _startingProcessingFilesCallback; + private _elementToMonitor; + static FilesTextures: any[]; + static FilesToLoad: any[]; + private _sceneFileToLoad; + private _filesToLoad; + constructor(p_engine: Engine, p_scene: Scene, p_canvas: HTMLCanvasElement, p_sceneLoadedCallback: any, p_progressCallback: any, p_additionnalRenderLoopLogicCallback: any, p_textureLoadingCallback: any, p_startingProcessingFilesCallback: any); + monitorElementForDragNDrop(p_elementToMonitor: HTMLElement): void; + private renderFunction(); + private drag(e); + private drop(eventDrop); + loadFiles(event: any): void; + reload(): void; + } +} + +declare namespace BABYLON { + class Gamepads { + private babylonGamepads; + private oneGamepadConnected; + private isMonitoring; + private gamepadEventSupported; + private gamepadSupportAvailable; + private _callbackGamepadConnected; + private static gamepadDOMInfo; + constructor(ongamedpadconnected: (gamepad: Gamepad) => void); + dispose(): void; + private _onGamepadConnected(evt); + private _addNewGamepad(gamepad); + private _onGamepadDisconnected(evt); + private _startMonitoringGamepads(); + private _stopMonitoringGamepads(); + private _checkGamepadsStatus(); + private _updateGamepadObjects(); + } + class StickValues { + x: any; + y: any; + constructor(x: any, y: any); + } + class Gamepad { + id: string; + index: number; + browserGamepad: any; + private _leftStick; + private _rightStick; + private _onleftstickchanged; + private _onrightstickchanged; + constructor(id: string, index: number, browserGamepad: any); + onleftstickchanged(callback: (values: StickValues) => void): void; + onrightstickchanged(callback: (values: StickValues) => void): void; + leftStick: StickValues; + rightStick: StickValues; + update(): void; + } + class GenericPad extends Gamepad { + id: string; + index: number; + gamepad: any; + private _buttons; + private _onbuttondown; + private _onbuttonup; + onbuttondown(callback: (buttonPressed: number) => void): void; + onbuttonup(callback: (buttonReleased: number) => void): void; + constructor(id: string, index: number, gamepad: any); + private _setButtonValue(newValue, currentValue, buttonIndex); + update(): void; + } + enum Xbox360Button { + A = 0, + B = 1, + X = 2, + Y = 3, + Start = 4, + Back = 5, + LB = 6, + RB = 7, + LeftStick = 8, + RightStick = 9, + } + enum Xbox360Dpad { + Up = 0, + Down = 1, + Left = 2, + Right = 3, + } + class Xbox360Pad extends Gamepad { + private _leftTrigger; + private _rightTrigger; + private _onlefttriggerchanged; + private _onrighttriggerchanged; + private _onbuttondown; + private _onbuttonup; + private _ondpaddown; + private _ondpadup; + private _buttonA; + private _buttonB; + private _buttonX; + private _buttonY; + private _buttonBack; + private _buttonStart; + private _buttonLB; + private _buttonRB; + private _buttonLeftStick; + private _buttonRightStick; + private _dPadUp; + private _dPadDown; + private _dPadLeft; + private _dPadRight; + onlefttriggerchanged(callback: (value: number) => void): void; + onrighttriggerchanged(callback: (value: number) => void): void; + leftTrigger: number; + rightTrigger: number; + onbuttondown(callback: (buttonPressed: Xbox360Button) => void): void; + onbuttonup(callback: (buttonReleased: Xbox360Button) => void): void; + ondpaddown(callback: (dPadPressed: Xbox360Dpad) => void): void; + ondpadup(callback: (dPadReleased: Xbox360Dpad) => void): void; + private _setButtonValue(newValue, currentValue, buttonType); + private _setDPadValue(newValue, currentValue, buttonType); + buttonA: number; + buttonB: number; + buttonX: number; + buttonY: number; + buttonStart: number; + buttonBack: number; + buttonLB: number; + buttonRB: number; + buttonLeftStick: number; + buttonRightStick: number; + dPadUp: number; + dPadDown: number; + dPadLeft: number; + dPadRight: number; + update(): void; + } +} +interface Navigator { + getGamepads(func?: any): any; + webkitGetGamepads(func?: any): any; + msGetGamepads(func?: any): any; + webkitGamepads(func?: any): any; +} + +declare namespace BABYLON { + interface ILoadingScreen { + displayLoadingUI: () => void; + hideLoadingUI: () => void; + loadingUIBackgroundColor: string; + loadingUIText: string; + } + class DefaultLoadingScreen implements ILoadingScreen { + private _renderingCanvas; + private _loadingText; + private _loadingDivBackgroundColor; + private _loadingDiv; + private _loadingTextDiv; + constructor(_renderingCanvas: HTMLCanvasElement, _loadingText?: string, _loadingDivBackgroundColor?: string); + displayLoadingUI(): void; + hideLoadingUI(): void; + loadingUIText: string; + loadingUIBackgroundColor: string; + private _resizeLoadingUI; + } +} + +declare namespace BABYLON { + class SceneOptimization { + priority: number; + apply: (scene: Scene) => boolean; + constructor(priority?: number); + } + class TextureOptimization extends SceneOptimization { + priority: number; + maximumSize: number; + constructor(priority?: number, maximumSize?: number); + apply: (scene: Scene) => boolean; + } + class HardwareScalingOptimization extends SceneOptimization { + priority: number; + maximumScale: number; + private _currentScale; + constructor(priority?: number, maximumScale?: number); + apply: (scene: Scene) => boolean; + } + class ShadowsOptimization extends SceneOptimization { + apply: (scene: Scene) => boolean; + } + class PostProcessesOptimization extends SceneOptimization { + apply: (scene: Scene) => boolean; + } + class LensFlaresOptimization extends SceneOptimization { + apply: (scene: Scene) => boolean; + } + class ParticlesOptimization extends SceneOptimization { + apply: (scene: Scene) => boolean; + } + class RenderTargetsOptimization extends SceneOptimization { + apply: (scene: Scene) => boolean; + } + class MergeMeshesOptimization extends SceneOptimization { + static _UpdateSelectionTree: boolean; + static UpdateSelectionTree: boolean; + private _canBeMerged; + apply: (scene: Scene, updateSelectionTree?: boolean) => boolean; + } + class SceneOptimizerOptions { + targetFrameRate: number; + trackerDuration: number; + optimizations: SceneOptimization[]; + constructor(targetFrameRate?: number, trackerDuration?: number); + static LowDegradationAllowed(targetFrameRate?: number): SceneOptimizerOptions; + static ModerateDegradationAllowed(targetFrameRate?: number): SceneOptimizerOptions; + static HighDegradationAllowed(targetFrameRate?: number): SceneOptimizerOptions; + } + class SceneOptimizer { + static _CheckCurrentState(scene: Scene, options: SceneOptimizerOptions, currentPriorityLevel: number, onSuccess?: () => void, onFailure?: () => void): void; + static OptimizeAsync(scene: Scene, options?: SceneOptimizerOptions, onSuccess?: () => void, onFailure?: () => void): void; + } +} + +declare namespace BABYLON { + class SceneSerializer { + static Serialize(scene: Scene): any; + static SerializeMesh(toSerialize: any, withParents?: boolean, withChildren?: boolean): any; + } +} + +declare namespace BABYLON { + class SmartArray { + data: Array; + length: number; + private _id; + private _duplicateId; + constructor(capacity: number); + push(value: any): void; + pushNoDuplicate(value: any): void; + sort(compareFn: any): void; + reset(): void; + concat(array: any): void; + concatWithNoDuplicate(array: any): void; + indexOf(value: any): number; + private static _GlobalId; + } +} + +declare namespace BABYLON { + class SmartCollection { + count: number; + items: any; + private _keys; + private _initialCapacity; + constructor(capacity?: number); + add(key: any, item: any): number; + remove(key: any): number; + removeItemOfIndex(index: number): number; + indexOf(key: any): number; + item(key: any): any; + getAllKeys(): any[]; + getKeyByIndex(index: number): any; + getItemByIndex(index: number): any; + empty(): void; + forEach(block: (item: any) => void): void; + } +} + +declare namespace BABYLON { + class Tags { + static EnableFor(obj: any): void; + static DisableFor(obj: any): void; + static HasTags(obj: any): boolean; + static GetTags(obj: any, asString?: boolean): any; + static AddTagsTo(obj: any, tagsString: string): void; + static _AddTagTo(obj: any, tag: string): void; + static RemoveTagsFrom(obj: any, tagsString: string): void; + static _RemoveTagFrom(obj: any, tag: string): void; + static MatchesQuery(obj: any, tagsQuery: string): boolean; + } +} + +declare namespace BABYLON.Internals { + interface DDSInfo { + width: number; + height: number; + mipmapCount: number; + isFourCC: boolean; + isRGB: boolean; + isLuminance: boolean; + isCube: boolean; + } + class DDSTools { + static GetDDSInfo(arrayBuffer: any): DDSInfo; + private static GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); + private static GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); + private static GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); + static UploadDDSLevels(gl: WebGLRenderingContext, ext: any, arrayBuffer: any, info: DDSInfo, loadMipmaps: boolean, faces: number): void; + } +} + +declare namespace BABYLON.Internals { + class TGATools { + private static _TYPE_NO_DATA; + private static _TYPE_INDEXED; + private static _TYPE_RGB; + private static _TYPE_GREY; + private static _TYPE_RLE_INDEXED; + private static _TYPE_RLE_RGB; + private static _TYPE_RLE_GREY; + private static _ORIGIN_MASK; + private static _ORIGIN_SHIFT; + private static _ORIGIN_BL; + private static _ORIGIN_BR; + private static _ORIGIN_UL; + private static _ORIGIN_UR; + static GetTGAHeader(data: Uint8Array): any; + static UploadContent(gl: WebGLRenderingContext, data: Uint8Array): void; + static _getImageData8bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; + static _getImageData16bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; + static _getImageData24bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; + static _getImageData32bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; + static _getImageDataGrey8bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; + static _getImageDataGrey16bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; + } +} + +declare namespace BABYLON { + interface IAnimatable { + animations: Array; + } + interface ISize { + width: number; + height: number; + } + class Tools { + static BaseUrl: string; + static CorsBehavior: any; + static UseFallbackTexture: boolean; + static Instantiate(className: string): any; + static GetConstructorName(obj: any): any; + static ToHex(i: number): string; + static SetImmediate(action: () => void): void; + static IsExponentOfTwo(value: number): boolean; + static GetExponentOfTwo(value: number, max: number): number; + static GetFilename(path: string): string; + static GetDOMTextContent(element: HTMLElement): string; + static ToDegrees(angle: number): number; + static ToRadians(angle: number): number; + static EncodeArrayBufferTobase64(buffer: ArrayBuffer): string; + static ExtractMinAndMaxIndexed(positions: number[] | Float32Array, indices: number[] | Int32Array, indexStart: number, indexCount: number): { + minimum: Vector3; + maximum: Vector3; + }; + static ExtractMinAndMax(positions: number[] | Float32Array, start: number, count: number): { + minimum: Vector3; + maximum: Vector3; + }; + static MakeArray(obj: any, allowsNullUndefined?: boolean): Array; + static GetPointerPrefix(): string; + static QueueNewFrame(func: any): void; + static RequestFullscreen(element: any): void; + static ExitFullscreen(): void; + static CleanUrl(url: string): string; + static LoadImage(url: any, onload: any, onerror: any, database: any): HTMLImageElement; + static LoadFile(url: string, callback: (data: any) => void, progressCallBack?: () => void, database?: any, useArrayBuffer?: boolean, onError?: () => void): void; + static ReadFileAsDataURL(fileToLoad: any, callback: any, progressCallback: any): void; + static ReadFile(fileToLoad: any, callback: any, progressCallBack: any, useArrayBuffer?: boolean): void; + static FileAsURL(content: string): string; + static Clamp(value: number, min?: number, max?: number): number; + static Sign(value: number): number; + static Format(value: number, decimals?: number): string; + static CheckExtends(v: Vector3, min: Vector3, max: Vector3): void; + static WithinEpsilon(a: number, b: number, epsilon?: number): boolean; + static DeepCopy(source: any, destination: any, doNotCopyList?: string[], mustCopyList?: string[]): void; + static IsEmpty(obj: any): boolean; + static RegisterTopRootEvents(events: { + name: string; + handler: EventListener; + }[]): void; + static UnregisterTopRootEvents(events: { + name: string; + handler: EventListener; + }[]): void; + static DumpFramebuffer(width: number, height: number, engine: Engine, successCallback?: (data: string) => void): void; + static CreateScreenshot(engine: Engine, camera: Camera, size: any, successCallback?: (data: string) => void): void; + static ValidateXHRData(xhr: XMLHttpRequest, dataType?: number): boolean; + private static _NoneLogLevel; + private static _MessageLogLevel; + private static _WarningLogLevel; + private static _ErrorLogLevel; + private static _LogCache; + static errorsCount: number; + static OnNewCacheEntry: (entry: string) => void; + static NoneLogLevel: number; + static MessageLogLevel: number; + static WarningLogLevel: number; + static ErrorLogLevel: number; + static AllLogLevel: number; + private static _AddLogEntry(entry); + private static _FormatMessage(message); + static Log: (message: string) => void; + private static _LogDisabled(message); + private static _LogEnabled(message); + static Warn: (message: string) => void; + private static _WarnDisabled(message); + private static _WarnEnabled(message); + static Error: (message: string) => void; + private static _ErrorDisabled(message); + private static _ErrorEnabled(message); + static LogCache: string; + static ClearLogCache(): void; + static LogLevels: number; + private static _PerformanceNoneLogLevel; + private static _PerformanceUserMarkLogLevel; + private static _PerformanceConsoleLogLevel; + private static _performance; + static PerformanceNoneLogLevel: number; + static PerformanceUserMarkLogLevel: number; + static PerformanceConsoleLogLevel: number; + static PerformanceLogLevel: number; + static _StartPerformanceCounterDisabled(counterName: string, condition?: boolean): void; + static _EndPerformanceCounterDisabled(counterName: string, condition?: boolean): void; + static _StartUserMark(counterName: string, condition?: boolean): void; + static _EndUserMark(counterName: string, condition?: boolean): void; + static _StartPerformanceConsole(counterName: string, condition?: boolean): void; + static _EndPerformanceConsole(counterName: string, condition?: boolean): void; + static StartPerformanceCounter: (counterName: string, condition?: boolean) => void; + static EndPerformanceCounter: (counterName: string, condition?: boolean) => void; + static Now: number; + } + /** + * An implementation of a loop for asynchronous functions. + */ + class AsyncLoop { + iterations: number; + private _fn; + private _successCallback; + index: number; + private _done; + /** + * Constroctor. + * @param iterations the number of iterations. + * @param _fn the function to run each iteration + * @param _successCallback the callback that will be called upon succesful execution + * @param offset starting offset. + */ + constructor(iterations: number, _fn: (asyncLoop: AsyncLoop) => void, _successCallback: () => void, offset?: number); + /** + * Execute the next iteration. Must be called after the last iteration was finished. + */ + executeNext(): void; + /** + * Break the loop and run the success callback. + */ + breakLoop(): void; + /** + * Helper function + */ + static Run(iterations: number, _fn: (asyncLoop: AsyncLoop) => void, _successCallback: () => void, offset?: number): AsyncLoop; + /** + * A for-loop that will run a given number of iterations synchronous and the rest async. + * @param iterations total number of iterations + * @param syncedIterations number of synchronous iterations in each async iteration. + * @param fn the function to call each iteration. + * @param callback a success call back that will be called when iterating stops. + * @param breakFunction a break condition (optional) + * @param timeout timeout settings for the setTimeout function. default - 0. + * @constructor + */ + static SyncAsyncForLoop(iterations: number, syncedIterations: number, fn: (iteration: number) => void, callback: () => void, breakFunction?: () => boolean, timeout?: number): void; + } +} + +declare namespace BABYLON { + enum JoystickAxis { + X = 0, + Y = 1, + Z = 2, + } + class VirtualJoystick { + reverseLeftRight: boolean; + reverseUpDown: boolean; + deltaPosition: Vector3; + pressed: boolean; + private static _globalJoystickIndex; + private static vjCanvas; + private static vjCanvasContext; + private static vjCanvasWidth; + private static vjCanvasHeight; + private static halfWidth; + private static halfHeight; + private _action; + private _axisTargetedByLeftAndRight; + private _axisTargetedByUpAndDown; + private _joystickSensibility; + private _inversedSensibility; + private _rotationSpeed; + private _inverseRotationSpeed; + private _rotateOnAxisRelativeToMesh; + private _joystickPointerID; + private _joystickColor; + private _joystickPointerPos; + private _joystickPreviousPointerPos; + private _joystickPointerStartPos; + private _deltaJoystickVector; + private _leftJoystick; + private _joystickIndex; + private _touches; + private _onPointerDownHandlerRef; + private _onPointerMoveHandlerRef; + private _onPointerUpHandlerRef; + private _onPointerOutHandlerRef; + private _onResize; + constructor(leftJoystick?: boolean); + setJoystickSensibility(newJoystickSensibility: number): void; + private _onPointerDown(e); + private _onPointerMove(e); + private _onPointerUp(e); + /** + * Change the color of the virtual joystick + * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000") + */ + setJoystickColor(newColor: string): void; + setActionOnTouch(action: () => any): void; + setAxisForLeftRight(axis: JoystickAxis): void; + setAxisForUpDown(axis: JoystickAxis): void; + private _clearCanvas(); + private _drawVirtualJoystick(); + releaseCanvas(): void; + } +} + +declare namespace BABYLON { + class VRDeviceOrientationFreeCamera extends FreeCamera { + _alpha: number; + _beta: number; + _gamma: number; + private _offsetOrientation; + private _deviceOrientationHandler; + constructor(name: string, position: Vector3, scene: Scene, compensateDistortion?: boolean); + _onOrientationEvent(evt: DeviceOrientationEvent): void; + attachControl(element: HTMLElement, noPreventDefault?: boolean): void; + detachControl(element: HTMLElement): void; + } +} + +declare var HMDVRDevice: any; +declare var PositionSensorVRDevice: any; +declare namespace BABYLON { + class WebVRFreeCamera extends FreeCamera { + _hmdDevice: any; + _sensorDevice: any; + _cacheState: any; + _cacheQuaternion: Quaternion; + _cacheRotation: Vector3; + _vrEnabled: boolean; + constructor(name: string, position: Vector3, scene: Scene, compensateDistortion?: boolean); + private _getWebVRDevices(devices); + _checkInputs(): void; + attachControl(element: HTMLElement, noPreventDefault?: boolean): void; + detachControl(element: HTMLElement): void; + } +} + +declare namespace BABYLON { + interface IOctreeContainer { + blocks: Array>; + } + class Octree { + maxDepth: number; + blocks: Array>; + dynamicContent: T[]; + private _maxBlockCapacity; + private _selectionContent; + private _creationFunc; + constructor(creationFunc: (entry: T, block: OctreeBlock) => void, maxBlockCapacity?: number, maxDepth?: number); + update(worldMin: Vector3, worldMax: Vector3, entries: T[]): void; + addMesh(entry: T): void; + select(frustumPlanes: Plane[], allowDuplicate?: boolean): SmartArray; + intersects(sphereCenter: Vector3, sphereRadius: number, allowDuplicate?: boolean): SmartArray; + intersectsRay(ray: Ray): SmartArray; + static _CreateBlocks(worldMin: Vector3, worldMax: Vector3, entries: T[], maxBlockCapacity: number, currentDepth: number, maxDepth: number, target: IOctreeContainer, creationFunc: (entry: T, block: OctreeBlock) => void): void; + static CreationFuncForMeshes: (entry: AbstractMesh, block: OctreeBlock) => void; + static CreationFuncForSubMeshes: (entry: SubMesh, block: OctreeBlock) => void; + } +} + +declare namespace BABYLON { + class OctreeBlock { + entries: T[]; + blocks: Array>; + private _depth; + private _maxDepth; + private _capacity; + private _minPoint; + private _maxPoint; + private _boundingVectors; + private _creationFunc; + constructor(minPoint: Vector3, maxPoint: Vector3, capacity: number, depth: number, maxDepth: number, creationFunc: (entry: T, block: OctreeBlock) => void); + capacity: number; + minPoint: Vector3; + maxPoint: Vector3; + addEntry(entry: T): void; + addEntries(entries: T[]): void; + select(frustumPlanes: Plane[], selection: SmartArray, allowDuplicate?: boolean): void; + intersects(sphereCenter: Vector3, sphereRadius: number, selection: SmartArray, allowDuplicate?: boolean): void; + intersectsRay(ray: Ray, selection: SmartArray): void; + createInnerBlocks(): void; + } +} + +declare namespace BABYLON { + class ShadowGenerator { + private static _FILTER_NONE; + private static _FILTER_VARIANCESHADOWMAP; + private static _FILTER_POISSONSAMPLING; + private static _FILTER_BLURVARIANCESHADOWMAP; + static FILTER_NONE: number; + static FILTER_VARIANCESHADOWMAP: number; + static FILTER_POISSONSAMPLING: number; + static FILTER_BLURVARIANCESHADOWMAP: number; + private _filter; + blurScale: number; + private _blurBoxOffset; + private _bias; + private _lightDirection; + forceBackFacesOnly: boolean; + bias: number; + blurBoxOffset: number; + filter: number; + useVarianceShadowMap: boolean; + usePoissonSampling: boolean; + useBlurVarianceShadowMap: boolean; + private _light; + private _scene; + private _shadowMap; + private _shadowMap2; + private _darkness; + private _transparencyShadow; + private _effect; + private _viewMatrix; + private _projectionMatrix; + private _transformMatrix; + private _worldViewProjection; + private _cachedPosition; + private _cachedDirection; + private _cachedDefines; + private _currentRenderID; + private _downSamplePostprocess; + private _boxBlurPostprocess; + private _mapSize; + private _currentFaceIndex; + private _currentFaceIndexCache; + constructor(mapSize: number, light: IShadowLight); + isReady(subMesh: SubMesh, useInstances: boolean): boolean; + getShadowMap(): RenderTargetTexture; + getShadowMapForRendering(): RenderTargetTexture; + getLight(): IShadowLight; + getTransformMatrix(): Matrix; + getDarkness(): number; + setDarkness(darkness: number): void; + setTransparencyShadow(hasShadow: boolean): void; + private _packHalf(depth); + dispose(): void; + serialize(): any; + static Parse(parsedShadowGenerator: any, scene: Scene): ShadowGenerator; + } +} + +declare namespace BABYLON.Internals { +} + +declare namespace BABYLON { + class BaseTexture { + name: string; + delayLoadState: number; + hasAlpha: boolean; + getAlphaFromRGB: boolean; + level: number; + isCube: boolean; + isRenderTarget: boolean; + animations: Animation[]; + onDispose: () => void; + coordinatesIndex: number; + coordinatesMode: number; + wrapU: number; + wrapV: number; + anisotropicFilteringLevel: number; + _cachedAnisotropicFilteringLevel: number; + private _scene; + _texture: WebGLTexture; + constructor(scene: Scene); + getScene(): Scene; + getTextureMatrix(): Matrix; + getReflectionTextureMatrix(): Matrix; + getInternalTexture(): WebGLTexture; + isReady(): boolean; + getSize(): ISize; + getBaseSize(): ISize; + scale(ratio: number): void; + canRescale: boolean; + _removeFromCache(url: string, noMipmap: boolean): void; + _getFromCache(url: string, noMipmap: boolean, sampling?: number): WebGLTexture; + delayLoad(): void; + clone(): BaseTexture; + releaseInternalTexture(): void; + dispose(): void; + serialize(): any; + } +} + +declare namespace BABYLON { + class CubeTexture extends BaseTexture { + url: string; + coordinatesMode: number; + private _noMipmap; + private _files; + private _extensions; + private _textureMatrix; + static CreateFromImages(files: string[], scene: Scene, noMipmap?: boolean): CubeTexture; + constructor(rootUrl: string, scene: Scene, extensions?: string[], noMipmap?: boolean, files?: string[]); + clone(): CubeTexture; + delayLoad(): void; + getReflectionTextureMatrix(): Matrix; + static Parse(parsedTexture: any, scene: Scene, rootUrl: string): CubeTexture; + serialize(): any; + } +} + +declare namespace BABYLON { + class DynamicTexture extends Texture { + private _generateMipMaps; + private _canvas; + private _context; + constructor(name: string, options: any, scene: Scene, generateMipMaps: boolean, samplingMode?: number); + canRescale: boolean; + scale(ratio: number): void; + getContext(): CanvasRenderingContext2D; + clear(): void; + update(invertY?: boolean): void; + drawText(text: string, x: number, y: number, font: string, color: string, clearColor: string, invertY?: boolean, update?: boolean): void; + clone(): DynamicTexture; + } +} + +declare namespace BABYLON { + class MirrorTexture extends RenderTargetTexture { + mirrorPlane: Plane; + private _transformMatrix; + private _mirrorMatrix; + private _savedViewMatrix; + constructor(name: string, size: number, scene: Scene, generateMipMaps?: boolean); + clone(): MirrorTexture; + serialize(): any; + } +} + +declare namespace BABYLON { + class RawTexture extends Texture { + format: number; + constructor(data: ArrayBufferView, width: number, height: number, format: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number); + update(data: ArrayBufferView): void; + static CreateLuminanceTexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; + static CreateLuminanceAlphaTexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; + static CreateAlphaTexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; + static CreateRGBTexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; + static CreateRGBATexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; + } +} + +declare namespace BABYLON { + class RenderTargetTexture extends Texture { + isCube: boolean; + static _REFRESHRATE_RENDER_ONCE: number; + static _REFRESHRATE_RENDER_ONEVERYFRAME: number; + static _REFRESHRATE_RENDER_ONEVERYTWOFRAMES: number; + static REFRESHRATE_RENDER_ONCE: number; + static REFRESHRATE_RENDER_ONEVERYFRAME: number; + static REFRESHRATE_RENDER_ONEVERYTWOFRAMES: number; + renderList: AbstractMesh[]; + renderParticles: boolean; + renderSprites: boolean; + coordinatesMode: number; + onBeforeRender: (faceIndex: number) => void; + onAfterRender: (faceIndex: number) => void; + onAfterUnbind: () => void; + onClear: (engine: Engine) => void; + activeCamera: Camera; + customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, beforeTransparents?: () => void) => void; + private _size; + _generateMipMaps: boolean; + private _renderingManager; + _waitingRenderList: string[]; + private _doNotChangeAspectRatio; + private _currentRefreshId; + private _refreshRate; + private _textureMatrix; + constructor(name: string, size: any, scene: Scene, generateMipMaps?: boolean, doNotChangeAspectRatio?: boolean, type?: number, isCube?: boolean); + resetRefreshCounter(): void; + refreshRate: number; + _shouldRender(): boolean; + isReady(): boolean; + getRenderSize(): number; + canRescale: boolean; + scale(ratio: number): void; + getReflectionTextureMatrix(): Matrix; + resize(size: any, generateMipMaps?: boolean): void; + render(useCameraPostProcess?: boolean, dumpForDebug?: boolean): void; + renderToTarget(faceIndex: number, currentRenderList: AbstractMesh[], useCameraPostProcess: boolean, dumpForDebug: boolean): void; + clone(): RenderTargetTexture; + serialize(): any; + } +} + +declare namespace BABYLON { + class Texture extends BaseTexture { + static NEAREST_SAMPLINGMODE: number; + static BILINEAR_SAMPLINGMODE: number; + static TRILINEAR_SAMPLINGMODE: number; + static EXPLICIT_MODE: number; + static SPHERICAL_MODE: number; + static PLANAR_MODE: number; + static CUBIC_MODE: number; + static PROJECTION_MODE: number; + static SKYBOX_MODE: number; + static INVCUBIC_MODE: number; + static EQUIRECTANGULAR_MODE: number; + static FIXED_EQUIRECTANGULAR_MODE: number; + static CLAMP_ADDRESSMODE: number; + static WRAP_ADDRESSMODE: number; + static MIRROR_ADDRESSMODE: number; + url: string; + uOffset: number; + vOffset: number; + uScale: number; + vScale: number; + uAng: number; + vAng: number; + wAng: number; + private _noMipmap; + _invertY: boolean; + private _rowGenerationMatrix; + private _cachedTextureMatrix; + private _projectionModeMatrix; + private _t0; + private _t1; + private _t2; + private _cachedUOffset; + private _cachedVOffset; + private _cachedUScale; + private _cachedVScale; + private _cachedUAng; + private _cachedVAng; + private _cachedWAng; + private _cachedCoordinatesMode; + _samplingMode: number; + private _buffer; + private _deleteBuffer; + constructor(url: string, scene: Scene, noMipmap?: boolean, invertY?: boolean, samplingMode?: number, onLoad?: () => void, onError?: () => void, buffer?: any, deleteBuffer?: boolean); + delayLoad(): void; + updateSamplingMode(samplingMode: number): void; + private _prepareRowForTextureGeneration(x, y, z, t); + getTextureMatrix(): Matrix; + getReflectionTextureMatrix(): Matrix; + clone(): Texture; + serialize(): any; + static CreateFromBase64String(data: string, name: string, scene: Scene, noMipmap?: boolean, invertY?: boolean, samplingMode?: number, onLoad?: () => void, onError?: () => void): Texture; + static Parse(parsedTexture: any, scene: Scene, rootUrl: string): BaseTexture; + } +} + +declare namespace BABYLON { + class VideoTexture extends Texture { + video: HTMLVideoElement; + private _autoLaunch; + private _lastUpdate; + constructor(name: string, urls: string[], scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number); + update(): boolean; + } +} + +declare namespace BABYLON { + class CannonJSPlugin implements IPhysicsEnginePlugin { + private _useDeltaForWorldStep; + private _world; + private _registeredMeshes; + private _physicsMaterials; + private _gravity; + private _fixedTimeStep; + name: string; + constructor(_useDeltaForWorldStep?: boolean); + initialize(iterations?: number): void; + private _checkWithEpsilon(value); + runOneStep(delta: number): void; + setGravity(gravity: Vector3): void; + getGravity(): Vector3; + registerMesh(mesh: AbstractMesh, impostor: number, options?: PhysicsBodyCreationOptions): any; + private _createShape(mesh, impostor); + private _createConvexPolyhedron(rawVerts, rawFaces, mesh); + private _createHeightmap(mesh, pointDepth?); + private _addMaterial(friction, restitution); + private _createRigidBodyFromShape(shape, mesh, options); + registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any; + private _unbindBody(body); + unregisterMesh(mesh: AbstractMesh): void; + applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void; + updateBodyPosition: (mesh: AbstractMesh) => void; + createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3): boolean; + dispose(): void; + isSupported(): boolean; + getWorldObject(): any; + getPhysicsBodyOfMesh(mesh: AbstractMesh): any; + } +} + +declare namespace BABYLON { + class OimoJSPlugin implements IPhysicsEnginePlugin { + private _world; + private _registeredMeshes; + name: string; + private _gravity; + private _checkWithEpsilon(value); + initialize(iterations?: number): void; + setGravity(gravity: Vector3): void; + getGravity(): Vector3; + registerMesh(mesh: AbstractMesh, impostor: number, options: PhysicsBodyCreationOptions): any; + registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any; + private _createBodyAsCompound(part, options, initialMesh); + unregisterMesh(mesh: AbstractMesh): void; + private _unbindBody(body); + /** + * Update the body position according to the mesh position + * @param mesh + */ + updateBodyPosition: (mesh: AbstractMesh) => void; + applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void; + createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3, options?: any): boolean; + dispose(): void; + isSupported(): boolean; + getWorldObject(): any; + getPhysicsBodyOfMesh(mesh: AbstractMesh): any; + private _getLastShape(body); + runOneStep(time: number): void; + } +} + +declare namespace BABYLON { + class PostProcessRenderEffect { + private _engine; + private _postProcesses; + private _getPostProcess; + private _singleInstance; + private _cameras; + private _indicesForCamera; + private _renderPasses; + private _renderEffectAsPasses; + _name: string; + applyParameters: (postProcess: PostProcess) => void; + constructor(engine: Engine, name: string, getPostProcess: () => PostProcess, singleInstance?: boolean); + isSupported: boolean; + _update(): void; + addPass(renderPass: PostProcessRenderPass): void; + removePass(renderPass: PostProcessRenderPass): void; + addRenderEffectAsPass(renderEffect: PostProcessRenderEffect): void; + getPass(passName: string): void; + emptyPasses(): void; + _attachCameras(cameras: Camera): any; + _attachCameras(cameras: Camera[]): any; + _detachCameras(cameras: Camera): any; + _detachCameras(cameras: Camera[]): any; + _enable(cameras: Camera): any; + _enable(cameras: Camera[]): any; + _disable(cameras: Camera): any; + _disable(cameras: Camera[]): any; + getPostProcess(camera?: Camera): PostProcess; + private _linkParameters(); + private _linkTextures(effect); + } +} + +declare namespace BABYLON { + class PostProcessRenderPass { + private _enabled; + private _renderList; + private _renderTexture; + private _scene; + private _refCount; + _name: string; + constructor(scene: Scene, name: string, size: number, renderList: Mesh[], beforeRender: () => void, afterRender: () => void); + _incRefCount(): number; + _decRefCount(): number; + _update(): void; + setRenderList(renderList: Mesh[]): void; + getRenderTexture(): RenderTargetTexture; + } +} + +declare namespace BABYLON { + class PostProcessRenderPipeline { + private _engine; + private _renderEffects; + private _renderEffectsForIsolatedPass; + private _cameras; + _name: string; + private static PASS_EFFECT_NAME; + private static PASS_SAMPLER_NAME; + constructor(engine: Engine, name: string); + isSupported: boolean; + addEffect(renderEffect: PostProcessRenderEffect): void; + _enableEffect(renderEffectName: string, cameras: Camera): any; + _enableEffect(renderEffectName: string, cameras: Camera[]): any; + _disableEffect(renderEffectName: string, cameras: Camera): any; + _disableEffect(renderEffectName: string, cameras: Camera[]): any; + _attachCameras(cameras: Camera, unique: boolean): any; + _attachCameras(cameras: Camera[], unique: boolean): any; + _detachCameras(cameras: Camera): any; + _detachCameras(cameras: Camera[]): any; + _enableDisplayOnlyPass(passName: any, cameras: Camera): any; + _enableDisplayOnlyPass(passName: any, cameras: Camera[]): any; + _disableDisplayOnlyPass(cameras: Camera): any; + _disableDisplayOnlyPass(cameras: Camera[]): any; + _update(): void; + dispose(): void; + } +} + +declare namespace BABYLON { + class PostProcessRenderPipelineManager { + private _renderPipelines; + constructor(); + addPipeline(renderPipeline: PostProcessRenderPipeline): void; + attachCamerasToRenderPipeline(renderPipelineName: string, cameras: Camera, unique?: boolean): any; + attachCamerasToRenderPipeline(renderPipelineName: string, cameras: Camera[], unique?: boolean): any; + detachCamerasFromRenderPipeline(renderPipelineName: string, cameras: Camera): any; + detachCamerasFromRenderPipeline(renderPipelineName: string, cameras: Camera[]): any; + enableEffectInPipeline(renderPipelineName: string, renderEffectName: string, cameras: Camera): any; + enableEffectInPipeline(renderPipelineName: string, renderEffectName: string, cameras: Camera[]): any; + disableEffectInPipeline(renderPipelineName: string, renderEffectName: string, cameras: Camera): any; + disableEffectInPipeline(renderPipelineName: string, renderEffectName: string, cameras: Camera[]): any; + enableDisplayOnlyPassInPipeline(renderPipelineName: string, passName: string, cameras: Camera): any; + enableDisplayOnlyPassInPipeline(renderPipelineName: string, passName: string, cameras: Camera[]): any; + disableDisplayOnlyPassInPipeline(renderPipelineName: string, cameras: Camera): any; + disableDisplayOnlyPassInPipeline(renderPipelineName: string, cameras: Camera[]): any; + update(): void; + } +} + +declare namespace BABYLON { + class CustomProceduralTexture extends ProceduralTexture { + private _animate; + private _time; + private _config; + private _texturePath; + constructor(name: string, texturePath: any, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); + private loadJson(jsonUrl); + isReady(): boolean; + render(useCameraPostProcess?: boolean): void; + updateTextures(): void; + updateShaderUniforms(): void; + animate: boolean; + } +} + +declare namespace BABYLON { + class ProceduralTexture extends Texture { + isCube: boolean; + private _size; + _generateMipMaps: boolean; + isEnabled: boolean; + private _doNotChangeAspectRatio; + private _currentRefreshId; + private _refreshRate; + onGenerated: () => void; + private _vertexBuffer; + private _indexBuffer; + private _effect; + private _vertexDeclaration; + private _vertexStrideSize; + private _uniforms; + private _samplers; + private _fragment; + _textures: Texture[]; + private _floats; + private _floatsArrays; + private _colors3; + private _colors4; + private _vectors2; + private _vectors3; + private _matrices; + private _fallbackTexture; + private _fallbackTextureUsed; + constructor(name: string, size: any, fragment: any, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean, isCube?: boolean); + reset(): void; + isReady(): boolean; + resetRefreshCounter(): void; + setFragment(fragment: any): void; + refreshRate: number; + _shouldRender(): boolean; + getRenderSize(): number; + resize(size: any, generateMipMaps: any): void; + private _checkUniform(uniformName); + setTexture(name: string, texture: Texture): ProceduralTexture; + setFloat(name: string, value: number): ProceduralTexture; + setFloats(name: string, value: number[]): ProceduralTexture; + setColor3(name: string, value: Color3): ProceduralTexture; + setColor4(name: string, value: Color4): ProceduralTexture; + setVector2(name: string, value: Vector2): ProceduralTexture; + setVector3(name: string, value: Vector3): ProceduralTexture; + setMatrix(name: string, value: Matrix): ProceduralTexture; + render(useCameraPostProcess?: boolean): void; + clone(): ProceduralTexture; + dispose(): void; + } +} diff --git a/babylonjs/tsconfig.json b/babylonjs/tsconfig.json new file mode 100644 index 0000000000..c4a777d01c --- /dev/null +++ b/babylonjs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "babylon-tests.ts" + ] +} \ No newline at end of file diff --git a/babyparse/babyparse-tests.ts b/babyparse/babyparse-tests.ts index 29d2d22891..65d798845c 100644 --- a/babyparse/babyparse-tests.ts +++ b/babyparse/babyparse-tests.ts @@ -1,4 +1,4 @@ -/// + import * as Baby from "babyparse"; var RECORD_SEP = String.fromCharCode(30); diff --git a/babyparse/babyparse.d.ts b/babyparse/index.d.ts similarity index 100% rename from babyparse/babyparse.d.ts rename to babyparse/index.d.ts diff --git a/babyparse/tsconfig.json b/babyparse/tsconfig.json new file mode 100644 index 0000000000..eccc8cd69a --- /dev/null +++ b/babyparse/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "babyparse-tests.ts" + ] +} \ No newline at end of file diff --git a/backbone-associations/backbone-associations-tests.ts b/backbone-associations/backbone-associations-tests.ts index 36dc6cbe87..eebd48895d 100644 --- a/backbone-associations/backbone-associations-tests.ts +++ b/backbone-associations/backbone-associations-tests.ts @@ -1,9 +1,9 @@ -/// -/// - // borrowed from the Backbone.Associations tutorials // separated out into modules to avoid namespace clashes -namespace Backbone.Associations.Tests { + +import * as Backbone from 'backbone'; + +namespace BackboneAssociationsTests { namespace OneToOne { class EmployeeWithManager extends Backbone.AssociatedModel { constructor(options?) { diff --git a/backbone-associations/backbone-associations-tests.ts.tscparams b/backbone-associations/backbone-associations-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/backbone-associations/backbone-associations-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/backbone-associations/backbone-associations.d.ts b/backbone-associations/backbone-associations.d.ts deleted file mode 100644 index c093c01854..0000000000 --- a/backbone-associations/backbone-associations.d.ts +++ /dev/null @@ -1,75 +0,0 @@ -// Type definitions for Backbone-associations 0.6.4 -// Project: https://github.com/dhruvaray/backbone-associations/ -// Definitions by: Craig Brett -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Backbone { - export module Associations { - /** Defines a 1:Many relationship type */ - export var Many: string; - /** Defines a 1:1 relationship type */ - export var One: string; - /** Defines a special relationship to itself */ - export var Self: string; - - // these seem to be used internally, but can't see a reason not to include them just in case - export var SEPARATOR: string; - export function getSeparator(): any; - export function setSeparator(value: any): void; - export var EVENTS_BUBBLE: boolean; - export var EVENTS_WILDCARD: boolean; - export var EVENTS_NC: boolean; - - interface IRelation { - /** The type of model for this relationship */ - relatedModel: string|typeof Backbone.Associations.AssociatedModel; - /** The key for this relationship on this model */ - key: string; - // meh, no string enums in TS. Just have to trust the user not to be a fool - /** The cardinality of this relationship. */ - type: string; - /** Determines the type of collection used. If used, the relatedModel property is ignored */ - collectionType?: typeof Backbone.Collection|string; - /** If set to true, then the attribute will not be serialized in toJSON() calls. Defaults to false */ - isTransient?: boolean; - /** Specify remoteKey to serialize the key to a different key name in toJSON() calls. Useful in ROR nested-attributes like scenarios. */ - remoteKey?: string; - /** the attributes to serialize when calling toJSON */ - serialize?: string[]; - /** A transformation function to convert the value before it is assigned to the key on the relatedModel */ - map?: (...args: any[]) => any; - } - - /** A Backbone model with special provision for handling relations to other models */ - export class AssociatedModel extends Backbone.Model { - /** Relations with their associated model */ - relations: IRelation[]; - _proxyCalls: any; - /** Reverse association lookup for objects that contain this object */ - parents: any[]; - /** Cleans up any parent relations on other AssociatedModels */ - cleanup(): void; - } - } - // copies of properties also put onto the Backbone scope - /** Defines a 1:Many relationship type */ - export var Many: string; - /** Defines a 1:1 relationship type */ - export var One: string; - /** Defines a special relationship to itself */ - export var Self: string; - - // I'm sure this should be doable with imports or type aliases, but doesn't seem to work - /** A Backbone model with special provision for handling relations to other models */ - export class AssociatedModel extends Backbone.Model { - /** Relations with their associated model */ - relations: Associations.IRelation[]; - _proxyCalls: any; - /** Reverse association lookup for objects that contain this object */ - parents: any[]; - /** Cleans up any parent relations on other AssociatedModels */ - cleanup(): void; - } -} diff --git a/backbone-associations/index.d.ts b/backbone-associations/index.d.ts new file mode 100644 index 0000000000..84532c482d --- /dev/null +++ b/backbone-associations/index.d.ts @@ -0,0 +1,75 @@ +// Type definitions for Backbone-associations 0.6.4 +// Project: https://github.com/dhruvaray/backbone-associations/ +// Definitions by: Craig Brett +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Backbone from 'backbone'; + +declare module 'backbone' { + export module Associations { + /** Defines a 1:Many relationship type */ + export var Many: string; + /** Defines a 1:1 relationship type */ + export var One: string; + /** Defines a special relationship to itself */ + export var Self: string; + + // these seem to be used internally, but can't see a reason not to include them just in case + export var SEPARATOR: string; + export function getSeparator(): any; + export function setSeparator(value: any): void; + export var EVENTS_BUBBLE: boolean; + export var EVENTS_WILDCARD: boolean; + export var EVENTS_NC: boolean; + + interface IRelation { + /** The type of model for this relationship */ + relatedModel: string|typeof Backbone.Associations.AssociatedModel; + /** The key for this relationship on this model */ + key: string; + // meh, no string enums in TS. Just have to trust the user not to be a fool + /** The cardinality of this relationship. */ + type: string; + /** Determines the type of collection used. If used, the relatedModel property is ignored */ + collectionType?: typeof Backbone.Collection|string; + /** If set to true, then the attribute will not be serialized in toJSON() calls. Defaults to false */ + isTransient?: boolean; + /** Specify remoteKey to serialize the key to a different key name in toJSON() calls. Useful in ROR nested-attributes like scenarios. */ + remoteKey?: string; + /** the attributes to serialize when calling toJSON */ + serialize?: string[]; + /** A transformation function to convert the value before it is assigned to the key on the relatedModel */ + map?: (...args: any[]) => any; + } + + /** A Backbone model with special provision for handling relations to other models */ + export class AssociatedModel extends Backbone.Model { + /** Relations with their associated model */ + relations: IRelation[]; + _proxyCalls: any; + /** Reverse association lookup for objects that contain this object */ + parents: any[]; + /** Cleans up any parent relations on other AssociatedModels */ + cleanup(): void; + } + } + // copies of properties also put onto the Backbone scope + /** Defines a 1:Many relationship type */ + export var Many: string; + /** Defines a 1:1 relationship type */ + export var One: string; + /** Defines a special relationship to itself */ + export var Self: string; + + // I'm sure this should be doable with imports or type aliases, but doesn't seem to work + /** A Backbone model with special provision for handling relations to other models */ + export class AssociatedModel extends Backbone.Model { + /** Relations with their associated model */ + relations: Associations.IRelation[]; + _proxyCalls: any; + /** Reverse association lookup for objects that contain this object */ + parents: any[]; + /** Cleans up any parent relations on other AssociatedModels */ + cleanup(): void; + } +} diff --git a/backbone-associations/tsconfig.json b/backbone-associations/tsconfig.json new file mode 100644 index 0000000000..3b603741a5 --- /dev/null +++ b/backbone-associations/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "backbone-associations-tests.ts" + ] +} \ No newline at end of file diff --git a/backbone-relational/backbone-relational-tests.ts b/backbone-relational/backbone-relational-tests.ts index a642c66716..90433cd153 100644 --- a/backbone-relational/backbone-relational-tests.ts +++ b/backbone-relational/backbone-relational-tests.ts @@ -1,6 +1,4 @@ -/// -/// -/// +import * as Backbone from 'backbone'; class House extends Backbone.RelationalModel { // The 'relations' property, on the House's prototype. Initialized separately for each diff --git a/backbone-relational/backbone-relational-tests.ts.tscparams b/backbone-relational/backbone-relational-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/backbone-relational/backbone-relational-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/backbone-relational/backbone-relational.d.ts b/backbone-relational/backbone-relational.d.ts deleted file mode 100644 index d51991e55d..0000000000 --- a/backbone-relational/backbone-relational.d.ts +++ /dev/null @@ -1,172 +0,0 @@ -// Type definitions for Backbone-relational 0.8.5 -// Project: http://backbonerelational.org/ -// Definitions by: Eirik Hoem -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -/// -/// - -declare namespace Backbone { - class RelationalModel extends Model { - /** - * Do not use, prefer TypeScript's extend functionality. - **/ - //private static extend(properties:any, classProperties?:any):any; - - relations:any; - subModelTypes:any; - subModelTypeAttribute:any; - - - initializeRelations(options:any):void; - - updateRelations(options:any):void; - - queue(func:any):void; - - processQueue():void; - - getRelation(name:string):Relation; - - getRelations():Relation[]; - - fetchRelated(key:string, options?:any, update?:boolean):any; - - toJSON():any; - - static setup(); - - static build(attributes:any, options?:any); - - static findOrCreate(attributes:string, options?:any); - - static findOrCreate(attributes:number, options?:any); - - static findOrCreate(attributes:any, options?:any); - } - - export class Relation extends Model { - - options:any; - instance:any; - key:any; - keyContents:any; - relatedModel:any; - relatedCollection:any; - reverseRelation:any; - related:any; - - checkPreconditions():boolean; - - setRelated(related:Model):void; - - setRelated(related:Collection):void; - - getReverseRelations(model:RelationalModel):Relation; - - destroy():void; - } - - export class HasOne extends Relation { - collectionType:any; - - findRelated(options:any):Model; - - setKeyContents(keyContents:string):void; - - setKeyContents(keyContents:string[]):void; - - setKeyContents(keyContents:number):void; - - setKeyContents(keyContents:number[]):void; - - setKeyContents(keyContents:Collection):void; - - onChange(model:Model, attr:any, options:any):void; - - handleAddition(model:Model, coll:Collection, options:any):void; - - handleRemoval(model:Model, coll:Collection, options:any):void; - - handleReset(coll:Collection, options:any):void; - - tryAddRelated(model:Model, coll:any, options:any):void; - - addRelated(model:Model, options:any):void; - - removeRelated(model:Model, coll:any, options:any):void; - - } - - - export class HasMany extends Relation { - collectionType:any; - - findRelated(options:any):Model; - - setKeyContents(keyContents:string):void; - - setKeyContents(keyContents:number):void; - - setKeyContents(keyContents:Model):void; - - onChange(model:Model, attr:any, options:any):void; - - tryAddRelated(model:Model, coll:any, options:any):void; - - addRelated(model:Model, options:any):void; - - removeRelated(model:Model, coll:any, options:any):void; - - } - - export class Store extends Events { - initializeRelation(model, relation, options); - - addModelScope(scope:any):void; - - removeModelScope(scope):void; - - addSubModels(subModelTypes:RelationalModel, superModelType:RelationalModel):void; - - setupSuperModel(modelType:RelationalModel):void; - - addReverseRelation(relation:any):void; - - addOrphanRelation(relation:any):void; - - processOrphanRelations():void; - - retroFitRelation(relation:RelationalModel, create:boolean):Collection; - - getCollection(type:RelationalModel, create:boolean):Collection; - - getObjectByName(name:string):any; - - - resolveIdForItem(type:any, item:any):any; - - static find(type:any, item:string):RelationalModel; - - static find(type:any, item:number):RelationalModel; - - static find(type:any, item:RelationalModel):RelationalModel; - - static find(type:any, item:any):RelationalModel; - - register(model:RelationalModel):void; - - checkId(model:RelationalModel, id:any):void; - - update(model:RelationalModel):void; - - unregister(model:RelationalModel, collection:Collection, options:any):void; - - reset():void; - - - } - -} - diff --git a/backbone-relational/backbone-relational.d.ts.tscparams b/backbone-relational/backbone-relational.d.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/backbone-relational/backbone-relational.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/backbone-relational/index.d.ts b/backbone-relational/index.d.ts new file mode 100644 index 0000000000..f985a52d8f --- /dev/null +++ b/backbone-relational/index.d.ts @@ -0,0 +1,172 @@ +// Type definitions for Backbone-relational 0.8.5 +// Project: http://backbonerelational.org/ +// Definitions by: Eirik Hoem +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as Backbone from 'backbone'; + +declare module 'backbone' { + class RelationalModel extends Model { + /** + * Do not use, prefer TypeScript's extend functionality. + **/ + //private static extend(properties:any, classProperties?:any):any; + + relations:any; + subModelTypes:any; + subModelTypeAttribute:any; + + + initializeRelations(options:any):void; + + updateRelations(options:any):void; + + queue(func:any):void; + + processQueue():void; + + getRelation(name:string):Relation; + + getRelations():Relation[]; + + fetchRelated(key:string, options?:any, update?:boolean):any; + + toJSON():any; + + static setup(); + + static build(attributes:any, options?:any); + + static findOrCreate(attributes:string, options?:any); + + static findOrCreate(attributes:number, options?:any); + + static findOrCreate(attributes:any, options?:any); + } + + export class Relation extends Model { + + options:any; + instance:any; + key:any; + keyContents:any; + relatedModel:any; + relatedCollection:any; + reverseRelation:any; + related:any; + + checkPreconditions():boolean; + + setRelated(related:Model):void; + + setRelated(related:Collection):void; + + getReverseRelations(model:RelationalModel):Relation; + + destroy():void; + } + + export class HasOne extends Relation { + collectionType:any; + + findRelated(options:any):Model; + + setKeyContents(keyContents:string):void; + + setKeyContents(keyContents:string[]):void; + + setKeyContents(keyContents:number):void; + + setKeyContents(keyContents:number[]):void; + + setKeyContents(keyContents:Collection):void; + + onChange(model:Model, attr:any, options:any):void; + + handleAddition(model:Model, coll:Collection, options:any):void; + + handleRemoval(model:Model, coll:Collection, options:any):void; + + handleReset(coll:Collection, options:any):void; + + tryAddRelated(model:Model, coll:any, options:any):void; + + addRelated(model:Model, options:any):void; + + removeRelated(model:Model, coll:any, options:any):void; + + } + + + export class HasMany extends Relation { + collectionType:any; + + findRelated(options:any):Model; + + setKeyContents(keyContents:string):void; + + setKeyContents(keyContents:number):void; + + setKeyContents(keyContents:Model):void; + + onChange(model:Model, attr:any, options:any):void; + + tryAddRelated(model:Model, coll:any, options:any):void; + + addRelated(model:Model, options:any):void; + + removeRelated(model:Model, coll:any, options:any):void; + + } + + export class Store extends Events { + initializeRelation(model, relation, options); + + addModelScope(scope:any):void; + + removeModelScope(scope):void; + + addSubModels(subModelTypes:RelationalModel, superModelType:RelationalModel):void; + + setupSuperModel(modelType:RelationalModel):void; + + addReverseRelation(relation:any):void; + + addOrphanRelation(relation:any):void; + + processOrphanRelations():void; + + retroFitRelation(relation:RelationalModel, create:boolean):Collection; + + getCollection(type:RelationalModel, create:boolean):Collection; + + getObjectByName(name:string):any; + + + resolveIdForItem(type:any, item:any):any; + + static find(type:any, item:string):RelationalModel; + + static find(type:any, item:number):RelationalModel; + + static find(type:any, item:RelationalModel):RelationalModel; + + static find(type:any, item:any):RelationalModel; + + register(model:RelationalModel):void; + + checkId(model:RelationalModel, id:any):void; + + update(model:RelationalModel):void; + + unregister(model:RelationalModel, collection:Collection, options:any):void; + + reset():void; + + + } + +} + diff --git a/backbone-relational/tsconfig.json b/backbone-relational/tsconfig.json new file mode 100644 index 0000000000..20a9ccb3a0 --- /dev/null +++ b/backbone-relational/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "backbone-relational-tests.ts" + ] +} \ No newline at end of file diff --git a/backbone.layoutmanager/backbone.layoutmanager-tests.ts b/backbone.layoutmanager/backbone.layoutmanager-tests.ts index 93c87cf197..fe11ce9b18 100644 --- a/backbone.layoutmanager/backbone.layoutmanager-tests.ts +++ b/backbone.layoutmanager/backbone.layoutmanager-tests.ts @@ -1,6 +1,6 @@ -/// -/// -/// +/// + +import * as Backbone from 'backbone'; // Example code. class DisplayView extends Backbone.View { diff --git a/backbone.layoutmanager/backbone.layoutmanager.d.ts b/backbone.layoutmanager/backbone.layoutmanager.d.ts deleted file mode 100644 index 2051458367..0000000000 --- a/backbone.layoutmanager/backbone.layoutmanager.d.ts +++ /dev/null @@ -1,57 +0,0 @@ -// Type definitions for Backbone.LayoutManager 0.9.5 -// Project: http://layoutmanager.org/ -// Definitions by: He Jiang -// Definitions: https://github.com/hejiang2000/DefinitelyTyped - -/// -/// -/// - -declare namespace Backbone { - - interface LayoutOptions extends ViewOptions { - template?: string; - views?: { [viewName: string]: View }; - } - - interface LayoutManagerOptions { - manage?: boolean; - el?: boolean; - } - - class Layout extends View { - template: string; - constructor(options?: LayoutOptions); - - beforeRender(): void; - afterRender(): void; - cleanup(): void; - - fetchTemplate(path: string): (context:any)=>string; - async():(compiled:(context:any)=>void)=>void; - promise(): JQueryPromise; - - getAllOptions(): LayoutOptions; - - getView(fn?:any): any; - getViews(fn?:any): any[]; - - insertView(selector:any, view?:any): any; // return view; - insertViews(views:any): Layout; // return this; - - remove(): Layout; - removeView(fn:any): Layout; - - render(): Layout; // return this - renderViews(): Layout; // return this - setView(name: any, view: U, insert?:boolean): U; // return view - setViews(views:any): Layout; // return this - then(fn:()=>void):void; - - static cache(path: string, contents?: any): any; - static cleanViews(views: any): void; - static configure(options: LayoutManagerOptions): void; - static setupView(views: any, options?: LayoutOptions): void; - } -} - diff --git a/backbone.layoutmanager/index.d.ts b/backbone.layoutmanager/index.d.ts new file mode 100644 index 0000000000..a5c469eb1b --- /dev/null +++ b/backbone.layoutmanager/index.d.ts @@ -0,0 +1,56 @@ +// Type definitions for Backbone.LayoutManager 0.9.5 +// Project: http://layoutmanager.org/ +// Definitions by: He Jiang +// Definitions: https://github.com/hejiang2000/DefinitelyTyped + +/// + +import * as Backbone from 'backbone'; + +declare module 'backbone' { + interface LayoutOptions extends ViewOptions { + template?: string; + views?: { [viewName: string]: View }; + } + + interface LayoutManagerOptions { + manage?: boolean; + el?: boolean; + } + + class Layout extends View { + template: string; + constructor(options?: LayoutOptions); + + beforeRender(): void; + afterRender(): void; + cleanup(): void; + + fetchTemplate(path: string): (context:any)=>string; + async():(compiled:(context:any)=>void)=>void; + promise(): JQueryPromise; + + getAllOptions(): LayoutOptions; + + getView(fn?:any): any; + getViews(fn?:any): any[]; + + insertView(selector:any, view?:any): any; // return view; + insertViews(views:any): Layout; // return this; + + remove(): Layout; + removeView(fn:any): Layout; + + render(): Layout; // return this + renderViews(): Layout; // return this + setView(name: any, view: U, insert?:boolean): U; // return view + setViews(views:any): Layout; // return this + then(fn:()=>void):void; + + static cache(path: string, contents?: any): any; + static cleanViews(views: any): void; + static configure(options: LayoutManagerOptions): void; + static setupView(views: any, options?: LayoutOptions): void; + } +} + diff --git a/backbone.layoutmanager/tsconfig.json b/backbone.layoutmanager/tsconfig.json new file mode 100644 index 0000000000..f287941417 --- /dev/null +++ b/backbone.layoutmanager/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "backbone.layoutmanager-tests.ts" + ] +} \ No newline at end of file diff --git a/backbone.localstorage/backbone.localstorage-tests.ts b/backbone.localstorage/backbone.localstorage-tests.ts index 0d44897a80..20ab8ba80a 100644 --- a/backbone.localstorage/backbone.localstorage-tests.ts +++ b/backbone.localstorage/backbone.localstorage-tests.ts @@ -1,5 +1,3 @@ -/// - var store: Store = new Store('testStore'); store.findAll(); diff --git a/backbone.localstorage/backbone.localstorage.d.ts b/backbone.localstorage/backbone.localstorage.d.ts deleted file mode 100644 index 25c9e4cb72..0000000000 --- a/backbone.localstorage/backbone.localstorage.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -// Type definitions for backbone.localStorage 1.0.0 -// Project: https://github.com/jeromegn/Backbone.localStorage -// Definitions by: Louis Grignon -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Backbone { - interface Serializer { - serialize(item: any): any; - deserialize(data: any): any; - } - - class LocalStorage { - name: string; - serializer: Serializer; - records: string[]; - - constructor(name: string, serializer?: Serializer); - - save(): void; - - // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already - // have an id of it's own. - create(model: any): any; - - // Update a model by replacing its copy in `this.data`. - update(model: any): any; - - // Retrieve a model from `this.data` by id. - find(model: any): any; - - // Return the array of all models currently in storage. - findAll(): any; - - // Delete a model from `this.data`, returning it. - destroy(model: T): T; - - localStorage(): any; - - // Clear localStorage for specific collection. - _clear(): void; - - _storageSize(): number; - - _itemName(id: any): string; - } -} - -import Store = Backbone.LocalStorage; - diff --git a/backbone.localstorage/index.d.ts b/backbone.localstorage/index.d.ts new file mode 100644 index 0000000000..d08d546ec2 --- /dev/null +++ b/backbone.localstorage/index.d.ts @@ -0,0 +1,55 @@ +// Type definitions for backbone.localStorage 1.0.0 +// Project: https://github.com/jeromegn/Backbone.localStorage +// Definitions by: Louis Grignon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Backbone from 'backbone'; + +declare global { + const Store: typeof Backbone.LocalStorage; + type Store = Backbone.LocalStorage; +} + +declare module 'backbone' { + interface Serializer { + serialize(item: any): any; + deserialize(data: any): any; + } + + class LocalStorage { + name: string; + serializer: Serializer; + records: string[]; + + constructor(name: string, serializer?: Serializer); + + save(): void; + + // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already + // have an id of it's own. + create(model: any): any; + + // Update a model by replacing its copy in `this.data`. + update(model: any): any; + + // Retrieve a model from `this.data` by id. + find(model: any): any; + + // Return the array of all models currently in storage. + findAll(): any; + + // Delete a model from `this.data`, returning it. + destroy(model: T): T; + + localStorage(): any; + + // Clear localStorage for specific collection. + _clear(): void; + + _storageSize(): number; + + _itemName(id: any): string; + } +} + + diff --git a/backbone.localstorage/tsconfig.json b/backbone.localstorage/tsconfig.json new file mode 100644 index 0000000000..0eabeb7dca --- /dev/null +++ b/backbone.localstorage/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "backbone.localstorage-tests.ts" + ] +} \ No newline at end of file diff --git a/backbone.marionette/index.d.ts b/backbone.marionette/index.d.ts new file mode 100644 index 0000000000..fd49a89cc1 --- /dev/null +++ b/backbone.marionette/index.d.ts @@ -0,0 +1,1508 @@ +// Type definitions for Marionette +// Project: https://github.com/marionettejs/ +// Definitions by: Zeeshan Hamid , Natan Vivo , Sven Tschui +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Backbone from 'backbone'; + +export as namespace Marionette; +export = Marionette; + +// declarations for Backbone.BabySitter and Backbone.Wreqr, different projects but included in MarionetteJS +declare module 'backbone' { + // Backbone.BabySitter + class ChildViewContainer> { + + constructor(initialViews?: any[]); + + add(view: TView, customIndex?: number): void; + findByModel(model: TModel): TView; + findByModelCid(modelCid: string): TView; + findByCustom(index: number): TView; + findByIndex(index: number): TView; + findByCid(cid: string): TView; + remove(view: TView): void; + call(method: any): void; + apply(method: any, args?: any[]): void; + + //mixins from Collection (copied from Backbone's Collection declaration) + + all(iterator: (element: TView, index: number) => boolean, context?: any): boolean; + any(iterator: (element: TView, index: number) => boolean, context?: any): boolean; + contains(value: any): boolean; + detect(iterator: (item: any) => boolean, context?: any): any; + each(iterator: (element: TView, index: number, list?: any) => void, context?: any): any; + every(iterator: (element: TView, index: number) => boolean, context?: any): boolean; + filter(iterator: (element: TView, index: number) => boolean, context?: any): TView[]; + find(iterator: (element: TView, index: number) => boolean, context?: any): TView; + first(): TView; + forEach(iterator: (element: TView, index: number, list?: any) => void, context?: any): void; + include(value: any): boolean; + initial(): TView; + initial(n: number): TView[]; + invoke(methodName: string, args?: any[]): any; + isEmpty(object: any): boolean; + last(): TView; + last(n: number): TView[]; + lastIndexOf(element: TView, fromIndex?: number): number; + map(iterator: (element: TView, index: number, context?: any) => U, context?: any): U[]; + pluck(attribute: string): any[]; + reject(iterator: (element: TView, index: number) => boolean, context?: any): TView[]; + rest(): TView; + rest(n: number): TView[]; + select(iterator: any, context?: any): any[]; + some(iterator: (element: TView, index: number) => boolean, context?: any): boolean; + toArray(): any[]; + without(...values: any[]): TView[]; + } + + // Backbone.Wreqr + namespace Wreqr { + + namespace radio { + + function channel(channelName: string): Channel; + + } + + class Channel { + + constructor(channelName: string); + + vent: Backbone.Wreqr.EventAggregator; + reqres: Backbone.Wreqr.RequestResponse; + commands: Backbone.Wreqr.Commands; + channelName: string; + + reset(): Channel; + connectEvents(hash: string, context: any): Channel; + connectCommands(hash: string, context: any): Channel; + connectRequests(hash: string, context: any): Channel; + + } + + class Handlers extends Backbone.Events { + + constructor(options?: any); + + options: any; + + setHandler(name: string, handler: any, context?: any): void; + hasHandler(name: string): boolean; + getHandler(name: string): Function; + removeHandler(name: string): void; + removeAllHandlers(): void; + } + + class CommandStorage { + + constructor(options?: any); + + getCommands(commandName: string): Commands; + addCommand(commandName: string, args: any): void; + clearCommands(commandName: string): void; + } + + class Commands extends Handlers { + + constructor(options?: any); + + storageType: CommandStorage; + execute(name: string, ...args: any[]): void; + } + + class RequestResponse extends Handlers { + + constructor(options?: any); + + request(...args: any[]): any; + } + + class EventAggregator extends Backbone.Events { + + constructor(options?: any); + } + } +} + +declare namespace Marionette { + + /** + * Retrieve an object's attribute either directly from the object, or + * from the object's this.options, with this.options taking precedence. + */ + function getOption(target: any, optionName: string): any; + + /** + * Trigger an event and a corresponding method on the target object. + * All arguments that are passed to the triggerMethod call are passed along + * to both the event and the method, with the exception of the event name not + * being passed to the corresponding method. + */ + function triggerMethod(name: string, ...args: any[]): any; + + /** + * Invoke triggerMethod on a specific context. + * This is useful when it's not clear that the object has triggerMethod defined. + */ + function triggerMethodOn(ctx: any, name: string, ...args: any[]): any; + + /** + * Monitor a view's state, and after it has been rendered and shown in the DOM, + * trigger a "dom:refresh" event every time it is re-rendered. + */ + function MonitorDOMRefresh(view: Backbone.View): void; + + /** + * This method is used to bind a backbone "entity" (collection/model) to methods on a target object. + * @param target An object that must have a listenTo method from the EventBinder object. + * @param entity The entity (Backbone.Model or Backbone.Collection) to bind the events from. + * @param bindings a hash of { "event:name": "eventHandler" } configuration. Multiple handlers can be separated by a space. A function can be supplied instead of a string handler name. + */ + function bindEntityEvents(target: any, entity: any, bindings: any): void; + + /** + * This method can be used to unbind callbacks from entities' (collection/model) events. It's the opposite of bindEntityEvents + * @param target An object that must have a listenTo method from the EventBinder object. + * @param entity The entity (Backbone.Model or Backbone.Collection) to bind the events from. + * @param bindings a hash of { "event:name": "eventHandler" } configuration. Multiple handlers can be separated by a space. A function can be supplied instead of a string handler name. + */ + function unbindEntityEvents(target: any, entity: any, bindings: any): void; + + class Callbacks { + add(callback: Function, contextOverride: any): void; + run(options: any, context: any): void; + reset(): void; + } + + /** + * A base class which other classes can extend from. Object incorporates many + * backbone conventions and utilities like initialize and Backbone.Events. + */ + class Object extends Backbone.Events { + /** + * Initialize is called immediately after the Object has been instantiated, + * and is invoked with the same arguments that the constructor received. + */ + initialize(options?: any): void; + + /** + * Retrieve an object's attribute either directly from the object, or from + * the object's this.options, with this.options taking precedence. + * @param optionName the name of the option to retrieve. + */ + getOption(optionName: string): any; + + /** + * Objects have a destroy method that unbind the events that are directly + * attached to the instance. Invoking the destroy method will trigger a + * "before:destroy" event and corresponding onBeforeDestroy method call. + * These calls will be passed any arguments destroy was invoked with. + * @param args any arguments to pass to the "before:destory" event and call to + * onBeforeDestroy. + */ + destroy(...args: any[]): void; + } + + /** + * A Controller is an object used in the Marionette Router. Controllers are + * where you store your Router's callbacks. + */ + class Controller extends Backbone.Events { + /** + * @param options Options that should be stored in this options. Can be retreived via + * getOption. + */ + constructor(options?: any); + + /** + * Handles unbinding all of the events that are directly attached to the + * controller instance, as well as those that are bound using the + * EventBinder from the controller. + * + * Invoking the destroy method will trigger the "before:destroy" and + * "destroy" events and the corresponding onBeforeDestory and onDestroy + * method calls. These calls will be passed any arguments destroy was + * invoked with. + */ + destroy(...args: any[]): void; + + /** + * Retrieve an object's attribute either directly from the object, or from + * the object's this.options, with this.options taking precedence. + * @param optionName the name of the option to retrieve. + */ + getOption(optionName: string): any; + + triggerMethod(name: string, ...args: any[]): any; + } + + interface RegionConstructionOptions { + /** + * Specifies the element for the region to manage. This may be + * a selector string, a raw DOM node reference or a jQuery wrapped + * DOM node. + */ + el?: any; + } + + interface RegionShowOptions { + /** + * If you replace the current view with a new view by calling show, by + * default it will automatically destroy the previous view. You can + * prevent this behavior by setting this option to true. + */ + preventDestroy?: boolean; + + /** + * If you re-call show with the same view, by default nothing will happen + * because the view is already in the region. You can force the view to be + * re-shown by setting this option to true. + */ + forceShow?: boolean; + + /** + * Regions that are attached to the document when you execute show are + * special in that the views that they show will also become attached + * to the document. These regions fire a pair of triggerMethods on all + * of the views that are about to be attached � even the nested ones. + * This can cause a performance issue if you're rendering hundreds or + * thousands of views at once. + * If you think these events might be causing some lag in your app, you + * can selectively turn them off with the triggerBeforeAttach + * and triggerAttach properties. + */ + triggerBeforeAttach?: boolean; + + /** + * Regions that are attached to the document when you execute show are + * special in that the views that they show will also become attached + * to the document. These regions fire a pair of triggerMethods on all + * of the views that are about to be attached � even the nested ones. + * This can cause a performance issue if you're rendering hundreds or + * thousands of views at once. + * If you think these events might be causing some lag in your app, you + * can selectively turn them off with the triggerBeforeAttach + * and triggerAttach properties. + */ + triggerAttach?: boolean; + } + + /** + * Regions provide consistent methods to manage, show and destroy views in + * your applications and layouts. They use a jQuery selector to show your + * views in the correct place. + */ + class Region extends Marionette.Object { + + /** + * Build an instance of a region by passing in a configuration object and + * a default region class to use if none is specified in the config. + * The config object should either be a string as a jQuery DOM selector, + * a Region class directly, or an object literal that specifies a selector, + * a custom regionClass, and any options to be supplied to the region + */ + static buildRegion(regionConfig: any, defaultRegionType: any): Region; + + /** + * You can specify an el for the region to manage at the time the region + * is instantiated. + */ + constructor(options?: RegionConstructionOptions); + + /** + * Contains the element that this region should manage. + */ + el: any; + + /** + * Renders and displays the specified view in this region. + * @param view the view to display. + */ + show(view: Backbone.View, options?: RegionShowOptions): void; + + /** + * Attaches an existing view to a region, without rendering or showing the view, + * and without replacing the HTML content of the region. + */ + attachView(view: Backbone.View, options?: RegionShowOptions): any; + + /** + * Override this method to change how the new view is + * appended to the `$el` that the region is managing + */ + attachHtml(view: Backbone.View): void; + + /** + * A region can be reset at any time. This destroys any existing view + * being displayed, and deletes the cached el. The next time the region + * shows a view, the region's el is queried from the DOM. + */ + reset(): any; + + /** + * If you wish to check whether a region has a view, you can use the hasView function. This will return a boolean value depending whether or not the region is showing a view. + */ + hasView(): boolean; + + /** + * Empties the current view from the region. + */ + empty(): any; + + /** + * @returns view that this region has. + */ + currentView: Backbone.View; + } + + interface RegionDefaults { + /** + * A selector string indicating which element to assign the region two. + */ + selector?: string; + + /** + * A selector string, a jQuery object, or an HTML node indicating which element + * the region should use. + */ + el?: any; + + /** + * A custom region class. + */ + regionClass?: any; + + /** + * Ordinarily regions enforce the presence of a backing DOM element. In + * some instances it may be desirable to allow regions to be instantiated + * and used without an element, such as when regions defined by a parent + * LayoutView class are used by only some of its subclasses. In these + * instances, the region can be defined with this option set to true, + * suppressing the missing element error and causing show calls to the + * region to be treated as no-ops. + */ + allowMissingEl?: boolean; + } + + /** + * Region managers provide a consistent way to manage a number of Marionette.Region + * objects within an application. The RegionManager is intended to be used by + * other objects, to facilitate the addition, storage, retrieval, and removal of + * regions from that object. + */ + class RegionManager extends Controller { + + /** + * Constructor. + * @param options May contain an optional `regions` option. These regions + * are passed directly into addRegions for this instance. + */ + constructor(options?: any); + + /** + * Adds one or more regions to this RegionManager instance. + * @param regionDefinitions a function returning an object literal with the region definitions. The function will + * be called with the RegionManager instance context and all the arguments passed to addRegions. + * @param defaults Specifies default options that will be applied to every region added. + * @returns an object literal with all the created regions. + */ + addRegions(regionDefinitions: Function, defaults?: RegionDefaults): any; + + /** + * Adds one or more regions to this RegionManager instance. + * @param regionDefinitions an object literal containing region names as keys and region + * definitions as values. + * @param defaults Specifies default options that will be applied to every region added. + * @returns an object literal with all the created regions. + */ + addRegions(regionDefinitions: { [regionName: string]: any }, defaults?: RegionDefaults): any; + + /** + * Adds a region to this RegionManager. + * @param name the region name. + * @param definition the region definition. This may be a selector, object literal + * with various region creation options or an instance of a region object. + */ + addRegion(name: string, definition: any): Region; + + /** + * Gets the region with the specified name from this RegionManager. + */ + get(name: string): Region; + + /** + * Removes the region with the specified name from this RegionManager. + */ + removeRegion(name: string): void; + + /** + * Removes all regions from the RegionManager. + */ + removeRegions(): void; + + /** + * Empties all regions from the RegionManager instance. + */ + emptyRegions(): void; + + /** + * Destroys the RegionManager instance entierly which both destroys and + * removes all regions from the RegionManager instance. + */ + destroy(): void; + + //mixins from Collection (copied from Backbone's Collection declaration) + + /** + * Returns true if all of the values in the list pass the predicate truth test. + * @alias every + */ + all(iterator: (element: Region, index: number) => boolean, context?: any): boolean; + + /** + * Returns true if any of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a true element is found. + */ + any(iterator: (element: Region, index: number) => boolean, context?: any): boolean; + + /** + * Returns true if the value is present in the list. + * @alias include + */ + contains(value: any): boolean; + + /** + * Looks through each value in the list, returning the first one that passes a truth test (predicate), or undefined if no value passes the test.The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list. + * @alias find + */ + detect(iterator: (item: any) => boolean, context?: any): any; + + /** + * Iterates over the regions in this instance, yielding each in turn to an + * iterator function. The iterator is bound to the context object, if one + * is passed. + * @alias forEach + */ + each(iterator: (element: Region, index: number, list?: any) => void, context?: any): void; + + /** + * Returns true if all of the values in the list pass the predicate truth test. + * @alias all + */ + every(iterator: (element: Region, index: number) => boolean, context?: any): boolean; + + /** + * Looks through each Region in the collection, returning an array of all + * the values that pass a truth test (predicate). + * @alias select + */ + filter(iterator: (element: Region, index: number) => boolean, context?: any): Region[]; + + /** + * Looks through each Region in this instance, returning the first one that passes a truth test (predicate), or undefined if no value passes the test.The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list. + * @alias detect + */ + find(iterator: (element: Region, index: number) => boolean, context?: any): Region; + + /** + * Returns the first Region of this RegionManager. + */ + first(): Region; + + /** + * Returns the first n Regions of this RegionManager. + */ + first(n: number): Region[]; + + /** + * Iterates over the regions in this instance, yielding each in turn to an + * iterator function. The iterator is bound to the context object, if one + * is passed. + * @alias each + */ + forEach(iterator: (element: Region, index: number, list?: any) => void, context?: any): void; + + /** + * Returns true if the value is present in the list. + * @alias contains + */ + include(value: any): boolean; + + /** + * Returns everything but the last n Regions of this instance. + * @param n if specified determines the number of regions to exclude, + * otherwise only the last element is excluded. + */ + initial(n: number): Region[]; + + /** + * Calls the method named by methodName on each value in the collection. Any extra + * arguments passed to invoke will be forwarded on to the method invocation. + */ + invoke(methodName: string, args?: any[]): any; + + /** + * Returns true if the RegionManager contains no regions. + */ + isEmpty(object: any): boolean; + + /** + * Returns the last element of a collection. + */ + last(): Region; + + /** + * Returns the last n elements of the collection. + */ + last(n: number): Region[]; + + /** + * Returns the index of the last occurrence of element in the collection, or -1 if + * element is not present. + * @param fromIndex if specified starts the search at the given index. + */ + lastIndexOf(element: Region, fromIndex?: number): number; + + /** + * Produces a new array of values by mapping each value in the collection through a + * transformation function (iterator). + * @alias collect + */ + map(iterator: (element: Region, index: number, context?: any) => any[], context?: any): any[]; + + /** + * Pluck an attribute from each model in the collection. Equivalent to + * calling map and returning a single attribute from the iterator. + */ + pluck(attribute: string): any[]; + + /** + * Returns the values in the collection without the elements that the truth test + * (predicate) passes. The opposite of filter. + */ + reject(iterator: (element: Region, index: number) => boolean, context?: any): Region[]; + + /** + * Returns the rest of the elements of the collection. + * Pass an index to return the values of the array from that index onward. If not + * specified the first item in the collection is dropped. + * @alias tail, drop + */ + rest(n: number): Region[]; + + /** + * Looks through each value in the collection, returning an array of all + * the values that pass a truth test (predicate). + * @alias filter + */ + select(iterator: any, context?: any): Region[]; + + /** + * Returns true if any of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a true element is found. + * @alias any + */ + some(iterator: (element: Region, index: number) => boolean, context?: any): boolean; + + /** + * Creates an array containing the regions in this instance. + */ + toArray(): Region[]; + + /** + * Returns an array of all the regions in the RegionManager except the ones specified. + */ + without(...values: any[]): Region[]; + } + + /** + * The TemplateCache provides a cache for retrieving templates from script blocks + * in your HTML. This will improve the speed of subsequent calls to get a template. + */ + class TemplateCache { + /** + * To use the TemplateCache, call the get method on TemplateCache directly. Internally, instances of the TemplateCache class will be created and stored but you do not have to manually create these instances yourself. get will return a compiled template function. + */ + static get(templateId: string): any; + + /** + * You can clear one or more, or all items from the cache using the clear + * method. Clearing a template from the cache will force it to re-load + * from the DOM the next time it is retrieved. + * @param the templateId used for loading / caching of the templates to clear. If none specified, all templates will be cleared from the cache. + */ + static clear(...templateId: string[]): void; + + /** + * The default template retrieval is to select the template contents from the + * DOM using jQuery. If you wish to change the way this works, you can + * override this method on the TemplateCache object. + */ + loadTemplate(templateId: string): any; + + /** + * he default template compilation passes the results from loadTemplate to + * the compileTemplate function, which returns an underscore.js compiled + * template function. When overriding compileTemplate remember that it + * must return a function which takes an object of parameters and values + * and returns a formatted HTML string. + */ + compileTemplate(rawTemplate: any): any; + } + + /** + * The Renderer object was extracted from the ItemView rendering process, in + * order to create a consistent and re-usable method of rendering a template + * with or without data. + */ + class Renderer { + /** + * This method returns a string containing the result of applying the + * template using the data object as the context. + * @param template The template to render. If this is a function this is + * treated as a pre-compiled template and does not try to compile it again. This + * allows any view that supports a template parameter to specify a pre-compiled + * template function as the template setting. The template function does not + * have to be any specific template engine. It only needs to be a function + * that returns valid HTML as a string from the data parameter passed to + * the function. + */ + static render(template: any, data: any): string; + } + + /** + * This base view provides some common and core functionality for other views + * to take advantage of. + * Note: The Marionette.View class is not intended to be used directly. It + * exists as a base view for other view classes to be extended from, and to + * provide a common location for behaviors that are shared across all views. + */ + class View extends Backbone.View { + + constructor(options?: Backbone.ViewOptions); + + /** + * Defines behaviors attached to this view. + */ + behaviors: any; + + /** + * Defines `triggers` to forward DOM events to view + * events. `triggers: {"click .foo": "do:foo"}` + */ + triggers:{[key:string]:any}; + + /** + * A configuration hash for models. The left side is the event on + * the model, and the right side is the name of the + * method on the view or a function to handle the event. This property + * can also be a function that returns the hash described above. + */ + modelEvents: any; + + /** + * A configuration hash for collections. The left side is the event on + * the collection, and the right side is the name of the + * method on the view or a function to handle the event. This property + * can also be a function that returns the hash described above. + */ + collectionEvents: any; + + /** + * In several cases you need to access ui elements inside the view to + * retrieve their data or manipulate them. For example you have a certain + * div element you need to show/hide based on some state, or other ui + * element that you wish to set a css class to it. Instead of having + * jQuery selectors hanging around in the view's code you can define a + * ui hash that contains a mapping between the ui element's name and its + * jQuery selector. Afterwards you can simply access it via + * this.ui.elementName. + */ + ui: any; + + /** + * There may be some cases where you need to change the template that is + * used for a view, based on some simple logic such as the value of a + * specific attribute in the view's model. To do this, you can provide a + * getTemplate function on your views and use this to return the template + * that you need. + */ + getTemplate(): any; + + + /** + * Retrieve an object's attribute either directly from the object, or + * from the object's this.options, with this.options taking precedence. + */ + getOption(optionName:string): T; + + mixinTemplateHelpers(target?: any): any; + configureTriggers(): any; + + /** + * View implements a destroy method, which is called by the region managers automatically. As part of the implementation. + */ + destroy(...args: any[]): void; + + /** + * In several cases you need to access ui elements inside the view to + * retrieve their data or manipulate them. For example you have a certain + * div element you need to show/hide based on some state, or other ui + * element that you wish to set a css class to it. Instead of having jQuery + * selectors hanging around in the view's code you can define a ui hash + * that contains a mapping between the ui element's name and its jQuery + * selector. Afterwards you can simply access it via this.ui.elementName. + * This functionality is provided via the bindUIElements method. + * Since View doesn't implement the render method, then if you directly + * extend from View you will need to invoke this method from your render + * method. In ItemView and CompositeView this is already taken care of. + */ + bindUIElements(): any; + + unbindUIElements(): any; + + triggerMethod(name: string, ...args: any[]): any; + + /** + * Called on the view instance when the view has been rendered and + * displayed. This event can be used to react to when a view has been + * shown via a region. A common use case for the onShow method is to + * use it to add children views. + */ + onShow(): void; + + /** + * Triggered just after the view has been destroyed. + */ + onDestroy(): void; + + /** + * When destroying a view, an onBeforeDestroy method will be called, if + * it has been provided, just before the view destroys. It will be passed + * any arguments that destroy was invoked with. + */ + onBeforeDestroy(...args: any[]): void; + + /** + * Called anytime that showing the view in a Region causes it to be + * attached to the document. + */ + onAttach(): void; + + /** + * Triggered right before the view is attached to the document. + */ + onBeforeAttach(): void; + + /** + * Triggered after the view has been rendered, has been shown in the DOM via a Marionette.Region, and has been re-rendered. + * This event / callback is useful for DOM-dependent UI plugins such as jQueryUI or KendoUI. + */ + onDomRefresh(): void; + + /** + * Internal properties extended in Marionette.View. + */ + isDestroyed: boolean; + supportsRenderLifecycle: boolean; + supportsDestroyLifecycle: boolean; + } + + /** + * An ItemView is a view that represents a single item. That item may be + * a Backbone.Model or may be a Backbone.Collection. Whichever it is though, + * it will be treated as a single item. + */ + class ItemView extends View { + + constructor(options?: Backbone.ViewOptions); + + /** + * Item views will serialize a model or collection, by default, by calling + * .toJSON on either the model or collection. If both a model and + * collection are attached to an item view, the model will be used as the + * data source. The results of the data serialization will be passed to + * the template that is rendered. + * + * If you need custom serialization for your data, you can provide a serializeData + * method on your view. It must return a valid JSON object, as if you had + * called .toJSON on a model or collection. + */ + serializeData(): any; + + /** + * Renders the view. It is unwise to override the render method of any + * Marionette view. Instead, you should use the onBeforeRender and + * onRender callbacks to layer in additional functionality to the + * rendering of your view. + */ + render(): ItemView; + + /** + * Triggered before an ItemView is rendered. + */ + onBeforeRender(): void; + + /** + * Triggered after the view has been rendered. You can implement this in + * your view to provide custom code for dealing with the view's el after + * it has been rendered. + */ + onRender(): void; + } + + + interface CollectionViewOptions extends Backbone.ViewOptions { + + /** + * By default the CollectionView will maintain a sorted collection's order + * in the DOM. This behavior can be disabled by specifying {sort: false} + * on initialize. + */ + sort?: boolean; + + /** + * This option is useful when you have performance issues when you + * resort your CollectionView. Without this option, your CollectionView + * will be completely re-rendered, which can be costly if you have a + * large number of elements or if your ChildViews are complex. If this + * option is activated, when you sort your Collection, there will be no + * re-rendering, only the DOM nodes will be reordered. This can be a + * problem if your ChildViews use their collection's index in their + * rendering. In this case, you cannot use this option as you need to + * re-render each ChildView. + * + * If you combine this option with a filter that changes the views that + * are to be displayed, reorderOnSort will be bypassed to render new + * children and remove those that are rejected by the filter. + */ + reorderOnSort?: boolean; + } + + /** + * The CollectionView will loop through all of the models in the specified + * collection, render each of them using a specified childView, then append + * the results of the child view's el to the collection view's el. By + * default the CollectionView will maintain a sorted collection's order in the + * DOM. This behavior can be disabled by specifying {sort: false} on + * initialize. + */ + class CollectionView> extends View { + constructor(options?: CollectionViewOptions); + + /** + * Specify a childView in your collection view definition. This must be a + * Backbone view object definition, not an instance. It can be any + * Backbone.View or be derived from Marionette.ItemView + */ + childView: new (...args:any[]) => TView; + + /** + * There may be scenarios where you need to pass data from your parent + * collection view in to each of the childView instances. To do this, + * provide a childViewOptions definition on your collection view as an + * object literal. This will be passed to the constructor of your childView + * as part of the options. + * + * You can also specify the childViewOptions as a function, if you need to + * calculate the values to return at runtime. The model will be passed + * into the function should you need access to it when calculating + * childViewOptions. The function must return an object, and the attributes of + * the object will be copied to the childView instance's options. + */ + childViewOptions: any; + + /** + * You can customize the event prefix for events that are forwarded through + * the collection view. To do this, set the childViewEventPrefix on the + * collection view. + */ + childViewEventPrefix: string; + + /** + * You can specify a childEvents hash or method which allows you to + * capture all bubbling childEvents without having to manually set bindings. + * The keys of the hash can either be a function or a string that is the + * name of a method on the collection view. + */ + childEvents: any; + + /** + * When a collection has no children, and you need to render a view other than + * the list of childViews, you can specify an emptyView attribute on your collection + * view. + */ + emptyView: any; + + /** + * Similar to childView and childViewOptions, there is an emptyViewOptions + * property that will be passed to the emptyView constructor. It can be + * provided as an object literal or as a function. If emptyViewOptions + * aren't provided the CollectionView will default to passing the + * childViewOptions to the emptyView. + */ + emptyViewOptions: any; + + /** + * The CollectionView uses Backbone.BabySitter to store and manage its + * child views. This allows you to easily access the views within the + * collection view, iterate them, find them by a given indexer such as the + * view's model or collection, and more. + */ + children: Backbone.ChildViewContainer; + + /** + * The render method of the collection view is responsible for rendering the + * entire collection. It loops through each of the children in the collection + * and renders them individually as an childView. + */ + render(): CollectionView; + + /** + * The addChild method is responsible for rendering the childViews and + * adding them to the HTML for the collectionView instance. It is also + * responsible for triggering the events per ChildView. In most cases you + * should not override this method. + */ + addChild(item: any, ChildView: TView, index: Number): void; + + /** Render the child view */ + renderChildView(view: TView, index: Number): void; + + /** + * When a custom view instance needs to be created for the childView that + * represents a child, override the buildChildView method. This method + * takes three parameters and returns a view instance to be used as the + * child view. + */ + buildChildView(child: any, ItemViewType: any, itemViewOptions: any): TView; + + /** + * Remove the child view and destroy it. This function also updates the indices of + * later views in the collection in order to keep the children in sync with the collection. + */ + removeChildView(view: TView): TView; + + /** + * Determines if the view is empty. If you want to control when the empty + * view is rendered, you can override isEmpty. + */ + isEmpty(): boolean; + + /** + * If empty, show the empty view + */ + checkEmpty(): void; + + /** + * Destroy the child views that this collection view + * is holding on to, if any. This returns destroyed children. + */ + destroyChildren(): Backbone.ChildViewContainer; + + /** + * By default the CollectionView will maintain the order of its collection + * in the DOM. However on occasions the view may need to re-render to make + * this possible, for example if you were to change the comparator on the + * collection. By default CollectionView will call render when this happens, + * but there are cases where this may not be suitable. For instance when + * sorting the children in a CompositeView, you want to only render the + * internal collection. + */ + resortView(): void; + + /** + * By default the collection view will append the HTML of each ChildView + * into the element buffer, and then call jQuery's .append once at the end + * to move the HTML into the collection view's el. + * You can override this by specifying an attachHtml method in your view + * definition. + * @param collectionView the instance of the collection view that will receive the HTML. + * @param childView the current child view instance. + * @param index he index of the model that this childView instance represents, + * in the collection that the model came from. This is useful for sorting + * a collection and displaying the sorted list in the correct order on the + * screen. + */ + attachHtml(collectionView: CollectionView, childView: TView, index: number): void; + + /** + * The value returned by this method is the ChildView class that will be + * instantiated when a Model needs to be initially rendered. This method + * also gives you the ability to customize per Model ChildViews. + */ + getChildView(item: M): new (...args:any[]) => TView; + + /** + * If you need the emptyView's class chosen dynamically, specify + * getEmptyView. + */ + getEmptyView(): any; + + /** Serialize a collection by serializing each of its models. */ + serializeCollection(): any; + + /** + * Attaches the content of a given view. + * This method can be overridden to optimize rendering, + * or to render in a non standard way. + * + * For example, using `innerHTML` instead of `$el.html` + * + * @example + * attachElContent: function(html) { + * this.el.innerHTML = html; + * return this; + * } + */ + attachElContent(html: string): ItemView; + + /** + * Reorder DOM after sorting. When your element's rendering + * do not use their index, you can pass reorderOnSort: true + * to only reorder the DOM after a sort instead of rendering + * all the collectionView + */ + reorder(): void; + + /** + * Render and show the emptyView. Similar to addChild method + * but "add:child" events are not fired, and the event from + * emptyView are not forwarded + */ + addEmptyView(child: TModel, EmptyView: new (...args: any[]) => any): void; + + /** + * Handle cleanup and other destroying needs for the collection of views + */ + destroy(): CollectionView; + + /** + * Set up the child view event forwarding. Uses a "childview:" + * prefix in front of all forwarded events. + * @param view it might be ChildView or EmptyView. + */ + proxyChildEvents(view: any): void; + + /** + * Called just prior to rendering the collection view. + */ + onBeforeRender(): void; + + /** + * Triggered after the view has been rendered. You can implement this in + * your view to provide custom code for dealing with the view's el after + * it has been rendered. + */ + onRender(): void; + + /** + * This callback function allows you to know when a child / child view + * instance is about to be added to the collection view. It provides + * access to the view instance for the child that was added. + */ + onBeforeAddChild(childView: TView): void; + + /** + * This callback function allows you to know when a child / child view + * instance has been added to the collection view. It provides access to + * the view instance for the child that was added. + */ + onAddChild(childView: TView): void; + + /** + * This callback function allows you to know when a childView instance is + * about to be removed from the collectionView. It provides access to the + * view instance for the child that was removed. + */ + onBeforeRemoveChild(childView: TView): void; + + /** + * This callback function allows you to know when a child / childView + * instance has been deleted or removed from the collection. + */ + onRemoveChild(childView: TView): void; + } + + /** + * A CompositeView extends from CollectionView to be used as a composite view + * for scenarios where it should represent both a branch and leaf in a tree + * structure, or for scenarios where a collection needs to be rendered within + * a wrapper template. + */ + class CompositeView> extends CollectionView { + + constructor(options?: CollectionViewOptions); + + /** + * Each childView will be rendered using the childView's template. The + * CompositeView's template is rendered and the childView's templates are + * added to this. + */ + childView: new (...args:any[]) => TView; + + /** + * By default the composite view uses the same attachHtml method that the + * collection view provides. This means the view will call jQuery's + * .append to move the HTML contents from the child view instance in to + * the collection view's el. + * This is typically not very useful as a composite view will usually render + * a container DOM element in which the child views should be placed. + * This can be either a string or a function returning a string. + */ + childViewContainer: any; + + /** + * Renders the view. + */ + render(): CompositeView; + + /** + * Invoked before the model has been rendered + */ + onBeforeRenderTemplate(): void; + + /** + * Invoked after the model has been rendered. + */ + onRenderTemplate(): void; + + /** + * Invoked before the collection of models is rendered + */ + onBeforeRenderCollection(): void; + + /** + * Invoked after the collection of models has been rendered + */ + onRenderCollection(): void; + } + + interface LayoutViewOptions extends Backbone.ViewOptions { + /** + * The LayoutView takes an additional parameter where you can pass the regions as option on creation. + */ + regions?:any; + + /** + * This option removes the layoutView from the DOM before destroying the + * children preventing repaints as each option is removed. However, it + * makes it difficult to do close animations for a child view (false by + * default) + */ + destroyImmediate?: boolean; + } + + /** + * A LayoutView is a hybrid of an ItemView and a collection of Region objects. + * They are ideal for rendering application layouts with multiple sub-regions + * managed by specified region managers. + * A layoutView can also act as a composite-view to aggregate multiple views + * and sub-application areas of the screen allowing applications to attach + * multiple region managers to dynamically rendered HTML. + * You can create complex views by nesting layoutView managers within Regions. + */ + class LayoutView extends ItemView { + /** + * If you have the need to replace the Region with a region class of your + * own implementation, you can specify an alternate class to use with this + * property. + */ + regionClass: any; + + /** + * Constructor. + * A hash that can contain a regions hash that allows you to specify regions per + * LayoutView instance. + */ + constructor(options?: LayoutViewOptions); + + /** + * Handle destroying regions, and then destroy the view itself. + */ + destroy(): LayoutView; + + /** + * Regions hash or a method returning the regions hash that maps + * regions/selectors to methods on your View. + **/ + regions(): any; + + /** Adds a region to the layout view. */ + addRegion(name: string, definition: any): Region; + + /** + * Add multiple regions as a {name: definition, name2: def2} object literal. + */ + addRegions(regions: any): any; + + /** Returns a region from the layout view */ + getRegion(name: string): Region; + + /** + * Renders the view. It will use the existing region objects the first + * time it is called. Subsequent calls will destroy the views that the + * regions are showing and then reset the `el` for the regions to the + * newly rendered DOM elements. + */ + render(): LayoutView; + + /** + * Removes the region with the specified name. + * @param name the name of the region to remove. + */ + removeRegion(name: string): Region; + + /** Enable easy overriding of the default `RegionManager` + * for customized region interactions and business specific + * view logic for better control over single regions. + */ + getRegionManager(): RegionManager; + + /** + * Show a view into the region specified by `regionName`. + */ + showChildView(regionName: string, view: any, options?: RegionShowOptions): void; + + /** + * Get the current view that is shown in the region specified by + * `regionName`. + */ + getChildView(regionName: string): Backbone.View; + + /** + * Returns all regions from the layout view. The results contains an + * Object hash that has `string`s as keys and `Region`s as values. + */ + getRegions(): {[key: string]: Region}; + + /** + * You can customize the event prefix for events that are forwarded through + * the layout view with this property. + */ + childViewEventPrefix: string; + } + + interface AppRouterOptions extends Backbone.RouterOptions { + /** + * The appRoutes. + */ + appRoutes?: any; + + /** + * The controller to associate with this router. + */ + controller?: any; + } + + /** + * Reduce the boilerplate code of handling route events and then calling a + * single method on another object. Have your routers configured to call + * the method on your object, directly. + */ + class AppRouter extends Backbone.Router { + + /** + * Configure an AppRouter with appRoutes. The route definition + * is passed on to Backbone's standard routing handlers. This means + * that you define routes like you normally would. However, instead of + * providing a callback method that exists on the router, you provide a + * callback method that exists on the controller, which you specify for + * the router instance (see below.) + */ + constructor(options?: AppRouterOptions); + + /** + * You can specify a controller with the multiple routes at runtime with + * this method. However, In this case the current controller of AppRouter + * will not change. + */ + processAppRoutes(controller: any, appRoutes: any): void; + + /** + * Adds an app route at runtime to this instance. It works the same as the + * built-in router.route() call from Backbone's Router, but has all the + * same semantics and behavior of the appRoutes configuration. + */ + appRoute(route: string, methodName: string): void; + } + + /** + * The Backbone.Marionette.Application object is the hub of your composite + * application. It organizes, initializes and coordinates the various pieces + * of your app. It also provides a starting point for you to call into from + * your HTML script block, or directly from your JavaScript files if you + * prefer to go that route. The Application is meant to be instantiated + * directly, although you can extend it to add your own functionality. + */ + class Application extends Backbone.Events { + + constructor(options?: any); + + /** + * The Event Aggregator is available through this property. It is + * convenient for passively sharing information between pieces of your + * application as events occur. + * Note! To access this application channel from other objects within your + * app you are encouraged to get a handle of the systems through the + * Wreqr API instead of the Application instance itself. + */ + vent: Backbone.Wreqr.EventAggregator; + + /** + * Commands are used to make any component tell another component to + * perform an action without a direct reference to it. + */ + commands: Backbone.Wreqr.Commands; + + /** + * Request Response is a means for any component to request information + * from another component without being tightly coupled. + */ + reqres: Backbone.Wreqr.RequestResponse; + + submodules: any; + + /** Command execution, facilitated by Backbone.Wreqr.Commands */ + execute(...args: any[]): void; + + /** Request/response, facilitated by Backbone.Wreqr.RequestResponse */ + request(...args: any[]): any; + + /** Deprecated! Initializers, you should use events to manage start-up logic. */ + addInitializer(initializer: any): void; + + /** + * Once you have your application configured, you can kick everything off + * by calling this method. + * @param options This parameter will be passed to each of your initializer functions, as well as the initialize events. This allows you to provide extra configuration for various parts of your app throughout the initialization sequence. + */ + start(options?: any): void; + + /** Deprecated! nstead of using the Application as the root of your view tree, you should use a Layout View.*/ + addRegions(regions: any): any; + + /** Deprecated! nstead of using the Application as the root of your view tree, you should use a Layout View.*/ + emptyRegions(): void; + + /** Deprecated! nstead of using the Application as the root of your view tree, you should use a Layout View.*/ + removeRegion(region: Region): void; + + /** Deprecated! nstead of using the Application as the root of your view tree, you should use a Layout View.*/ + getRegion(regionName: string): Region; + + module(moduleNames: any, moduleDefinition: any): Module; + + /** + * Called just before the Application starts and before the initializers are executed. + */ + onBeforeStart(options?: any): void; + + /** + * Called after the Application has started and after the initializers have been executed. + */ + onStart(options?: any): void; + } + + // modules mapped for convenience, but you should probably use TypeScript modules instead + class Module extends Backbone.Events { + + constructor(moduleName: string, app: Application); + + submodules: any; + triggerMethod(name: string, ...args: any[]): any; + + addInitializer(callback: any): void; + addFinalizer(callback: any): void; + start(options?: any): void; + addDefinition(moduleDefinition: any, customArgs: any): any; + } + + /** + * A Behavior is an isolated set of DOM / user interactions that can be mixed + * into any View or another Behavior. Behaviors allow you to blackbox View + * specific interactions into portable logical chunks, keeping your views + * simple and your code DRY. + */ + class Behavior extends Marionette.Object { + constructor(options?: any, view?: any); + + options: any; + + /** + * Behaviors can have their own ui hash, which will be mixed into the ui + * hash of its associated View instance. ui elements defined on either the + * Behavior or the View will be made available within events and triggers. + * They also are attached directly to the Behavior and can be accessed within + * Behavior methods as this.ui. + */ + ui: any; + + /** + * Any triggers you define on the Behavior will be triggered in response to the appropriate event on the view. + */ + triggers: any; + + /** + * modelEvents will respond to the view's model events. + */ + modelEvents: any; + + /** + * collectionEvents will respond to the view's collection events. + */ + collectionEvents: any; + + /** + * The behaviors key allows a behavior to group multiple behaviors + * together. + */ + behaviors: any; + + /** + * defaults can be a hash or function to define the default options for + * your behavior. The default options will be overridden depending on + * what you set as the options per behavior (this works just like a + * backbone.model). + */ + defaults: any; + + /** + * el is a direct proxy of the view's el + */ + el: any; + + /** + * $el is a direct proxy of the view's el cached as a jQuery selector. + */ + $el: JQuery; + + /** A reference to the view instance that the behavior is on. */ + view: any; + + /** + * $ is a direct proxy of the views $ lookup method. + */ + $(selector: any): JQuery; + } + + /** + * Marionette.Behaviors' is a utility class that takes care of glueing your + * behavior instances to their given View. The most important part of this + * class is that you MUST override the class level behaviorsLookup method or + * set the option behaviorClass for things to work properly. + */ + class Behaviors { + /** + * This method defines where your behavior classes are stored. Override this to provide another lookup. + */ + static behaviorsLookup(): any; + + /** + * This method has a default implementation that is simple to override. It + * is responsible for the lookup of single behavior from within the + * Behaviors.behaviorsLookup or elsewhere. Note that it should return the type of the + * class to instantiate, not an instance of that class. + */ + static getBehaviorClass(options: any, key: string): any; + } +} diff --git a/marionette/marionette-tests.ts b/backbone.marionette/marionette-tests.ts similarity index 98% rename from marionette/marionette-tests.ts rename to backbone.marionette/marionette-tests.ts index 6a688467af..b5eb9d07c6 100644 --- a/marionette/marionette-tests.ts +++ b/backbone.marionette/marionette-tests.ts @@ -1,6 +1,7 @@ -/// +import * as Marionette from 'backbone.marionette'; +import * as Backbone from 'backbone'; -namespace Marionette.Tests { +namespace MarionetteTests { class DestroyWarn extends Marionette.Behavior { // you can set default options // just like you can in your Backbone Models diff --git a/backbone.marionette/tsconfig.json b/backbone.marionette/tsconfig.json new file mode 100644 index 0000000000..fa5166772f --- /dev/null +++ b/backbone.marionette/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "marionette-tests.ts" + ] +} \ No newline at end of file diff --git a/backbone.paginator/backbone.paginator-tests.ts b/backbone.paginator/backbone.paginator-tests.ts index c05a07b9d1..28b09d4fc5 100644 --- a/backbone.paginator/backbone.paginator-tests.ts +++ b/backbone.paginator/backbone.paginator-tests.ts @@ -1,6 +1,7 @@ -/// -/// -/// +/// + + +import * as Backbone from 'backbone'; namespace BackbonePaginatorTests { diff --git a/backbone.paginator/backbone.paginator.d.ts b/backbone.paginator/backbone.paginator.d.ts deleted file mode 100644 index b256919893..0000000000 --- a/backbone.paginator/backbone.paginator.d.ts +++ /dev/null @@ -1,116 +0,0 @@ -// Type definitions for backbone.paginator 2.0.2 -// Project: https://github.com/backbone-paginator/backbone.paginator -// Definitions by: Nyamazing -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Backbone { - - interface PageableState { - firstPage?: number; - lastPage?: number; - currentPage?: number; - pageSize?: number; - totalPages?: number; - totalRecords?: number; - sortKey?: string; - order?: number; - } - - interface PageableQueryParams { - currentPage?: string; - pageSize?: string; - totalPages?: string; - totalRecords?: string; - sortKey?: string; - order?: string; - directions?: any; - } - - interface PageableInitialOptions { - comparator?: (...options: any[]) => number; - full?: boolean; - state?: PageableState; - queryParam?: PageableQueryParams; - } - - interface PageableParseLinksOptions { - xhr?: JQueryXHR; - } - - interface PageableSetSortingOptions { - side?: string; - full?: boolean; - sortValue?: (model: TModel, sortKey: string) => any | string; - } - - interface PageableSwitchModeOptions { - fetch?: boolean; - resetState?: boolean; - } - - type PageableGetPageOptions = CollectionFetchOptions|Silenceable; - - class PageableCollection extends Collection{ - - fullCollection: Collection; - mode: string; - queryParams: PageableQueryParams; - state: PageableState; - - constructor(models?: TModel[], options?: PageableInitialOptions); - - fetch(options?: CollectionFetchOptions): JQueryXHR; - - getFirstPage(options?: PageableGetPageOptions): - JQueryXHR|PageableCollection; - - getLastPage(options?: PageableGetPageOptions): - JQueryXHR|PageableCollection; - - getNextPage(options?: PageableGetPageOptions): - JQueryXHR|PageableCollection; - - getPage(index: number|string, options?: PageableGetPageOptions): - JQueryXHR|PageableCollection; - - getPageByOffset(offset: number, options?: PageableGetPageOptions): - JQueryXHR|PageableCollection; - - getPreviousPage(options?: PageableGetPageOptions): - JQueryXHR|PageableCollection; - - hasNextPage(): boolean; - - hasPreviousPage(): boolean; - - parse(resp: any, options?: any): any[]; - - parseLinks(resp: any, options?: PageableParseLinksOptions): any; - - parseRecords(resp: any, options?: any): any[]; - - parseState(resp: any, queryParams: PageableQueryParams, - state: PageableState, options?: any): PageableState; - - setPageSize(pageSize: number, - options?: CollectionFetchOptions): - JQueryXHR|PageableCollection; - - setSorting(sortKey: string, order?: number, - options?: PageableSetSortingOptions): - PageableCollection; - - switchMode(mode?: string, options?: PageableSwitchModeOptions): - JQueryXHR|PageableCollection; - - sync(method: string, - model: TModel|Collection, - options?: any): JQueryXHR; - - static noConflict(): typeof PageableCollection; - - } -} - diff --git a/backbone.paginator/index.d.ts b/backbone.paginator/index.d.ts new file mode 100644 index 0000000000..521ccda8bf --- /dev/null +++ b/backbone.paginator/index.d.ts @@ -0,0 +1,115 @@ +// Type definitions for backbone.paginator 2.0.2 +// Project: https://github.com/backbone-paginator/backbone.paginator +// Definitions by: Nyamazing +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Backbone from 'backbone'; + +declare module 'backbone' { + interface PageableState { + firstPage?: number; + lastPage?: number; + currentPage?: number; + pageSize?: number; + totalPages?: number; + totalRecords?: number; + sortKey?: string; + order?: number; + } + + interface PageableQueryParams { + currentPage?: string; + pageSize?: string; + totalPages?: string; + totalRecords?: string; + sortKey?: string; + order?: string; + directions?: any; + } + + interface PageableInitialOptions { + comparator?: (...options: any[]) => number; + full?: boolean; + state?: PageableState; + queryParam?: PageableQueryParams; + } + + interface PageableParseLinksOptions { + xhr?: JQueryXHR; + } + + interface PageableSetSortingOptions { + side?: string; + full?: boolean; + sortValue?: (model: TModel, sortKey: string) => any | string; + } + + interface PageableSwitchModeOptions { + fetch?: boolean; + resetState?: boolean; + } + + type PageableGetPageOptions = CollectionFetchOptions|Silenceable; + + class PageableCollection extends Collection{ + + fullCollection: Collection; + mode: string; + queryParams: PageableQueryParams; + state: PageableState; + + constructor(models?: TModel[], options?: PageableInitialOptions); + + fetch(options?: CollectionFetchOptions): JQueryXHR; + + getFirstPage(options?: PageableGetPageOptions): + JQueryXHR|PageableCollection; + + getLastPage(options?: PageableGetPageOptions): + JQueryXHR|PageableCollection; + + getNextPage(options?: PageableGetPageOptions): + JQueryXHR|PageableCollection; + + getPage(index: number|string, options?: PageableGetPageOptions): + JQueryXHR|PageableCollection; + + getPageByOffset(offset: number, options?: PageableGetPageOptions): + JQueryXHR|PageableCollection; + + getPreviousPage(options?: PageableGetPageOptions): + JQueryXHR|PageableCollection; + + hasNextPage(): boolean; + + hasPreviousPage(): boolean; + + parse(resp: any, options?: any): any[]; + + parseLinks(resp: any, options?: PageableParseLinksOptions): any; + + parseRecords(resp: any, options?: any): any[]; + + parseState(resp: any, queryParams: PageableQueryParams, + state: PageableState, options?: any): PageableState; + + setPageSize(pageSize: number, + options?: CollectionFetchOptions): + JQueryXHR|PageableCollection; + + setSorting(sortKey: string, order?: number, + options?: PageableSetSortingOptions): + PageableCollection; + + switchMode(mode?: string, options?: PageableSwitchModeOptions): + JQueryXHR|PageableCollection; + + sync(method: string, + model: TModel|Collection, + options?: any): JQueryXHR; + + static noConflict(): typeof PageableCollection; + + } +} + diff --git a/backbone.paginator/tsconfig.json b/backbone.paginator/tsconfig.json new file mode 100644 index 0000000000..ca30ced10e --- /dev/null +++ b/backbone.paginator/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "backbone.paginator-tests.ts" + ] +} \ No newline at end of file diff --git a/backbone.radio/backbone.radio-tests.ts b/backbone.radio/backbone.radio-tests.ts index 295c552af2..27b95dba4a 100644 --- a/backbone.radio/backbone.radio-tests.ts +++ b/backbone.radio/backbone.radio-tests.ts @@ -1,5 +1,7 @@ -/// -/// + +/// + +import * as Backbone from 'backbone'; class MyCommands extends Backbone.Radio.Commands { diff --git a/backbone.radio/backbone.radio.d.ts b/backbone.radio/backbone.radio.d.ts deleted file mode 100644 index 50895b0275..0000000000 --- a/backbone.radio/backbone.radio.d.ts +++ /dev/null @@ -1,92 +0,0 @@ -// Type definitions for Backbone.Radio v0.8.3 -// Project: https://github.com/marionettejs/backbone.radio -// Definitions by: Peter Palotas -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Backbone { - interface Radio { - tuneIn(channelName: string): Radio; - tuneOut(channelName: string): Radio; - log(channelName: string, eventName: string, ...args: any[]): void; - channel(channelName: string): Radio.Channel; - } - - namespace Radio { - var VERSION: string; - var DEBUG: boolean; - - function log(channelName: string, eventName: string, ...args: any[]): void; - function tuneIn(channelName: string): Radio; - function tuneOut(channelName: string): Radio; - function channel(channelName: string): Channel; - - // Proxy functions for Commands - function command(channelName: string, commandName: string, ...args: any[]): void; - function comply(channelName: string, commandName: string, callback: (...args: any[]) => void, context?: any): Commands; - function comply(channelName: string, commands: { [key: string]: (...args: any[]) => any }, context?: any): Commands; - function complyOnce(channelName: string, commandName: string, callback: (...args: any[]) => void, context?: any): Commands; - function complyOnce(channelName: string, commands: { [key: string]: (...args: any[]) => any }, context?: any): Commands; - function stopComplying(channelName: string, commandName?: string, callback?: (...args: any[]) => void, context?: any): Commands; - - // Proxy functions for Requests - function request(channelName: string, requestName: string, ...args: any[]): any; - function reply(channelName: string, requestName: string, callback: (...args: any[]) => any, context?: any): Requests; - function reply(channelName: string, commands: { [key: string]: (...args: any[]) => any }, context?: any): Requests; - function replyOnce(channelName: string, requestName: string, callback: (...args: any[]) => any, context?: any): Requests; - function replyOnce(channelName: string, commands: { [key: string]: (...args: any[]) => any }, context?: any): Requests; - function stopReplying(channelName: string, commandName?: string, callback?: (...args: any[]) => any, context?: any): Requests; - - // Proxy functions for Backbone.Events - function on(channelName: string, eventName: string, callback?: Function, context?: any): any; - function off(channelName: string, eventName?: string, callback?: Function, context?: any): any; - function trigger(channelName: string, eventName: string, ...args: any[]): any; - function bind(channelName: string, eventName: string, callback: Function, context?: any): any; - function unbind(channelName: string, eventName?: string, callback?: Function, context?: any): any; - - function once(channelName: string, events: string, callback: Function, context?: any): any; - function listenTo(channelName: string, object: any, events: string, callback: Function): any; - function listenToOnce(channelName: string, object: any, events: string, callback: Function): any; - function stopListening(channelName: string, object?: any, events?: string, callback?: Function): any; - - class Commands { - command(commandName: string, ...args: any[]): void; - comply(commandName: string, callback: (...args: any[]) => void, context?: any): Commands; - comply(commands: { [key: string]: (...args: any[]) => any }, context?: any): Commands; - complyOnce(commands: { [key: string]: (...args: any[]) => any }, context?: any): Commands; - complyOnce(commandName: string, callback: (...args: any[]) => void, context?: any): Commands; - stopComplying(commandName?: string, callback?: (...args: any[]) => void, context?: any): Commands; - } - - class Requests { - request(requestName: string, ...args: any[]): any; - reply(requestName: string, callback: (...args: any[]) => any, context?: any): Requests; - reply(commands: { [key: string]: (...args: any[]) => any }, context?: any): Requests; - replyOnce(requestName: string, callback: (...args: any[]) => any, context?: any): Requests; - replyOnce(commands: { [key: string]: (...args: any[]) => any }, context?: any): Requests; - stopReplying(commandName?: string, callback?: (...args: any[]) => any, context?: any): Requests; - } - - class Channel extends Backbone.Events implements Commands, Requests { - channelName: string; - reset(): Channel; - - // Radio.Commands - command(commandName: string, ...args: any[]): void; - comply(commandName: string, callback: (...args: any[]) => void, context?: any): Commands; - comply(commands: { [key: string]: (...args: any[]) => any }, context?: any): Commands; - complyOnce(commandName: string, callback: (...args: any[]) => void, context?: any): Commands; - complyOnce(commands: { [key: string]: (...args: any[]) => any }, context?: any): Commands; - stopComplying(commandName?: string, callback?: (...args: any[]) => void, context?: any): Commands; - - // Radio.Requests - request(requestName: string, ...args: any[]): any; - reply(requestName: string, callback: (...args: any[]) => any, context?: any): Requests; - reply(commands: { [key: string]: (...args: any[]) => any }, context?: any): Requests; - replyOnce(requestName: string, callback: (...args: any[]) => any, context?: any): Requests; - replyOnce(commands: { [key: string]: (...args: any[]) => any }, context?: any): Requests; - stopReplying(commandName?: string, callback?: (...args: any[]) => any, context?: any): Requests; - } - } -} diff --git a/backbone.radio/index.d.ts b/backbone.radio/index.d.ts new file mode 100644 index 0000000000..5eaa7d2e6d --- /dev/null +++ b/backbone.radio/index.d.ts @@ -0,0 +1,92 @@ +// Type definitions for Backbone.Radio v0.8.3 +// Project: https://github.com/marionettejs/backbone.radio +// Definitions by: Peter Palotas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Backbone from 'backbone'; + +declare module "backbone" { + interface Radio { + tuneIn(channelName: string): Radio; + tuneOut(channelName: string): Radio; + log(channelName: string, eventName: string, ...args: any[]): void; + channel(channelName: string): Radio.Channel; + } + + namespace Radio { + var VERSION: string; + var DEBUG: boolean; + + function log(channelName: string, eventName: string, ...args: any[]): void; + function tuneIn(channelName: string): Radio; + function tuneOut(channelName: string): Radio; + function channel(channelName: string): Channel; + + // Proxy functions for Commands + function command(channelName: string, commandName: string, ...args: any[]): void; + function comply(channelName: string, commandName: string, callback: (...args: any[]) => void, context?: any): Commands; + function comply(channelName: string, commands: { [key: string]: (...args: any[]) => any }, context?: any): Commands; + function complyOnce(channelName: string, commandName: string, callback: (...args: any[]) => void, context?: any): Commands; + function complyOnce(channelName: string, commands: { [key: string]: (...args: any[]) => any }, context?: any): Commands; + function stopComplying(channelName: string, commandName?: string, callback?: (...args: any[]) => void, context?: any): Commands; + + // Proxy functions for Requests + function request(channelName: string, requestName: string, ...args: any[]): any; + function reply(channelName: string, requestName: string, callback: (...args: any[]) => any, context?: any): Requests; + function reply(channelName: string, commands: { [key: string]: (...args: any[]) => any }, context?: any): Requests; + function replyOnce(channelName: string, requestName: string, callback: (...args: any[]) => any, context?: any): Requests; + function replyOnce(channelName: string, commands: { [key: string]: (...args: any[]) => any }, context?: any): Requests; + function stopReplying(channelName: string, commandName?: string, callback?: (...args: any[]) => any, context?: any): Requests; + + // Proxy functions for Backbone.Events + function on(channelName: string, eventName: string, callback?: Function, context?: any): any; + function off(channelName: string, eventName?: string, callback?: Function, context?: any): any; + function trigger(channelName: string, eventName: string, ...args: any[]): any; + function bind(channelName: string, eventName: string, callback: Function, context?: any): any; + function unbind(channelName: string, eventName?: string, callback?: Function, context?: any): any; + + function once(channelName: string, events: string, callback: Function, context?: any): any; + function listenTo(channelName: string, object: any, events: string, callback: Function): any; + function listenToOnce(channelName: string, object: any, events: string, callback: Function): any; + function stopListening(channelName: string, object?: any, events?: string, callback?: Function): any; + + class Commands { + command(commandName: string, ...args: any[]): void; + comply(commandName: string, callback: (...args: any[]) => void, context?: any): Commands; + comply(commands: { [key: string]: (...args: any[]) => any }, context?: any): Commands; + complyOnce(commands: { [key: string]: (...args: any[]) => any }, context?: any): Commands; + complyOnce(commandName: string, callback: (...args: any[]) => void, context?: any): Commands; + stopComplying(commandName?: string, callback?: (...args: any[]) => void, context?: any): Commands; + } + + class Requests { + request(requestName: string, ...args: any[]): any; + reply(requestName: string, callback: (...args: any[]) => any, context?: any): Requests; + reply(commands: { [key: string]: (...args: any[]) => any }, context?: any): Requests; + replyOnce(requestName: string, callback: (...args: any[]) => any, context?: any): Requests; + replyOnce(commands: { [key: string]: (...args: any[]) => any }, context?: any): Requests; + stopReplying(commandName?: string, callback?: (...args: any[]) => any, context?: any): Requests; + } + + class Channel extends Backbone.Events implements Commands, Requests { + channelName: string; + reset(): Channel; + + // Radio.Commands + command(commandName: string, ...args: any[]): void; + comply(commandName: string, callback: (...args: any[]) => void, context?: any): Commands; + comply(commands: { [key: string]: (...args: any[]) => any }, context?: any): Commands; + complyOnce(commandName: string, callback: (...args: any[]) => void, context?: any): Commands; + complyOnce(commands: { [key: string]: (...args: any[]) => any }, context?: any): Commands; + stopComplying(commandName?: string, callback?: (...args: any[]) => void, context?: any): Commands; + + // Radio.Requests + request(requestName: string, ...args: any[]): any; + reply(requestName: string, callback: (...args: any[]) => any, context?: any): Requests; + reply(commands: { [key: string]: (...args: any[]) => any }, context?: any): Requests; + replyOnce(requestName: string, callback: (...args: any[]) => any, context?: any): Requests; + replyOnce(commands: { [key: string]: (...args: any[]) => any }, context?: any): Requests; + stopReplying(commandName?: string, callback?: (...args: any[]) => any, context?: any): Requests; + } + } +} diff --git a/backbone.radio/tsconfig.json b/backbone.radio/tsconfig.json new file mode 100644 index 0000000000..12aa65dc41 --- /dev/null +++ b/backbone.radio/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "backbone.radio-tests.ts" + ] +} \ No newline at end of file diff --git a/backbone/backbone-global.d.ts b/backbone/backbone-global.d.ts deleted file mode 100644 index be849cee04..0000000000 --- a/backbone/backbone-global.d.ts +++ /dev/null @@ -1,393 +0,0 @@ -// Type definitions for Backbone 1.0.0 -// Project: http://backbonejs.org/ -// Definitions by: Boris Yankov , Natan Vivo -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Backbone { - - interface AddOptions extends Silenceable { - at?: number; - } - - interface HistoryOptions extends Silenceable { - pushState?: boolean; - root?: string; - } - - interface NavigateOptions { - trigger?: boolean; - replace?: boolean; - } - - interface RouterOptions { - routes: any; - } - - interface Silenceable { - silent?: boolean; - } - - interface Validable { - validate?: boolean; - } - - interface Waitable { - wait?: boolean; - } - - interface Parseable { - parse?: any; - } - - interface PersistenceOptions { - url?: string; - data?: any; - beforeSend?: (jqxhr: JQueryXHR) => void; - success?: (modelOrCollection?: any, response?: any, options?: any) => void; - error?: (modelOrCollection?: any, jqxhr?: JQueryXHR, options?: any) => void; - } - - interface ModelSetOptions extends Silenceable, Validable { - } - - interface ModelFetchOptions extends PersistenceOptions, ModelSetOptions, Parseable { - } - - interface ModelSaveOptions extends Silenceable, Waitable, Validable, Parseable, PersistenceOptions { - patch?: boolean; - } - - interface ModelDestroyOptions extends Waitable, PersistenceOptions { - } - - interface CollectionFetchOptions extends PersistenceOptions, Parseable { - reset?: boolean; - } - - interface ObjectHash { - [key: string]: any; - } - - interface RoutesHash { - [routePattern: string]: string | {(...urlParts: string[]): void}; - } - - interface EventsHash { - [selector: string]: string | {(eventObject: JQueryEventObject): void}; - } - - class Events { - on(eventName: string, callback?: Function, context?: any): any; - on(eventMap: EventsHash): any; - off(eventName?: string, callback?: Function, context?: any): any; - trigger(eventName: string, ...args: any[]): any; - bind(eventName: string, callback: Function, context?: any): any; - unbind(eventName?: string, callback?: Function, context?: any): any; - - once(events: string, callback: Function, context?: any): any; - listenTo(object: any, events: string, callback: Function): any; - listenToOnce(object: any, events: string, callback: Function): any; - stopListening(object?: any, events?: string, callback?: Function): any; - } - - class ModelBase extends Events { - url: any; - parse(response: any, options?: any): any; - toJSON(options?: any): any; - sync(...arg: any[]): JQueryXHR; - } - - class Model extends ModelBase { - - /** - * Do not use, prefer TypeScript's extend functionality. - **/ - private static extend(properties: any, classProperties?: any): any; - - attributes: any; - changed: any[]; - cid: string; - collection: Collection; - - /** - * Default attributes for the model. It can be an object hash or a method returning an object hash. - * For assigning an object hash, do it like this: this.defaults = { attribute: value, ... }; - * That works only if you set it in the constructor or the initialize method. - **/ - defaults(): ObjectHash; - id: any; - idAttribute: string; - validationError: any; - urlRoot: any; - - constructor(attributes?: any, options?: any); - initialize(attributes?: any, options?: any): void; - - fetch(options?: ModelFetchOptions): JQueryXHR; - - /** - * 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; - changedAttributes(attributes?: any): any[]; - clear(options?: Silenceable): any; - clone(): Model; - destroy(options?: ModelDestroyOptions): any; - escape(attribute: string): string; - has(attribute: string): boolean; - hasChanged(attribute?: string): boolean; - isNew(): boolean; - isValid(options?:any): boolean; - previous(attribute: string): any; - previousAttributes(): any[]; - save(attributes?: any, options?: ModelSaveOptions): any; - unset(attribute: string, options?: Silenceable): Model; - validate(attributes: any, options?: any): any; - - private _validate(attributes: any, options: any): boolean; - - // mixins from underscore - - keys(): string[]; - values(): any[]; - pairs(): any[]; - invert(): any; - pick(keys: string[]): any; - pick(...keys: string[]): any; - omit(keys: string[]): any; - omit(...keys: string[]): any; - } - - class Collection extends ModelBase { - - /** - * Do not use, prefer TypeScript's extend functionality. - **/ - private static extend(properties: any, classProperties?: any): any; - - model: new (...args:any[]) => TModel; - models: TModel[]; - length: number; - - constructor(models?: TModel[] | Object[], options?: any); - initialize(models?: TModel[] | Object[], options?: any): void; - - fetch(options?: CollectionFetchOptions): JQueryXHR; - - /** - * Specify a model attribute name (string) or function that will be used to sort the collection. - */ - comparator: string | ((element: TModel) => number | string) | ((compare: TModel, to?: TModel) => number); - - add(model: {}|TModel, options?: AddOptions): TModel; - add(models: ({}|TModel)[], options?: AddOptions): TModel[]; - 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|string|Model): TModel; - create(attributes: any, options?: ModelSaveOptions): TModel; - pluck(attribute: string): any[]; - push(model: TModel, options?: AddOptions): TModel; - pop(options?: Silenceable): TModel; - remove(model: TModel, options?: Silenceable): TModel; - remove(models: TModel[], options?: Silenceable): TModel[]; - reset(models?: TModel[], options?: Silenceable): TModel[]; - set(models?: TModel[], options?: Silenceable): TModel[]; - shift(options?: Silenceable): TModel; - sort(options?: Silenceable): Collection; - unshift(model: TModel, options?: AddOptions): TModel; - where(properties: any): TModel[]; - findWhere(properties: any): TModel; - - private _prepareModel(attributes?: any, options?: any): any; - private _removeReference(model: TModel): void; - private _onModelEvent(event: string, model: TModel, collection: Collection, options: any): void; - - // mixins from underscore - - all(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; - any(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; - collect(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[]; - chain(): any; - contains(value: any): boolean; - countBy(iterator: (element: TModel, index: number) => any): _.Dictionary; - countBy(attribute: string): _.Dictionary; - detect(iterator: (item: any) => boolean, context?: any): any; // ??? - drop(): TModel; - drop(n: number): TModel[]; - each(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; - every(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; - filter(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[]; - find(iterator: (element: TModel, index: number) => boolean, context?: any): TModel; - first(): TModel; - first(n: number): TModel[]; - foldl(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; - forEach(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; - groupBy(iterator: (element: TModel, index: number) => string, context?: any): _.Dictionary; - groupBy(attribute: string, context?: any): _.Dictionary; - include(value: any): boolean; - indexOf(element: TModel, isSorted?: boolean): number; - initial(): TModel; - initial(n: number): TModel[]; - inject(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; - isEmpty(object: any): boolean; - invoke(methodName: string, args?: any[]): any; - last(): TModel; - last(n: number): TModel[]; - lastIndexOf(element: TModel, fromIndex?: number): number; - map(iterator: (element: TModel, index: number, context?: any) => any, context?: any): any[]; - max(iterator?: (element: TModel, index: number) => any, context?: any): TModel; - min(iterator?: (element: TModel, index: number) => any, context?: any): TModel; - reduce(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; - select(iterator: any, context?: any): any[]; - size(): number; - shuffle(): any[]; - slice(min: number, max?: number): TModel[]; - some(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; - sortBy(iterator: (element: TModel, index: number) => number, context?: any): TModel[]; - sortBy(attribute: string, context?: any): TModel[]; - sortedIndex(element: TModel, iterator?: (element: TModel, index: number) => number): number; - reduceRight(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any[]; - reject(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[]; - rest(): TModel; - rest(n: number): TModel[]; - tail(): TModel; - tail(n: number): TModel[]; - toArray(): any[]; - without(...values: any[]): TModel[]; - } - - class Router extends Events { - - /** - * Do not use, prefer TypeScript's extend functionality. - **/ - private static extend(properties: any, classProperties?: any): any; - - /** - * Routes hash or a method returning the routes hash that maps URLs with parameters to methods on your Router. - * For assigning routes as object hash, do it like this: this.routes = { "route": callback, ... }; - * That works only if you set it in the constructor or the initialize method. - **/ - routes: RoutesHash | any; - - constructor(options?: RouterOptions); - initialize(options?: RouterOptions): void; - route(route: string|RegExp, name: string, callback?: Function): Router; - navigate(fragment: string, options?: NavigateOptions): Router; - navigate(fragment: string, trigger?: boolean): Router; - - private _bindRoutes(): void; - private _routeToRegExp(route: string): RegExp; - private _extractParameters(route: RegExp, fragment: string): string[]; - } - - var history: History; - - class History extends Events { - - handlers: any[]; - interval: number; - - start(options?: HistoryOptions): boolean; - - getHash(window?: Window): string; - getFragment(fragment?: string, forcePushState?: boolean): string; - stop(): void; - route(route: string, callback: Function): number; - checkUrl(e?: any): void; - loadUrl(fragmentOverride: string): boolean; - navigate(fragment: string, options?: any): boolean; - static started: boolean; - options: any; - - private _updateHash(location: Location, fragment: string, replace: boolean): void; - } - - interface ViewOptions { - model?: TModel; - // TODO: quickfix, this can't be fixed easy. The collection does not need to have the same model as the parent view. - collection?: Backbone.Collection; //was: Collection; - el?: any; - id?: string; - className?: string; - tagName?: string; - attributes?: {[id: string]: any}; - } - - class View extends Events { - - /** - * Do not use, prefer TypeScript's extend functionality. - **/ - private static extend(properties: any, classProperties?: any): any; - - constructor(options?: ViewOptions); - initialize(options?: ViewOptions): void; - - /** - * Events hash or a method returning the events hash that maps events/selectors to methods on your View. - * For assigning events as object hash, do it like this: this.events = { "event:selector": callback, ... }; - * That works only if you set it in the constructor or the initialize method. - **/ - events(): EventsHash; - - $(selector: string): JQuery; - model: TModel; - collection: Collection; - //template: (json, options?) => string; - setElement(element: HTMLElement|JQuery, delegate?: boolean): View; - id: string; - cid: string; - className: string; - tagName: string; - - el: any; - $el: JQuery; - setElement(element: any): View; - attributes: any; - $(selector: any): JQuery; - render(): View; - remove(): View; - make(tagName: any, attributes?: any, content?: any): any; - delegateEvents(events?: EventsHash): any; - delegate(eventName: string, selector: string, listener: Function): View; - undelegateEvents(): any; - undelegate(eventName: string, selector?: string, listener?: Function): View; - - _ensureElement(): void; - } - - // SYNC - function sync(method: string, model: Model, options?: JQueryAjaxSettings): any; - function ajax(options?: JQueryAjaxSettings): JQueryXHR; - var emulateHTTP: boolean; - var emulateJSON: boolean; - - // Utility - function noConflict(): typeof Backbone; - var $: JQueryStatic; -} - -declare module "backbone" { - export = Backbone; -} diff --git a/backbone/backbone-global.d.ts.tscparams b/backbone/backbone-global.d.ts.tscparams deleted file mode 100644 index 99e26e8cbe..0000000000 --- a/backbone/backbone-global.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ ---noImplicitAny ./underscore/underscore.d.ts diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index 3669a6c4e1..1787b0eccf 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// function test_events() { diff --git a/backbone/backbone-with-lodash-tests.ts b/backbone/backbone-with-lodash-tests.ts index e0b04880bf..1fe91bcdab 100644 --- a/backbone/backbone-with-lodash-tests.ts +++ b/backbone/backbone-with-lodash-tests.ts @@ -1,314 +1,315 @@ -/// -/// -/// +/// +/// -function test_events() { +namespace WithLoDash { + function test_events() { - var object = new Backbone.Events(); - object.on("alert", (eventName: string) => alert("Triggered " + eventName)); + var object = new Backbone.Events(); + object.on("alert", (eventName: string) => alert("Triggered " + eventName)); - object.trigger("alert", "an event"); + object.trigger("alert", "an event"); - var onChange = () => alert('whatever'); - var context: any; + var onChange = () => alert('whatever'); + var context: any; - object.off("change", onChange); - object.off("change"); - object.off(null, onChange); - object.off(null, null, context); - object.off(); -} - -class SettingDefaults extends Backbone.Model { - - // 'defaults' could be set in one of the following ways: - - defaults() { - return { - name: "Joe" - } + object.off("change", onChange); + object.off("change"); + object.off(null, onChange); + object.off(null, null, context); + object.off(); } - constructor(attributes?: any, options?: any) { - super(attributes, options); // TODO error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. - this.defaults = { - name: "Joe" - } - // super has to come last - } + class SettingDefaults extends Backbone.Model { - // or set it like this - initialize() { - this.defaults = { - name: "Joe" - } + // 'defaults' could be set in one of the following ways: - } - - // same patterns could be used for setting 'Router.routes' and 'View.events' -} - -class Sidebar extends Backbone.Model { - - promptColor() { - var cssColor = prompt("Please enter a CSS color:"); - this.set({ color: cssColor }); - } -} - -class Note extends Backbone.Model { - initialize() { } - author() { } - coordinates() { } - allowedToEdit(account: any) { - return true; - } -} - -class PrivateNote extends Note { - allowedToEdit(account: any) { - return account.owns(this); - } - - set(attributes: any, options?: any): Backbone.Model { - return Backbone.Model.prototype.set.call(this, attributes, options); - } -} - -function test_models() { - - var sidebar = new Sidebar(); - sidebar.on('change:color', (model: {}, color: string) => $('#sidebar').css({ background: color })); - sidebar.set({ color: 'white' }); - sidebar.promptColor(); - - ////////// - - var note = new PrivateNote(); - - note.get("title"); - - note.set({ title: "March 20", content: "In his eyes she eclipses..." }); - - note.set("title", "A Scandal in Bohemia"); -} - -class Employee extends Backbone.Model { - reports: EmployeeCollection; - - constructor(attributes?: any, options?: any) { - super(options); - this.reports = new EmployeeCollection(); - this.reports.url = '../api/employees/' + this.id + '/reports'; - } - - more() { - this.reports.reset(); - } -} - -class EmployeeCollection extends Backbone.Collection { - findByName(key: any) { } -} - -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; -} - -class Books extends Backbone.Collection { } - -function test_collection() { - - var books = new Books(); - - var book1: Book = new Book({ title: "Title 1", author: "Mike" }); - books.add(book1); - - // 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 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); -} - -////////// - -Backbone.history.start(); - -namespace v1Changes { - namespace events { - function test_once() { - var model = new Employee; - model.once('invalid', () => { }, this); - model.once('invalid', () => { }); - } - - function test_listenTo() { - var model = new Employee; - var view = new Backbone.View(); - view.listenTo(model, 'invalid', () => { }); - } - - function test_listenToOnce() { - var model = new Employee; - var view = new Backbone.View(); - view.listenToOnce(model, 'invalid', () => { }); - } - - function test_stopListening() { - var model = new Employee; - var view = new Backbone.View(); - view.stopListening(model, 'invalid', () => { }); - view.stopListening(model, 'invalid'); - view.stopListening(model); - } - } - - namespace ModelAndCollection { - function test_url() { - Employee.prototype.url = () => '/employees'; - EmployeeCollection.prototype.url = () => '/employees'; - } - - function test_parse() { - var model = new Employee(); - model.parse('{}', {}); - var collection = new EmployeeCollection; - collection.parse('{}', {}); - } - - function test_toJSON() { - var model = new Employee(); - model.toJSON({}); - var collection = new EmployeeCollection; - collection.toJSON({}); - } - - function test_sync() { - var model = new Employee(); - model.sync(); - var collection = new EmployeeCollection; - collection.sync(); - } - } - - namespace Model { - function test_validationError() { - var model = new Employee; - if (model.validationError) { - console.log('has validation errors'); + defaults() { + return { + name: "Joe" } } - function test_fetch() { - var model = new Employee({ id: 1 }); - model.fetch({ - success: () => { }, - error: () => { } - }); + constructor(attributes?: any, options?: any) { + super(attributes, options); // TODO error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. + this.defaults = { + name: "Joe" + } + // super has to come last } - function test_set() { - var model = new Employee; - model.set({ name: 'JoeDoe', age: 21 }, { validate: false }); - model.set('name', 'JoeDoes', { validate: false }); + // or set it like this + initialize() { + this.defaults = { + name: "Joe" + } + } - function test_destroy() { - var model = new Employee; - model.destroy({ - wait: true, - success: (m?, response?, options?) => { }, - error: (m?, jqxhr?, options?) => { } - }); + // same patterns could be used for setting 'Router.routes' and 'View.events' + } - model.destroy({ - success: (m?, response?, options?) => { }, - error: (m?, jqxhr?) => { } - }); + class Sidebar extends Backbone.Model { - model.destroy({ - success: () => { }, - error: (m?, jqxhr?) => { } - }); + promptColor() { + var cssColor = prompt("Please enter a CSS color:"); + this.set({ color: cssColor }); + } + } + + class Note extends Backbone.Model { + initialize() { } + author() { } + coordinates() { } + allowedToEdit(account: any) { + return true; + } + } + + class PrivateNote extends Note { + allowedToEdit(account: any) { + return account.owns(this); } - function test_save() { - var model = new Employee; + set(attributes: any, options?: any): Backbone.Model { + return Backbone.Model.prototype.set.call(this, attributes, options); + } + } - model.save({ - name: 'Joe Doe', - age: 21 - }, - { + function test_models() { + + var sidebar = new Sidebar(); + sidebar.on('change:color', (model: {}, color: string) => $('#sidebar').css({ background: color })); + sidebar.set({ color: 'white' }); + sidebar.promptColor(); + + ////////// + + var note = new PrivateNote(); + + note.get("title"); + + note.set({ title: "March 20", content: "In his eyes she eclipses..." }); + + note.set("title", "A Scandal in Bohemia"); + } + + class Employee extends Backbone.Model { + reports: EmployeeCollection; + + constructor(attributes?: any, options?: any) { + super(options); + this.reports = new EmployeeCollection(); + this.reports.url = '../api/employees/' + this.id + '/reports'; + } + + more() { + this.reports.reset(); + } + } + + class EmployeeCollection extends Backbone.Collection { + findByName(key: any) { } + } + + 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; + } + + class Books extends Backbone.Collection { } + + function test_collection() { + + var books = new Books(); + + var book1: Book = new Book({ title: "Title 1", author: "Mike" }); + books.add(book1); + + // 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 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); + } + + ////////// + + Backbone.history.start(); + + namespace v1Changes { + namespace events { + function test_once() { + var model = new Employee; + model.once('invalid', () => { }, this); + model.once('invalid', () => { }); + } + + function test_listenTo() { + var model = new Employee; + var view = new Backbone.View(); + view.listenTo(model, 'invalid', () => { }); + } + + function test_listenToOnce() { + var model = new Employee; + var view = new Backbone.View(); + view.listenToOnce(model, 'invalid', () => { }); + } + + function test_stopListening() { + var model = new Employee; + var view = new Backbone.View(); + view.stopListening(model, 'invalid', () => { }); + view.stopListening(model, 'invalid'); + view.stopListening(model); + } + } + + namespace ModelAndCollection { + function test_url() { + Employee.prototype.url = () => '/employees'; + EmployeeCollection.prototype.url = () => '/employees'; + } + + function test_parse() { + var model = new Employee(); + model.parse('{}', {}); + var collection = new EmployeeCollection; + collection.parse('{}', {}); + } + + function test_toJSON() { + var model = new Employee(); + model.toJSON({}); + var collection = new EmployeeCollection; + collection.toJSON({}); + } + + function test_sync() { + var model = new Employee(); + model.sync(); + var collection = new EmployeeCollection; + collection.sync(); + } + } + + namespace Model { + function test_validationError() { + var model = new Employee; + if (model.validationError) { + console.log('has validation errors'); + } + } + + function test_fetch() { + var model = new Employee({ id: 1 }); + model.fetch({ + success: () => { }, + error: () => { } + }); + } + + function test_set() { + var model = new Employee; + model.set({ name: 'JoeDoe', age: 21 }, { validate: false }); + model.set('name', 'JoeDoes', { validate: false }); + } + + function test_destroy() { + var model = new Employee; + model.destroy({ wait: true, - validate: false, success: (m?, response?, options?) => { }, error: (m?, jqxhr?, options?) => { } }); - model.save({ - name: 'Joe Doe', - age: 21 - }, - { + model.destroy({ + success: (m?, response?, options?) => { }, + error: (m?, jqxhr?) => { } + }); + + model.destroy({ success: () => { }, error: (m?, jqxhr?) => { } }); + } + + function test_save() { + var model = new Employee; + + model.save({ + name: 'Joe Doe', + age: 21 + }, + { + wait: true, + validate: false, + success: (m?, response?, options?) => { }, + error: (m?, jqxhr?, options?) => { } + }); + + model.save({ + name: 'Joe Doe', + age: 21 + }, + { + success: () => { }, + error: (m?, jqxhr?) => { } + }); + } + + function test_validate() { + var model = new Employee; + + model.validate({ name: 'JoeDoe', age: 21 }, { validateAge: false }) + } } - function test_validate() { - var model = new Employee; + namespace Collection { + function test_fetch() { + var collection = new EmployeeCollection; + collection.fetch({ reset: true }); + } - model.validate({ name: 'JoeDoe', age: 21 }, { validateAge: false }) + function test_create() { + var collection = new EmployeeCollection; + var model = new Employee; + + collection.create(model, { + validate: false + }); + } + } + + namespace Router { + function test_navigate() { + var router = new Backbone.Router; + + router.navigate('/employees', { trigger: true }); + router.navigate('/employees', true); + } } } - - namespace Collection { - function test_fetch() { - var collection = new EmployeeCollection; - collection.fetch({ reset: true }); - } - - function test_create() { - var collection = new EmployeeCollection; - var model = new Employee; - - collection.create(model, { - validate: false - }); - } - } - - namespace Router { - function test_navigate() { - var router = new Backbone.Router; - - router.navigate('/employees', { trigger: true }); - router.navigate('/employees', true); - } - } -} +} \ No newline at end of file diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts deleted file mode 100644 index 65e273a61f..0000000000 --- a/backbone/backbone.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// Type definitions for Backbone 1.0.0 -// Project: http://backbonejs.org/ -// Definitions by: Boris Yankov , Natan Vivo -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// diff --git a/backbone/index.d.ts b/backbone/index.d.ts new file mode 100644 index 0000000000..d07d7e3c9d --- /dev/null +++ b/backbone/index.d.ts @@ -0,0 +1,395 @@ +// Type definitions for Backbone 1.0.0 +// Project: http://backbonejs.org/ +// Definitions by: Boris Yankov , Natan Vivo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = Backbone; +export as namespace Backbone; + +import * as _ from 'underscore'; + +declare namespace Backbone { + + interface AddOptions extends Silenceable { + at?: number; + } + + interface HistoryOptions extends Silenceable { + pushState?: boolean; + root?: string; + } + + interface NavigateOptions { + trigger?: boolean; + replace?: boolean; + } + + interface RouterOptions { + routes: any; + } + + interface Silenceable { + silent?: boolean; + } + + interface Validable { + validate?: boolean; + } + + interface Waitable { + wait?: boolean; + } + + interface Parseable { + parse?: any; + } + + interface PersistenceOptions { + url?: string; + data?: any; + beforeSend?: (jqxhr: JQueryXHR) => void; + success?: (modelOrCollection?: any, response?: any, options?: any) => void; + error?: (modelOrCollection?: any, jqxhr?: JQueryXHR, options?: any) => void; + } + + interface ModelSetOptions extends Silenceable, Validable { + } + + interface ModelFetchOptions extends PersistenceOptions, ModelSetOptions, Parseable { + } + + interface ModelSaveOptions extends Silenceable, Waitable, Validable, Parseable, PersistenceOptions { + patch?: boolean; + } + + interface ModelDestroyOptions extends Waitable, PersistenceOptions { + } + + interface CollectionFetchOptions extends PersistenceOptions, Parseable { + reset?: boolean; + } + + interface ObjectHash { + [key: string]: any; + } + + interface RoutesHash { + [routePattern: string]: string | {(...urlParts: string[]): void}; + } + + interface EventsHash { + [selector: string]: string | {(eventObject: JQueryEventObject): void}; + } + + class Events { + on(eventName: string, callback?: Function, context?: any): any; + on(eventMap: EventsHash): any; + off(eventName?: string, callback?: Function, context?: any): any; + trigger(eventName: string, ...args: any[]): any; + bind(eventName: string, callback: Function, context?: any): any; + unbind(eventName?: string, callback?: Function, context?: any): any; + + once(events: string, callback: Function, context?: any): any; + listenTo(object: any, events: string, callback: Function): any; + listenToOnce(object: any, events: string, callback: Function): any; + stopListening(object?: any, events?: string, callback?: Function): any; + } + + class ModelBase extends Events { + url: any; + parse(response: any, options?: any): any; + toJSON(options?: any): any; + sync(...arg: any[]): JQueryXHR; + } + + class Model extends ModelBase { + + /** + * Do not use, prefer TypeScript's extend functionality. + **/ + private static extend(properties: any, classProperties?: any): any; + + attributes: any; + changed: any[]; + cid: string; + collection: Collection; + + /** + * Default attributes for the model. It can be an object hash or a method returning an object hash. + * For assigning an object hash, do it like this: this.defaults = { attribute: value, ... }; + * That works only if you set it in the constructor or the initialize method. + **/ + defaults(): ObjectHash; + id: any; + idAttribute: string; + validationError: any; + urlRoot: any; + + constructor(attributes?: any, options?: any); + initialize(attributes?: any, options?: any): void; + + fetch(options?: ModelFetchOptions): JQueryXHR; + + /** + * 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; + changedAttributes(attributes?: any): any[]; + clear(options?: Silenceable): any; + clone(): Model; + destroy(options?: ModelDestroyOptions): any; + escape(attribute: string): string; + has(attribute: string): boolean; + hasChanged(attribute?: string): boolean; + isNew(): boolean; + isValid(options?:any): boolean; + previous(attribute: string): any; + previousAttributes(): any[]; + save(attributes?: any, options?: ModelSaveOptions): any; + unset(attribute: string, options?: Silenceable): Model; + validate(attributes: any, options?: any): any; + + private _validate(attributes: any, options: any): boolean; + + // mixins from underscore + + keys(): string[]; + values(): any[]; + pairs(): any[]; + invert(): any; + pick(keys: string[]): any; + pick(...keys: string[]): any; + omit(keys: string[]): any; + omit(...keys: string[]): any; + } + + class Collection extends ModelBase { + + /** + * Do not use, prefer TypeScript's extend functionality. + **/ + private static extend(properties: any, classProperties?: any): any; + + model: new (...args:any[]) => TModel; + models: TModel[]; + length: number; + + constructor(models?: TModel[] | Object[], options?: any); + initialize(models?: TModel[] | Object[], options?: any): void; + + fetch(options?: CollectionFetchOptions): JQueryXHR; + + /** + * Specify a model attribute name (string) or function that will be used to sort the collection. + */ + comparator: string | ((element: TModel) => number | string) | ((compare: TModel, to?: TModel) => number); + + add(model: {}|TModel, options?: AddOptions): TModel; + add(models: ({}|TModel)[], options?: AddOptions): TModel[]; + 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|string|Model): TModel; + create(attributes: any, options?: ModelSaveOptions): TModel; + pluck(attribute: string): any[]; + push(model: TModel, options?: AddOptions): TModel; + pop(options?: Silenceable): TModel; + remove(model: TModel, options?: Silenceable): TModel; + remove(models: TModel[], options?: Silenceable): TModel[]; + reset(models?: TModel[], options?: Silenceable): TModel[]; + set(models?: TModel[], options?: Silenceable): TModel[]; + shift(options?: Silenceable): TModel; + sort(options?: Silenceable): Collection; + unshift(model: TModel, options?: AddOptions): TModel; + where(properties: any): TModel[]; + findWhere(properties: any): TModel; + + private _prepareModel(attributes?: any, options?: any): any; + private _removeReference(model: TModel): void; + private _onModelEvent(event: string, model: TModel, collection: Collection, options: any): void; + + // mixins from underscore + + all(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; + any(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; + collect(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[]; + chain(): any; + contains(value: any): boolean; + countBy(iterator: (element: TModel, index: number) => any): _.Dictionary; + countBy(attribute: string): _.Dictionary; + detect(iterator: (item: any) => boolean, context?: any): any; // ??? + drop(): TModel; + drop(n: number): TModel[]; + each(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; + every(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; + filter(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[]; + find(iterator: (element: TModel, index: number) => boolean, context?: any): TModel; + first(): TModel; + first(n: number): TModel[]; + foldl(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; + forEach(iterator: (element: TModel, index: number, list?: any) => void, context?: any): any; + groupBy(iterator: (element: TModel, index: number) => string, context?: any): _.Dictionary; + groupBy(attribute: string, context?: any): _.Dictionary; + include(value: any): boolean; + indexOf(element: TModel, isSorted?: boolean): number; + initial(): TModel; + initial(n: number): TModel[]; + inject(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; + isEmpty(object: any): boolean; + invoke(methodName: string, args?: any[]): any; + last(): TModel; + last(n: number): TModel[]; + lastIndexOf(element: TModel, fromIndex?: number): number; + map(iterator: (element: TModel, index: number, context?: any) => any, context?: any): any[]; + max(iterator?: (element: TModel, index: number) => any, context?: any): TModel; + min(iterator?: (element: TModel, index: number) => any, context?: any): TModel; + reduce(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; + select(iterator: any, context?: any): any[]; + size(): number; + shuffle(): any[]; + slice(min: number, max?: number): TModel[]; + some(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; + sortBy(iterator: (element: TModel, index: number) => number, context?: any): TModel[]; + sortBy(attribute: string, context?: any): TModel[]; + sortedIndex(element: TModel, iterator?: (element: TModel, index: number) => number): number; + reduceRight(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any[]; + reject(iterator: (element: TModel, index: number) => boolean, context?: any): TModel[]; + rest(): TModel; + rest(n: number): TModel[]; + tail(): TModel; + tail(n: number): TModel[]; + toArray(): any[]; + without(...values: any[]): TModel[]; + } + + class Router extends Events { + + /** + * Do not use, prefer TypeScript's extend functionality. + **/ + private static extend(properties: any, classProperties?: any): any; + + /** + * Routes hash or a method returning the routes hash that maps URLs with parameters to methods on your Router. + * For assigning routes as object hash, do it like this: this.routes = { "route": callback, ... }; + * That works only if you set it in the constructor or the initialize method. + **/ + routes: RoutesHash | any; + + constructor(options?: RouterOptions); + initialize(options?: RouterOptions): void; + route(route: string|RegExp, name: string, callback?: Function): Router; + navigate(fragment: string, options?: NavigateOptions): Router; + navigate(fragment: string, trigger?: boolean): Router; + + private _bindRoutes(): void; + private _routeToRegExp(route: string): RegExp; + private _extractParameters(route: RegExp, fragment: string): string[]; + } + + var history: History; + + class History extends Events { + + handlers: any[]; + interval: number; + + start(options?: HistoryOptions): boolean; + + getHash(window?: Window): string; + getFragment(fragment?: string): string; + stop(): void; + route(route: string, callback: Function): number; + checkUrl(e?: any): void; + loadUrl(fragmentOverride: string): boolean; + navigate(fragment: string, options?: any): boolean; + static started: boolean; + options: any; + + private _updateHash(location: Location, fragment: string, replace: boolean): void; + } + + interface ViewOptions { + model?: TModel; + // TODO: quickfix, this can't be fixed easy. The collection does not need to have the same model as the parent view. + collection?: Backbone.Collection; //was: Collection; + el?: any; + events?: EventsHash; + id?: string; + className?: string; + tagName?: string; + attributes?: {[id: string]: any}; + } + + class View extends Events { + + /** + * Do not use, prefer TypeScript's extend functionality. + **/ + private static extend(properties: any, classProperties?: any): any; + + constructor(options?: ViewOptions); + initialize(options?: ViewOptions): void; + + /** + * Events hash or a method returning the events hash that maps events/selectors to methods on your View. + * For assigning events as object hash, do it like this: this.events = { "event:selector": callback, ... }; + * That works only if you set it in the constructor or the initialize method. + **/ + events(): EventsHash; + + $(selector: string): JQuery; + model: TModel; + collection: Collection; + //template: (json, options?) => string; + setElement(element: HTMLElement|JQuery, delegate?: boolean): View; + id: string; + cid: string; + className: string; + tagName: string; + + el: any; + $el: JQuery; + setElement(element: any): View; + attributes: any; + $(selector: any): JQuery; + render(): View; + remove(): View; + make(tagName: any, attributes?: any, content?: any): any; + delegateEvents(events?: EventsHash): any; + delegate(eventName: string, selector: string, listener: Function): View; + undelegateEvents(): any; + undelegate(eventName: string, selector?: string, listener?: Function): View; + + _ensureElement(): void; + } + + // SYNC + function sync(method: string, model: Model, options?: JQueryAjaxSettings): any; + function ajax(options?: JQueryAjaxSettings): JQueryXHR; + var emulateHTTP: boolean; + var emulateJSON: boolean; + + // Utility + function noConflict(): typeof Backbone; + var $: JQueryStatic; +} diff --git a/backbone/tsconfig.json b/backbone/tsconfig.json new file mode 100644 index 0000000000..85e19bf8a3 --- /dev/null +++ b/backbone/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "backbone-tests.ts" + ] +} \ No newline at end of file diff --git a/backgrid/backgrid-tests.ts b/backgrid/backgrid-tests.ts index f2a41a5587..225d8a6ef1 100644 --- a/backgrid/backgrid-tests.ts +++ b/backgrid/backgrid-tests.ts @@ -1,7 +1,7 @@ -/// -/// -/// +/// +import * as Backgrid from 'backgrid'; +import * as Backbone from 'backbone'; /* Uses getters and setters and requires ES >= 5 diff --git a/backgrid/backgrid-tests.ts.tscparams b/backgrid/backgrid-tests.ts.tscparams deleted file mode 100644 index 3af0fcfed7..0000000000 --- a/backgrid/backgrid-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ ---target ES5 diff --git a/backgrid/backgrid.d.ts b/backgrid/backgrid.d.ts deleted file mode 100644 index d208faf415..0000000000 --- a/backgrid/backgrid.d.ts +++ /dev/null @@ -1,128 +0,0 @@ -// Type definitions for Backgrid 0.2.6 -// Project: http://backgridjs.com/ -// Definitions by: Jeremy Lujan -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Backgrid { - - interface GridOptions { - columns: Column[]; - collection: Backbone.Collection; - header?: Header; - body?: Body; - row?: Row; - footer?: Footer; - } - - class Header extends Backbone.View { - } - - class Footer extends Backbone.View { - } - - class Row extends Backbone.View { - } - - class Command { - moveUp(): boolean; - moveDown(): boolean; - moveLeft(): boolean; - moveRight(): boolean; - save(): boolean; - cancel(): boolean; - passThru(): boolean; - } - - class CellFormatter { - fromRaw(rawData: any, model: Backbone.Model); - toRaw(formattedData: any, model: Backbone.Model); - } - - class NumberFormatter extends CellFormatter {} - - class PercentFormatter extends NumberFormatter {} - - class DateTimeFormatter extends CellFormatter {} - - class StringFormatter extends CellFormatter {} - - class EmailFormatter extends CellFormatter {} - - class SelectFormatter extends CellFormatter {} - - class CellEditor extends Backbone.View{ - initialize(options?: any); - postRender(model: Backbone.Model, column: Backbone.Model); - } - - class InputCellEditor extends CellEditor { - render(); - saveOrCancel(event: any); - } - - class Cell extends Backbone.View{ - tagName: string; - formatter: CellFormatter; - editor: InputCellEditor; - enterEditMode(); - renderError(); - exitEditMode(); - remove(); - } - - class StringCell extends Cell { - } - - interface ColumnAttr { - name: string; - cell: string; - headerCell: string; - label: string; - sortable: boolean; - editable: boolean; - renderable: boolean; - formater: string; - } - - class Column extends Backbone.Model { - initialize(options?: any); - } - - class Body extends Backbone.View { - tagName: string; - - initialize(options?: any); - insertRow(model: Backbone.Model, collection: Backbone.Collection, options: any); - moveToNextCell(model: Backbone.Model, cell: Column, command: Command); - refresh(): Body; - remove(): Body; - removeRow(model: Backbone.Model, collection: Backbone.Collection, options: any); - render(): Body; - } - - class Grid extends Backbone.View { - body: Backgrid.Body; - className: string; - footer: any; - header: any; - tagName: string; - - constructor(options: GridOptions); - - initialize(options: any); - getSelectedModels(): Backbone.Model[]; - insertColumn(...options: any[]): Grid; - insertRow(model: Backbone.Model, collection: Backbone.Collection, options: any); - remove(): Grid; - removeColumn(...options: any[]): Grid; - removeRow(model: Backbone.Model, collection: Backbone.Collection, options: any); - render(): Grid; - } - -} - -declare module "backgrid" { - export = Backgrid; -} diff --git a/backgrid/backgrid.d.ts.tscparams b/backgrid/backgrid.d.ts.tscparams deleted file mode 100644 index 5d4a276bca..0000000000 --- a/backgrid/backgrid.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ ---target es5 diff --git a/backgrid/index.d.ts b/backgrid/index.d.ts new file mode 100644 index 0000000000..83dc86bcbe --- /dev/null +++ b/backgrid/index.d.ts @@ -0,0 +1,127 @@ +// Type definitions for Backgrid 0.2.6 +// Project: http://backgridjs.com/ +// Definitions by: Jeremy Lujan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Backbone from 'backbone'; + +export as namespace Backgrid; +export = Backgrid; + +declare namespace Backgrid { + + interface GridOptions { + columns: Column[]; + collection: Backbone.Collection; + header?: Header; + body?: Body; + row?: Row; + footer?: Footer; + } + + class Header extends Backbone.View { + } + + class Footer extends Backbone.View { + } + + class Row extends Backbone.View { + } + + class Command { + moveUp(): boolean; + moveDown(): boolean; + moveLeft(): boolean; + moveRight(): boolean; + save(): boolean; + cancel(): boolean; + passThru(): boolean; + } + + class CellFormatter { + fromRaw(rawData: any, model: Backbone.Model); + toRaw(formattedData: any, model: Backbone.Model); + } + + class NumberFormatter extends CellFormatter {} + + class PercentFormatter extends NumberFormatter {} + + class DateTimeFormatter extends CellFormatter {} + + class StringFormatter extends CellFormatter {} + + class EmailFormatter extends CellFormatter {} + + class SelectFormatter extends CellFormatter {} + + class CellEditor extends Backbone.View{ + initialize(options?: any); + postRender(model: Backbone.Model, column: Backbone.Model); + } + + class InputCellEditor extends CellEditor { + render(); + saveOrCancel(event: any); + } + + class Cell extends Backbone.View{ + tagName: string; + formatter: CellFormatter; + editor: InputCellEditor; + enterEditMode(); + renderError(); + exitEditMode(); + remove(); + } + + class StringCell extends Cell { + } + + interface ColumnAttr { + name: string; + cell: string; + headerCell: string; + label: string; + sortable: boolean; + editable: boolean; + renderable: boolean; + formater: string; + } + + class Column extends Backbone.Model { + initialize(options?: any); + } + + class Body extends Backbone.View { + tagName: string; + + initialize(options?: any); + insertRow(model: Backbone.Model, collection: Backbone.Collection, options: any); + moveToNextCell(model: Backbone.Model, cell: Column, command: Command); + refresh(): Body; + remove(): Body; + removeRow(model: Backbone.Model, collection: Backbone.Collection, options: any); + render(): Body; + } + + class Grid extends Backbone.View { + body: Backgrid.Body; + className: string; + footer: any; + header: any; + tagName: string; + + constructor(options: GridOptions); + + initialize(options: any); + getSelectedModels(): Backbone.Model[]; + insertColumn(...options: any[]): Grid; + insertRow(model: Backbone.Model, collection: Backbone.Collection, options: any); + remove(): Grid; + removeColumn(...options: any[]): Grid; + removeRow(model: Backbone.Model, collection: Backbone.Collection, options: any); + render(): Grid; + } + +} diff --git a/backgrid/tsconfig.json b/backgrid/tsconfig.json new file mode 100644 index 0000000000..c4331d3a40 --- /dev/null +++ b/backgrid/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "backgrid-tests.ts" + ] +} \ No newline at end of file diff --git a/baconjs/baconjs-tests.ts b/baconjs/baconjs-tests.ts index ab5b671807..e948668dc7 100644 --- a/baconjs/baconjs-tests.ts +++ b/baconjs/baconjs-tests.ts @@ -1,4 +1,4 @@ -/// + function CreatingStreams() { $("#my-div").asEventStream("click"); diff --git a/baconjs/baconjs.d.ts b/baconjs/baconjs.d.ts deleted file mode 100644 index 50823ba422..0000000000 --- a/baconjs/baconjs.d.ts +++ /dev/null @@ -1,3132 +0,0 @@ -// Type definitions for Bacon.js 0.7.0 -// Project: https://baconjs.github.io/ -// Definitions by: Alexander Matsievsky -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -interface JQuery { - /** - * @method - * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. - * @param {string} eventName - * @returns {EventStream} - * @example - * $("#my-div").asEventStream("click"); - */ - asEventStream(eventName:string):Bacon.EventStream; - - /** - * @method - * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a jQuery live `selector`. - * @param {string} eventName - * @param {string} selector - * @returns {EventStream} - * @example - * $("#my-div").asEventStream("click", ".more-specific-selector"); - */ - asEventStream(eventName:string, selector:string):Bacon.EventStream; - - /** - * @callback JQuery#asEventStream1~f - * @param {JQueryEventObject} event - * @param {*[]} args - * @returns {A} - */ - /** - * @method JQuery#asEventStream1 - * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a function `f` that processes the jQuery event and its parameters. - * @param {string} eventName - * @param {JQuery#asEventStream1~f} f - * @returns {EventStream} - * @example - * $("#my-div").asEventStream("click", (event, args) => args[0]); - */ - asEventStream(eventName:string, f:(event:JQueryEventObject, args:any[]) => A):Bacon.EventStream; - - /** - * @callback JQuery#asEventStream2~f - * @param {JQueryEventObject} event - * @param {*[]} args - * @returns {A} - */ - /** - * @method JQuery#asEventStream2 - * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a jQuery live `selector` and a function `f` that processes the jQuery event and its parameters. - * @param {string} eventName - * @param {string} selector - * @param {JQuery#asEventStream2~f} f - * @returns {Bacon.EventStream} - * @example - * $("#my-div").asEventStream("click", ".more-specific-selector", (event, args) => args[0]); - */ - asEventStream(eventName:string, selector:string, f:(event:JQueryEventObject, args:any[]) => A):Bacon.EventStream; -} - -/** @module Bacon */ -declare namespace Bacon { - /** - * @function - * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the optional `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream. - * @param {Promise|JQueryXHR} promise - * @param {boolean} [abort] - * @returns {EventStream} - * @example - * Bacon.fromPromise($.ajax("https://baconjs.github.io/")); - * Bacon.fromPromise(Promise.resolve(1)); - * Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true); - * Bacon.fromPromise(Promise.resolve(1), false); - */ - function fromPromise(promise:Promise|JQueryXHR, abort?:boolean):EventStream; - - /** - * @callback Bacon.fromPromise~eventTransformer - * @param {A} value - * @returns {(Initial|Next|End|Error)[]} - */ - /** - * @function Bacon.fromPromise - * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream, and also pass a function `eventTransformer` that transforms the promise value into Events. The default is to transform the value into `[new Bacon.Next(value), new Bacon.End()]`. - * @param {Promise|JQueryXHR} promise - * @param {boolean} abort - * @param {Bacon.fromPromise~eventTransformer} eventTransformer - * @returns {EventStream} - * @example - * Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true, (n:string) => { - * return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; - * }); - * Bacon.fromPromise(Promise.resolve(1), false, n => { - * return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; - * }); - */ - function fromPromise(promise:Promise|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial|Next|End|Error)[]):EventStream; - - /** - * @function - * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods. - * @param {EventTarget|NodeJS.EventEmitter|JQuery} target - * @param {string} eventName - * @returns {EventStream} - * @example - * Bacon.fromEvent(document.body, "click").onValue(() => { - * alert("Bacon!"); - * }); - * Bacon.fromEvent(process.stdin, "readable", () => { - * alert("Bacon!"); - * }); - * Bacon.fromEvent($("body"), "click").onValue(() => { - * alert("Bacon!"); - * }); - */ - function fromEvent(target:EventTarget|NodeJS.EventEmitter|JQuery, eventName:string):EventStream; - - /** - * @callback Bacon.fromEvent~eventTransformer - * @param {A} event - * @returns {B} - */ - /** - * @function Bacon.fromEvent - * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods. You can pass a function `eventTransformer` that transforms the emitted events' parameters. - * @param {EventTarget|NodeJS.EventEmitter|JQuery} target - * @param {string} eventName - * @param {Bacon.fromEvent~eventTransformer} eventTransformer - * @returns {EventStream} - * @example - * Bacon.fromEvent(document.body, "click", (event:MouseEvent) => event.clientX).onValue(clientX => { - * alert("Bacon!"); - * }); - */ - function fromEvent(target:EventTarget|NodeJS.EventEmitter|JQuery, eventName:string, eventTransformer:(event:A) => B):EventStream; - - /** - * @callback Bacon.fromCallback1~f - * @param {Bacon.fromCallback1~callback} callback - * @returns {void} - */ - /** - * @callback Bacon.fromCallback1~callback - * @param {...*} args - * @returns {void} - */ - /** - * @function Bacon.fromCallback1 - * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a `callback`. The function is supposed to call its callback just once. - * @param {Bacon.fromCallback1~f} f - * @returns {EventStream} - * @example - * // This would create a stream that outputs a single value "Bacon!" and ends after that. The use of setTimeout causes the value to be delayed by 1 second. - * Bacon.fromCallback(callback => { - * setTimeout(() => { - * callback("Bacon!"); - * }, 1000); - * }); - */ - function fromCallback(f:(callback:(...args:any[]) => void) => void):EventStream; - - /** - * @callback Bacon.fromCallback2~f - * @param {...*} args - * @returns {void} - */ - /** - * @function Bacon.fromCallback2 - * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a `callback`. The function is supposed to call its callback just once. - * @param {Bacon.fromCallback2~f} f - * @param {...*} args - * @returns {EventStream} - * @example - * // You can also give any number of arguments to `fromCallback`, which will be passed to the function. These arguments can be simple variables, Bacon EventStreams or Properties. For example the following will output "Bacon rules": - * Bacon.fromCallback((a, b, callback) => { - * callback(a + " " + b); - * }, Bacon.constant("bacon"), "rules").log(); - */ - function fromCallback(f:(...args:any[]) => void, ...args:any[]):EventStream; - - /** - * @function - * @description Creates an [EventStream]{@link Bacon.EventStream} from a `methodName` method of a given `object`. The function is supposed to call its callback just once. - * @param {Object} object - * @param {string} methodName - * @param {...*} args - * @returns {EventStream} - */ - function fromCallback(object:Object, methodName:string, ...args:any[]):EventStream; - - /** - * @callback Bacon.fromNodeCallback~f - * @param {Bacon.fromNodeCallback~callback} callback - * @returns {void} - */ - /** - * @callback Bacon.fromNodeCallback~callback - * @param {E} error - * @param {A} data - * @returns {void} - */ - /** - * @function Bacon.fromNodeCallback - * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a Node.js `callback`: callback(error, data), where error is `null` if everything is fine. The function is supposed to call its callback just once. - * @param {Bacon.fromNodeCallback~f} f - * @param {...*} args - * @returns {EventStream} - * @example - * { - * let fs = require("fs"), - * read = Bacon.fromNodeCallback(fs.readFile, "input.txt"); - * read.onError(error => { - * console.log("Reading failed: " + error); - * }); - * read.onValue(value => { - * console.log("Read contents: " + value); - * }); - * } - */ - function fromNodeCallback(f:(callback:(error:E, data:A) => void) => void, ...args:any[]):EventStream; - - /** - * @function - * @description Creates an [EventStream]{@link Bacon.EventStream} from a `methodName` method of a given `object`. - * @param {Object} object - * @param {string} methodName - * @param {...*} args - * @returns {EventStream} - */ - function fromNodeCallback(object:Object, methodName:string, ...args:any[]):EventStream; - - /** - * @callback Bacon.fromPoll~f - * @returns {Next|End} - */ - /** - * @function Bacon.fromPoll - * @description Polls given function `f` with given `interval`. Function should return events: either [Next]{@link Bacon.Next} or [End]{@link Bacon.End}. Polling occurs only when there are subscribers to the stream. Polling ends permanently when `f` returns [End]{@link Bacon.End}. - * @param {number} interval - * @param {Bacon.fromPoll~f} f - * @returns {EventStream} - */ - function fromPoll(interval:number, f:() => Next|End):EventStream; - - /** - * @function Bacon.once - * @description Creates an [EventStream]{@link Bacon.EventStream} that delivers the given single `value` for the first subscriber. The stream will end immediately after this value. You can also send an [Error]{@link Bacon.Error} event instead of a `value`. - * @param {A|Error} value - * @returns {EventStream} - * @example - * Bacon.once(new Bacon.Error("fail")); - */ - function once(value:A|Error):EventStream; - - /** - * @function - * @description Creates an [EventStream]{@link Bacon.EventStream} that delivers the given series of `values` (given as array) to the first subscriber. The stream ends after these values have been delivered. You can also send [Error]{@link Bacon.Error} events, or any combination of pure values and error events. - * @param {(A|Error)[]} values - * @returns {EventStream} - * @example - * Bacon.fromArray([1, new Bacon.Error("")]); - */ - function fromArray(values:(A|Error)[]):EventStream; - - /** - * @function - * @description Repeats the single `value` indefinitely with the given `interval` (in milliseconds). - * @param {number} interval - * @param {A} value - * @returns {EventStream} - */ - function interval(interval:number, value:A):EventStream; - - /** - * @function - * @description Creates a [EventStream]{@link Bacon.EventStream} containing given `values` (given as array) with the given `interval` (in milliseconds). - * @param {number} interval - * @param {A[]} values - * @returns {EventStream} - */ - function sequentially(interval:number, values:A[]):EventStream; - - /** - * @function - * @description Repeats given `values` indefinitely with then given `interval` (in milliseconds). - * @param {number} interval - * @param {A[]} values - * @returns {EventStream} - * @example - * // The following would lead to `1,2,3,1,2,3...` to be repeated indefinitely: - * Bacon.fromArray([1, new Bacon.Error("")]); - */ - function repeatedly(interval:number, values:A[]):EventStream; - - /** - * @callback Bacon.repeat~f - * @param {number} iteration - * @returns {boolean|Observable} - */ - /** - * @function Bacon.repeat - * @description Calls generator function `f` which is expected to return an [Observable]{@link Bacon.Observable}. The returned [EventStream]{@link Bacon.EventStream} contains values and errors from the spawned observable. When the spawned Observable ends, the generator `f` is called again to spawn a new Observable. This is repeated until the generator `f` returns a falsy value (such as `undefined` or `false`). The generator `f` is called with one argument — `iteration` number starting from `0`. - * @param {Bacon.repeat~f} f - * @returns {EventStream} - * @example - * // The following will produce values `0,1,2`. - * Bacon.repeat(i => { - * if (i < 3) { - * return Bacon.once(i); - * } else { - * return false; - * } - * }).log(); - */ - function repeat(f:(iteration:number) => boolean|Observable):EventStream; - - /** - * @function Bacon.never - * @description Creates an [EventStream]{@link Bacon.EventStream} that immediately ends. - * @returns {EventStream} - */ - function never():EventStream; - - /** - * @function - * @description Creates a single-element [EventStream]{@link Bacon.EventStream} that produces given `value` after a given `delay` (in milliseconds). - * @param {number} delay - * @param {A} value - * @returns {EventStream} - */ - function later(delay:number, value:A):EventStream; - - /** - * @function - * @description Creates a constant [Property]{@link Bacon.Property} with value `x`. - * @param {A} x - * @returns {Property} - */ - function constant(x:A):Property; - - /** - * @callback Bacon.fromBinder~subscribe - * @param {Bacon.fromBinder~sink} sink - * @returns {Bacon.fromBinder~unsubscribe} - */ - /** - * @callback Bacon.fromBinder~sink - * @param {More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]} value - * @returns {void} - */ - /** - * @callback Bacon.fromBinder~unsubscribe - * @returns {void} - */ - /** - * @function Bacon.fromBinder - * @description Creates an [EventStream]{@link Bacon.EventStream} with the given [subscribe]{@link Bacon.fromBinder~subscribe} function. The parameter `subscribe` is a function that accepts a [sink]{@link Bacon.fromBinder~sink} which is a function that your `subscribe` function can "push" events to. You can push: a plain value, like `"first value"`; an [Event]{@link Bacon.Event} object including [Error]{@link Bacon.Error} (wraps an error) and [End]{@link Bacon.End} (indicates stream end); an array of event objects at once. The `subscribe` function must return a function. Let's call that function [unsubscribe]{@link Bacon.fromBinder~unsubscribe}. The returned function can be used by the subscriber (directly or indirectly) to unsubscribe from the EventStream. It should release all resources that the `subscribe` function reserved. The `sink` function may return [noMore]{@link Bacon.noMore} (as well as [more]{@link Bacon.more} or any other value). If it returns `noMore`, no further events will be consumed by the subscriber. The `subscribe` function may choose to clean up all resources at this point (e.g., by calling `unsubscribe`). This is usually not necessary, because further calls to `sink` are ignored, but doing so can increase performance in rare cases. The EventStream will wrap your `subscribe` function so that it will only be called when the first stream listener is added, and the `unsubscribe` function is called only after the last listener has been removed. The subscribe-unsubscribe cycle may of course be repeated indefinitely, so prepare for multiple calls to the `subscribe` function. - * @param {Bacon.fromBinder~subscribe} subscribe - * @returns {EventStream} - * @example - * let stream = Bacon.fromBinder(sink => { - * sink("first value"); - * sink([new Bacon.Next("2nd"), new Bacon.Next("3rd")]); - * sink(new Bacon.Next(() => { - * return "This one will be evaluated lazily" - * })); - * sink(new Bacon.Error("oops, an error")); - * sink(new Bacon.End()); - * return () => { - * // unsub functionality here, this one's a no-op - * }; - * }); - * stream.log(); - */ - function fromBinder(subscribe:(sink:(value:More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]) => void) => (() => void)):EventStream; - - /** - * @interface - * @see Bacon.more - */ - interface More { - } - /** - * @property more - * @constant - * @description The opaque value `sink` function may return. See [Bacon.fromBinder]{@link Bacon.fromBinder}. - */ - var more:More; - - /** - * @interface - * @see Bacon.noMore - */ - interface NoMore { - } - /** - * @property noMore - * @constant - * @description The opaque value `sink` function may return. See [Bacon.fromBinder]{@link Bacon.fromBinder}. - */ - var noMore:NoMore; - - /** - * @class Observable - * @description A superclass for [EventStream]{@link Bacon.EventStream} and [Property]{@link Bacon.Property}. - * */ - interface Observable { - /** - * @callback Observable#onValue~f - * @param {A} value - * @returns {void} - */ - /** - * @callback Observable#onValue~unsubscribe - * @returns {void} - */ - /** - * @method Observable#onValue - * @description Subscribes a given handler function `f` to the [Observable]{@link Bacon.Observable}. Function will be called for each new value. This is the simplest way to assign a side-effect to an Observable. The difference to the [EventStream.subscribe]{@link Bacon.EventStream#subscribe} and [Property.subscribe]{@link Bacon.Property#subscribe} methods is that the actual stream `value`s are received, instead of [Event]{@link Bacon.Event} objects. [EventStream.onValue]{@link Bacon.EventStream#onValue} and [Property.onValue]{@link Bacon.Property#onValue} behave similarly, except that the latter also pushes the initial value of the Property, in case there is one. - * @param {Observable#onValue~f} f - * @returns {Observable#onValue~unsubscribe} - */ - onValue(f:(value:A) => void):() => void; - - /** - * @callback Observable#onError~f - * @param {E} error - * @returns {void} - */ - /** - * @callback Observable#onError~unsubscribe - * @returns {void} - */ - /** - * @method Observable#onError - * @description Subscribes a given handler function `f` to [Error]{@link Bacon.Error} events. The function `f` will be called for each error in the [Observable]{@link Bacon.Observable}. - * @param {Observable#onError~f} f - * @returns {Observable#onError~unsubscribe} - */ - onError(f:(error:E) => void):() => void; - - /** - * @callback Observable#onEnd~f - * @returns {void} - */ - /** - * @callback Observable#onEnd~unsubscribe - * @returns {void} - */ - /** - * @method Observable#onEnd - * @description Subscribes a given handler function `f` to [End]{@link Bacon.End} event. The function `f` will be called when the [Observable]{@link Bacon.Observable} ends. Just like [EventStream.subscribe]{@link Bacon.EventStream#subscribe} and [Property.subscribe]{@link Bacon.Property#subscribe}, this method returns a function for `unsubscribe`ing. - * @param {Observable#onEnd~f} f - * @returns {Observable#onEnd~unsubscribe} - */ - onEnd(f:() => void):() => void; - - /** - * @callback Observable#toPromise~promiseCtr - * @param {A} value - * @returns {Promise} - */ - /** - * @method Observable#toPromise - * @description Returns a Promise which will be resolved with the last event coming from an [Observable]{@link Bacon.Observable}. The global ES6 promise implementation will be used unless a promise constructor `promiseCtr` is given. Use a shim if you need to support legacy browsers or platforms. - * @param {Observable#toPromise~promiseCtr} [promiseCtr] - * @returns {Promise} - */ - toPromise(promiseCtr?:(value:A) => Promise):Promise; - - /** - * @callback Observable#firstToPromise~promiseCtr - * @param {A} value - * @returns {Promise} - */ - /** - * @method Observable#firstToPromise - * @description Returns a Promise which will be resolved with the first event coming from an [Observable]{@link Bacon.Observable}. Like [Observable.toPromise]{@link Bacon.Observable#toPromise}, the global ES6 promise implementation will be used unless a promise constructor `promiseCtr` is given. - * @param {Observable#firstToPromise~promiseCtr} [promiseCtr] - * @returns {Promise} - */ - firstToPromise(promiseCtr?:(value:A) => Promise):Promise; - - /** - * @method - * @description Throttles the [Observable]{@link Bacon.Observable} using a buffer so that at most one value event in `minimumInteval` is issued. Unlike [EventStream.throttle]{@link Bacon.EventStream#throttle} and [Property.throttle]{@link Bacon.Property#throttle}, it doesn't discard the excessive events but buffers them instead, outputting them with a rate of at most one value per `minimumInterval`. - * @param {number} minimumInterval - * @returns {EventStream} - */ - bufferingThrottle(minimumInterval:number):EventStream; - - /** - * @callback Observable#flatMap~f - * @param {A} value - * @returns {B|Initial|Next|End|Error|Observable} - */ - /** - * @method Observable#flatMap - * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMap]{@link Bacon.Observable#flatMap} is always an EventStream. The "Function Construction rules" apply here. `flatMap` can be used conveniently with [Bacon.once]{@link Bacon.once} and [Bacon.never]{@link Bacon.never} for converting and filtering at the same time, including only some of the results. - * @param {Observable#flatMap~f} f - * @returns {EventStream} - * @example - * // Converting strings to integers, skipping empty values: - * Bacon.once("").flatMap(text => { - * return text != "" ? parseInt(text) : Bacon.never(); - * }); - */ - flatMap(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; - - /** - * @callback Observable#flatMapLatest~f - * @param {A} value - * @returns {B|Initial|Next|End|Error|Observable} - */ - /** - * @method Observable#flatMapLatest - * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, but instead of including events from all spawned streams, only includes them from the latest spawned stream into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapLatest]{@link Bacon.Observable#flatMapLatest} is always an EventStream. - * @param {Observable#flatMapLatest~f} f - * @returns {EventStream} - */ - flatMapLatest(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; - - /** - * @callback Observable#flatMapFirst~f - * @param {A} value - * @returns {B|Initial|Next|End|Error|Observable} - */ - /** - * @method Observable#flatMapFirst - * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f` only if the previously spawned stream has ended, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapFirst]{@link Bacon.Observable#flatMapFirst} is always an EventStream. - * @param {Observable#flatMapFirst~f} f - * @returns {EventStream} - */ - flatMapFirst(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; - - /** - * @callback Observable#flatMapError~f - * @param {E} error - * @returns {B|Initial|Next|End|Error|Observable} - */ - /** - * @method Observable#flatMapError - * @description For each [Error]{@link Bacon.Error} event in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapError]{@link Bacon.Observable#flatMapError} is always an EventStream. - * @param {Observable#flatMapError~f} f - * @returns {EventStream} - */ - flatMapError(f:(error:E) => B|Initial|Next|End|Error|Observable):EventStream; - - /** - * @callback Observable#flatMapWithConcurrencyLimit~f - * @param {A} value - * @returns {B|Initial|Next|End|Error|Observable} - */ - /** - * @method Observable#flatMapWithConcurrencyLimit - * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}, but limit the number of open spawned streams and buffers incoming events by `limit` amount. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. [flatMapConcat]{@link Bacon.Observable#flatMapConcat} is [flatMapWithConcurrencyLimit]{@link Bacon.Observable#flatMapWithConcurrencyLimit}(1) (only one input active), and [flatMap]{@link Bacon.Observable#flatMap} is [flatMapWithConcurrencyLimit]{@link Bacon.Observable#flatMapWithConcurrencyLimit}(∞) (all inputs are piped to output). The result of `flatMapWithConcurrencyLimit` is always an EventStream. - * @param {number} limit - * @param {Observable#flatMapWithConcurrencyLimit~f} f - * @returns {EventStream} - */ - flatMapWithConcurrencyLimit(limit:number, f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; - - /** - * @callback Observable#flatMapConcat~f - * @param {A} value - * @returns {B|Initial|Next|End|Error|Observable} - */ - /** - * @method Observable#flatMapConcat - * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}, but limit the number of open spawned streams and buffers incoming events to 1. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of `flatMapConcat` is always an EventStream. - * @param {Observable#flatMapConcat~f} f - * @returns {EventStream} - */ - flatMapConcat(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; - - /** - * @callback Observable#scan~f - * @param {B} acc - * @param {A} next - * @returns {B} - */ - /** - * @method Observable#scan - * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, resulting to a [Property]{@link Bacon.Property}. For example, you might use zero as `seed` and a "plus" function as the accumulator to create an "integral" Property. When applied to a Property as in `r = p.scan(seed, f)`, there's a (hopefully insignificant) catch: the starting value for `r` depends on whether `p` has an initial value when `scan` is applied. If there's no initial value, this works identically to `[EventStream]{@link Bacon.EventStream}.scan`: the `seed` will be the initial value of `r`. However, if `r` already has a current/initial value `x`, the seed won't be output as is. Instead, the initial value of `r` will be `f(seed, x)`. This makes sense, because there can only be 1 initial value for a Property at a time. - * @param {B} seed - * @param {Observable#scan~f} f - * @returns {Property} - * @example - * Bacon.sequentially(1, [1, 2, 3]).scan(0, (a, b) => a + b); - */ - scan(seed:B, f:(acc:B, next:A) => B):Property; - - /** - * @callback Observable#fold~f - * @param {B} acc - * @param {A} next - * @returns {B} - */ - /** - * @method Observable#fold - * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, but only emits the final value, i.e. the value just before the Observable ends. Returns a [Property]{@link Bacon.Property}. - * @param {B} seed - * @param {Observable#fold~f} f - * @returns {Property} - */ - fold(seed:B, f:(acc:B, next:A) => B):Property; - - /** - * @callback Observable#reduce~f - * @param {B} acc - * @param {A} next - * @returns {B} - */ - /** - * @method Observable#reduce - * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, but only emits the final value, i.e. the value just before the Observable ends. Returns a [Property]{@link Bacon.Property}. - * @param {B} seed - * @param {Observable#reduce~f} f - * @returns {Property} - */ - reduce(seed:B, f:(acc:B, next:A) => B):Property; - - /** - * @callback Observable#diff~f - * @param {A} a - * @param {B} b - * @returns {B} - */ - /** - * @method Observable#diff - * @description Returns a [Property]{@link Bacon.Property} that represents the result of a comparison `f` between the previous and current value of the [Observable]{@link Bacon.Observable}. For the initial value of the Observable, the previous value will be the given `start`. - * @param {A} start - * @param {Observable#diff~f} f - * @returns {Property} - * @example - * Bacon.sequentially(1, [1, 2, 3]).diff(0, (a, b) => Math.abs(b - a)); - */ - diff(start:A, f:(a:A, b:A) => B):Property; - - /** - * @callback Observable#zip~f - * @param {A} a - * @param {B} b - * @returns {C} - */ - /** - * @method Observable#zip - * @description Returns an [EventStream]{@link Bacon.EventStream} with elements pair-wise lined up with events from this and the `other` EventStream. A zipped EventStream will publish only when it has a value from each EventStream and will only produce values up to when any single EventStream ends. The given function `f` is used to create the result value from value in the two source EventStream. If no function `f` is given, the values are zipped into an array. Be careful not to have too much "drift" between streams. If one stream produces many more values than some other excessive buffering will occur inside the zipped observable. - * @param {EventStream} other - * @param {Observable#zip~f} f - * @returns {EventStream} - * @example - * { - * let x = Bacon.fromArray([1, 2]), - * y = Bacon.fromArray([3, 4]); - * x.zip(y, (x, y) => x + y); - * } - */ - zip(other:EventStream, f:(a:A, b:B) => C):EventStream; - - /** - * @method - * @description Returns a [Property]{@link Bacon.Property} that represents a "sliding window" into the history of the values of the [Observable]{@link Bacon.Observable}. The resulting Property will have a value that is an array containing the last `n` values of the original Observable, where `n` is at most the value of the `max` argument, and at least the value of the `min` argument. If the `min` argument is omitted, there's no lower limit of values. - * @param {number} max - * @param {number} [min] - * @returns {Property} - * @example - * // If you have a EventStream `s` with a value sequence `1,2,3,4,5`, the respective values in `s.slidingWindow(2)` would be `[],[1],[1,2],[2,3],[3,4],[4,5]`: - * Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2); - * // The values of `s.slidingWindow(2,2)`would be `[1,2],[2,3],[3,4],[4,5]`: - * Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2, 2); - */ - slidingWindow(max:number, min?:number):Property; - - /** - * @callback Observable#combine~f - * @param {A} a - * @param {B} b - * @returns {C} - */ - /** - * @method Observable#combine - * @description Combines the latest values of the two [EventStream]{@link Bacon.EventStream}s or [Property]{@link Bacon.Property}s using a two-arg function `f`. The result is a Property. - * @param {Property} property2 - * @param {Observable#combine~f} f - * @returns {Property} - */ - combine(property2:Property, f:(a:A, b:B) => C):Property; - - /** - * @callback Observable#withStateMachine~f - * @param {B} state - * @param {Initial|Next|End|Error} event - * @returns {[B, (Initial|Next|End|Error)[]]} - */ - /** - * @method Observable#withStateMachine - * @description Lets you run a state machine on an [Observable]{@link Bacon.Observable}. Give it an initial state `initState` object and a state transformation function `f` that processes each incoming [Event]{@link Bacon.Event} and returns and array containing the next `state` and an array of output Event's. - * @param {B} initState - * @param {Observable#withStateMachine~f} f - * @returns {EventStream} - * @example - * // Calculate the total sum of all numbers in the stream and output the value on stream end: - * Bacon.fromArray([1, 2, 3]).withStateMachine(0, (sum, event) => { - * if (event.hasValue()) { - * // had to cast to `number` because event:Bacon.Next|Bacon.Error<{}> - * return [sum + event.value(), []]; - * } else if (event.isEnd()) { - * return [undefined, [new Bacon.Next(sum), event]]; - * } else { - * return [sum, [event]]; - * } - * }); - */ - withStateMachine(initState:B, f:(state:B, event:Initial|Next|End|Error) => [B, (Initial|Next|End|Error)[]]):EventStream; - - /** - * @method - * @description Decodes input [Observable]{@link Bacon.Observable} using the given `mapping`. Is a bit like a switch-case or the decode function in Oracle SQL. The return value of `decode` is always a [Property]{@link Bacon.Property}. - * @param {Object} mapping - * @returns {Property} - * @example - * { - * let property = Bacon.fromArray([1, 2, 3]).toProperty(), - * who = Bacon.fromArray(["A", "B", "C"]).toProperty(); - * // The following would map the value 1 into the string "mike" and the value 2 into the value of the `who` property: - * property.decode({1: "mike", 2: who}); - * // You can compose static and dynamic data quite freely, as in: - * property.decode({1: {type: "mike"}, 2: {type: "other", whoThen: who}}); - * } - */ - decode(mapping:Object):Property; - - /** - * @method - * @description Creates a [Property]{@link Bacon.Property} that indicates whether Observable is awaiting `otherObservable`, i.e. has produced a value after the latest value from `otherObservable`. - * @param {Observable} otherObservable - * @returns {Property} - * @example - * { - * // This is handy for keeping track whether we are currently awaiting an AJAX response: - * let ajaxRequest = >{}, - * ajaxResponse = >{}, - * showAjaxIndicator = ajaxRequest.awaiting(ajaxResponse); - * } - */ - awaiting(otherObservable:Observable):Property; - } - - /** - * @class EventStream - * @augments Bacon.Observable - * @description A stream of events. - * */ - interface EventStream extends Observable { - /** - * @callback EventStream#map~f - * @param {A} value - * @returns {B} - */ - /** - * @method EventStream#map - * @description Maps [EventStream]{@link Bacon.EventStream} values using given function `f`, returning a new EventStream. The `map` method, among many others, uses lazy evaluation. - * @param {EventStream#map~f} f - * @returns {EventStream} - * */ - map(f:(value:A) => B):EventStream; - - /** - * @method - * @description Maps [EventStream]{@link Bacon.EventStream} values using given `constant` value, returning a new EventStream. The `map` method, among many others, uses lazy evaluation. - * @param {B} constant - * @returns {EventStream} - * */ - map(constant:B):EventStream; - - /** - * @method - * @description Maps [EventStream]{@link Bacon.EventStream} values using given `propertyExtractor` string like ".keyCode", returning a new EventStream. So, if `propertyExtractor` is a string starting with a dot, the elements will be mapped to the corresponding field/function in the event value. For instance map(".keyCode") will pluck the keyCode field from the input values. If `keyCode` was a function, the result EventStream would contain the values returned by the function. The "Function Construction rules" apply here. The `map` method, among many others, uses lazy evaluation. - * @param {string} propertyExtractor - * @returns {EventStream} - * */ - map(propertyExtractor:string):EventStream; - - /** - * @method - * @description Maps [EventStream]{@link Bacon.EventStream} events to the current value of the given [Property]{@link Bacon.Property} `property`. This is equivalent to [Property.sampledBy]{@link Bacon.Property#sampledBy}. - * @param {Property} property - * @returns {EventStream} - */ - map(property:Property):EventStream; - - /** - * @callback EventStream#mapError~f - * @param {E} error - * @returns {B} - */ - /** - * @method EventStream#mapError - * @description Maps [EventStream]{@link Bacon.EventStream} [Error]{@link Bacon.Error}s using given function `f`. More specifically, feeds the "error" field of the Error event to the function and produces a [Next]{@link Bacon.Next} event based on the return value. The "Function Construction rules" apply here. - * @param {EventStream#mapError~f} f - * @returns {EventStream} - */ - mapError(f:(error:E) => B):EventStream; - - /** - * @method - * @description Returns an [EventStream]{@link Bacon.EventStream} containing [Error]{@link Bacon.Error} events only. Same as filtering with a function that always returns `false`. - * @returns {EventStream} - */ - errors():EventStream; - - /** - * @method - * @description Skips all [Error]{@link Bacon.Error}s. - * @returns {EventStream} - */ - skipErrors():EventStream; - - /** - * @callback EventStream#mapEnd~f - * @returns {A} - */ - /** - * @method EventStream#mapEnd - * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} to [EventStream]{@link Bacon.EventStream}. The value is created by calling the given function `f` when the source [EventStream]{@link Bacon.EventStream} ends. - * @param {EventStream#mapEnd~f} f - * @returns {EventStream} - */ - mapEnd(f:() => A):EventStream; - - /** - * @method - * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} to [EventStream]{@link Bacon.EventStream}. A static `value` is used. - * @param {A} value - * @returns {EventStream} - */ - mapEnd(value:A):EventStream; - - /** - * @callback EventStream#filter~f - * @param {A} value - * @returns {boolean} - */ - /** - * @method EventStream#filter - * @description Filters [EventStream]{@link Bacon.EventStream} `value`s using a given predicate function `f`. - * @param {EventStream#filter~f} f - * @returns {EventStream} - */ - filter(f:(value:A) => boolean):EventStream; - - /** - * @method - * @description Filters [EventStream]{@link Bacon.EventStream} values using a given `constant` value (`true` to include all, `false` to exclude all). - * @param {boolean} bool - * @returns {EventStream} - */ - filter(bool:boolean):EventStream; - - /** - * @method - * @description Filters [EventStream]{@link Bacon.EventStream} values using a given `propertyExtractor` string (like ".isValuable"). - * @param {string} propertyExtractor - * @returns {EventStream} - */ - filter(propertyExtractor:string):EventStream; - - /** - * @method - * @description Filters [EventStream]{@link Bacon.EventStream} values based on the value of a [Property]{@link Bacon.Property} `property`. [Event]{@link Bacon.Event} will be included in output IF AND ONLY IF the `property` holds `true` at the time of the event. - * @param {Property} property - * @returns {EventStream} - */ - filter(property:Property):EventStream; - - /** - * @callback EventStream#takeWhile~f - * @param {A} value - * @returns {boolean} - */ - /** - * @method EventStream#takeWhile - * @description Takes [EventStream]{@link Bacon.EventStream} values while given predicate function `f` holds `true`, and then ends. - * @param {EventStream#takeWhile} f - * @returns {EventStream} - */ - takeWhile(f:(value:A) => boolean):EventStream; - - /** - * @method - * @description Takes [EventStream]{@link Bacon.EventStream} values while the value of a `property` holds `true`, and then ends. - * @param {Property} property - * @returns {EventStream} - */ - takeWhile(property:Property):EventStream; - - /** - * @method - * @description Takes at most n elements from the [EventStream]{@link Bacon.EventStream}. Equal to `Bacon.never()` if `n <= 0`. - * @param {number} n - * @returns {EventStream} - */ - take(n:number):EventStream; - - /** - * @method - * @description Takes elements from [EventStream]{@link Bacon.EventStream} until a [Next]{@link Bacon.Next} event appears in the EventStream `stream`. If `stream` ends without value, it is ignored. - * @param {EventStream} stream - * @returns {EventStream} - */ - takeUntil(stream:EventStream):EventStream; - - /** - * @method - * @description Takes the first element from the [EventStream]{@link Bacon.EventStream}. Essentially [Observable.take]{@link Bacon.EventStream#take}(1). - * @returns {EventStream} - */ - first():EventStream; - - /** - * @method - * @description Takes the last element from the [EventStream]{@link Bacon.EventStream}. None, if EventStream is empty. - * @returns {EventStream} - * @example - * // This creates the stream which doesn't produce any events and never ends: - * Bacon.interval(1e1, 0).last(); - */ - last():EventStream; - - /** - * @method - * @description Skips the first `n` elements from the [EventStream]{@link Bacon.EventStream}. - * @param {number} n - * @returns {EventStream} - */ - skip(n:number):EventStream; - - /** - * @method - * @description Delays the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds). - * @param {number} delay - * @returns {EventStream} - */ - delay(delay:number):EventStream; - - /** - * @method EventStream#throttle - * @description Throttles the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds). Events are emitted with the minimum interval of `delay`. The implementation is based on [EventStream.bufferWithTime]{@link Bacon.EventStream#bufferWithTime}. - * @param {number} delay - * @returns {EventStream} - */ - throttle(delay:number):EventStream; - - /** - * @method EventStream#debounce - * @description Throttles the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds), but so that event is only emitted after the given "quiet period". The difference of [throttle]{@link Bacon.EventStream#throttle} and [debounce]{@link Bacon.EventStream#debounce} is the same as it is in the same methods in jQuery. - * @param {number} delay - * @returns {EventStream} - */ - debounce(delay:number):EventStream; - - /** - * @method - * @description Passes the first event in the [EventStream]{@link Bacon.EventStream} through, but after that, only passes events after a given `delay` (in milliseconds) have passed since previous output. - * @param {number} delay - * @returns {EventStream} - */ - debounceImmediate(delay:number):EventStream; - - /** - * @callback EventStream#doAction~f - * @param {A} value - * @returns {void} - */ - /** - * @method EventStream#doAction - * @description Returns an [EventStream]{@link Bacon.EventStream} where the function `f` is executed for each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. - * @param {EventStream#doAction~f} f - * @returns {EventStream} - */ - doAction(f:(value:A) => void):EventStream; - - /** - * @method - * @description Returns an [EventStream]{@link Bacon.EventStream} where the `propertyExtractor` string is applied to each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. - * @param {string} propertyExtractor - * @returns {EventStream} - */ - doAction(propertyExtractor:string):EventStream; - - /** - * @callback EventStream#doError~f - * @param {E} error - * @returns {void} - */ - /** - * @method EventStream#doError - * @description Returns an [EventStream]{@link Bacon.EventStream} where the function `f` is executed for each error, before dispatching to subscribers. That is, same as `doAction` but for errors. - * @param {EventStream#doError~f} f - * @returns {EventStream} - */ - doError(f:(error:E) => void):EventStream; - - /** - * @method - * @description Returns an [EventStream]{@link Bacon.EventStream} that inverts boolean values. - * @returns {EventStream} - */ - not():EventStream; - - /** - * @method EventStream#log - * @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. It optionally takes a `label` argument to pass to `console.log()` alongside each value. To assist with chaining, it returns the original EventStream. Note that as a side-effect, the EventStream will have a constant listener and will not be garbage-collected. So, use this for debugging only and remove from production code. - * @param {string} [label] - * @returns {EventStream} - */ - log(label?:string):EventStream; - - /** - * @method EventStream#doLog - * @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. [doLog]{@link Bacon.EventStream#doLog} behaves like [log]{@link Bacon.EventStream#log} but does not subscribe to the EventStream. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. - * @returns {EventStream} - */ - doLog():EventStream; - - /** - * @method - * @description Ends the [EventStream]{@link Bacon.EventStream} on first [Error]{@link Bacon.Error} event. The error is included in the output of the returned EventStream. - * @returns {EventStream} - */ - endOnError():EventStream; - - /** - * @callback EventStream#endOnError~f - * @param {E} error - * @returns {boolean} - */ - /** - * @method EventStream#endOnError - * @description Ends the [EventStream]{@link Bacon.EventStream} on first [Error]{@link Bacon.Error} event for which the given predicate function `f` returns `true`. The error is included in the output of the returned EventStream. - * @param {EventStream#endOnError} f - * @returns {EventStream} - */ - endOnError(f:(error:E) => boolean):EventStream; - - /** - * @callback EventStream#withHandler~f - * @param {Initial|Next|End|Error} event - * @returns {*} - */ - /** - * @method EventStream#withHandler - * @description Lets you do more custom event handling on [EventStream]{@link Bacon.EventStream}: you get all events to your function `f` and you can output any number of events and end the stream if you choose. Note that it's important to return the value from `this.push` so that the connection to the underlying stream will be closed when no more events are needed. - * @param {EventStream#withHandler~f} f - * @returns {EventStream} - * @example - * // Send an error and end the stream in case a value is below zero: - * Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { - * if (event.hasValue() && event.value() < 0) { - * this.push(new Bacon.Error("Value below zero")); - * return this.push(new Bacon.End()); - * } else { - * return this.push(event); - * } - * }); - */ - withHandler(f:(event:Initial|Next|End|Error) => any):EventStream; - - /** - * @method - * @description Sets the name of the [EventStream]{@link Bacon.EventStream}. Overrides the default implementation of `toString` and `inspect`. Returns itself. - * @param {string} newName - * @returns {EventStream} - */ - name(newName:string):EventStream; - - /** - * @method - * @description Sets the structured description of the [EventStream]{@link Bacon.EventStream}. The `toString` and `inspect` methods use this data recursively to create a string representation for the `EventStream`. This method is probably useful for Bacon core/library/plugin development only. - * @param {...*} param - * @returns {EventStream} - * @example - * { - * let src = Bacon.once(1), - * obs = src.map(x => -x); - * - * console.log(obs.toString()); - * // Bacon.once(1).map(function) - * - * obs.withDescription(src, "times", -1); - * console.log(obs.toString()); - * // Bacon.once(1).times(-1) - */ - withDescription(...param:any[]):EventStream; - - /** - * @callback EventStream#groupBy1~keyF - * @param {A} value - * @returns {B} - */ - /** - * @method EventStream#groupBy1 - * @description Groups [EventStream]{@link Bacon.EventStream} events to new EventStream's by `keyF`. - * @param {EventStream#groupBy1~keyF} keyF - * @returns {EventStream>} - */ - groupBy(keyF:(value:A) => B):EventStream>; - - /** - * @callback keyF - * @param {A} value - * @returns {B} - */ - /** - * @callback limitF - * @param {EventStream} groupedStream - * @param {Initial|Next|End|Error} groupStartingEvent - * @returns {EventStream} - */ - /** - * @description Groups [EventStream]{@link Bacon.EventStream} events to new EventStream's by `keyF`. `limitF` is provided to limit grouped stream life. EventStream transformed by `limitF` is passed on if provided. `limitF` gets grouped stream and the original [Event]{@link Bacon.Event} causing the EventStream to start as parameters. - * @param {keyF} keyF - * @param {limitF} limitF - * @returns {EventStream>} Grouped streams. - */ - groupBy(keyF:(value:A) => B, limitF:(groupedStream:EventStream, groupStartingEvent:Initial|Next|End|Error) => EventStream):EventStream>; - - /** - * @callback EventStream#subscribe~f - * @param {Event} event - * @returns {void|NoMore} - */ - /** - * @callback EventStream#subscribe~unsubscribe - * @returns {void} - */ - /** - * @method EventStream#subscribe - * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Function will receive [Event]{@link Bacon.Event} objects. The [subscribe]{@link EventStream#subscribe} call returns an [unsubscribe function]{@link EventStream#subscribe~unsubscribe} that you can call to unsubscribe. You can also unsubscribe by returning [Bacon.noMore]{@link Bacon.noMore} from the handler function as a reply to an Event. - * @param {EventStream#subscribe~f} f - * @returns {EventStream#subscribe~unsubscribe} - */ - subscribe(f:(event:Event) => void|NoMore):() => void; - - /** - * @callback EventStream#onValue~f - * @param {A} value - * @returns {void} - */ - /** - * @callback EventStream#onValue~unsubscribe - * @returns {void} - */ - /** - * @method EventStream#onValue - * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Function will be called for each new value in the EventStream. This is the simplest way to assign a side-effect to a EventStream. The difference to the [subscribe]{@link Bacon.EventStream#subscribe} method is that the actual EventStream values are received, instead of [Event]{@link Bacon.Event} objects. Just like `subscribe`, this method returns a function for `unsubscribe`ing. - * @param {EventStream#onValue~f} f - * @returns {EventStream#onValue~unsubscribe} - */ - onValue(f:(value:A) => void):() => void; - - /** - * @callback EventStream#onValues~f - * @param {*[]} args - * @returns {void} - */ - /** - * @callback EventStream#onValues~unsubscribe - * @returns {void} - */ - /** - * @method EventStream#onValues - * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Like [EventStream.onValue]{@link Bacon.EventStream#onValue}, but splits the value (assuming its an array) as function arguments to `f`. - * @param {EventStream#onValues~f} f - * @returns {EventStream#onValues~unsubscribe} - */ - onValues(f:(...args:any[]) => void):() => void; - - /** - * @callback EventStream#skipDuplicates~isEqual - * @param {A} oldValue - * @param {A} newValue - * @returns {boolean} - */ - /** - * @method EventStream#skipDuplicates - * @description Drops consecutive equal elements of the [EventStream]{@link Bacon.EventStream}. Uses the === operator for equality checking by default. If the `isEqual` argument is supplied, checks by calling [isEqual]{@link EventStream#skipDuplicates~isEqual}. For instance, to do a deep comparison, you can use the `isEqual` function from underscore.js like `stream.skipDuplicates(_.isEqual)`. - * @param {EventStream#skipDuplicates~isEqual} [isEqual] - * @returns {EventStream} - * @example - * Bacon.fromArray([1, 2, 2, 1]).skipDuplicates().log(); - * // > returns [1, 2, 1] in an order - */ - skipDuplicates(isEqual?:(oldValue:A, newValue:A) => boolean):EventStream; - - /** - * @method - * @description Concatenates two [EventStream]{@link Bacon.EventStream}s into one so that it will deliver events from EventStream until it ends and then deliver events from `otherStream`. This means too that events from `otherStream`, occurring before the end of EventStream will not be included in the result EventStream. - * @param {EventStream} otherStream - * @returns {EventStream} - */ - concat(otherStream:EventStream):EventStream; - - /** - * @method - * @description Merges two [EventStream]{@link Bacon.EventStream}s into one that delivers events from both. - * @param {EventStream} otherStream - * @returns {EventStream} - */ - merge(otherStream:EventStream):EventStream; - - /** - * @method - * @description Pauses and buffers the [EventStream]{@link Bacon.EventStream} if last event in `valve` is truthy. All buffered events are released when `valve` becomes falsy. - * @param {Observable} valve - * @returns {EventStream} - */ - holdWhen(valve:Observable):EventStream; - - /** - * @method - * @description Adds a starting `value` to the [EventStream]{@link Bacon.EventStream}, i.e. concats a EventStream containing a single `value` with this EventStream. - * @param {A} value - * @returns {EventStream} - */ - startWith(value:A):EventStream; - - /** - * @callback EventStream#skipWhile~f - * @param {A} value - * @returns {boolean} - */ - /** - * @method EventStream#skipWhile - * @description Skips elements in the [EventStream]{@link Bacon.EventStream} until the given predicate function `f` returns falsy once, and then lets all events pass through. - * @param {EventStream#skipWhile~f} f - * @returns {EventStream} - */ - skipWhile(f:(value:A) => boolean):EventStream; - - /** - * @method - * @description Skips elements in the [EventStream]{@link Bacon.EventStream} until the value of the given [Property]{@link Bacon.Property} `property` is falsy once, and then lets all events pass through. - * @param {Property} property - * @returns {EventStream} - */ - skipWhile(property:Property):EventStream; - - /** - * @method - * @description Skips elements from the [EventStream]{@link Bacon.EventStream} until a [Next]{@link Bacon.Next} event appears in `stream2`. In other words, starts delivering values from `stream` after first event appears in `stream2`. - * @param {EventStream} stream2 - * @returns {EventStream} - */ - skipUntil(stream2:EventStream):EventStream; - - /** - * @method - * @description Buffers the [EventStream]{@link Bacon.EventStream} with given `delay` (in milliseconds). The buffer is flushed at most once in the given `delay`. - * @param {number} delay - * @returns {EventStream} - * @example - * // You might get two events containing [1,2,3,4] and [5,6,7] respectively, given that the flush occurs between numbers 4 and 5: - * Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]).bufferWithTime(0); - */ - bufferWithTime(delay:number):EventStream; - - /** - * @callback EventStream#bufferWithTime~f - * @param {EventStream#bufferWithTime~defer} defer - * @returns {void} - */ - /** - * @callback EventStream#bufferWithTime~defer - * @param {...*} args - * @returns {void} - */ - /** - * @method EventStream#bufferWithTime - * @description Buffers the [EventStream]{@link Bacon.EventStream} with given "defer-function" `f`. - * @param {EventStream#bufferWithTime~f} f - * @returns {EventStream} - * @example - * // Here's an equivalent to `stream.bufferWithTime(10)`: - * let stream = Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]); - * stream.bufferWithTime(f => { setTimeout(f, 10); }); } - */ - bufferWithTime(f:(defer:(...args:any[]) => void) => void):EventStream; - - /** - * @method - * @description Buffers the [EventStream]{@link Bacon.EventStream} events with given `count`. The buffer is flushed when it contains the given `count` of elements. - * @param {number} count - * @returns {EventStream} - * @example - * // You will get output events with values `[1, 2]`, `[3, 4]` and `[5]`. - * Bacon.fromArray([1, 2, 3, 4, 5]).bufferWithCount(2); - */ - bufferWithCount(count:number):EventStream; - - /** - * @method - * @description Buffers the [EventStream]{@link Bacon.EventStream} events and flushes when either the buffer contains the given `count` of elements or the given `delay` (in milliseconds) has passed since last buffered event. - * @param {number} delay - * @param {number} count - * @returns {EventStream} - */ - bufferWithTimeOrCount(delay:number, count:number):EventStream; - - /** - * @method EventStream#toProperty - * @description Creates a [Property]{@link Bacon.Property} based on the [EventStream]{@link Bacon.EventStream}. Without arguments, you'll get a Property without an initial value and will get its first actual value from the EventStream, and after that it'll always have a current value. Given `initialValue` will be used as the current value until the first value comes from the EventStream. - * @param {A} [initialValue] - * @returns {Property} - */ - toProperty(initialValue?:A):Property; - } - - var EventStream:{ - /** - * @callback EventStream#new~subscribe - * @param {EventStream#new~sink} sink - * @returns {EventStream#new~unsubscribe} - */ - /** - * @callback EventStream#new~sink - * @param {More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]} value - * @returns {void} - */ - /** - * @callback EventStream#new~unsubscribe - * @returns {void} - */ - /** - * @constructor EventStream#new - * @constructs Bacon.EventStream - * @description Creates an [EventStream]{@link Bacon.EventStream} with the given `subscribe` function. - * @param {EventStream#new~subscribe} subscribe - * @returns {EventStream} - */ - new(subscribe:(sink:(value:More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]) => void) => (() => void)):EventStream; - }; - - /** - * @class Property - * @augments Bacon.Observable - * @description A reactive property. Has the concept of "current value". You can create a Property from an [EventStream]{@link Bacon.EventStream} by using either [EventStream.toProperty]{@link Bacon.EventStream#toProperty} or [Observable.scan]{@link Bacon.Observable#scan} method. Note: depending on how a Property is created, it may or may not have an initial value. The current value stays as its last value after the EventStream has ended. - * */ - interface Property extends Observable { - /** - * @callback Property#map~f - * @param {A} value - * @returns {B} - */ - /** - * @method Property#map - * @description Maps the [Property]{@link Bacon.Property} values using given function `f`, returning a new Property. This method, among many others, uses lazy evaluation. - * @param {Property#map~f} f - * @returns {Property} - * */ - map(f:(value:A) => B):Property; - - /** - * @method - * @description Maps the [Property]{@link Bacon.Property} values using given `constant` value, returning a new Property. This method, among many others, uses lazy evaluation. - * @param {B} constant - * @returns {Property} - * */ - map(constant:B):Property; - - /** - * @method - * @description Maps the [Property]{@link Bacon.Property} values using given `propertyExtractor` string like ".keyCode", returning a new Property. So, if f is a string starting with a dot, the elements will be mapped to the corresponding field/function in the event value. For instance map(".keyCode") will pluck the keyCode field from the input values. If "keyCode" was a function, the resulting Property would contain the values returned by the function. This method, among many others, uses lazy evaluation. - * @param {string} propertyExtractor - * @returns {Property} - * */ - map(propertyExtractor:string):Property; - - /** - * @callback Property#mapError~f - * @param {E} error - * @returns {B} - */ - /** - * @method Property#mapError - * @description Maps the [Property]{@link Bacon.Property} errors using given function `f`. More specifically, feeds the "error" field of the [Error]{@link Bacon.Error} event to the function `f` and produces a [Next]{@link Bacon.Next} event based on the return value. - * @param {Property#mapError~f} f - * @returns {Property} - */ - mapError(f:(error:E) => B):Property; - - /** - * @method - * @description Returns a [Property]{@link Bacon.Property} containing [Error]{@link Bacon.Error} events only. Same as filtering with a function that always returns false. - * @returns {Property} - */ - errors():Property; - - /** - * @method - * @description Skips all [Error]{@link Bacon.Error}s. - * @returns {Property} - */ - skipErrors():Property; - - /** - * @callback Property#mapEnd~f - * @returns {A} - */ - /** - * @method Property#mapEnd - * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} of the [Property]{@link Bacon.Property}. The value is created by calling the given function `f` when the source Property ends. - * @param {Property#mapEnd~f} f - * @returns {Property} - */ - mapEnd(f:() => A):Property; - - /** - * @method - * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} of the [Property]{@link Bacon.Property}. A static `value` is used. - * @param {A} value - * @returns {Property} - */ - mapEnd(value:A):Property; - - /** - * @callback Property#filter~f - * @param {A} value - * @returns {boolean} - */ - /** - * @method Property#filter - * @description Filters the [Property]{@link Bacon.Property} values using a given predicate function `f`. - * @param {Property#filter~f} f - * @returns {Property} - */ - filter(f:(value:A) => boolean):Property; - - /** - * @method - * @description Filters the [Property]{@link Bacon.Property} values using a given constant `bool` value (`true` to include all, `false` to exclude all). - * @param {boolean} bool - * @returns {Property} - */ - filter(bool:boolean):Property; - - /** - * @method - * @description Filters the [Property]{@link Bacon.Property} values using a given `propertyExtractor` string (like ".isValuable"). - * @param {string} propertyExtractor - * @returns {Property} - */ - filter(propertyExtractor:string):Property; - - /** - * @method - * @description Filters the [Property]{@link Bacon.Property} values based on the value of the Property `property`. Event will be included in output IF AND ONLY IF the `property` holds `true` at the time of the event. - * @param {Property} property - * @returns {Property} - */ - filter(property:Property):Property; - - /** - * @callback Property#takeWhile~f - * @param {A} value - * @returns {boolean} - */ - /** - * @method Property#takeWhile - * @description Takes the [Property]{@link Bacon.Property} values while given predicate function `f` holds `true`, and then ends. - * @param {Property#takeWhile~f} f - * @returns {Property} - */ - takeWhile(f:(value:A) => boolean):Property; - - /** - * @method - * @description Takes the [Property]{@link Bacon.Property} values while the value of a `property` holds `true`, and then ends. - * @param {Property} property - * @returns {Property} - */ - takeWhile(property:Property):Property; - - /** - * @method Property#take - * @description Takes at most `n` elements from the [Property]{@link Bacon.Property}. Equal to `Bacon.never()` if `n <= 0`. - * @param {number} n - * @returns {Property} - */ - take(n:number):Property; - - /** - * @method - * @description Takes elements from the [Property]{@link Bacon.Property} until a [Next]{@link Bacon.Next} event appears in the `stream`. If `stream` ends without value, it is ignored. - * @param {EventStream} stream - * @returns {Property} - */ - takeUntil(stream:EventStream):Property; - - /** - * @method - * @description Takes the first element from the [Property]{@link Bacon.Property}. Essentially [Property.take]{@link Bacon.Property#take}(1). - * @returns {Property} - */ - first():Property; - - /** - * @method - * @description Takes the last element from the [Property]{@link Bacon.Property}. None, if Property is empty. - * @returns {Property} - * @example - * // This creates the property which doesn't produce any events and never ends: - * Bacon.interval(1e1, 0).toProperty().last(); - */ - last():Property; - - /** - * @method - * @description Skips the first `n` elements from the [Property]{@link Bacon.Property}. - * @param {number} n - * @returns {Property} - */ - skip(n:number):Property; - - /** - * @method - * @description Delays the [Property]{@link Bacon.Property} by given `delay` (in milliseconds). Does not delay the initial value of a Property. - * @param {number} delay - * @returns {Property} - */ - delay(delay:number):Property; - - /** - * @method Property#throttle - * @description Throttles the [Property]{@link Bacon.Property} by given `delay` (in milliseconds). Events are emitted with the minimum interval of `delay`. The implementation is based on [EventStream.bufferWithTime]{@link Bacon.EventStream#bufferWithTime}. Does not affect emitting the initial value of a Property. - * @param {number} delay - * @returns {Property} - */ - throttle(delay:number):Property; - - /** - * @method Property#debounce - * @description Throttles the [Property]{@link Bacon.Property} by given `delay` (in milliseconds), but so that event is only emitted after the given "quiet period". Does not affect emitting the initial value of a Property. The difference of [throttle]{@link Bacon.Property#throttle} and [debounce]{@link Bacon.Property#debounce} is the same as it is in the same methods in jQuery. - * @param {number} delay - * @returns {Property} - */ - debounce(delay:number):Property; - - /** - * @method - * @description Passes the first event in the [Property]{@link Bacon.Property} through, but after that, only passes events after a given `delay` (in milliseconds) have passed since previous output. - * @param {number} delay - * @returns {Property} - */ - debounceImmediate(delay:number):Property; - - /** - * @callback Property#doAction~f - * @param {A} value - * @returns {void} - */ - /** - * @method Property#doAction - * @description Returns a [Property]{@link Bacon.Property} where the function `f` is executed for each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. - * @param {Property#doAction~f} f - * @returns {Property} - */ - doAction(f:(value:A) => void):Property; - - /** - * @method - * @description Returns a [Property]{@link Bacon.Property} where the `propertyExtractor` string is applied to each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. - * @param {string} propertyExtractor - * @returns {Property} - */ - doAction(propertyExtractor:string):Property; - - /** - * @callback Property#doError~f - * @param {E} error - * @returns {void} - */ - /** - * @method Property#doError - * @description Returns a [Property]{@link Bacon.Property} where the function `f` is executed for each error, before dispatching to subscribers. That is, same as [doAction]{@link Bacon.Property#doAction} but for [Error]{@link Bacon.Error}s. - * @param {Property#doError~f} f - * @returns {Property} - */ - doError(f:(error:E) => void):Property; - - /** - * @method - * @description Returns a [Property]{@link Bacon.Property} that inverts boolean values. - * @returns {Property} - */ - not():Property; - - /** - * @method Property#log - * @description Logs each value of the [Property]{@link Bacon.Property} to the console. It optionally takes a `label` argument to pass to `console.log()` alongside each value. To assist with chaining, it returns the original Property. Note that as a side-effect, the Property will have a constant listener and will not be garbage-collected. So, use this for debugging only and remove from production code. - * @param {string} [label] - * @returns {Property} - */ - log(label?:string):Property; - - /** - * @method Property#doLog - * @description Logs each value of the [Property]{@link Bacon.Property} to the console. [doLog]{@link Bacon.Property#doLog} behaves like [log]{@link Bacon.Property#log} but does not subscribe to the Property. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. - * @returns {Property} - */ - doLog():Property; - - /** - * @method - * @description Ends the [Property]{@link Bacon.Property} on first [Error]{@link Bacon.Error} event. The error is included in the output of the returned Property. - * @returns {Property} - */ - endOnError():Property; - - /** - * @callback Property#endOnError~f - * @param {E} error - * @returns {boolean} - */ - /** - * @method Property#endOnError - * @description Ends the [Property]{@link Bacon.Property} on first [Error]{@link Bacon.Error} event for which the given predicate function `f` returns `true`. The error is included in the output of the returned Property. - * @param {Property#endOnError~f} f - * @returns {Property} - */ - endOnError(f:(error:E) => boolean):Property; - - /** - * @callback Property#withHandler~f - * @param {Initial|Next|End|Error} event - * @returns {*} - */ - /** - * @method Property#withHandler - * @description Lets you do more custom event handling on the [Property]{@link Bacon.Property}: you get all events to your function `f` and you can output any number of [Event]{@link Bacon.Event}s and end the Property if you choose. Note that it's important to return the value from `this.push` so that the connection to the underlying stream will be closed when no more events are needed. - * @param {Property#withHandler~f} f - * @returns {Property} - * @example - * // Send an error and end the stream in case a value is below zero: - * Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { - * if (event.hasValue() && event.value() < 0) { - * this.push(new Bacon.Error("Value below zero")); - * return this.push(new Bacon.End()); - * } else { - * return this.push(event); - * } - * }); - */ - withHandler(f:(event:Initial|Next|End|Error) => any):Property; - - /** - * @method - * @description Sets the `newName` of the [Property]{@link Bacon.Property}. Overrides the default implementation of `toString` and `inspect`. Returns itself. - * @param {string} newName - * @returns {Property} - */ - name(newName:string):Property; - - /** - * @method - * @description Sets the structured description of the [Property]{@link Bacon.Property}. The `toString` and `inspect` methods use this data recursively to create a string representation for the Property. This method is probably useful for Bacon core/library/plugin development only. - * @param {...*} param - * @returns {Property} - * @example - * let src = Bacon.once(1), - * obs = src.map(x => -x); - * - * console.log(obs.toString()); - * // Bacon.once(1).map(function) - * - * obs.withDescription(src, "times", -1); - * console.log(obs.toString()); - * // Bacon.once(1).times(-1) - */ - withDescription(...param:any[]):Property; - - /** - * @method - * @description Creates an [EventStream]{@link Bacon.EventStream} based on this [Property]{@link Bacon.Property}. The EventStream contains also an event for the current value of this Property at the time this method was called. - * @returns {EventStream} - */ - toEventStream():EventStream; - - /** - * @callback Property#subscribe~f - * @param {Event} event - * @returns {void} - */ - /** - * @callback Property#subscribe~unsubscribe - * @returns {void} - */ - /** - * @method Property#subscribe - * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. If there's a current value, an [Initial]{@link Bacon.Initial} event will be pushed immediately. [Next]{@link Bacon.Next} event will be pushed on updates and an [End]{@link Bacon.End} event in case the source Property ends. Returns a function that you call to `unsubscribe`. - * @param {Property#subscribe~f} f - * @returns {Property#subscribe~unsubscribe} - */ - subscribe(f:(event:Event) => void):() => void; - - /** - * @callback Property#onValue~f - * @param {A} value - * @returns {void} - */ - /** - * @callback Property#onValue~unsubscribe - * @returns {void} - */ - /** - * @method Property#onValue - * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. Similar to [EventStream.onValue]{@link Bacon.EventStream#onValue}, except that also pushes the initial value of the Property, in case there is one. Just like [subscribe]{@link Bacon.Property#subscribe}, this method returns a function for `unsubscribe`ing. - * @param {Property#onValue~f} f - * @returns {Property#onValue~unsubscribe} - */ - onValue(f:(value:A) => void):() => void; - - /** - * @callback Property#onValues~f - * @param {*[]} args - * @returns {void} - */ - /** - * @callback Property#onValues~unsubscribe - * @returns {void} - */ - /** - * @method Property#onValues - * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. Like [onValue]{@link Bacon.Property#onValue}, but splits the value (assuming its an array) as function arguments to `f`. - * @param {Property#onValues~f} f - * @returns {Property#onValues~unsubscribe} - */ - onValues(f:(...args:any[]) => void):() => void; - - /** - * @method Property#assign - * @description Calls the `method` of the given `object` with each value of this [Property]{@link Bacon.Property}. You can optionally supply `params` which will be used as the first arguments of the `method` call. Note that the [assign]{@link Bacon.Property#assign} method is actually just a synonym for [onValue]{@link Bacon.Property#onValue}. - * @param {Object} obj - * @param {string} method - * @param {...*} params - * @returns {void} - * @example - * let property = Bacon.fromArray([1, 2, 3, 4, 5]).toProperty(); - * // If you want to assign your Property to the "disabled" attribute of a JQuery object, you can do this: - * property.assign($("#my-button"), "attr", "disabled"); - * // A simpler example would be to toggle the visibility of an element based on a Property: - * property.assign($("#my-button"), "toggle"); - */ - assign(obj:Object, method:string, ...params:any[]):void; - - /** - * @method - * @description Creates an [EventStream]{@link Bacon.EventStream} by sampling the [Property]{@link Bacon.Property} value at given `interval` (in milliseconds). - * @param {number} interval - * @returns {EventStream} - */ - sample(interval:number):EventStream; - - /** - * @method Property#sampledBy - * @description Creates an [EventStream]{@link Bacon.EventStream} by sampling the [Property]{@link Bacon.Property} value at each event from the given `stream`. The result EventStream will contain the value at each event in the source Property. - * @param {EventStream} stream - * @returns {EventStream} - */ - sampledBy(stream:EventStream):EventStream; - - /** - * @method - * @description Creates a [Property]{@link Bacon.Property} by sampling the value at each event from the given [Property]{@link Bacon.Property} `property`. The result Property will contain the value at each event in the source Property. - * @param {Property} property - * @returns {Property} - */ - sampledBy(property:Property):Property; - - /** - * @callback Property#sampledBy~f - * @param {A} propertyValue - * @param {B} samplerValue - * @returns {C} - */ - /** - * @method Property#sampledBy - * @description Samples the [Property]{@link Bacon.Property} on `streamOrProperty` events. The result values will be formed using the given function `f`. - * @param {Observable} streamOrProperty - * @param {Property#sampledBy~f} f - * @returns {EventStream} - */ - sampledBy(streamOrProperty:Observable, f:(propertyValue:A, samplerValue:B) => C):EventStream; - - /** - * @callback Property#skipDuplicates~isEqual - * @param {A} oldValue - * @param {A} newValue - * @returns {boolean} - */ - /** - * @method Property#skipDuplicates - * @description Drops consecutive equal elements. Uses the `===` operator for equality checking by default. If the `isEqual` argument is supplied, checks by calling `isEqual(oldValue, newValue)`. The old name for this method was `distinctUntilChanged`. - * @param {Property#skipDuplicates~isEqual} [isEqual] - * @returns {Property} - */ - skipDuplicates(isEqual?:(oldValue:A, newValue:A) => boolean):Property; - - /** - * @method Property#changes - * @description Returns an [EventStream]{@link Bacon.EventStream} of [Property]{@link Bacon.Property} value changes. Returns exactly the same events as the Property itself, except any [Initial]{@link Bacon.Initial} events (the stream DOES NOT include an event for the current value of the Property at the time this method was called). Note that [Property.changes]{@link Bacon.Property#changes} DOES NOT skip duplicate values, use [Property.skipDuplicates]{@link Bacon.Property#skipDuplicates} for that. - * @returns {EventStream} - */ - changes():EventStream; - - /** - * @method - * @description Combines [Property]{@link Bacon.Property}s with the && operator. - * @param {Property} other - * @returns {Property} - */ - and(other:Property):Property; - - /** - * @method - * @description Combines [Property]{@link Bacon.Property}s with the || operator. - * @param {Property} other - * @returns {Property} - */ - or(other:Property):Property; - - /** - * @method - * @description Adds an initial "default" value for the [Property]{@link Bacon.Property}. If the Property doesn't have an initial value of it's own, the given `value` will be used as the initial value. If the property has an initial value of its own, the given `value` will be ignored. - * @param {A} value - * @returns {Property} - */ - startWith(value:A):Property; - } - - /** - * @function Bacon.combineAsArray - * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values so that the result Property will have an array of all property values as its value. The input array may contain both Properties and EventStreams. In the latter case, the stream is first converted into a Property and then combined with the other Property's. - * @param {(A|Observable)[]} streams - * @returns {Property} - */ - function combineAsArray(streams:(A|Observable)[]):Property; - - /** - * @function - * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values so that the result Property will have an array of all property values as its value. Like [Bacon.combineAsArray]{@link Bacon.combineAsArray}, but `streams` are provided as a list of arguments as opposed to a single array. - * @param {...(A|Observable)} streams - * @returns {Property} - */ - function combineAsArray(...streams:(A|Observable)[]):Property; - - /** - * @callback Property#combineWith~f - * @param {...A} args - * @returns {B} - */ - /** - * @function Property#combineWith - * @description Combines given n [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values using the given n-ary function `f`. - * @param {Property#combineWith~f} f - * @param {...(A|Observable)} streams - * @returns {Property} - */ - function combineWith(f:(...args:A[]) => B, ...streams:(A|Observable)[]):Property; - - /** - * @function - * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values using a `template` object. - * @param {{string:number|boolean|string|Object|Observable}} template - * @returns {Property} - */ - function combineTemplate(template:{[label:string]:number|boolean|string|Object|Observable}):Property; - - /** - * @function - * @description Merges given array of [EventStream]{@link Bacon.EventStream}s. - * @param {EventStream[]} streams - * @returns {EventStream} - */ - function mergeAll(streams:EventStream[]):EventStream; - - /** - * @function - * @description Merges given array of [EventStream]{@link Bacon.EventStream}s. - * @param {...EventStream} streams - * @returns {EventStream} - */ - function mergeAll(...streams:EventStream[]):EventStream; - - /** - * @function - * @description Zips the array of `streams` in to a new [EventStream]{@link Bacon.EventStream} that will have an array of values from each source EventStream as its value. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. - * @param {EventStream[]} streams - * @returns {EventStream} - */ - function zipAsArray(streams:EventStream[]):EventStream; - - /** - * @function - * @description Zips the `streams` in to a new [EventStream]{@link Bacon.EventStream} that will have an array of values from each source EventStream as its value. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. EventStream's are provided as a list of arguments as opposed to a single array. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. - * @param {...EventStream} streams - * @returns {EventStream} - */ - function zipAsArray(...streams:EventStream[]):EventStream; - - /** - * @callback Bacon.zipWith1~f - * @param {...A} args - * @returns {B} - */ - /** - * @function Bacon.zipWith1 - * @description Zips the array of `streams` in to a new [EventStream]{@link Bacon.EventStream} that will combine the n values from EventStream's with n-ary function `f`. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. - * @param {EventStream[]} streams - * @param {Bacon.zipWith1~f} f - * @returns {EventStream} - */ - function zipWith(streams:EventStream[], f:(...args:A[]) => B):EventStream; - - /** - * @callback Bacon.zipWith2~f - * @param {...A} args - * @returns {B} - */ - /** - * @function Bacon.zipWith2 - * @description Zips the `streams` in to a new [EventStream]{@link Bacon.EventStream} that will combine the n values from EventStream's with n-ary function `f`. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Streams are provided as a list of arguments as opposed to a single array. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. - * @param {Bacon.zipWith2~f} f - * @param {...EventStream} streams - * @returns {EventStream} - */ - function zipWith(f:(...args:A[]) => B, ...streams:EventStream[]):EventStream; - - /** - * @function - * @description Is a shorthand for combining multiple sources ([EventStream]{@link Bacon.EventStream}s, [Property]{@link Bacon.Property}s, constants) as array and assigning the side-effect function `f` for the values. - * @param {...*} args - * @returns {void} - */ - function onValues(...args:any[]):void; - - /** - * @class Bus - * @augments Bacon.EventStream - * @description An [EventStream]{@link Bacon.EventStream} that allows you to [push]{@link Bacon.Bus#push} values into the EventStream. It also allows [plug]{@link Bacon.Bus#plug}ging other EventStream's into the Bus. The Bus practically merges all plugged-in streams and the values pushed using the [push]{@link Bacon.Bus#push} method. - */ - interface Bus extends EventStream { - /** - * @method Bus#push - * @description Pushes the given `value` to the [Bus]{@link Bacon.Bus}. - * @param {A} value - * @returns {void} - */ - push(value:A):void; - - /** - * @method - * @description Ends the [Bus]{@link Bacon.Bus}. Sends an [End]{@link Bacon.End} event to all subscribers. After this call, there'll be no more events to the subscribers. Also, the [Bus.push]{@link Bacon.Bus#push} and [Bus.plug]{@link Bacon.Bus#plug} methods have no effect. - * @returns {void} - */ - end():void; - - /** - * @method - * @description Sends an [Error]{@link Bacon.Error} with given `error` message to all subscribers. - * @param {E} error - * @returns {void} - */ - error(error:E):void; - - /** - * @callback Bus#plug~unplug - * @returns {void} - */ - /** - * @method Bus#plug - * @description Plugs the given [EventStream]{@link Bacon.EventStream} to the [Bus]{@link Bacon.Bus}. All events from the given `stream` will be delivered to the subscribers of the Bus. Returns a function `unplug` that can be used to unplug the same stream. The [plug]{@link Bacon.Bus#plug} method practically allows you to merge in other EventStream's after the creation of the Bus. - * @param {EventStream} stream - * @returns {Bus#plug~unplug} - */ - plug(stream:EventStream):() => void; - } - - var Bus:{ - /** - * @constructor - * @constructs Bacon.Bus - * @description Returns a new [Bus]{@link Bacon.Bus}. - * @returns {Bus} - */ - new():Bus; - }; - - /** - * @class Event - * @description Has subclasses [Initial]{@link Bacon.Initial}, [Next]{@link Bacon.Next}, [End]{@link Bacon.End} and [Error]{@link Bacon.Error}. - * */ - class Event { - /** - * @method - * @description Returns the value associated with a [Initial]{@link Bacon.Initial} or [Next]{@link Bacon.Next} event. - * @returns {A} - */ - value():A; - - /** - * @method - * @description Returns `true` for events of type [Initial]{@link Bacon.Initial} or [Next]{@link Bacon.Next}. - * @returns {boolean} - */ - hasValue():boolean; - - /** - * @method Error#isInitial - * @description Returns `true` for events of type [Initial]{@link Bacon.Initial}. - * @returns {boolean} - */ - isInitial():boolean; - - /** - * @method Error#isNext - * @description Returns `true` for events of type [Next]{@link Bacon.Next}. - * @returns {boolean} - */ - isNext():boolean; - - /** - * @method Error#isError - * @description Returns `true` for events of type [Error]{@link Bacon.Error}. - * @returns {boolean} - */ - isError():boolean; - - /** - * @method Error#isEnd - * @description Returns `true` for events of type [End]{@link Bacon.End}. - * @returns {boolean} - */ - isEnd():boolean; - } - - /** - * @class Error - * @augments Bacon.Event - * @description An error event. Call [Event.isError]{@link Bacon.Event#isError} to distinguish these events in your subscriber, or use [onError]{@link Bacon.Observable#onError} to react to error events only. [Error.error]{@link Bacon.Error#error} returns the associated error object (usually string). [Error]{@link Bacon.Error} events are always passed through all stream combinators. So, even if you filter all values out, the error events will pass through. If you use [Observable.flatMap]{@link Bacon.Observable#flatMap}, the result stream will contain Error events from the source as well as all the spawned stream. You can take action on errors by using the [Observable.onError]{@link Bacon.Observable#onError}. See documentation on [Observable.onError]{@link Bacon.Observable#onError}, [EventStream.mapError]{@link Bacon.EventStream#mapError}, [Property.mapError]{@link Bacon.Property#mapError}, [EventStream.errors]{@link Bacon.EventStream#errors}, [Property.errors]{@link Bacon.Property#errors}, [EventStream.skipErrors]{@link Bacon.EventStream#skipErrors}, [Property.skipErrors]{@link Bacon.Property#skipErrors}, [Bacon.retry]{@link Bacon.retry} and [Observable.flatMapError]{@link Bacon.Observable#flatMapError}. An Error does not terminate the stream. The methods [EventStream.endOnError]{@link Bacon.EventStream#endOnError} and [EventStream.endOnError]{@link Bacon.EventStream#endOnError} returns a stream/property that ends immediately after first error. Bacon.js doesn't currently generate any Error events itself (except when converting errors using [Bacon.fromPromise]{@link Bacon.fromPromise}). Error events definitely would be generated by streams derived from IO sources such as AJAX calls. - * @example - * // In case you want to convert (some) value events into Error events, you may use `flatMap` like this: - * Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { - * NOTE: had to explicitly specify the `` typing for `flatMap`. - * return x > 2 ? new Bacon.Error("too big") : x; - * }); - * - * // Conversely, if you want to convert some Error events into value events, you may use `flatMapError`: - * Bacon.fromArray([1, 2, 3, 4]).flatMapError(error => { - * let isNonCriticalError = error => Math.random() < .5, - * handleNonCriticalError = error => 42; - * return isNonCriticalError(error) ? handleNonCriticalError(error) : new Bacon.Error(error); - * }); - * - * // Note also that Bacon.js combinators do not catch errors that are thrown. Especially `map` doesn't do so. If you want to map things and wrap caught errors into Error events, you can do the following: - * Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { - * let dangerousFunction = x => { - * throw new Error("dangerous function!"); - * }; - * try { - * return dangerousFunction(x); - * } catch (e) { - * return new Bacon.Error(e); - * } - * }); - */ - class Error extends Event { - /** - * @constructor - * @constructs Error - * @param {E} error - * */ - constructor(error:E); - - /** - * @property Error#error - * @description Returns the `error` associated with an [Error]{@link Bacon.Error} event. - * @returns {E} - */ - error:E; - } - - /** - * @class End - * @augments Bacon.Event - * @description An end-of-stream event of [EventStream]{@link Bacon.EventStream} or [Property]{@link Bacon.Property}. Call [Event.isEnd]{@link Bacon.Event#isEnd} to distinguish an End from other events. - * */ - class End extends Event { - /** - * @constructor - * @constructs Bacon.End - * */ - constructor(); - } - - /** - * @class Initial - * @augments Bacon.Event - * @description The initial (current) value of a [Property]{@link Bacon.Property}. Call [Event.isInitial]{@link Bacon.Event#isInitial} to distinguish from other events. Only sent immediately after subscription to a Property. - * */ - class Initial extends Event { - /** - * @constructor - * @constructs Bacon.Initial - * @param {A} value - * */ - constructor(value:A); - } - - /** - * @class Next - * @augments Bacon.Event - * @description Next value in an [EventStream]{@link Bacon.EventStream} or a [Property]{@link Bacon.Property}. Call [Event.isNext]{@link Bacon.Event#isNext} to distinguish a Next event from other events. - * */ - class Next extends Event { - /** - * @constructor - * @constructs Bacon.Next - * @param {A} value - * @example - * new Bacon.Next("value"); - * */ - constructor(value:A); - - /** - * @callback Next#constructor - * @returns {A} - */ - /** - * @constructor Next#constructor - * @constructs Bacon.Next - * @description This version is safe only when you know that the actual value in the stream is not a function. The idea in using a function `f` instead of a plain value is that the internals on Bacon.js take advantage of lazy evaluation by deferring the evaluations of values created by `map`, `combine`. - * @param {Next#constructor} f - * @example - * new Bacon.Next(() => "value"); - * */ - constructor(f:() => A); - } - - /** - * @callback Bacon.retry1~source - * @description Function that produces an [EventStream]{@link Bacon.EventStream}. - * @returns {EventStream} - */ - /** - * @callback Bacon.retry1~isRetryable - * @description Function returning `true` to continue retrying, `false` to stop. Defaults to `true`. The [Error]{@link Bacon.Error} that occurred is given as a parameter. For example, there is usually no reason to retry a 404 HTTP error, whereas a 500 or a timeout might work on the next attempt. - * @param {E} error - * @returns {boolean} - */ - /** - * @callback Bacon.retry1~delay - * @description Function that returns the time in milliseconds to wait before retrying. Defaults to `0`. The function is given a `context` object with the keys `error` (the [Error]{@link Bacon.Error} that occurred) and `retriesDone` (the number of retries already performed) to help determine the appropriate delay, e.g. for an incremental backoff. - * @param {Object} context - * @param {E} context.error [Error]{@link Bacon.Error} that occurred - * @param {number} context.retriesDone number of retries already performed - * @returns {number} - */ - /** - * @function Bacon.retry1 - * @description Is used to retry the call when there is an [Error]{@link Bacon.Error} event in the [EventStream]{@link Bacon.EventStream} produced by the `source` function. - * @param {Object} options - * @param {Bacon.retry1~source} options.source function that produces an [EventStream]{@link Bacon.EventStream} - * @param {number} options.retries number of times to retry the `source` function in addition to the initial attempt - * @param {Bacon.retry1~isRetryable} [options.isRetryable] function returning `true` to continue retrying, `false` to stop. Defaults to `true`. - * @param {Bacon.retry1~delay} [options.delay] - function that returns the time in milliseconds to wait before retrying. Defaults to `0`. - * @returns {EventStream} - */ - function retry(options:{ - source:() => EventStream; - retries:number; - isRetryable?:(error:E) => boolean; - delay?:(context:{error:E; retriesDone:number}) => number; - }):EventStream; - - /** - * @callback Bacon.retry1~source - * @description Function that produces an [Property]{@link Bacon.Property}. - * @returns {Property} - */ - /** - * @callback Bacon.retry1~isRetryable - * @description Function returning `true` to continue retrying, `false` to stop. Defaults to `true`. The [Error]{@link Bacon.Error} that occurred is given as a parameter. For example, there is usually no reason to retry a 404 HTTP error, whereas a 500 or a timeout might work on the next attempt. - * @param {E} error - * @returns {boolean} - */ - /** - * @callback Bacon.retry1~delay - * @description Function that returns the time in milliseconds to wait before retrying. Defaults to `0`. The function is given a `context` object with the keys `error` (the [Error]{@link Bacon.Error} that occurred) and `retriesDone` (the number of retries already performed) to help determine the appropriate delay, e.g. for an incremental backoff. - * @param {Object} context - * @param {E} context.error [Error]{@link Bacon.Error} that occurred - * @param {number} context.retriesDone number of retries already performed - * @returns {number} - */ - /** - * @function Bacon.retry1 - * @description Is used to retry the call when there is an [Error]{@link Bacon.Error} event in the [Property]{@link Bacon.Property} produced by the `source` function. - * @param {Object} options - * @param {Bacon.retry1~source} options.source function that produces an [Property]{@link Bacon.Property} - * @param {number} options.retries number of times to retry the `source` function in addition to the initial attempt - * @param {Bacon.retry1~isRetryable} [options.isRetryable] function returning `true` to continue retrying, `false` to stop. Defaults to `true`. - * @param {Bacon.retry1~delay} [options.delay] - function that returns the time in milliseconds to wait before retrying. Defaults to `0`. - * @returns {Property} - */ - function retry(options:{ - source:() => Property; - retries:number; - isRetryable?:(error:E) => boolean; - delay?:(context:{error:E; retriesDone:number}) => number; - }):Property; - - /** - * @callback Bacon.when1~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @method Bacon.when1 - * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. - * @param {Observable[]} pattern1 - * @param {Bacon.when1~f1} f1 - * @returns {EventStream} - * @example - * { - * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: - * let tick = Bacon.interval(1e2, 0), - * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), - * handleTick = _ => `timestamp: NONE`, - * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; - * Bacon.when( - * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), - * [tick], handleTick - * ); - * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. - * } - * - * { - * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: - * let a = Bacon.once("a"), - * b = Bacon.once("b"), - * c = Bacon.once("c"), - * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; - * Bacon.zipWith(f, a, b, c); - * Bacon.when([a, b, c], f); - * } - * - * { - * // Join patterns as a "chemical machine". - * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: - * let oxygen = Bacon.interval(1e3, "O"), - * hydrogen = Bacon.interval(2e3, "H"), - * carbon = Bacon.interval(1.5e3, "C"), - * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, - * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; - * Bacon.when( - * [oxygen, hydrogen, hydrogen], makeWater, - * [oxygen, carbon], makeCarbonMonoxide - * ); - * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. - * } - * - * { - * // Join patterns and properties. - * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: - * // -- updating `quantity` sets `total` to `price * quantity`; - * // -- updating `total` sets `price` to `total / quantity`. - * let random = (x:number) => Math.round(x * Math.random()), - * id = (x:A):A => x; - * let $quantity = Bacon.interval(1e3, 10).map(random), - * $price = Bacon.interval(2e3, 100).map(random), - * $total = Bacon.interval(1.5e3, 1000).map(random); - * let quantity = $quantity.toProperty(1), - * price = Bacon.when( - * [$price], id, - * [$total, quantity], (x, y) => x / y - * ).toProperty(0), - * total = Bacon.when( - * [$total], id, - * [$price, quantity], (x, y) => x * y, - * [price, $quantity], (x, y) => x * y - * ).toProperty(0); - * } - * - * { - * // Join patterns and `Bacon.Bus`. - * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: - * // Availability of chopsticks are implemented using bus. - * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], - * // Hungry could be any type of observable, but we'll use bus here. - * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], - * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. - * eat = (i:number) => () => { - * setTimeout(() => { - * console.log("done!"); - * chopsticks[i].push({}); - * chopsticks[(i + 1) % 3].push({}); - * }, 1e3); - * return `philosopher ${i} eating`; - * }, - * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. - * dining = Bacon.when( - * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), - * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), - * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) - * ).log("dining"); - * // Make all chopsticks initially available. - * chopsticks[0].push({}); - * chopsticks[1].push({}); - * chopsticks[2].push({}); - * // Make philosophers hungry in some way, in this case we just push to their bus. - * for (let i = 0; i < 3; i++) { - * hungry[0].push({}); - * hungry[1].push({}); - * hungry[2].push({}); - * } - * } - */ - function when(pattern1:Observable[], f1:(...args:A1[]) => B):EventStream; - - /** - * @callback Bacon.when2~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.when2~f2 - * @param {...A2} args - * @returns {B} - */ - /** - * @method Bacon.when2 - * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. - * @param {Observable[]} pattern1 - * @param {Bacon.when2~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.when2~f2} f2 - * @returns {EventStream} - * @example - * { - * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: - * let tick = Bacon.interval(1e2, 0), - * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), - * handleTick = _ => `timestamp: NONE`, - * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; - * Bacon.when( - * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), - * [tick], handleTick - * ); - * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. - * } - * - * { - * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: - * let a = Bacon.once("a"), - * b = Bacon.once("b"), - * c = Bacon.once("c"), - * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; - * Bacon.zipWith(f, a, b, c); - * Bacon.when([a, b, c], f); - * } - * - * { - * // Join patterns as a "chemical machine". - * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: - * let oxygen = Bacon.interval(1e3, "O"), - * hydrogen = Bacon.interval(2e3, "H"), - * carbon = Bacon.interval(1.5e3, "C"), - * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, - * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; - * Bacon.when( - * [oxygen, hydrogen, hydrogen], makeWater, - * [oxygen, carbon], makeCarbonMonoxide - * ); - * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. - * } - * - * { - * // Join patterns and properties. - * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: - * // -- updating `quantity` sets `total` to `price * quantity`; - * // -- updating `total` sets `price` to `total / quantity`. - * let random = (x:number) => Math.round(x * Math.random()), - * id = (x:A):A => x; - * let $quantity = Bacon.interval(1e3, 10).map(random), - * $price = Bacon.interval(2e3, 100).map(random), - * $total = Bacon.interval(1.5e3, 1000).map(random); - * let quantity = $quantity.toProperty(1), - * price = Bacon.when( - * [$price], id, - * [$total, quantity], (x, y) => x / y - * ).toProperty(0), - * total = Bacon.when( - * [$total], id, - * [$price, quantity], (x, y) => x * y, - * [price, $quantity], (x, y) => x * y - * ).toProperty(0); - * } - * - * { - * // Join patterns and `Bacon.Bus`. - * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: - * // Availability of chopsticks are implemented using bus. - * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], - * // Hungry could be any type of observable, but we'll use bus here. - * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], - * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. - * eat = (i:number) => () => { - * setTimeout(() => { - * console.log("done!"); - * chopsticks[i].push({}); - * chopsticks[(i + 1) % 3].push({}); - * }, 1e3); - * return `philosopher ${i} eating`; - * }, - * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. - * dining = Bacon.when( - * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), - * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), - * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) - * ).log("dining"); - * // Make all chopsticks initially available. - * chopsticks[0].push({}); - * chopsticks[1].push({}); - * chopsticks[2].push({}); - * // Make philosophers hungry in some way, in this case we just push to their bus. - * for (let i = 0; i < 3; i++) { - * hungry[0].push({}); - * hungry[1].push({}); - * hungry[2].push({}); - * } - * } - */ - function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B):EventStream; - - /** - * @callback Bacon.when3~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.when3~f2 - * @param {...A2} args - * @returns {B} - */ - /** - * @callback Bacon.when3~f3 - * @param {...A3} args - * @returns {B} - */ - /** - * @method Bacon.when3 - * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. - * @param {Observable[]} pattern1 - * @param {Bacon.when3~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.when3~f2} f2 - * @param {Observable[]} pattern3 - * @param {Bacon.when3~f3} f3 - * @returns {EventStream} - * @example - * { - * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: - * let tick = Bacon.interval(1e2, 0), - * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), - * handleTick = _ => `timestamp: NONE`, - * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; - * Bacon.when( - * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), - * [tick], handleTick - * ); - * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. - * } - * - * { - * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: - * let a = Bacon.once("a"), - * b = Bacon.once("b"), - * c = Bacon.once("c"), - * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; - * Bacon.zipWith(f, a, b, c); - * Bacon.when([a, b, c], f); - * } - * - * { - * // Join patterns as a "chemical machine". - * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: - * let oxygen = Bacon.interval(1e3, "O"), - * hydrogen = Bacon.interval(2e3, "H"), - * carbon = Bacon.interval(1.5e3, "C"), - * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, - * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; - * Bacon.when( - * [oxygen, hydrogen, hydrogen], makeWater, - * [oxygen, carbon], makeCarbonMonoxide - * ); - * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. - * } - * - * { - * // Join patterns and properties. - * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: - * // -- updating `quantity` sets `total` to `price * quantity`; - * // -- updating `total` sets `price` to `total / quantity`. - * let random = (x:number) => Math.round(x * Math.random()), - * id = (x:A):A => x; - * let $quantity = Bacon.interval(1e3, 10).map(random), - * $price = Bacon.interval(2e3, 100).map(random), - * $total = Bacon.interval(1.5e3, 1000).map(random); - * let quantity = $quantity.toProperty(1), - * price = Bacon.when( - * [$price], id, - * [$total, quantity], (x, y) => x / y - * ).toProperty(0), - * total = Bacon.when( - * [$total], id, - * [$price, quantity], (x, y) => x * y, - * [price, $quantity], (x, y) => x * y - * ).toProperty(0); - * } - * - * { - * // Join patterns and `Bacon.Bus`. - * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: - * // Availability of chopsticks are implemented using bus. - * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], - * // Hungry could be any type of observable, but we'll use bus here. - * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], - * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. - * eat = (i:number) => () => { - * setTimeout(() => { - * console.log("done!"); - * chopsticks[i].push({}); - * chopsticks[(i + 1) % 3].push({}); - * }, 1e3); - * return `philosopher ${i} eating`; - * }, - * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. - * dining = Bacon.when( - * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), - * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), - * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) - * ).log("dining"); - * // Make all chopsticks initially available. - * chopsticks[0].push({}); - * chopsticks[1].push({}); - * chopsticks[2].push({}); - * // Make philosophers hungry in some way, in this case we just push to their bus. - * for (let i = 0; i < 3; i++) { - * hungry[0].push({}); - * hungry[1].push({}); - * hungry[2].push({}); - * } - * } - */ - function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B):EventStream; - - /** - * @callback Bacon.when4~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.when4~f2 - * @param {...A2} args - * @returns {B} - */ - /** - * @callback Bacon.when4~f3 - * @param {...A3} args - * @returns {B} - */ - /** - * @callback Bacon.when4~f4 - * @param {...A4} args - * @returns {B} - */ - /** - * @method Bacon.when4 - * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. - * @param {Observable[]} pattern1 - * @param {Bacon.when4~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.when4~f2} f2 - * @param {Observable[]} pattern3 - * @param {Bacon.when4~f3} f3 - * @param {Observable[]} pattern4 - * @param {Bacon.when4~f4} f4 - * @returns {EventStream} - * @example - * { - * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: - * let tick = Bacon.interval(1e2, 0), - * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), - * handleTick = _ => `timestamp: NONE`, - * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; - * Bacon.when( - * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), - * [tick], handleTick - * ); - * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. - * } - * - * { - * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: - * let a = Bacon.once("a"), - * b = Bacon.once("b"), - * c = Bacon.once("c"), - * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; - * Bacon.zipWith(f, a, b, c); - * Bacon.when([a, b, c], f); - * } - * - * { - * // Join patterns as a "chemical machine". - * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: - * let oxygen = Bacon.interval(1e3, "O"), - * hydrogen = Bacon.interval(2e3, "H"), - * carbon = Bacon.interval(1.5e3, "C"), - * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, - * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; - * Bacon.when( - * [oxygen, hydrogen, hydrogen], makeWater, - * [oxygen, carbon], makeCarbonMonoxide - * ); - * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. - * } - * - * { - * // Join patterns and properties. - * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: - * // -- updating `quantity` sets `total` to `price * quantity`; - * // -- updating `total` sets `price` to `total / quantity`. - * let random = (x:number) => Math.round(x * Math.random()), - * id = (x:A):A => x; - * let $quantity = Bacon.interval(1e3, 10).map(random), - * $price = Bacon.interval(2e3, 100).map(random), - * $total = Bacon.interval(1.5e3, 1000).map(random); - * let quantity = $quantity.toProperty(1), - * price = Bacon.when( - * [$price], id, - * [$total, quantity], (x, y) => x / y - * ).toProperty(0), - * total = Bacon.when( - * [$total], id, - * [$price, quantity], (x, y) => x * y, - * [price, $quantity], (x, y) => x * y - * ).toProperty(0); - * } - * - * { - * // Join patterns and `Bacon.Bus`. - * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: - * // Availability of chopsticks are implemented using bus. - * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], - * // Hungry could be any type of observable, but we'll use bus here. - * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], - * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. - * eat = (i:number) => () => { - * setTimeout(() => { - * console.log("done!"); - * chopsticks[i].push({}); - * chopsticks[(i + 1) % 3].push({}); - * }, 1e3); - * return `philosopher ${i} eating`; - * }, - * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. - * dining = Bacon.when( - * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), - * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), - * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) - * ).log("dining"); - * // Make all chopsticks initially available. - * chopsticks[0].push({}); - * chopsticks[1].push({}); - * chopsticks[2].push({}); - * // Make philosophers hungry in some way, in this case we just push to their bus. - * for (let i = 0; i < 3; i++) { - * hungry[0].push({}); - * hungry[1].push({}); - * hungry[2].push({}); - * } - * } - */ - function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B, pattern4:Observable[], f4:(...args:A4[]) => B):EventStream; - - /** - * @callback Bacon.when5~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.when5~f2 - * @param {...A2} args - * @returns {B} - */ - /** - * @callback Bacon.when5~f3 - * @param {...A3} args - * @returns {B} - */ - /** - * @callback Bacon.when5~f4 - * @param {...A4} args - * @returns {B} - */ - /** - * @callback Bacon.when5~f5 - * @param {...A5} args - * @returns {B} - */ - /** - * @method Bacon.when5 - * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. - * @param {Observable[]} pattern1 - * @param {Bacon.when5~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.when5~f2} f2 - * @param {Observable[]} pattern3 - * @param {Bacon.when5~f3} f3 - * @param {Observable[]} pattern4 - * @param {Bacon.when5~f4} f4 - * @param {Observable[]} pattern5 - * @param {Bacon.when5~f5} f5 - * @returns {EventStream} - * @example - * { - * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: - * let tick = Bacon.interval(1e2, 0), - * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), - * handleTick = _ => `timestamp: NONE`, - * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; - * Bacon.when( - * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), - * [tick], handleTick - * ); - * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. - * } - * - * { - * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: - * let a = Bacon.once("a"), - * b = Bacon.once("b"), - * c = Bacon.once("c"), - * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; - * Bacon.zipWith(f, a, b, c); - * Bacon.when([a, b, c], f); - * } - * - * { - * // Join patterns as a "chemical machine". - * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: - * let oxygen = Bacon.interval(1e3, "O"), - * hydrogen = Bacon.interval(2e3, "H"), - * carbon = Bacon.interval(1.5e3, "C"), - * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, - * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; - * Bacon.when( - * [oxygen, hydrogen, hydrogen], makeWater, - * [oxygen, carbon], makeCarbonMonoxide - * ); - * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. - * } - * - * { - * // Join patterns and properties. - * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: - * // -- updating `quantity` sets `total` to `price * quantity`; - * // -- updating `total` sets `price` to `total / quantity`. - * let random = (x:number) => Math.round(x * Math.random()), - * id = (x:A):A => x; - * let $quantity = Bacon.interval(1e3, 10).map(random), - * $price = Bacon.interval(2e3, 100).map(random), - * $total = Bacon.interval(1.5e3, 1000).map(random); - * let quantity = $quantity.toProperty(1), - * price = Bacon.when( - * [$price], id, - * [$total, quantity], (x, y) => x / y - * ).toProperty(0), - * total = Bacon.when( - * [$total], id, - * [$price, quantity], (x, y) => x * y, - * [price, $quantity], (x, y) => x * y - * ).toProperty(0); - * } - * - * { - * // Join patterns and `Bacon.Bus`. - * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: - * // Availability of chopsticks are implemented using bus. - * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], - * // Hungry could be any type of observable, but we'll use bus here. - * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], - * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. - * eat = (i:number) => () => { - * setTimeout(() => { - * console.log("done!"); - * chopsticks[i].push({}); - * chopsticks[(i + 1) % 3].push({}); - * }, 1e3); - * return `philosopher ${i} eating`; - * }, - * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. - * dining = Bacon.when( - * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), - * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), - * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) - * ).log("dining"); - * // Make all chopsticks initially available. - * chopsticks[0].push({}); - * chopsticks[1].push({}); - * chopsticks[2].push({}); - * // Make philosophers hungry in some way, in this case we just push to their bus. - * for (let i = 0; i < 3; i++) { - * hungry[0].push({}); - * hungry[1].push({}); - * hungry[2].push({}); - * } - * } - */ - function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B, pattern4:Observable[], f4:(...args:A4[]) => B, pattern5:Observable[], f5:(...args:A5[]) => B):EventStream; - - /** - * @callback Bacon.update1~f1 - * @param {B} initial - * @param {...A1} args - * @returns {B} - */ - /** - * @method Bacon.update1 - * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. - * @param {B} initial - * @param {Observable[]} pattern1 - * @param {Bacon.update1~f1} f1 - * @returns {Property} - * @example - * { - * // The inputs to `Bacon.update` are defined like this: - * let initial = 0, - * x = Bacon.interval(1e3, 1), - * y = Bacon.interval(2e3, 1), - * z = Bacon.interval(1.5e3, 1); - * // NOTE: had to explicitly specify the typing for `previous:number` - * Bacon.update(initial, - * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, - * [x, y], (previous:number, x, y) => previous + x + y + z - * ); - * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. - * } - * - * { - * // Here's a simple gaming example: - * let scoreMultiplier = Bacon.constant(1), - * hitUfo = new Bacon.Bus(), - * hitMotherShip = new Bacon.Bus(), - * score = Bacon.update(0, - * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, - * [hitMotherShip], (score, _) => score + 2000 - * ); - * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. - * } - */ - function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B):Property; - - /** - * @callback Bacon.update2~f1 - * @param {B} initial - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.update2~f2 - * @param {B} initial - * @param {...A2} args - * @returns {B} - */ - /** - * @method Bacon.update2 - * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. - * @param {B} initial - * @param {Observable[]} pattern1 - * @param {Bacon.update2~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.update2~f2} f2 - * @returns {Property} - * @example - * { - * // The inputs to `Bacon.update` are defined like this: - * let initial = 0, - * x = Bacon.interval(1e3, 1), - * y = Bacon.interval(2e3, 1), - * z = Bacon.interval(1.5e3, 1); - * // NOTE: had to explicitly specify the typing for `previous:number` - * Bacon.update(initial, - * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, - * [x, y], (previous:number, x, y) => previous + x + y + z - * ); - * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. - * } - * - * { - * // Here's a simple gaming example: - * let scoreMultiplier = Bacon.constant(1), - * hitUfo = new Bacon.Bus(), - * hitMotherShip = new Bacon.Bus(), - * score = Bacon.update(0, - * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, - * [hitMotherShip], (score, _) => score + 2000 - * ); - * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. - * } - */ - function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => B):Property; - - /** - * @callback Bacon.update3~f1 - * @param {B} initial - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.update3~f2 - * @param {B} initial - * @param {...A2} args - * @returns {B} - */ - /** - * @callback Bacon.update3~f3 - * @param {B} initial - * @param {...A3} args - * @returns {B} - */ - /** - * @method Bacon.update3 - * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. - * @param {B} initial - * @param {Observable[]} pattern1 - * @param {Bacon.update3~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.update3~f2} f2 - * @param {Observable[]} pattern3 - * @param {Bacon.update3~f3} f3 - * @returns {Property} - * @example - * { - * // The inputs to `Bacon.update` are defined like this: - * let initial = 0, - * x = Bacon.interval(1e3, 1), - * y = Bacon.interval(2e3, 1), - * z = Bacon.interval(1.5e3, 1); - * // NOTE: had to explicitly specify the typing for `previous:number` - * Bacon.update(initial, - * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, - * [x, y], (previous:number, x, y) => previous + x + y + z - * ); - * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. - * } - * - * { - * // Here's a simple gaming example: - * let scoreMultiplier = Bacon.constant(1), - * hitUfo = new Bacon.Bus(), - * hitMotherShip = new Bacon.Bus(), - * score = Bacon.update(0, - * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, - * [hitMotherShip], (score, _) => score + 2000 - * ); - * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. - * } - */ - function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => B, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => B):Property; - - /** - * @callback Bacon.update4~f1 - * @param {B} initial - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.update4~f2 - * @param {B} initial - * @param {...A2} args - * @returns {B} - */ - /** - * @callback Bacon.update4~f3 - * @param {B} initial - * @param {...A3} args - * @returns {B} - */ - /** - * @callback Bacon.update4~f4 - * @param {B} initial - * @param {...A4} args - * @returns {B} - */ - /** - * @method Bacon.update4 - * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. - * @param {B} initial - * @param {Observable[]} pattern1 - * @param {Bacon.update4~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.update4~f2} f2 - * @param {Observable[]} pattern3 - * @param {Bacon.update4~f3} f3 - * @param {Observable[]} pattern4 - * @param {Bacon.update4~f4} f4 - * @returns {Property} - * @example - * { - * // The inputs to `Bacon.update` are defined like this: - * let initial = 0, - * x = Bacon.interval(1e3, 1), - * y = Bacon.interval(2e3, 1), - * z = Bacon.interval(1.5e3, 1); - * // NOTE: had to explicitly specify the typing for `previous:number` - * Bacon.update(initial, - * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, - * [x, y], (previous:number, x, y) => previous + x + y + z - * ); - * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. - * } - * - * { - * // Here's a simple gaming example: - * let scoreMultiplier = Bacon.constant(1), - * hitUfo = new Bacon.Bus(), - * hitMotherShip = new Bacon.Bus(), - * score = Bacon.update(0, - * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, - * [hitMotherShip], (score, _) => score + 2000 - * ); - * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. - * } - */ - function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => B, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => B, pattern4:Observable[], f4:(initial:B, ...args:A4[]) => B):Property; - - /** - * @callback Bacon.update5~f1 - * @param {B} initial - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.update5~f2 - * @param {B} initial - * @param {...A2} args - * @returns {B} - */ - /** - * @callback Bacon.update5~f3 - * @param {B} initial - * @param {...A3} args - * @returns {B} - */ - /** - * @callback Bacon.update5~f4 - * @param {B} initial - * @param {...A4} args - * @returns {B} - */ - /** - * @callback Bacon.update5~f5 - * @param {B} initial - * @param {...A5} args - * @returns {B} - */ - /** - * @method Bacon.update5 - * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. - * @param {B} initial - * @param {Observable[]} pattern1 - * @param {Bacon.update5~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.update5~f2} f2 - * @param {Observable[]} pattern3 - * @param {Bacon.update5~f3} f3 - * @param {Observable[]} pattern4 - * @param {Bacon.update5~f4} f4 - * @param {Observable[]} pattern5 - * @param {Bacon.update5~f5} f5 - * @returns {Property} - * @example - * { - * // The inputs to `Bacon.update` are defined like this: - * let initial = 0, - * x = Bacon.interval(1e3, 1), - * y = Bacon.interval(2e3, 1), - * z = Bacon.interval(1.5e3, 1); - * // NOTE: had to explicitly specify the typing for `previous:number` - * Bacon.update(initial, - * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, - * [x, y], (previous:number, x, y) => previous + x + y + z - * ); - * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. - * } - * - * { - * // Here's a simple gaming example: - * let scoreMultiplier = Bacon.constant(1), - * hitUfo = new Bacon.Bus(), - * hitMotherShip = new Bacon.Bus(), - * score = Bacon.update(0, - * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, - * [hitMotherShip], (score, _) => score + 2000 - * ); - * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. - * } - */ - function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => B, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => B, pattern4:Observable[], f4:(initial:B, ...args:A4[]) => B, pattern5:Observable[], f5:(initial:B, ...args:A5[]) => B):Property; -} - -declare module "baconjs" { - export = Bacon; -} diff --git a/baconjs/index.d.ts b/baconjs/index.d.ts new file mode 100644 index 0000000000..8659ea9115 --- /dev/null +++ b/baconjs/index.d.ts @@ -0,0 +1,3132 @@ +// Type definitions for Bacon.js 0.7.0 +// Project: https://baconjs.github.io/ +// Definitions by: Alexander Matsievsky +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +interface JQuery { + /** + * @method + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. + * @param {string} eventName + * @returns {EventStream} + * @example + * $("#my-div").asEventStream("click"); + */ + asEventStream(eventName:string):Bacon.EventStream; + + /** + * @method + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a jQuery live `selector`. + * @param {string} eventName + * @param {string} selector + * @returns {EventStream} + * @example + * $("#my-div").asEventStream("click", ".more-specific-selector"); + */ + asEventStream(eventName:string, selector:string):Bacon.EventStream; + + /** + * @callback JQuery#asEventStream1~f + * @param {JQueryEventObject} event + * @param {*[]} args + * @returns {A} + */ + /** + * @method JQuery#asEventStream1 + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a function `f` that processes the jQuery event and its parameters. + * @param {string} eventName + * @param {JQuery#asEventStream1~f} f + * @returns {EventStream} + * @example + * $("#my-div").asEventStream("click", (event, args) => args[0]); + */ + asEventStream(eventName:string, f:(event:JQueryEventObject, args:any[]) => A):Bacon.EventStream; + + /** + * @callback JQuery#asEventStream2~f + * @param {JQueryEventObject} event + * @param {*[]} args + * @returns {A} + */ + /** + * @method JQuery#asEventStream2 + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a jQuery live `selector` and a function `f` that processes the jQuery event and its parameters. + * @param {string} eventName + * @param {string} selector + * @param {JQuery#asEventStream2~f} f + * @returns {Bacon.EventStream} + * @example + * $("#my-div").asEventStream("click", ".more-specific-selector", (event, args) => args[0]); + */ + asEventStream(eventName:string, selector:string, f:(event:JQueryEventObject, args:any[]) => A):Bacon.EventStream; +} + +/** @module Bacon */ +declare namespace Bacon { + /** + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the optional `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream. + * @param {Promise|JQueryXHR} promise + * @param {boolean} [abort] + * @returns {EventStream} + * @example + * Bacon.fromPromise($.ajax("https://baconjs.github.io/")); + * Bacon.fromPromise(Promise.resolve(1)); + * Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true); + * Bacon.fromPromise(Promise.resolve(1), false); + */ + function fromPromise(promise:Promise|JQueryXHR, abort?:boolean):EventStream; + + /** + * @callback Bacon.fromPromise~eventTransformer + * @param {A} value + * @returns {(Initial|Next|End|Error)[]} + */ + /** + * @function Bacon.fromPromise + * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream, and also pass a function `eventTransformer` that transforms the promise value into Events. The default is to transform the value into `[new Bacon.Next(value), new Bacon.End()]`. + * @param {Promise|JQueryXHR} promise + * @param {boolean} abort + * @param {Bacon.fromPromise~eventTransformer} eventTransformer + * @returns {EventStream} + * @example + * Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true, (n:string) => { + * return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; + * }); + * Bacon.fromPromise(Promise.resolve(1), false, n => { + * return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; + * }); + */ + function fromPromise(promise:Promise|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial|Next|End|Error)[]):EventStream; + + /** + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods. + * @param {EventTarget|NodeJS.EventEmitter|JQuery} target + * @param {string} eventName + * @returns {EventStream} + * @example + * Bacon.fromEvent(document.body, "click").onValue(() => { + * alert("Bacon!"); + * }); + * Bacon.fromEvent(process.stdin, "readable", () => { + * alert("Bacon!"); + * }); + * Bacon.fromEvent($("body"), "click").onValue(() => { + * alert("Bacon!"); + * }); + */ + function fromEvent(target:EventTarget|NodeJS.EventEmitter|JQuery, eventName:string):EventStream; + + /** + * @callback Bacon.fromEvent~eventTransformer + * @param {A} event + * @returns {B} + */ + /** + * @function Bacon.fromEvent + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods. You can pass a function `eventTransformer` that transforms the emitted events' parameters. + * @param {EventTarget|NodeJS.EventEmitter|JQuery} target + * @param {string} eventName + * @param {Bacon.fromEvent~eventTransformer} eventTransformer + * @returns {EventStream} + * @example + * Bacon.fromEvent(document.body, "click", (event:MouseEvent) => event.clientX).onValue(clientX => { + * alert("Bacon!"); + * }); + */ + function fromEvent(target:EventTarget|NodeJS.EventEmitter|JQuery, eventName:string, eventTransformer:(event:A) => B):EventStream; + + /** + * @callback Bacon.fromCallback1~f + * @param {Bacon.fromCallback1~callback} callback + * @returns {void} + */ + /** + * @callback Bacon.fromCallback1~callback + * @param {...*} args + * @returns {void} + */ + /** + * @function Bacon.fromCallback1 + * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a `callback`. The function is supposed to call its callback just once. + * @param {Bacon.fromCallback1~f} f + * @returns {EventStream} + * @example + * // This would create a stream that outputs a single value "Bacon!" and ends after that. The use of setTimeout causes the value to be delayed by 1 second. + * Bacon.fromCallback(callback => { + * setTimeout(() => { + * callback("Bacon!"); + * }, 1000); + * }); + */ + function fromCallback(f:(callback:(...args:any[]) => void) => void):EventStream; + + /** + * @callback Bacon.fromCallback2~f + * @param {...*} args + * @returns {void} + */ + /** + * @function Bacon.fromCallback2 + * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a `callback`. The function is supposed to call its callback just once. + * @param {Bacon.fromCallback2~f} f + * @param {...*} args + * @returns {EventStream} + * @example + * // You can also give any number of arguments to `fromCallback`, which will be passed to the function. These arguments can be simple variables, Bacon EventStreams or Properties. For example the following will output "Bacon rules": + * Bacon.fromCallback((a, b, callback) => { + * callback(a + " " + b); + * }, Bacon.constant("bacon"), "rules").log(); + */ + function fromCallback(f:(...args:any[]) => void, ...args:any[]):EventStream; + + /** + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} from a `methodName` method of a given `object`. The function is supposed to call its callback just once. + * @param {Object} object + * @param {string} methodName + * @param {...*} args + * @returns {EventStream} + */ + function fromCallback(object:Object, methodName:string, ...args:any[]):EventStream; + + /** + * @callback Bacon.fromNodeCallback~f + * @param {Bacon.fromNodeCallback~callback} callback + * @returns {void} + */ + /** + * @callback Bacon.fromNodeCallback~callback + * @param {E} error + * @param {A} data + * @returns {void} + */ + /** + * @function Bacon.fromNodeCallback + * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a Node.js `callback`: callback(error, data), where error is `null` if everything is fine. The function is supposed to call its callback just once. + * @param {Bacon.fromNodeCallback~f} f + * @param {...*} args + * @returns {EventStream} + * @example + * { + * let fs = require("fs"), + * read = Bacon.fromNodeCallback(fs.readFile, "input.txt"); + * read.onError(error => { + * console.log("Reading failed: " + error); + * }); + * read.onValue(value => { + * console.log("Read contents: " + value); + * }); + * } + */ + function fromNodeCallback(f:(callback:(error:E, data:A) => void) => void, ...args:any[]):EventStream; + + /** + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} from a `methodName` method of a given `object`. + * @param {Object} object + * @param {string} methodName + * @param {...*} args + * @returns {EventStream} + */ + function fromNodeCallback(object:Object, methodName:string, ...args:any[]):EventStream; + + /** + * @callback Bacon.fromPoll~f + * @returns {Next|End} + */ + /** + * @function Bacon.fromPoll + * @description Polls given function `f` with given `interval`. Function should return events: either [Next]{@link Bacon.Next} or [End]{@link Bacon.End}. Polling occurs only when there are subscribers to the stream. Polling ends permanently when `f` returns [End]{@link Bacon.End}. + * @param {number} interval + * @param {Bacon.fromPoll~f} f + * @returns {EventStream} + */ + function fromPoll(interval:number, f:() => Next|End):EventStream; + + /** + * @function Bacon.once + * @description Creates an [EventStream]{@link Bacon.EventStream} that delivers the given single `value` for the first subscriber. The stream will end immediately after this value. You can also send an [Error]{@link Bacon.Error} event instead of a `value`. + * @param {A|Error} value + * @returns {EventStream} + * @example + * Bacon.once(new Bacon.Error("fail")); + */ + function once(value:A|Error):EventStream; + + /** + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} that delivers the given series of `values` (given as array) to the first subscriber. The stream ends after these values have been delivered. You can also send [Error]{@link Bacon.Error} events, or any combination of pure values and error events. + * @param {(A|Error)[]} values + * @returns {EventStream} + * @example + * Bacon.fromArray([1, new Bacon.Error("")]); + */ + function fromArray(values:(A|Error)[]):EventStream; + + /** + * @function + * @description Repeats the single `value` indefinitely with the given `interval` (in milliseconds). + * @param {number} interval + * @param {A} value + * @returns {EventStream} + */ + function interval(interval:number, value:A):EventStream; + + /** + * @function + * @description Creates a [EventStream]{@link Bacon.EventStream} containing given `values` (given as array) with the given `interval` (in milliseconds). + * @param {number} interval + * @param {A[]} values + * @returns {EventStream} + */ + function sequentially(interval:number, values:A[]):EventStream; + + /** + * @function + * @description Repeats given `values` indefinitely with then given `interval` (in milliseconds). + * @param {number} interval + * @param {A[]} values + * @returns {EventStream} + * @example + * // The following would lead to `1,2,3,1,2,3...` to be repeated indefinitely: + * Bacon.fromArray([1, new Bacon.Error("")]); + */ + function repeatedly(interval:number, values:A[]):EventStream; + + /** + * @callback Bacon.repeat~f + * @param {number} iteration + * @returns {boolean|Observable} + */ + /** + * @function Bacon.repeat + * @description Calls generator function `f` which is expected to return an [Observable]{@link Bacon.Observable}. The returned [EventStream]{@link Bacon.EventStream} contains values and errors from the spawned observable. When the spawned Observable ends, the generator `f` is called again to spawn a new Observable. This is repeated until the generator `f` returns a falsy value (such as `undefined` or `false`). The generator `f` is called with one argument — `iteration` number starting from `0`. + * @param {Bacon.repeat~f} f + * @returns {EventStream} + * @example + * // The following will produce values `0,1,2`. + * Bacon.repeat(i => { + * if (i < 3) { + * return Bacon.once(i); + * } else { + * return false; + * } + * }).log(); + */ + function repeat(f:(iteration:number) => boolean|Observable):EventStream; + + /** + * @function Bacon.never + * @description Creates an [EventStream]{@link Bacon.EventStream} that immediately ends. + * @returns {EventStream} + */ + function never():EventStream; + + /** + * @function + * @description Creates a single-element [EventStream]{@link Bacon.EventStream} that produces given `value` after a given `delay` (in milliseconds). + * @param {number} delay + * @param {A} value + * @returns {EventStream} + */ + function later(delay:number, value:A):EventStream; + + /** + * @function + * @description Creates a constant [Property]{@link Bacon.Property} with value `x`. + * @param {A} x + * @returns {Property} + */ + function constant(x:A):Property; + + /** + * @callback Bacon.fromBinder~subscribe + * @param {Bacon.fromBinder~sink} sink + * @returns {Bacon.fromBinder~unsubscribe} + */ + /** + * @callback Bacon.fromBinder~sink + * @param {More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]} value + * @returns {void} + */ + /** + * @callback Bacon.fromBinder~unsubscribe + * @returns {void} + */ + /** + * @function Bacon.fromBinder + * @description Creates an [EventStream]{@link Bacon.EventStream} with the given [subscribe]{@link Bacon.fromBinder~subscribe} function. The parameter `subscribe` is a function that accepts a [sink]{@link Bacon.fromBinder~sink} which is a function that your `subscribe` function can "push" events to. You can push: a plain value, like `"first value"`; an [Event]{@link Bacon.Event} object including [Error]{@link Bacon.Error} (wraps an error) and [End]{@link Bacon.End} (indicates stream end); an array of event objects at once. The `subscribe` function must return a function. Let's call that function [unsubscribe]{@link Bacon.fromBinder~unsubscribe}. The returned function can be used by the subscriber (directly or indirectly) to unsubscribe from the EventStream. It should release all resources that the `subscribe` function reserved. The `sink` function may return [noMore]{@link Bacon.noMore} (as well as [more]{@link Bacon.more} or any other value). If it returns `noMore`, no further events will be consumed by the subscriber. The `subscribe` function may choose to clean up all resources at this point (e.g., by calling `unsubscribe`). This is usually not necessary, because further calls to `sink` are ignored, but doing so can increase performance in rare cases. The EventStream will wrap your `subscribe` function so that it will only be called when the first stream listener is added, and the `unsubscribe` function is called only after the last listener has been removed. The subscribe-unsubscribe cycle may of course be repeated indefinitely, so prepare for multiple calls to the `subscribe` function. + * @param {Bacon.fromBinder~subscribe} subscribe + * @returns {EventStream} + * @example + * let stream = Bacon.fromBinder(sink => { + * sink("first value"); + * sink([new Bacon.Next("2nd"), new Bacon.Next("3rd")]); + * sink(new Bacon.Next(() => { + * return "This one will be evaluated lazily" + * })); + * sink(new Bacon.Error("oops, an error")); + * sink(new Bacon.End()); + * return () => { + * // unsub functionality here, this one's a no-op + * }; + * }); + * stream.log(); + */ + function fromBinder(subscribe:(sink:(value:More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]) => void) => (() => void)):EventStream; + + /** + * @interface + * @see Bacon.more + */ + interface More { + } + /** + * @property more + * @constant + * @description The opaque value `sink` function may return. See [Bacon.fromBinder]{@link Bacon.fromBinder}. + */ + var more:More; + + /** + * @interface + * @see Bacon.noMore + */ + interface NoMore { + } + /** + * @property noMore + * @constant + * @description The opaque value `sink` function may return. See [Bacon.fromBinder]{@link Bacon.fromBinder}. + */ + var noMore:NoMore; + + /** + * @class Observable + * @description A superclass for [EventStream]{@link Bacon.EventStream} and [Property]{@link Bacon.Property}. + * */ + interface Observable { + /** + * @callback Observable#onValue~f + * @param {A} value + * @returns {void} + */ + /** + * @callback Observable#onValue~unsubscribe + * @returns {void} + */ + /** + * @method Observable#onValue + * @description Subscribes a given handler function `f` to the [Observable]{@link Bacon.Observable}. Function will be called for each new value. This is the simplest way to assign a side-effect to an Observable. The difference to the [EventStream.subscribe]{@link Bacon.EventStream#subscribe} and [Property.subscribe]{@link Bacon.Property#subscribe} methods is that the actual stream `value`s are received, instead of [Event]{@link Bacon.Event} objects. [EventStream.onValue]{@link Bacon.EventStream#onValue} and [Property.onValue]{@link Bacon.Property#onValue} behave similarly, except that the latter also pushes the initial value of the Property, in case there is one. + * @param {Observable#onValue~f} f + * @returns {Observable#onValue~unsubscribe} + */ + onValue(f:(value:A) => void):() => void; + + /** + * @callback Observable#onError~f + * @param {E} error + * @returns {void} + */ + /** + * @callback Observable#onError~unsubscribe + * @returns {void} + */ + /** + * @method Observable#onError + * @description Subscribes a given handler function `f` to [Error]{@link Bacon.Error} events. The function `f` will be called for each error in the [Observable]{@link Bacon.Observable}. + * @param {Observable#onError~f} f + * @returns {Observable#onError~unsubscribe} + */ + onError(f:(error:E) => void):() => void; + + /** + * @callback Observable#onEnd~f + * @returns {void} + */ + /** + * @callback Observable#onEnd~unsubscribe + * @returns {void} + */ + /** + * @method Observable#onEnd + * @description Subscribes a given handler function `f` to [End]{@link Bacon.End} event. The function `f` will be called when the [Observable]{@link Bacon.Observable} ends. Just like [EventStream.subscribe]{@link Bacon.EventStream#subscribe} and [Property.subscribe]{@link Bacon.Property#subscribe}, this method returns a function for `unsubscribe`ing. + * @param {Observable#onEnd~f} f + * @returns {Observable#onEnd~unsubscribe} + */ + onEnd(f:() => void):() => void; + + /** + * @callback Observable#toPromise~promiseCtr + * @param {A} value + * @returns {Promise} + */ + /** + * @method Observable#toPromise + * @description Returns a Promise which will be resolved with the last event coming from an [Observable]{@link Bacon.Observable}. The global ES6 promise implementation will be used unless a promise constructor `promiseCtr` is given. Use a shim if you need to support legacy browsers or platforms. + * @param {Observable#toPromise~promiseCtr} [promiseCtr] + * @returns {Promise} + */ + toPromise(promiseCtr?:(value:A) => Promise):Promise; + + /** + * @callback Observable#firstToPromise~promiseCtr + * @param {A} value + * @returns {Promise} + */ + /** + * @method Observable#firstToPromise + * @description Returns a Promise which will be resolved with the first event coming from an [Observable]{@link Bacon.Observable}. Like [Observable.toPromise]{@link Bacon.Observable#toPromise}, the global ES6 promise implementation will be used unless a promise constructor `promiseCtr` is given. + * @param {Observable#firstToPromise~promiseCtr} [promiseCtr] + * @returns {Promise} + */ + firstToPromise(promiseCtr?:(value:A) => Promise):Promise; + + /** + * @method + * @description Throttles the [Observable]{@link Bacon.Observable} using a buffer so that at most one value event in `minimumInteval` is issued. Unlike [EventStream.throttle]{@link Bacon.EventStream#throttle} and [Property.throttle]{@link Bacon.Property#throttle}, it doesn't discard the excessive events but buffers them instead, outputting them with a rate of at most one value per `minimumInterval`. + * @param {number} minimumInterval + * @returns {EventStream} + */ + bufferingThrottle(minimumInterval:number):EventStream; + + /** + * @callback Observable#flatMap~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMap + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMap]{@link Bacon.Observable#flatMap} is always an EventStream. The "Function Construction rules" apply here. `flatMap` can be used conveniently with [Bacon.once]{@link Bacon.once} and [Bacon.never]{@link Bacon.never} for converting and filtering at the same time, including only some of the results. + * @param {Observable#flatMap~f} f + * @returns {EventStream} + * @example + * // Converting strings to integers, skipping empty values: + * Bacon.once("").flatMap(text => { + * return text != "" ? parseInt(text) : Bacon.never(); + * }); + */ + flatMap(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapLatest~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapLatest + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, but instead of including events from all spawned streams, only includes them from the latest spawned stream into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapLatest]{@link Bacon.Observable#flatMapLatest} is always an EventStream. + * @param {Observable#flatMapLatest~f} f + * @returns {EventStream} + */ + flatMapLatest(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapFirst~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapFirst + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f` only if the previously spawned stream has ended, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapFirst]{@link Bacon.Observable#flatMapFirst} is always an EventStream. + * @param {Observable#flatMapFirst~f} f + * @returns {EventStream} + */ + flatMapFirst(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapError~f + * @param {E} error + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapError + * @description For each [Error]{@link Bacon.Error} event in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapError]{@link Bacon.Observable#flatMapError} is always an EventStream. + * @param {Observable#flatMapError~f} f + * @returns {EventStream} + */ + flatMapError(f:(error:E) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapWithConcurrencyLimit~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapWithConcurrencyLimit + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}, but limit the number of open spawned streams and buffers incoming events by `limit` amount. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. [flatMapConcat]{@link Bacon.Observable#flatMapConcat} is [flatMapWithConcurrencyLimit]{@link Bacon.Observable#flatMapWithConcurrencyLimit}(1) (only one input active), and [flatMap]{@link Bacon.Observable#flatMap} is [flatMapWithConcurrencyLimit]{@link Bacon.Observable#flatMapWithConcurrencyLimit}(∞) (all inputs are piped to output). The result of `flatMapWithConcurrencyLimit` is always an EventStream. + * @param {number} limit + * @param {Observable#flatMapWithConcurrencyLimit~f} f + * @returns {EventStream} + */ + flatMapWithConcurrencyLimit(limit:number, f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapConcat~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapConcat + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}, but limit the number of open spawned streams and buffers incoming events to 1. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of `flatMapConcat` is always an EventStream. + * @param {Observable#flatMapConcat~f} f + * @returns {EventStream} + */ + flatMapConcat(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#scan~f + * @param {B} acc + * @param {A} next + * @returns {B} + */ + /** + * @method Observable#scan + * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, resulting to a [Property]{@link Bacon.Property}. For example, you might use zero as `seed` and a "plus" function as the accumulator to create an "integral" Property. When applied to a Property as in `r = p.scan(seed, f)`, there's a (hopefully insignificant) catch: the starting value for `r` depends on whether `p` has an initial value when `scan` is applied. If there's no initial value, this works identically to `[EventStream]{@link Bacon.EventStream}.scan`: the `seed` will be the initial value of `r`. However, if `r` already has a current/initial value `x`, the seed won't be output as is. Instead, the initial value of `r` will be `f(seed, x)`. This makes sense, because there can only be 1 initial value for a Property at a time. + * @param {B} seed + * @param {Observable#scan~f} f + * @returns {Property} + * @example + * Bacon.sequentially(1, [1, 2, 3]).scan(0, (a, b) => a + b); + */ + scan(seed:B, f:(acc:B, next:A) => B):Property; + + /** + * @callback Observable#fold~f + * @param {B} acc + * @param {A} next + * @returns {B} + */ + /** + * @method Observable#fold + * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, but only emits the final value, i.e. the value just before the Observable ends. Returns a [Property]{@link Bacon.Property}. + * @param {B} seed + * @param {Observable#fold~f} f + * @returns {Property} + */ + fold(seed:B, f:(acc:B, next:A) => B):Property; + + /** + * @callback Observable#reduce~f + * @param {B} acc + * @param {A} next + * @returns {B} + */ + /** + * @method Observable#reduce + * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, but only emits the final value, i.e. the value just before the Observable ends. Returns a [Property]{@link Bacon.Property}. + * @param {B} seed + * @param {Observable#reduce~f} f + * @returns {Property} + */ + reduce(seed:B, f:(acc:B, next:A) => B):Property; + + /** + * @callback Observable#diff~f + * @param {A} a + * @param {B} b + * @returns {B} + */ + /** + * @method Observable#diff + * @description Returns a [Property]{@link Bacon.Property} that represents the result of a comparison `f` between the previous and current value of the [Observable]{@link Bacon.Observable}. For the initial value of the Observable, the previous value will be the given `start`. + * @param {A} start + * @param {Observable#diff~f} f + * @returns {Property} + * @example + * Bacon.sequentially(1, [1, 2, 3]).diff(0, (a, b) => Math.abs(b - a)); + */ + diff(start:A, f:(a:A, b:A) => B):Property; + + /** + * @callback Observable#zip~f + * @param {A} a + * @param {B} b + * @returns {C} + */ + /** + * @method Observable#zip + * @description Returns an [EventStream]{@link Bacon.EventStream} with elements pair-wise lined up with events from this and the `other` EventStream. A zipped EventStream will publish only when it has a value from each EventStream and will only produce values up to when any single EventStream ends. The given function `f` is used to create the result value from value in the two source EventStream. If no function `f` is given, the values are zipped into an array. Be careful not to have too much "drift" between streams. If one stream produces many more values than some other excessive buffering will occur inside the zipped observable. + * @param {EventStream} other + * @param {Observable#zip~f} f + * @returns {EventStream} + * @example + * { + * let x = Bacon.fromArray([1, 2]), + * y = Bacon.fromArray([3, 4]); + * x.zip(y, (x, y) => x + y); + * } + */ + zip(other:EventStream, f:(a:A, b:B) => C):EventStream; + + /** + * @method + * @description Returns a [Property]{@link Bacon.Property} that represents a "sliding window" into the history of the values of the [Observable]{@link Bacon.Observable}. The resulting Property will have a value that is an array containing the last `n` values of the original Observable, where `n` is at most the value of the `max` argument, and at least the value of the `min` argument. If the `min` argument is omitted, there's no lower limit of values. + * @param {number} max + * @param {number} [min] + * @returns {Property} + * @example + * // If you have a EventStream `s` with a value sequence `1,2,3,4,5`, the respective values in `s.slidingWindow(2)` would be `[],[1],[1,2],[2,3],[3,4],[4,5]`: + * Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2); + * // The values of `s.slidingWindow(2,2)`would be `[1,2],[2,3],[3,4],[4,5]`: + * Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2, 2); + */ + slidingWindow(max:number, min?:number):Property; + + /** + * @callback Observable#combine~f + * @param {A} a + * @param {B} b + * @returns {C} + */ + /** + * @method Observable#combine + * @description Combines the latest values of the two [EventStream]{@link Bacon.EventStream}s or [Property]{@link Bacon.Property}s using a two-arg function `f`. The result is a Property. + * @param {Property} property2 + * @param {Observable#combine~f} f + * @returns {Property} + */ + combine(property2:Property, f:(a:A, b:B) => C):Property; + + /** + * @callback Observable#withStateMachine~f + * @param {B} state + * @param {Initial|Next|End|Error} event + * @returns {[B, (Initial|Next|End|Error)[]]} + */ + /** + * @method Observable#withStateMachine + * @description Lets you run a state machine on an [Observable]{@link Bacon.Observable}. Give it an initial state `initState` object and a state transformation function `f` that processes each incoming [Event]{@link Bacon.Event} and returns and array containing the next `state` and an array of output Event's. + * @param {B} initState + * @param {Observable#withStateMachine~f} f + * @returns {EventStream} + * @example + * // Calculate the total sum of all numbers in the stream and output the value on stream end: + * Bacon.fromArray([1, 2, 3]).withStateMachine(0, (sum, event) => { + * if (event.hasValue()) { + * // had to cast to `number` because event:Bacon.Next|Bacon.Error<{}> + * return [sum + event.value(), []]; + * } else if (event.isEnd()) { + * return [undefined, [new Bacon.Next(sum), event]]; + * } else { + * return [sum, [event]]; + * } + * }); + */ + withStateMachine(initState:B, f:(state:B, event:Initial|Next|End|Error) => [B, (Initial|Next|End|Error)[]]):EventStream; + + /** + * @method + * @description Decodes input [Observable]{@link Bacon.Observable} using the given `mapping`. Is a bit like a switch-case or the decode function in Oracle SQL. The return value of `decode` is always a [Property]{@link Bacon.Property}. + * @param {Object} mapping + * @returns {Property} + * @example + * { + * let property = Bacon.fromArray([1, 2, 3]).toProperty(), + * who = Bacon.fromArray(["A", "B", "C"]).toProperty(); + * // The following would map the value 1 into the string "mike" and the value 2 into the value of the `who` property: + * property.decode({1: "mike", 2: who}); + * // You can compose static and dynamic data quite freely, as in: + * property.decode({1: {type: "mike"}, 2: {type: "other", whoThen: who}}); + * } + */ + decode(mapping:Object):Property; + + /** + * @method + * @description Creates a [Property]{@link Bacon.Property} that indicates whether Observable is awaiting `otherObservable`, i.e. has produced a value after the latest value from `otherObservable`. + * @param {Observable} otherObservable + * @returns {Property} + * @example + * { + * // This is handy for keeping track whether we are currently awaiting an AJAX response: + * let ajaxRequest = >{}, + * ajaxResponse = >{}, + * showAjaxIndicator = ajaxRequest.awaiting(ajaxResponse); + * } + */ + awaiting(otherObservable:Observable):Property; + } + + /** + * @class EventStream + * @augments Bacon.Observable + * @description A stream of events. + * */ + interface EventStream extends Observable { + /** + * @callback EventStream#map~f + * @param {A} value + * @returns {B} + */ + /** + * @method EventStream#map + * @description Maps [EventStream]{@link Bacon.EventStream} values using given function `f`, returning a new EventStream. The `map` method, among many others, uses lazy evaluation. + * @param {EventStream#map~f} f + * @returns {EventStream} + * */ + map(f:(value:A) => B):EventStream; + + /** + * @method + * @description Maps [EventStream]{@link Bacon.EventStream} values using given `constant` value, returning a new EventStream. The `map` method, among many others, uses lazy evaluation. + * @param {B} constant + * @returns {EventStream} + * */ + map(constant:B):EventStream; + + /** + * @method + * @description Maps [EventStream]{@link Bacon.EventStream} values using given `propertyExtractor` string like ".keyCode", returning a new EventStream. So, if `propertyExtractor` is a string starting with a dot, the elements will be mapped to the corresponding field/function in the event value. For instance map(".keyCode") will pluck the keyCode field from the input values. If `keyCode` was a function, the result EventStream would contain the values returned by the function. The "Function Construction rules" apply here. The `map` method, among many others, uses lazy evaluation. + * @param {string} propertyExtractor + * @returns {EventStream} + * */ + map(propertyExtractor:string):EventStream; + + /** + * @method + * @description Maps [EventStream]{@link Bacon.EventStream} events to the current value of the given [Property]{@link Bacon.Property} `property`. This is equivalent to [Property.sampledBy]{@link Bacon.Property#sampledBy}. + * @param {Property} property + * @returns {EventStream} + */ + map(property:Property):EventStream; + + /** + * @callback EventStream#mapError~f + * @param {E} error + * @returns {B} + */ + /** + * @method EventStream#mapError + * @description Maps [EventStream]{@link Bacon.EventStream} [Error]{@link Bacon.Error}s using given function `f`. More specifically, feeds the "error" field of the Error event to the function and produces a [Next]{@link Bacon.Next} event based on the return value. The "Function Construction rules" apply here. + * @param {EventStream#mapError~f} f + * @returns {EventStream} + */ + mapError(f:(error:E) => B):EventStream; + + /** + * @method + * @description Returns an [EventStream]{@link Bacon.EventStream} containing [Error]{@link Bacon.Error} events only. Same as filtering with a function that always returns `false`. + * @returns {EventStream} + */ + errors():EventStream; + + /** + * @method + * @description Skips all [Error]{@link Bacon.Error}s. + * @returns {EventStream} + */ + skipErrors():EventStream; + + /** + * @callback EventStream#mapEnd~f + * @returns {A} + */ + /** + * @method EventStream#mapEnd + * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} to [EventStream]{@link Bacon.EventStream}. The value is created by calling the given function `f` when the source [EventStream]{@link Bacon.EventStream} ends. + * @param {EventStream#mapEnd~f} f + * @returns {EventStream} + */ + mapEnd(f:() => A):EventStream; + + /** + * @method + * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} to [EventStream]{@link Bacon.EventStream}. A static `value` is used. + * @param {A} value + * @returns {EventStream} + */ + mapEnd(value:A):EventStream; + + /** + * @callback EventStream#filter~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method EventStream#filter + * @description Filters [EventStream]{@link Bacon.EventStream} `value`s using a given predicate function `f`. + * @param {EventStream#filter~f} f + * @returns {EventStream} + */ + filter(f:(value:A) => boolean):EventStream; + + /** + * @method + * @description Filters [EventStream]{@link Bacon.EventStream} values using a given `constant` value (`true` to include all, `false` to exclude all). + * @param {boolean} bool + * @returns {EventStream} + */ + filter(bool:boolean):EventStream; + + /** + * @method + * @description Filters [EventStream]{@link Bacon.EventStream} values using a given `propertyExtractor` string (like ".isValuable"). + * @param {string} propertyExtractor + * @returns {EventStream} + */ + filter(propertyExtractor:string):EventStream; + + /** + * @method + * @description Filters [EventStream]{@link Bacon.EventStream} values based on the value of a [Property]{@link Bacon.Property} `property`. [Event]{@link Bacon.Event} will be included in output IF AND ONLY IF the `property` holds `true` at the time of the event. + * @param {Property} property + * @returns {EventStream} + */ + filter(property:Property):EventStream; + + /** + * @callback EventStream#takeWhile~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method EventStream#takeWhile + * @description Takes [EventStream]{@link Bacon.EventStream} values while given predicate function `f` holds `true`, and then ends. + * @param {EventStream#takeWhile} f + * @returns {EventStream} + */ + takeWhile(f:(value:A) => boolean):EventStream; + + /** + * @method + * @description Takes [EventStream]{@link Bacon.EventStream} values while the value of a `property` holds `true`, and then ends. + * @param {Property} property + * @returns {EventStream} + */ + takeWhile(property:Property):EventStream; + + /** + * @method + * @description Takes at most n elements from the [EventStream]{@link Bacon.EventStream}. Equal to `Bacon.never()` if `n <= 0`. + * @param {number} n + * @returns {EventStream} + */ + take(n:number):EventStream; + + /** + * @method + * @description Takes elements from [EventStream]{@link Bacon.EventStream} until a [Next]{@link Bacon.Next} event appears in the EventStream `stream`. If `stream` ends without value, it is ignored. + * @param {EventStream} stream + * @returns {EventStream} + */ + takeUntil(stream:EventStream):EventStream; + + /** + * @method + * @description Takes the first element from the [EventStream]{@link Bacon.EventStream}. Essentially [Observable.take]{@link Bacon.EventStream#take}(1). + * @returns {EventStream} + */ + first():EventStream; + + /** + * @method + * @description Takes the last element from the [EventStream]{@link Bacon.EventStream}. None, if EventStream is empty. + * @returns {EventStream} + * @example + * // This creates the stream which doesn't produce any events and never ends: + * Bacon.interval(1e1, 0).last(); + */ + last():EventStream; + + /** + * @method + * @description Skips the first `n` elements from the [EventStream]{@link Bacon.EventStream}. + * @param {number} n + * @returns {EventStream} + */ + skip(n:number):EventStream; + + /** + * @method + * @description Delays the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds). + * @param {number} delay + * @returns {EventStream} + */ + delay(delay:number):EventStream; + + /** + * @method EventStream#throttle + * @description Throttles the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds). Events are emitted with the minimum interval of `delay`. The implementation is based on [EventStream.bufferWithTime]{@link Bacon.EventStream#bufferWithTime}. + * @param {number} delay + * @returns {EventStream} + */ + throttle(delay:number):EventStream; + + /** + * @method EventStream#debounce + * @description Throttles the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds), but so that event is only emitted after the given "quiet period". The difference of [throttle]{@link Bacon.EventStream#throttle} and [debounce]{@link Bacon.EventStream#debounce} is the same as it is in the same methods in jQuery. + * @param {number} delay + * @returns {EventStream} + */ + debounce(delay:number):EventStream; + + /** + * @method + * @description Passes the first event in the [EventStream]{@link Bacon.EventStream} through, but after that, only passes events after a given `delay` (in milliseconds) have passed since previous output. + * @param {number} delay + * @returns {EventStream} + */ + debounceImmediate(delay:number):EventStream; + + /** + * @callback EventStream#doAction~f + * @param {A} value + * @returns {void} + */ + /** + * @method EventStream#doAction + * @description Returns an [EventStream]{@link Bacon.EventStream} where the function `f` is executed for each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. + * @param {EventStream#doAction~f} f + * @returns {EventStream} + */ + doAction(f:(value:A) => void):EventStream; + + /** + * @method + * @description Returns an [EventStream]{@link Bacon.EventStream} where the `propertyExtractor` string is applied to each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. + * @param {string} propertyExtractor + * @returns {EventStream} + */ + doAction(propertyExtractor:string):EventStream; + + /** + * @callback EventStream#doError~f + * @param {E} error + * @returns {void} + */ + /** + * @method EventStream#doError + * @description Returns an [EventStream]{@link Bacon.EventStream} where the function `f` is executed for each error, before dispatching to subscribers. That is, same as `doAction` but for errors. + * @param {EventStream#doError~f} f + * @returns {EventStream} + */ + doError(f:(error:E) => void):EventStream; + + /** + * @method + * @description Returns an [EventStream]{@link Bacon.EventStream} that inverts boolean values. + * @returns {EventStream} + */ + not():EventStream; + + /** + * @method EventStream#log + * @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. It optionally takes a `label` argument to pass to `console.log()` alongside each value. To assist with chaining, it returns the original EventStream. Note that as a side-effect, the EventStream will have a constant listener and will not be garbage-collected. So, use this for debugging only and remove from production code. + * @param {string} [label] + * @returns {EventStream} + */ + log(label?:string):EventStream; + + /** + * @method EventStream#doLog + * @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. [doLog]{@link Bacon.EventStream#doLog} behaves like [log]{@link Bacon.EventStream#log} but does not subscribe to the EventStream. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. + * @returns {EventStream} + */ + doLog():EventStream; + + /** + * @method + * @description Ends the [EventStream]{@link Bacon.EventStream} on first [Error]{@link Bacon.Error} event. The error is included in the output of the returned EventStream. + * @returns {EventStream} + */ + endOnError():EventStream; + + /** + * @callback EventStream#endOnError~f + * @param {E} error + * @returns {boolean} + */ + /** + * @method EventStream#endOnError + * @description Ends the [EventStream]{@link Bacon.EventStream} on first [Error]{@link Bacon.Error} event for which the given predicate function `f` returns `true`. The error is included in the output of the returned EventStream. + * @param {EventStream#endOnError} f + * @returns {EventStream} + */ + endOnError(f:(error:E) => boolean):EventStream; + + /** + * @callback EventStream#withHandler~f + * @param {Initial|Next|End|Error} event + * @returns {*} + */ + /** + * @method EventStream#withHandler + * @description Lets you do more custom event handling on [EventStream]{@link Bacon.EventStream}: you get all events to your function `f` and you can output any number of events and end the stream if you choose. Note that it's important to return the value from `this.push` so that the connection to the underlying stream will be closed when no more events are needed. + * @param {EventStream#withHandler~f} f + * @returns {EventStream} + * @example + * // Send an error and end the stream in case a value is below zero: + * Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { + * if (event.hasValue() && event.value() < 0) { + * this.push(new Bacon.Error("Value below zero")); + * return this.push(new Bacon.End()); + * } else { + * return this.push(event); + * } + * }); + */ + withHandler(f:(event:Initial|Next|End|Error) => any):EventStream; + + /** + * @method + * @description Sets the name of the [EventStream]{@link Bacon.EventStream}. Overrides the default implementation of `toString` and `inspect`. Returns itself. + * @param {string} newName + * @returns {EventStream} + */ + name(newName:string):EventStream; + + /** + * @method + * @description Sets the structured description of the [EventStream]{@link Bacon.EventStream}. The `toString` and `inspect` methods use this data recursively to create a string representation for the `EventStream`. This method is probably useful for Bacon core/library/plugin development only. + * @param {...*} param + * @returns {EventStream} + * @example + * { + * let src = Bacon.once(1), + * obs = src.map(x => -x); + * + * console.log(obs.toString()); + * // Bacon.once(1).map(function) + * + * obs.withDescription(src, "times", -1); + * console.log(obs.toString()); + * // Bacon.once(1).times(-1) + */ + withDescription(...param:any[]):EventStream; + + /** + * @callback EventStream#groupBy1~keyF + * @param {A} value + * @returns {B} + */ + /** + * @method EventStream#groupBy1 + * @description Groups [EventStream]{@link Bacon.EventStream} events to new EventStream's by `keyF`. + * @param {EventStream#groupBy1~keyF} keyF + * @returns {EventStream>} + */ + groupBy(keyF:(value:A) => B):EventStream>; + + /** + * @callback keyF + * @param {A} value + * @returns {B} + */ + /** + * @callback limitF + * @param {EventStream} groupedStream + * @param {Initial|Next|End|Error} groupStartingEvent + * @returns {EventStream} + */ + /** + * @description Groups [EventStream]{@link Bacon.EventStream} events to new EventStream's by `keyF`. `limitF` is provided to limit grouped stream life. EventStream transformed by `limitF` is passed on if provided. `limitF` gets grouped stream and the original [Event]{@link Bacon.Event} causing the EventStream to start as parameters. + * @param {keyF} keyF + * @param {limitF} limitF + * @returns {EventStream>} Grouped streams. + */ + groupBy(keyF:(value:A) => B, limitF:(groupedStream:EventStream, groupStartingEvent:Initial|Next|End|Error) => EventStream):EventStream>; + + /** + * @callback EventStream#subscribe~f + * @param {Event} event + * @returns {void|NoMore} + */ + /** + * @callback EventStream#subscribe~unsubscribe + * @returns {void} + */ + /** + * @method EventStream#subscribe + * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Function will receive [Event]{@link Bacon.Event} objects. The [subscribe]{@link EventStream#subscribe} call returns an [unsubscribe function]{@link EventStream#subscribe~unsubscribe} that you can call to unsubscribe. You can also unsubscribe by returning [Bacon.noMore]{@link Bacon.noMore} from the handler function as a reply to an Event. + * @param {EventStream#subscribe~f} f + * @returns {EventStream#subscribe~unsubscribe} + */ + subscribe(f:(event:Event) => void|NoMore):() => void; + + /** + * @callback EventStream#onValue~f + * @param {A} value + * @returns {void} + */ + /** + * @callback EventStream#onValue~unsubscribe + * @returns {void} + */ + /** + * @method EventStream#onValue + * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Function will be called for each new value in the EventStream. This is the simplest way to assign a side-effect to a EventStream. The difference to the [subscribe]{@link Bacon.EventStream#subscribe} method is that the actual EventStream values are received, instead of [Event]{@link Bacon.Event} objects. Just like `subscribe`, this method returns a function for `unsubscribe`ing. + * @param {EventStream#onValue~f} f + * @returns {EventStream#onValue~unsubscribe} + */ + onValue(f:(value:A) => void):() => void; + + /** + * @callback EventStream#onValues~f + * @param {*[]} args + * @returns {void} + */ + /** + * @callback EventStream#onValues~unsubscribe + * @returns {void} + */ + /** + * @method EventStream#onValues + * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Like [EventStream.onValue]{@link Bacon.EventStream#onValue}, but splits the value (assuming its an array) as function arguments to `f`. + * @param {EventStream#onValues~f} f + * @returns {EventStream#onValues~unsubscribe} + */ + onValues(f:(...args:any[]) => void):() => void; + + /** + * @callback EventStream#skipDuplicates~isEqual + * @param {A} oldValue + * @param {A} newValue + * @returns {boolean} + */ + /** + * @method EventStream#skipDuplicates + * @description Drops consecutive equal elements of the [EventStream]{@link Bacon.EventStream}. Uses the === operator for equality checking by default. If the `isEqual` argument is supplied, checks by calling [isEqual]{@link EventStream#skipDuplicates~isEqual}. For instance, to do a deep comparison, you can use the `isEqual` function from underscore.js like `stream.skipDuplicates(_.isEqual)`. + * @param {EventStream#skipDuplicates~isEqual} [isEqual] + * @returns {EventStream} + * @example + * Bacon.fromArray([1, 2, 2, 1]).skipDuplicates().log(); + * // > returns [1, 2, 1] in an order + */ + skipDuplicates(isEqual?:(oldValue:A, newValue:A) => boolean):EventStream; + + /** + * @method + * @description Concatenates two [EventStream]{@link Bacon.EventStream}s into one so that it will deliver events from EventStream until it ends and then deliver events from `otherStream`. This means too that events from `otherStream`, occurring before the end of EventStream will not be included in the result EventStream. + * @param {EventStream} otherStream + * @returns {EventStream} + */ + concat(otherStream:EventStream):EventStream; + + /** + * @method + * @description Merges two [EventStream]{@link Bacon.EventStream}s into one that delivers events from both. + * @param {EventStream} otherStream + * @returns {EventStream} + */ + merge(otherStream:EventStream):EventStream; + + /** + * @method + * @description Pauses and buffers the [EventStream]{@link Bacon.EventStream} if last event in `valve` is truthy. All buffered events are released when `valve` becomes falsy. + * @param {Observable} valve + * @returns {EventStream} + */ + holdWhen(valve:Observable):EventStream; + + /** + * @method + * @description Adds a starting `value` to the [EventStream]{@link Bacon.EventStream}, i.e. concats a EventStream containing a single `value` with this EventStream. + * @param {A} value + * @returns {EventStream} + */ + startWith(value:A):EventStream; + + /** + * @callback EventStream#skipWhile~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method EventStream#skipWhile + * @description Skips elements in the [EventStream]{@link Bacon.EventStream} until the given predicate function `f` returns falsy once, and then lets all events pass through. + * @param {EventStream#skipWhile~f} f + * @returns {EventStream} + */ + skipWhile(f:(value:A) => boolean):EventStream; + + /** + * @method + * @description Skips elements in the [EventStream]{@link Bacon.EventStream} until the value of the given [Property]{@link Bacon.Property} `property` is falsy once, and then lets all events pass through. + * @param {Property} property + * @returns {EventStream} + */ + skipWhile(property:Property):EventStream; + + /** + * @method + * @description Skips elements from the [EventStream]{@link Bacon.EventStream} until a [Next]{@link Bacon.Next} event appears in `stream2`. In other words, starts delivering values from `stream` after first event appears in `stream2`. + * @param {EventStream} stream2 + * @returns {EventStream} + */ + skipUntil(stream2:EventStream):EventStream; + + /** + * @method + * @description Buffers the [EventStream]{@link Bacon.EventStream} with given `delay` (in milliseconds). The buffer is flushed at most once in the given `delay`. + * @param {number} delay + * @returns {EventStream} + * @example + * // You might get two events containing [1,2,3,4] and [5,6,7] respectively, given that the flush occurs between numbers 4 and 5: + * Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]).bufferWithTime(0); + */ + bufferWithTime(delay:number):EventStream; + + /** + * @callback EventStream#bufferWithTime~f + * @param {EventStream#bufferWithTime~defer} defer + * @returns {void} + */ + /** + * @callback EventStream#bufferWithTime~defer + * @param {...*} args + * @returns {void} + */ + /** + * @method EventStream#bufferWithTime + * @description Buffers the [EventStream]{@link Bacon.EventStream} with given "defer-function" `f`. + * @param {EventStream#bufferWithTime~f} f + * @returns {EventStream} + * @example + * // Here's an equivalent to `stream.bufferWithTime(10)`: + * let stream = Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]); + * stream.bufferWithTime(f => { setTimeout(f, 10); }); } + */ + bufferWithTime(f:(defer:(...args:any[]) => void) => void):EventStream; + + /** + * @method + * @description Buffers the [EventStream]{@link Bacon.EventStream} events with given `count`. The buffer is flushed when it contains the given `count` of elements. + * @param {number} count + * @returns {EventStream} + * @example + * // You will get output events with values `[1, 2]`, `[3, 4]` and `[5]`. + * Bacon.fromArray([1, 2, 3, 4, 5]).bufferWithCount(2); + */ + bufferWithCount(count:number):EventStream; + + /** + * @method + * @description Buffers the [EventStream]{@link Bacon.EventStream} events and flushes when either the buffer contains the given `count` of elements or the given `delay` (in milliseconds) has passed since last buffered event. + * @param {number} delay + * @param {number} count + * @returns {EventStream} + */ + bufferWithTimeOrCount(delay:number, count:number):EventStream; + + /** + * @method EventStream#toProperty + * @description Creates a [Property]{@link Bacon.Property} based on the [EventStream]{@link Bacon.EventStream}. Without arguments, you'll get a Property without an initial value and will get its first actual value from the EventStream, and after that it'll always have a current value. Given `initialValue` will be used as the current value until the first value comes from the EventStream. + * @param {A} [initialValue] + * @returns {Property} + */ + toProperty(initialValue?:A):Property; + } + + var EventStream:{ + /** + * @callback EventStream#new~subscribe + * @param {EventStream#new~sink} sink + * @returns {EventStream#new~unsubscribe} + */ + /** + * @callback EventStream#new~sink + * @param {More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]} value + * @returns {void} + */ + /** + * @callback EventStream#new~unsubscribe + * @returns {void} + */ + /** + * @constructor EventStream#new + * @constructs Bacon.EventStream + * @description Creates an [EventStream]{@link Bacon.EventStream} with the given `subscribe` function. + * @param {EventStream#new~subscribe} subscribe + * @returns {EventStream} + */ + new(subscribe:(sink:(value:More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]) => void) => (() => void)):EventStream; + }; + + /** + * @class Property + * @augments Bacon.Observable + * @description A reactive property. Has the concept of "current value". You can create a Property from an [EventStream]{@link Bacon.EventStream} by using either [EventStream.toProperty]{@link Bacon.EventStream#toProperty} or [Observable.scan]{@link Bacon.Observable#scan} method. Note: depending on how a Property is created, it may or may not have an initial value. The current value stays as its last value after the EventStream has ended. + * */ + interface Property extends Observable { + /** + * @callback Property#map~f + * @param {A} value + * @returns {B} + */ + /** + * @method Property#map + * @description Maps the [Property]{@link Bacon.Property} values using given function `f`, returning a new Property. This method, among many others, uses lazy evaluation. + * @param {Property#map~f} f + * @returns {Property} + * */ + map(f:(value:A) => B):Property; + + /** + * @method + * @description Maps the [Property]{@link Bacon.Property} values using given `constant` value, returning a new Property. This method, among many others, uses lazy evaluation. + * @param {B} constant + * @returns {Property} + * */ + map(constant:B):Property; + + /** + * @method + * @description Maps the [Property]{@link Bacon.Property} values using given `propertyExtractor` string like ".keyCode", returning a new Property. So, if f is a string starting with a dot, the elements will be mapped to the corresponding field/function in the event value. For instance map(".keyCode") will pluck the keyCode field from the input values. If "keyCode" was a function, the resulting Property would contain the values returned by the function. This method, among many others, uses lazy evaluation. + * @param {string} propertyExtractor + * @returns {Property} + * */ + map(propertyExtractor:string):Property; + + /** + * @callback Property#mapError~f + * @param {E} error + * @returns {B} + */ + /** + * @method Property#mapError + * @description Maps the [Property]{@link Bacon.Property} errors using given function `f`. More specifically, feeds the "error" field of the [Error]{@link Bacon.Error} event to the function `f` and produces a [Next]{@link Bacon.Next} event based on the return value. + * @param {Property#mapError~f} f + * @returns {Property} + */ + mapError(f:(error:E) => B):Property; + + /** + * @method + * @description Returns a [Property]{@link Bacon.Property} containing [Error]{@link Bacon.Error} events only. Same as filtering with a function that always returns false. + * @returns {Property} + */ + errors():Property; + + /** + * @method + * @description Skips all [Error]{@link Bacon.Error}s. + * @returns {Property} + */ + skipErrors():Property; + + /** + * @callback Property#mapEnd~f + * @returns {A} + */ + /** + * @method Property#mapEnd + * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} of the [Property]{@link Bacon.Property}. The value is created by calling the given function `f` when the source Property ends. + * @param {Property#mapEnd~f} f + * @returns {Property} + */ + mapEnd(f:() => A):Property; + + /** + * @method + * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} of the [Property]{@link Bacon.Property}. A static `value` is used. + * @param {A} value + * @returns {Property} + */ + mapEnd(value:A):Property; + + /** + * @callback Property#filter~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method Property#filter + * @description Filters the [Property]{@link Bacon.Property} values using a given predicate function `f`. + * @param {Property#filter~f} f + * @returns {Property} + */ + filter(f:(value:A) => boolean):Property; + + /** + * @method + * @description Filters the [Property]{@link Bacon.Property} values using a given constant `bool` value (`true` to include all, `false` to exclude all). + * @param {boolean} bool + * @returns {Property} + */ + filter(bool:boolean):Property; + + /** + * @method + * @description Filters the [Property]{@link Bacon.Property} values using a given `propertyExtractor` string (like ".isValuable"). + * @param {string} propertyExtractor + * @returns {Property} + */ + filter(propertyExtractor:string):Property; + + /** + * @method + * @description Filters the [Property]{@link Bacon.Property} values based on the value of the Property `property`. Event will be included in output IF AND ONLY IF the `property` holds `true` at the time of the event. + * @param {Property} property + * @returns {Property} + */ + filter(property:Property):Property; + + /** + * @callback Property#takeWhile~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method Property#takeWhile + * @description Takes the [Property]{@link Bacon.Property} values while given predicate function `f` holds `true`, and then ends. + * @param {Property#takeWhile~f} f + * @returns {Property} + */ + takeWhile(f:(value:A) => boolean):Property; + + /** + * @method + * @description Takes the [Property]{@link Bacon.Property} values while the value of a `property` holds `true`, and then ends. + * @param {Property} property + * @returns {Property} + */ + takeWhile(property:Property):Property; + + /** + * @method Property#take + * @description Takes at most `n` elements from the [Property]{@link Bacon.Property}. Equal to `Bacon.never()` if `n <= 0`. + * @param {number} n + * @returns {Property} + */ + take(n:number):Property; + + /** + * @method + * @description Takes elements from the [Property]{@link Bacon.Property} until a [Next]{@link Bacon.Next} event appears in the `stream`. If `stream` ends without value, it is ignored. + * @param {EventStream} stream + * @returns {Property} + */ + takeUntil(stream:EventStream):Property; + + /** + * @method + * @description Takes the first element from the [Property]{@link Bacon.Property}. Essentially [Property.take]{@link Bacon.Property#take}(1). + * @returns {Property} + */ + first():Property; + + /** + * @method + * @description Takes the last element from the [Property]{@link Bacon.Property}. None, if Property is empty. + * @returns {Property} + * @example + * // This creates the property which doesn't produce any events and never ends: + * Bacon.interval(1e1, 0).toProperty().last(); + */ + last():Property; + + /** + * @method + * @description Skips the first `n` elements from the [Property]{@link Bacon.Property}. + * @param {number} n + * @returns {Property} + */ + skip(n:number):Property; + + /** + * @method + * @description Delays the [Property]{@link Bacon.Property} by given `delay` (in milliseconds). Does not delay the initial value of a Property. + * @param {number} delay + * @returns {Property} + */ + delay(delay:number):Property; + + /** + * @method Property#throttle + * @description Throttles the [Property]{@link Bacon.Property} by given `delay` (in milliseconds). Events are emitted with the minimum interval of `delay`. The implementation is based on [EventStream.bufferWithTime]{@link Bacon.EventStream#bufferWithTime}. Does not affect emitting the initial value of a Property. + * @param {number} delay + * @returns {Property} + */ + throttle(delay:number):Property; + + /** + * @method Property#debounce + * @description Throttles the [Property]{@link Bacon.Property} by given `delay` (in milliseconds), but so that event is only emitted after the given "quiet period". Does not affect emitting the initial value of a Property. The difference of [throttle]{@link Bacon.Property#throttle} and [debounce]{@link Bacon.Property#debounce} is the same as it is in the same methods in jQuery. + * @param {number} delay + * @returns {Property} + */ + debounce(delay:number):Property; + + /** + * @method + * @description Passes the first event in the [Property]{@link Bacon.Property} through, but after that, only passes events after a given `delay` (in milliseconds) have passed since previous output. + * @param {number} delay + * @returns {Property} + */ + debounceImmediate(delay:number):Property; + + /** + * @callback Property#doAction~f + * @param {A} value + * @returns {void} + */ + /** + * @method Property#doAction + * @description Returns a [Property]{@link Bacon.Property} where the function `f` is executed for each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. + * @param {Property#doAction~f} f + * @returns {Property} + */ + doAction(f:(value:A) => void):Property; + + /** + * @method + * @description Returns a [Property]{@link Bacon.Property} where the `propertyExtractor` string is applied to each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. + * @param {string} propertyExtractor + * @returns {Property} + */ + doAction(propertyExtractor:string):Property; + + /** + * @callback Property#doError~f + * @param {E} error + * @returns {void} + */ + /** + * @method Property#doError + * @description Returns a [Property]{@link Bacon.Property} where the function `f` is executed for each error, before dispatching to subscribers. That is, same as [doAction]{@link Bacon.Property#doAction} but for [Error]{@link Bacon.Error}s. + * @param {Property#doError~f} f + * @returns {Property} + */ + doError(f:(error:E) => void):Property; + + /** + * @method + * @description Returns a [Property]{@link Bacon.Property} that inverts boolean values. + * @returns {Property} + */ + not():Property; + + /** + * @method Property#log + * @description Logs each value of the [Property]{@link Bacon.Property} to the console. It optionally takes a `label` argument to pass to `console.log()` alongside each value. To assist with chaining, it returns the original Property. Note that as a side-effect, the Property will have a constant listener and will not be garbage-collected. So, use this for debugging only and remove from production code. + * @param {string} [label] + * @returns {Property} + */ + log(label?:string):Property; + + /** + * @method Property#doLog + * @description Logs each value of the [Property]{@link Bacon.Property} to the console. [doLog]{@link Bacon.Property#doLog} behaves like [log]{@link Bacon.Property#log} but does not subscribe to the Property. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. + * @returns {Property} + */ + doLog():Property; + + /** + * @method + * @description Ends the [Property]{@link Bacon.Property} on first [Error]{@link Bacon.Error} event. The error is included in the output of the returned Property. + * @returns {Property} + */ + endOnError():Property; + + /** + * @callback Property#endOnError~f + * @param {E} error + * @returns {boolean} + */ + /** + * @method Property#endOnError + * @description Ends the [Property]{@link Bacon.Property} on first [Error]{@link Bacon.Error} event for which the given predicate function `f` returns `true`. The error is included in the output of the returned Property. + * @param {Property#endOnError~f} f + * @returns {Property} + */ + endOnError(f:(error:E) => boolean):Property; + + /** + * @callback Property#withHandler~f + * @param {Initial|Next|End|Error} event + * @returns {*} + */ + /** + * @method Property#withHandler + * @description Lets you do more custom event handling on the [Property]{@link Bacon.Property}: you get all events to your function `f` and you can output any number of [Event]{@link Bacon.Event}s and end the Property if you choose. Note that it's important to return the value from `this.push` so that the connection to the underlying stream will be closed when no more events are needed. + * @param {Property#withHandler~f} f + * @returns {Property} + * @example + * // Send an error and end the stream in case a value is below zero: + * Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { + * if (event.hasValue() && event.value() < 0) { + * this.push(new Bacon.Error("Value below zero")); + * return this.push(new Bacon.End()); + * } else { + * return this.push(event); + * } + * }); + */ + withHandler(f:(event:Initial|Next|End|Error) => any):Property; + + /** + * @method + * @description Sets the `newName` of the [Property]{@link Bacon.Property}. Overrides the default implementation of `toString` and `inspect`. Returns itself. + * @param {string} newName + * @returns {Property} + */ + name(newName:string):Property; + + /** + * @method + * @description Sets the structured description of the [Property]{@link Bacon.Property}. The `toString` and `inspect` methods use this data recursively to create a string representation for the Property. This method is probably useful for Bacon core/library/plugin development only. + * @param {...*} param + * @returns {Property} + * @example + * let src = Bacon.once(1), + * obs = src.map(x => -x); + * + * console.log(obs.toString()); + * // Bacon.once(1).map(function) + * + * obs.withDescription(src, "times", -1); + * console.log(obs.toString()); + * // Bacon.once(1).times(-1) + */ + withDescription(...param:any[]):Property; + + /** + * @method + * @description Creates an [EventStream]{@link Bacon.EventStream} based on this [Property]{@link Bacon.Property}. The EventStream contains also an event for the current value of this Property at the time this method was called. + * @returns {EventStream} + */ + toEventStream():EventStream; + + /** + * @callback Property#subscribe~f + * @param {Event} event + * @returns {void} + */ + /** + * @callback Property#subscribe~unsubscribe + * @returns {void} + */ + /** + * @method Property#subscribe + * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. If there's a current value, an [Initial]{@link Bacon.Initial} event will be pushed immediately. [Next]{@link Bacon.Next} event will be pushed on updates and an [End]{@link Bacon.End} event in case the source Property ends. Returns a function that you call to `unsubscribe`. + * @param {Property#subscribe~f} f + * @returns {Property#subscribe~unsubscribe} + */ + subscribe(f:(event:Event) => void):() => void; + + /** + * @callback Property#onValue~f + * @param {A} value + * @returns {void} + */ + /** + * @callback Property#onValue~unsubscribe + * @returns {void} + */ + /** + * @method Property#onValue + * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. Similar to [EventStream.onValue]{@link Bacon.EventStream#onValue}, except that also pushes the initial value of the Property, in case there is one. Just like [subscribe]{@link Bacon.Property#subscribe}, this method returns a function for `unsubscribe`ing. + * @param {Property#onValue~f} f + * @returns {Property#onValue~unsubscribe} + */ + onValue(f:(value:A) => void):() => void; + + /** + * @callback Property#onValues~f + * @param {*[]} args + * @returns {void} + */ + /** + * @callback Property#onValues~unsubscribe + * @returns {void} + */ + /** + * @method Property#onValues + * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. Like [onValue]{@link Bacon.Property#onValue}, but splits the value (assuming its an array) as function arguments to `f`. + * @param {Property#onValues~f} f + * @returns {Property#onValues~unsubscribe} + */ + onValues(f:(...args:any[]) => void):() => void; + + /** + * @method Property#assign + * @description Calls the `method` of the given `object` with each value of this [Property]{@link Bacon.Property}. You can optionally supply `params` which will be used as the first arguments of the `method` call. Note that the [assign]{@link Bacon.Property#assign} method is actually just a synonym for [onValue]{@link Bacon.Property#onValue}. + * @param {Object} obj + * @param {string} method + * @param {...*} params + * @returns {void} + * @example + * let property = Bacon.fromArray([1, 2, 3, 4, 5]).toProperty(); + * // If you want to assign your Property to the "disabled" attribute of a JQuery object, you can do this: + * property.assign($("#my-button"), "attr", "disabled"); + * // A simpler example would be to toggle the visibility of an element based on a Property: + * property.assign($("#my-button"), "toggle"); + */ + assign(obj:Object, method:string, ...params:any[]):void; + + /** + * @method + * @description Creates an [EventStream]{@link Bacon.EventStream} by sampling the [Property]{@link Bacon.Property} value at given `interval` (in milliseconds). + * @param {number} interval + * @returns {EventStream} + */ + sample(interval:number):EventStream; + + /** + * @method Property#sampledBy + * @description Creates an [EventStream]{@link Bacon.EventStream} by sampling the [Property]{@link Bacon.Property} value at each event from the given `stream`. The result EventStream will contain the value at each event in the source Property. + * @param {EventStream} stream + * @returns {EventStream} + */ + sampledBy(stream:EventStream):EventStream; + + /** + * @method + * @description Creates a [Property]{@link Bacon.Property} by sampling the value at each event from the given [Property]{@link Bacon.Property} `property`. The result Property will contain the value at each event in the source Property. + * @param {Property} property + * @returns {Property} + */ + sampledBy(property:Property):Property; + + /** + * @callback Property#sampledBy~f + * @param {A} propertyValue + * @param {B} samplerValue + * @returns {C} + */ + /** + * @method Property#sampledBy + * @description Samples the [Property]{@link Bacon.Property} on `streamOrProperty` events. The result values will be formed using the given function `f`. + * @param {Observable} streamOrProperty + * @param {Property#sampledBy~f} f + * @returns {EventStream} + */ + sampledBy(streamOrProperty:Observable, f:(propertyValue:A, samplerValue:B) => C):EventStream; + + /** + * @callback Property#skipDuplicates~isEqual + * @param {A} oldValue + * @param {A} newValue + * @returns {boolean} + */ + /** + * @method Property#skipDuplicates + * @description Drops consecutive equal elements. Uses the `===` operator for equality checking by default. If the `isEqual` argument is supplied, checks by calling `isEqual(oldValue, newValue)`. The old name for this method was `distinctUntilChanged`. + * @param {Property#skipDuplicates~isEqual} [isEqual] + * @returns {Property} + */ + skipDuplicates(isEqual?:(oldValue:A, newValue:A) => boolean):Property; + + /** + * @method Property#changes + * @description Returns an [EventStream]{@link Bacon.EventStream} of [Property]{@link Bacon.Property} value changes. Returns exactly the same events as the Property itself, except any [Initial]{@link Bacon.Initial} events (the stream DOES NOT include an event for the current value of the Property at the time this method was called). Note that [Property.changes]{@link Bacon.Property#changes} DOES NOT skip duplicate values, use [Property.skipDuplicates]{@link Bacon.Property#skipDuplicates} for that. + * @returns {EventStream} + */ + changes():EventStream; + + /** + * @method + * @description Combines [Property]{@link Bacon.Property}s with the && operator. + * @param {Property} other + * @returns {Property} + */ + and(other:Property):Property; + + /** + * @method + * @description Combines [Property]{@link Bacon.Property}s with the || operator. + * @param {Property} other + * @returns {Property} + */ + or(other:Property):Property; + + /** + * @method + * @description Adds an initial "default" value for the [Property]{@link Bacon.Property}. If the Property doesn't have an initial value of it's own, the given `value` will be used as the initial value. If the property has an initial value of its own, the given `value` will be ignored. + * @param {A} value + * @returns {Property} + */ + startWith(value:A):Property; + } + + /** + * @function Bacon.combineAsArray + * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values so that the result Property will have an array of all property values as its value. The input array may contain both Properties and EventStreams. In the latter case, the stream is first converted into a Property and then combined with the other Property's. + * @param {(A|Observable)[]} streams + * @returns {Property} + */ + function combineAsArray(streams:(A|Observable)[]):Property; + + /** + * @function + * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values so that the result Property will have an array of all property values as its value. Like [Bacon.combineAsArray]{@link Bacon.combineAsArray}, but `streams` are provided as a list of arguments as opposed to a single array. + * @param {...(A|Observable)} streams + * @returns {Property} + */ + function combineAsArray(...streams:(A|Observable)[]):Property; + + /** + * @callback Property#combineWith~f + * @param {...A} args + * @returns {B} + */ + /** + * @function Property#combineWith + * @description Combines given n [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values using the given n-ary function `f`. + * @param {Property#combineWith~f} f + * @param {...(A|Observable)} streams + * @returns {Property} + */ + function combineWith(f:(...args:A[]) => B, ...streams:(A|Observable)[]):Property; + + /** + * @function + * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values using a `template` object. + * @param {{string:number|boolean|string|Object|Observable}} template + * @returns {Property} + */ + function combineTemplate(template:{[label:string]:number|boolean|string|Object|Observable}):Property; + + /** + * @function + * @description Merges given array of [EventStream]{@link Bacon.EventStream}s. + * @param {EventStream[]} streams + * @returns {EventStream} + */ + function mergeAll(streams:EventStream[]):EventStream; + + /** + * @function + * @description Merges given array of [EventStream]{@link Bacon.EventStream}s. + * @param {...EventStream} streams + * @returns {EventStream} + */ + function mergeAll(...streams:EventStream[]):EventStream; + + /** + * @function + * @description Zips the array of `streams` in to a new [EventStream]{@link Bacon.EventStream} that will have an array of values from each source EventStream as its value. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. + * @param {EventStream[]} streams + * @returns {EventStream} + */ + function zipAsArray(streams:EventStream[]):EventStream; + + /** + * @function + * @description Zips the `streams` in to a new [EventStream]{@link Bacon.EventStream} that will have an array of values from each source EventStream as its value. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. EventStream's are provided as a list of arguments as opposed to a single array. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. + * @param {...EventStream} streams + * @returns {EventStream} + */ + function zipAsArray(...streams:EventStream[]):EventStream; + + /** + * @callback Bacon.zipWith1~f + * @param {...A} args + * @returns {B} + */ + /** + * @function Bacon.zipWith1 + * @description Zips the array of `streams` in to a new [EventStream]{@link Bacon.EventStream} that will combine the n values from EventStream's with n-ary function `f`. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. + * @param {EventStream[]} streams + * @param {Bacon.zipWith1~f} f + * @returns {EventStream} + */ + function zipWith(streams:EventStream[], f:(...args:A[]) => B):EventStream; + + /** + * @callback Bacon.zipWith2~f + * @param {...A} args + * @returns {B} + */ + /** + * @function Bacon.zipWith2 + * @description Zips the `streams` in to a new [EventStream]{@link Bacon.EventStream} that will combine the n values from EventStream's with n-ary function `f`. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Streams are provided as a list of arguments as opposed to a single array. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. + * @param {Bacon.zipWith2~f} f + * @param {...EventStream} streams + * @returns {EventStream} + */ + function zipWith(f:(...args:A[]) => B, ...streams:EventStream[]):EventStream; + + /** + * @function + * @description Is a shorthand for combining multiple sources ([EventStream]{@link Bacon.EventStream}s, [Property]{@link Bacon.Property}s, constants) as array and assigning the side-effect function `f` for the values. + * @param {...*} args + * @returns {void} + */ + function onValues(...args:any[]):void; + + /** + * @class Bus + * @augments Bacon.EventStream + * @description An [EventStream]{@link Bacon.EventStream} that allows you to [push]{@link Bacon.Bus#push} values into the EventStream. It also allows [plug]{@link Bacon.Bus#plug}ging other EventStream's into the Bus. The Bus practically merges all plugged-in streams and the values pushed using the [push]{@link Bacon.Bus#push} method. + */ + interface Bus extends EventStream { + /** + * @method Bus#push + * @description Pushes the given `value` to the [Bus]{@link Bacon.Bus}. + * @param {A} value + * @returns {void} + */ + push(value:A):void; + + /** + * @method + * @description Ends the [Bus]{@link Bacon.Bus}. Sends an [End]{@link Bacon.End} event to all subscribers. After this call, there'll be no more events to the subscribers. Also, the [Bus.push]{@link Bacon.Bus#push} and [Bus.plug]{@link Bacon.Bus#plug} methods have no effect. + * @returns {void} + */ + end():void; + + /** + * @method + * @description Sends an [Error]{@link Bacon.Error} with given `error` message to all subscribers. + * @param {E} error + * @returns {void} + */ + error(error:E):void; + + /** + * @callback Bus#plug~unplug + * @returns {void} + */ + /** + * @method Bus#plug + * @description Plugs the given [EventStream]{@link Bacon.EventStream} to the [Bus]{@link Bacon.Bus}. All events from the given `stream` will be delivered to the subscribers of the Bus. Returns a function `unplug` that can be used to unplug the same stream. The [plug]{@link Bacon.Bus#plug} method practically allows you to merge in other EventStream's after the creation of the Bus. + * @param {EventStream} stream + * @returns {Bus#plug~unplug} + */ + plug(stream:EventStream):() => void; + } + + var Bus:{ + /** + * @constructor + * @constructs Bacon.Bus + * @description Returns a new [Bus]{@link Bacon.Bus}. + * @returns {Bus} + */ + new():Bus; + }; + + /** + * @class Event + * @description Has subclasses [Initial]{@link Bacon.Initial}, [Next]{@link Bacon.Next}, [End]{@link Bacon.End} and [Error]{@link Bacon.Error}. + * */ + class Event { + /** + * @method + * @description Returns the value associated with a [Initial]{@link Bacon.Initial} or [Next]{@link Bacon.Next} event. + * @returns {A} + */ + value():A; + + /** + * @method + * @description Returns `true` for events of type [Initial]{@link Bacon.Initial} or [Next]{@link Bacon.Next}. + * @returns {boolean} + */ + hasValue():boolean; + + /** + * @method Error#isInitial + * @description Returns `true` for events of type [Initial]{@link Bacon.Initial}. + * @returns {boolean} + */ + isInitial():boolean; + + /** + * @method Error#isNext + * @description Returns `true` for events of type [Next]{@link Bacon.Next}. + * @returns {boolean} + */ + isNext():boolean; + + /** + * @method Error#isError + * @description Returns `true` for events of type [Error]{@link Bacon.Error}. + * @returns {boolean} + */ + isError():boolean; + + /** + * @method Error#isEnd + * @description Returns `true` for events of type [End]{@link Bacon.End}. + * @returns {boolean} + */ + isEnd():boolean; + } + + /** + * @class Error + * @augments Bacon.Event + * @description An error event. Call [Event.isError]{@link Bacon.Event#isError} to distinguish these events in your subscriber, or use [onError]{@link Bacon.Observable#onError} to react to error events only. [Error.error]{@link Bacon.Error#error} returns the associated error object (usually string). [Error]{@link Bacon.Error} events are always passed through all stream combinators. So, even if you filter all values out, the error events will pass through. If you use [Observable.flatMap]{@link Bacon.Observable#flatMap}, the result stream will contain Error events from the source as well as all the spawned stream. You can take action on errors by using the [Observable.onError]{@link Bacon.Observable#onError}. See documentation on [Observable.onError]{@link Bacon.Observable#onError}, [EventStream.mapError]{@link Bacon.EventStream#mapError}, [Property.mapError]{@link Bacon.Property#mapError}, [EventStream.errors]{@link Bacon.EventStream#errors}, [Property.errors]{@link Bacon.Property#errors}, [EventStream.skipErrors]{@link Bacon.EventStream#skipErrors}, [Property.skipErrors]{@link Bacon.Property#skipErrors}, [Bacon.retry]{@link Bacon.retry} and [Observable.flatMapError]{@link Bacon.Observable#flatMapError}. An Error does not terminate the stream. The methods [EventStream.endOnError]{@link Bacon.EventStream#endOnError} and [EventStream.endOnError]{@link Bacon.EventStream#endOnError} returns a stream/property that ends immediately after first error. Bacon.js doesn't currently generate any Error events itself (except when converting errors using [Bacon.fromPromise]{@link Bacon.fromPromise}). Error events definitely would be generated by streams derived from IO sources such as AJAX calls. + * @example + * // In case you want to convert (some) value events into Error events, you may use `flatMap` like this: + * Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { + * NOTE: had to explicitly specify the `` typing for `flatMap`. + * return x > 2 ? new Bacon.Error("too big") : x; + * }); + * + * // Conversely, if you want to convert some Error events into value events, you may use `flatMapError`: + * Bacon.fromArray([1, 2, 3, 4]).flatMapError(error => { + * let isNonCriticalError = error => Math.random() < .5, + * handleNonCriticalError = error => 42; + * return isNonCriticalError(error) ? handleNonCriticalError(error) : new Bacon.Error(error); + * }); + * + * // Note also that Bacon.js combinators do not catch errors that are thrown. Especially `map` doesn't do so. If you want to map things and wrap caught errors into Error events, you can do the following: + * Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { + * let dangerousFunction = x => { + * throw new Error("dangerous function!"); + * }; + * try { + * return dangerousFunction(x); + * } catch (e) { + * return new Bacon.Error(e); + * } + * }); + */ + class Error extends Event { + /** + * @constructor + * @constructs Error + * @param {E} error + * */ + constructor(error:E); + + /** + * @property Error#error + * @description Returns the `error` associated with an [Error]{@link Bacon.Error} event. + * @returns {E} + */ + error:E; + } + + /** + * @class End + * @augments Bacon.Event + * @description An end-of-stream event of [EventStream]{@link Bacon.EventStream} or [Property]{@link Bacon.Property}. Call [Event.isEnd]{@link Bacon.Event#isEnd} to distinguish an End from other events. + * */ + class End extends Event { + /** + * @constructor + * @constructs Bacon.End + * */ + constructor(); + } + + /** + * @class Initial + * @augments Bacon.Event + * @description The initial (current) value of a [Property]{@link Bacon.Property}. Call [Event.isInitial]{@link Bacon.Event#isInitial} to distinguish from other events. Only sent immediately after subscription to a Property. + * */ + class Initial extends Event { + /** + * @constructor + * @constructs Bacon.Initial + * @param {A} value + * */ + constructor(value:A); + } + + /** + * @class Next + * @augments Bacon.Event + * @description Next value in an [EventStream]{@link Bacon.EventStream} or a [Property]{@link Bacon.Property}. Call [Event.isNext]{@link Bacon.Event#isNext} to distinguish a Next event from other events. + * */ + class Next extends Event { + /** + * @constructor + * @constructs Bacon.Next + * @param {A} value + * @example + * new Bacon.Next("value"); + * */ + constructor(value:A); + + /** + * @callback Next#constructor + * @returns {A} + */ + /** + * @constructor Next#constructor + * @constructs Bacon.Next + * @description This version is safe only when you know that the actual value in the stream is not a function. The idea in using a function `f` instead of a plain value is that the internals on Bacon.js take advantage of lazy evaluation by deferring the evaluations of values created by `map`, `combine`. + * @param {Next#constructor} f + * @example + * new Bacon.Next(() => "value"); + * */ + constructor(f:() => A); + } + + /** + * @callback Bacon.retry1~source + * @description Function that produces an [EventStream]{@link Bacon.EventStream}. + * @returns {EventStream} + */ + /** + * @callback Bacon.retry1~isRetryable + * @description Function returning `true` to continue retrying, `false` to stop. Defaults to `true`. The [Error]{@link Bacon.Error} that occurred is given as a parameter. For example, there is usually no reason to retry a 404 HTTP error, whereas a 500 or a timeout might work on the next attempt. + * @param {E} error + * @returns {boolean} + */ + /** + * @callback Bacon.retry1~delay + * @description Function that returns the time in milliseconds to wait before retrying. Defaults to `0`. The function is given a `context` object with the keys `error` (the [Error]{@link Bacon.Error} that occurred) and `retriesDone` (the number of retries already performed) to help determine the appropriate delay, e.g. for an incremental backoff. + * @param {Object} context + * @param {E} context.error [Error]{@link Bacon.Error} that occurred + * @param {number} context.retriesDone number of retries already performed + * @returns {number} + */ + /** + * @function Bacon.retry1 + * @description Is used to retry the call when there is an [Error]{@link Bacon.Error} event in the [EventStream]{@link Bacon.EventStream} produced by the `source` function. + * @param {Object} options + * @param {Bacon.retry1~source} options.source function that produces an [EventStream]{@link Bacon.EventStream} + * @param {number} options.retries number of times to retry the `source` function in addition to the initial attempt + * @param {Bacon.retry1~isRetryable} [options.isRetryable] function returning `true` to continue retrying, `false` to stop. Defaults to `true`. + * @param {Bacon.retry1~delay} [options.delay] - function that returns the time in milliseconds to wait before retrying. Defaults to `0`. + * @returns {EventStream} + */ + function retry(options:{ + source:() => EventStream; + retries:number; + isRetryable?:(error:E) => boolean; + delay?:(context:{error:E; retriesDone:number}) => number; + }):EventStream; + + /** + * @callback Bacon.retry1~source + * @description Function that produces an [Property]{@link Bacon.Property}. + * @returns {Property} + */ + /** + * @callback Bacon.retry1~isRetryable + * @description Function returning `true` to continue retrying, `false` to stop. Defaults to `true`. The [Error]{@link Bacon.Error} that occurred is given as a parameter. For example, there is usually no reason to retry a 404 HTTP error, whereas a 500 or a timeout might work on the next attempt. + * @param {E} error + * @returns {boolean} + */ + /** + * @callback Bacon.retry1~delay + * @description Function that returns the time in milliseconds to wait before retrying. Defaults to `0`. The function is given a `context` object with the keys `error` (the [Error]{@link Bacon.Error} that occurred) and `retriesDone` (the number of retries already performed) to help determine the appropriate delay, e.g. for an incremental backoff. + * @param {Object} context + * @param {E} context.error [Error]{@link Bacon.Error} that occurred + * @param {number} context.retriesDone number of retries already performed + * @returns {number} + */ + /** + * @function Bacon.retry1 + * @description Is used to retry the call when there is an [Error]{@link Bacon.Error} event in the [Property]{@link Bacon.Property} produced by the `source` function. + * @param {Object} options + * @param {Bacon.retry1~source} options.source function that produces an [Property]{@link Bacon.Property} + * @param {number} options.retries number of times to retry the `source` function in addition to the initial attempt + * @param {Bacon.retry1~isRetryable} [options.isRetryable] function returning `true` to continue retrying, `false` to stop. Defaults to `true`. + * @param {Bacon.retry1~delay} [options.delay] - function that returns the time in milliseconds to wait before retrying. Defaults to `0`. + * @returns {Property} + */ + function retry(options:{ + source:() => Property; + retries:number; + isRetryable?:(error:E) => boolean; + delay?:(context:{error:E; retriesDone:number}) => number; + }):Property; + + /** + * @callback Bacon.when1~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @method Bacon.when1 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when1~f1} f1 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + * + * { + * // Join patterns as a "chemical machine". + * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: + * let oxygen = Bacon.interval(1e3, "O"), + * hydrogen = Bacon.interval(2e3, "H"), + * carbon = Bacon.interval(1.5e3, "C"), + * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, + * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; + * Bacon.when( + * [oxygen, hydrogen, hydrogen], makeWater, + * [oxygen, carbon], makeCarbonMonoxide + * ); + * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. + * } + * + * { + * // Join patterns and properties. + * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: + * // -- updating `quantity` sets `total` to `price * quantity`; + * // -- updating `total` sets `price` to `total / quantity`. + * let random = (x:number) => Math.round(x * Math.random()), + * id = (x:A):A => x; + * let $quantity = Bacon.interval(1e3, 10).map(random), + * $price = Bacon.interval(2e3, 100).map(random), + * $total = Bacon.interval(1.5e3, 1000).map(random); + * let quantity = $quantity.toProperty(1), + * price = Bacon.when( + * [$price], id, + * [$total, quantity], (x, y) => x / y + * ).toProperty(0), + * total = Bacon.when( + * [$total], id, + * [$price, quantity], (x, y) => x * y, + * [price, $quantity], (x, y) => x * y + * ).toProperty(0); + * } + * + * { + * // Join patterns and `Bacon.Bus`. + * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: + * // Availability of chopsticks are implemented using bus. + * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // Hungry could be any type of observable, but we'll use bus here. + * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. + * eat = (i:number) => () => { + * setTimeout(() => { + * console.log("done!"); + * chopsticks[i].push({}); + * chopsticks[(i + 1) % 3].push({}); + * }, 1e3); + * return `philosopher ${i} eating`; + * }, + * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. + * dining = Bacon.when( + * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), + * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), + * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) + * ).log("dining"); + * // Make all chopsticks initially available. + * chopsticks[0].push({}); + * chopsticks[1].push({}); + * chopsticks[2].push({}); + * // Make philosophers hungry in some way, in this case we just push to their bus. + * for (let i = 0; i < 3; i++) { + * hungry[0].push({}); + * hungry[1].push({}); + * hungry[2].push({}); + * } + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B):EventStream; + + /** + * @callback Bacon.when2~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.when2~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @method Bacon.when2 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when2~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.when2~f2} f2 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + * + * { + * // Join patterns as a "chemical machine". + * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: + * let oxygen = Bacon.interval(1e3, "O"), + * hydrogen = Bacon.interval(2e3, "H"), + * carbon = Bacon.interval(1.5e3, "C"), + * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, + * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; + * Bacon.when( + * [oxygen, hydrogen, hydrogen], makeWater, + * [oxygen, carbon], makeCarbonMonoxide + * ); + * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. + * } + * + * { + * // Join patterns and properties. + * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: + * // -- updating `quantity` sets `total` to `price * quantity`; + * // -- updating `total` sets `price` to `total / quantity`. + * let random = (x:number) => Math.round(x * Math.random()), + * id = (x:A):A => x; + * let $quantity = Bacon.interval(1e3, 10).map(random), + * $price = Bacon.interval(2e3, 100).map(random), + * $total = Bacon.interval(1.5e3, 1000).map(random); + * let quantity = $quantity.toProperty(1), + * price = Bacon.when( + * [$price], id, + * [$total, quantity], (x, y) => x / y + * ).toProperty(0), + * total = Bacon.when( + * [$total], id, + * [$price, quantity], (x, y) => x * y, + * [price, $quantity], (x, y) => x * y + * ).toProperty(0); + * } + * + * { + * // Join patterns and `Bacon.Bus`. + * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: + * // Availability of chopsticks are implemented using bus. + * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // Hungry could be any type of observable, but we'll use bus here. + * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. + * eat = (i:number) => () => { + * setTimeout(() => { + * console.log("done!"); + * chopsticks[i].push({}); + * chopsticks[(i + 1) % 3].push({}); + * }, 1e3); + * return `philosopher ${i} eating`; + * }, + * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. + * dining = Bacon.when( + * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), + * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), + * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) + * ).log("dining"); + * // Make all chopsticks initially available. + * chopsticks[0].push({}); + * chopsticks[1].push({}); + * chopsticks[2].push({}); + * // Make philosophers hungry in some way, in this case we just push to their bus. + * for (let i = 0; i < 3; i++) { + * hungry[0].push({}); + * hungry[1].push({}); + * hungry[2].push({}); + * } + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B):EventStream; + + /** + * @callback Bacon.when3~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.when3~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.when3~f3 + * @param {...A3} args + * @returns {B} + */ + /** + * @method Bacon.when3 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when3~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.when3~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.when3~f3} f3 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + * + * { + * // Join patterns as a "chemical machine". + * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: + * let oxygen = Bacon.interval(1e3, "O"), + * hydrogen = Bacon.interval(2e3, "H"), + * carbon = Bacon.interval(1.5e3, "C"), + * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, + * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; + * Bacon.when( + * [oxygen, hydrogen, hydrogen], makeWater, + * [oxygen, carbon], makeCarbonMonoxide + * ); + * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. + * } + * + * { + * // Join patterns and properties. + * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: + * // -- updating `quantity` sets `total` to `price * quantity`; + * // -- updating `total` sets `price` to `total / quantity`. + * let random = (x:number) => Math.round(x * Math.random()), + * id = (x:A):A => x; + * let $quantity = Bacon.interval(1e3, 10).map(random), + * $price = Bacon.interval(2e3, 100).map(random), + * $total = Bacon.interval(1.5e3, 1000).map(random); + * let quantity = $quantity.toProperty(1), + * price = Bacon.when( + * [$price], id, + * [$total, quantity], (x, y) => x / y + * ).toProperty(0), + * total = Bacon.when( + * [$total], id, + * [$price, quantity], (x, y) => x * y, + * [price, $quantity], (x, y) => x * y + * ).toProperty(0); + * } + * + * { + * // Join patterns and `Bacon.Bus`. + * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: + * // Availability of chopsticks are implemented using bus. + * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // Hungry could be any type of observable, but we'll use bus here. + * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. + * eat = (i:number) => () => { + * setTimeout(() => { + * console.log("done!"); + * chopsticks[i].push({}); + * chopsticks[(i + 1) % 3].push({}); + * }, 1e3); + * return `philosopher ${i} eating`; + * }, + * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. + * dining = Bacon.when( + * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), + * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), + * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) + * ).log("dining"); + * // Make all chopsticks initially available. + * chopsticks[0].push({}); + * chopsticks[1].push({}); + * chopsticks[2].push({}); + * // Make philosophers hungry in some way, in this case we just push to their bus. + * for (let i = 0; i < 3; i++) { + * hungry[0].push({}); + * hungry[1].push({}); + * hungry[2].push({}); + * } + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B):EventStream; + + /** + * @callback Bacon.when4~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.when4~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.when4~f3 + * @param {...A3} args + * @returns {B} + */ + /** + * @callback Bacon.when4~f4 + * @param {...A4} args + * @returns {B} + */ + /** + * @method Bacon.when4 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when4~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.when4~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.when4~f3} f3 + * @param {Observable[]} pattern4 + * @param {Bacon.when4~f4} f4 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + * + * { + * // Join patterns as a "chemical machine". + * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: + * let oxygen = Bacon.interval(1e3, "O"), + * hydrogen = Bacon.interval(2e3, "H"), + * carbon = Bacon.interval(1.5e3, "C"), + * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, + * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; + * Bacon.when( + * [oxygen, hydrogen, hydrogen], makeWater, + * [oxygen, carbon], makeCarbonMonoxide + * ); + * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. + * } + * + * { + * // Join patterns and properties. + * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: + * // -- updating `quantity` sets `total` to `price * quantity`; + * // -- updating `total` sets `price` to `total / quantity`. + * let random = (x:number) => Math.round(x * Math.random()), + * id = (x:A):A => x; + * let $quantity = Bacon.interval(1e3, 10).map(random), + * $price = Bacon.interval(2e3, 100).map(random), + * $total = Bacon.interval(1.5e3, 1000).map(random); + * let quantity = $quantity.toProperty(1), + * price = Bacon.when( + * [$price], id, + * [$total, quantity], (x, y) => x / y + * ).toProperty(0), + * total = Bacon.when( + * [$total], id, + * [$price, quantity], (x, y) => x * y, + * [price, $quantity], (x, y) => x * y + * ).toProperty(0); + * } + * + * { + * // Join patterns and `Bacon.Bus`. + * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: + * // Availability of chopsticks are implemented using bus. + * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // Hungry could be any type of observable, but we'll use bus here. + * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. + * eat = (i:number) => () => { + * setTimeout(() => { + * console.log("done!"); + * chopsticks[i].push({}); + * chopsticks[(i + 1) % 3].push({}); + * }, 1e3); + * return `philosopher ${i} eating`; + * }, + * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. + * dining = Bacon.when( + * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), + * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), + * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) + * ).log("dining"); + * // Make all chopsticks initially available. + * chopsticks[0].push({}); + * chopsticks[1].push({}); + * chopsticks[2].push({}); + * // Make philosophers hungry in some way, in this case we just push to their bus. + * for (let i = 0; i < 3; i++) { + * hungry[0].push({}); + * hungry[1].push({}); + * hungry[2].push({}); + * } + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B, pattern4:Observable[], f4:(...args:A4[]) => B):EventStream; + + /** + * @callback Bacon.when5~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.when5~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.when5~f3 + * @param {...A3} args + * @returns {B} + */ + /** + * @callback Bacon.when5~f4 + * @param {...A4} args + * @returns {B} + */ + /** + * @callback Bacon.when5~f5 + * @param {...A5} args + * @returns {B} + */ + /** + * @method Bacon.when5 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when5~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.when5~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.when5~f3} f3 + * @param {Observable[]} pattern4 + * @param {Bacon.when5~f4} f4 + * @param {Observable[]} pattern5 + * @param {Bacon.when5~f5} f5 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + * + * { + * // Join patterns as a "chemical machine". + * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: + * let oxygen = Bacon.interval(1e3, "O"), + * hydrogen = Bacon.interval(2e3, "H"), + * carbon = Bacon.interval(1.5e3, "C"), + * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, + * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; + * Bacon.when( + * [oxygen, hydrogen, hydrogen], makeWater, + * [oxygen, carbon], makeCarbonMonoxide + * ); + * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. + * } + * + * { + * // Join patterns and properties. + * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: + * // -- updating `quantity` sets `total` to `price * quantity`; + * // -- updating `total` sets `price` to `total / quantity`. + * let random = (x:number) => Math.round(x * Math.random()), + * id = (x:A):A => x; + * let $quantity = Bacon.interval(1e3, 10).map(random), + * $price = Bacon.interval(2e3, 100).map(random), + * $total = Bacon.interval(1.5e3, 1000).map(random); + * let quantity = $quantity.toProperty(1), + * price = Bacon.when( + * [$price], id, + * [$total, quantity], (x, y) => x / y + * ).toProperty(0), + * total = Bacon.when( + * [$total], id, + * [$price, quantity], (x, y) => x * y, + * [price, $quantity], (x, y) => x * y + * ).toProperty(0); + * } + * + * { + * // Join patterns and `Bacon.Bus`. + * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: + * // Availability of chopsticks are implemented using bus. + * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // Hungry could be any type of observable, but we'll use bus here. + * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. + * eat = (i:number) => () => { + * setTimeout(() => { + * console.log("done!"); + * chopsticks[i].push({}); + * chopsticks[(i + 1) % 3].push({}); + * }, 1e3); + * return `philosopher ${i} eating`; + * }, + * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. + * dining = Bacon.when( + * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), + * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), + * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) + * ).log("dining"); + * // Make all chopsticks initially available. + * chopsticks[0].push({}); + * chopsticks[1].push({}); + * chopsticks[2].push({}); + * // Make philosophers hungry in some way, in this case we just push to their bus. + * for (let i = 0; i < 3; i++) { + * hungry[0].push({}); + * hungry[1].push({}); + * hungry[2].push({}); + * } + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B, pattern4:Observable[], f4:(...args:A4[]) => B, pattern5:Observable[], f5:(...args:A5[]) => B):EventStream; + + /** + * @callback Bacon.update1~f1 + * @param {B} initial + * @param {...A1} args + * @returns {B} + */ + /** + * @method Bacon.update1 + * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update1~f1} f1 + * @returns {Property} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B):Property; + + /** + * @callback Bacon.update2~f1 + * @param {B} initial + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.update2~f2 + * @param {B} initial + * @param {...A2} args + * @returns {B} + */ + /** + * @method Bacon.update2 + * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update2~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.update2~f2} f2 + * @returns {Property} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => B):Property; + + /** + * @callback Bacon.update3~f1 + * @param {B} initial + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.update3~f2 + * @param {B} initial + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.update3~f3 + * @param {B} initial + * @param {...A3} args + * @returns {B} + */ + /** + * @method Bacon.update3 + * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update3~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.update3~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.update3~f3} f3 + * @returns {Property} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => B, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => B):Property; + + /** + * @callback Bacon.update4~f1 + * @param {B} initial + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.update4~f2 + * @param {B} initial + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.update4~f3 + * @param {B} initial + * @param {...A3} args + * @returns {B} + */ + /** + * @callback Bacon.update4~f4 + * @param {B} initial + * @param {...A4} args + * @returns {B} + */ + /** + * @method Bacon.update4 + * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update4~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.update4~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.update4~f3} f3 + * @param {Observable[]} pattern4 + * @param {Bacon.update4~f4} f4 + * @returns {Property} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => B, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => B, pattern4:Observable[], f4:(initial:B, ...args:A4[]) => B):Property; + + /** + * @callback Bacon.update5~f1 + * @param {B} initial + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.update5~f2 + * @param {B} initial + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.update5~f3 + * @param {B} initial + * @param {...A3} args + * @returns {B} + */ + /** + * @callback Bacon.update5~f4 + * @param {B} initial + * @param {...A4} args + * @returns {B} + */ + /** + * @callback Bacon.update5~f5 + * @param {B} initial + * @param {...A5} args + * @returns {B} + */ + /** + * @method Bacon.update5 + * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update5~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.update5~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.update5~f3} f3 + * @param {Observable[]} pattern4 + * @param {Bacon.update5~f4} f4 + * @param {Observable[]} pattern5 + * @param {Bacon.update5~f5} f5 + * @returns {Property} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => B, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => B, pattern4:Observable[], f4:(initial:B, ...args:A4[]) => B, pattern5:Observable[], f5:(initial:B, ...args:A5[]) => B):Property; +} + +declare module "baconjs" { + export = Bacon; +} diff --git a/baconjs/tsconfig.json b/baconjs/tsconfig.json new file mode 100644 index 0000000000..3cd0556304 --- /dev/null +++ b/baconjs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "baconjs-tests.ts" + ] +} \ No newline at end of file diff --git a/barcode/barcode-tests.ts b/barcode/barcode-tests.ts index bb7b67187e..2748143a3b 100644 --- a/barcode/barcode-tests.ts +++ b/barcode/barcode-tests.ts @@ -1,4 +1,4 @@ -/// + import barcode = require('barcode'); import path = require('path'); diff --git a/barcode/barcode.d.ts b/barcode/barcode.d.ts deleted file mode 100644 index c2ad43eb76..0000000000 --- a/barcode/barcode.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Type definitions for barcode -// Project: https://github.com/samt/barcode -// Definitions by: Pascal Vomhoff -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "barcode" { - - interface BarcodeOptions { - data:string|number; - width:number; - height:number; - } - - interface BarcodeResult { - getStream(callback:(err:NodeJS.ErrnoException, stream:NodeJS.ReadableStream) => void):void; - saveImage(outputfilePath:string, callback:(err:NodeJS.ErrnoException) => void):void; - getBase64(callback:(err:NodeJS.ErrnoException, base64String:string) => void):void; - } - - function barcode(type:string, options:BarcodeOptions):BarcodeResult; - - export = barcode; -} diff --git a/barcode/index.d.ts b/barcode/index.d.ts new file mode 100644 index 0000000000..122eb98e5a --- /dev/null +++ b/barcode/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for barcode +// Project: https://github.com/samt/barcode +// Definitions by: Pascal Vomhoff +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + + +interface BarcodeOptions { + data: string | number; + width: number; + height: number; +} + +interface BarcodeResult { + getStream(callback: (err: NodeJS.ErrnoException, stream: NodeJS.ReadableStream) => void): void; + saveImage(outputfilePath: string, callback: (err: NodeJS.ErrnoException) => void): void; + getBase64(callback: (err: NodeJS.ErrnoException, base64String: string) => void): void; +} + +declare function barcode(type: string, options: BarcodeOptions): BarcodeResult; + +export = barcode; diff --git a/barcode/tsconfig.json b/barcode/tsconfig.json new file mode 100644 index 0000000000..f66f5c6204 --- /dev/null +++ b/barcode/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "barcode-tests.ts" + ] +} \ No newline at end of file diff --git a/bardjs/bardjs-tests.ts b/bardjs/bardjs-tests.ts index b29900ad7d..4dad9b9ad9 100644 --- a/bardjs/bardjs-tests.ts +++ b/bardjs/bardjs-tests.ts @@ -1,8 +1,6 @@ -/// -/// -/// -/// -/// +/// +/// +/// namespace bardTests { var expect = chai.expect, diff --git a/bardjs/bardjs.d.ts b/bardjs/bardjs.d.ts deleted file mode 100644 index 4395ef6ddb..0000000000 --- a/bardjs/bardjs.d.ts +++ /dev/null @@ -1,174 +0,0 @@ -// Type definitions for bardjs 0.1.4 -// Project: https://github.com/wardbell/bardjs -// Definitions by: Andrew Archibald -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// -/// - -/** - * Module for bardjs functions - */ -declare namespace bard { - /** - * Replaces the ngMock'ed $httpBackend with the real one from ng thus - * restoring the ability to issue AJAX calls to the backend with $http. - * - * Note that $q remains ngMocked so you must flush $http calls ($rootScope.$digest). - * Use $rootScope.$apply() for this purpose. - * - * Could restore $q with $qReal in which case don't need to flush. - */ - function $httpBackend($provide: angular.auto.IProvideService): any; - - /** - * Replaces the ngMock'ed $q with the real one from ng thus - * obviating the need to flush $http and $q queues - * at the expense of ability to control $q timing. - */ - function $q($provide: angular.auto.IProvideService): any; - - /** - * Add names of globals to list of OK globals for this mocha spec - * NB: Call this method ONLY if you're using mocha! - * NB: Turn off browser-sync else mocha detects the browser-sync globals - * like ` ___browserSync___` - */ - function addGlobals(...globals: any[]): void; - - /** - * Prepare ngMocked application feature module - * along with faked toastr, routehelper, - * and faked router services. - * Especially useful for controller testing - * Use it as you would the ngMocks#module method - * - * DO NOT USE IF YOU NEED THE REAL ROUTER SERVICES! - * Fall back to `angular.mock.module(...)` or just `module(...)` - */ - function appModule(...fns: (string | Function | Object)[]): () => void; - - /** - * Assert a failure in mocha, without condition - */ - function assertFail(message: string): Chai.AssertionError; - - /** - * Prepare ngMocked module definition that makes real $http and $q calls - * Also adds fakeLogger to the end of the definition - * Use it as you would the ngMocks#module method - */ - function asyncModule(...fns: (string | Function | Object)[]): () => void; - - /** - * Get or set bard debugging flag - */ - function debugging(newFlag?: any): boolean; - - /** - * Registers a fake logger service that you can spy on - */ - function fakeLogger($provide: angular.auto.IProvideService): void; - - /** - * Registers a fake route helper provider service that you can spy on - */ - function fakeRouteHelperProvider($provide: angular.auto.IProvideService): void; - - /** - * Stub out the $routeProvider so we avoid - * all routing calls, including the default route - * which runs on every test otherwise. - * Make sure this goes before the inject in the spec. - */ - function fakeRouteProvider($provide: angular.auto.IProvideService): void; - - /** - * Stub out the $stateProvider so we avoid - * all routing calls, including the default state - * which runs on every test otherwise. - * Make sure this goes before the inject in the spec. - */ - function fakeStateProvider($provide: angular.auto.IProvideService): void; - - /** - * Registers a fake toastr service that you can spy on - */ - function fakeToastr($provide: angular.auto.IProvideService): void; - - /** - * Inject selected services into the windows object during test - * then remove them when test ends with an `afterEach`. - * - * spares us the repetition of creating common service vars and injecting them - * - * Option: the first argument may be the mocha spec context object (`this`) - * It MUST be `this` if you what to check for mocha global leaks. - * Do NOT supply `this` as the first arg if you're not running mocha specs. - * - * remaining inject arguments may take one of 3 forms : - * - * function - This fn will be passed to ngMocks.inject. - * Annotations extracted after inject does its thing. - * [strings] - same string array you'd use to set fn.$inject - * (...string) - string arguments turned into a string array - */ - function inject(context?: Function, ...args: string[]): void; - - /** - * Write to console if bard debugging flag is on - */ - function log(message: any): void; - - /** - * Listen to mocha test runner events - * Usage in browser: - * var runner = mocha.run(); - * bard.mochaRunnerListener(runner); - */ - function mochaRunnerListener(runner: Mocha.IRunner): void; - - /** - * Mocks out a service with sinon stubbed functions - * that return the values specified in the config - * - * If the config value is `undefined`, - * stub the service method with a dummy that doesn't return a value - * - * If the config value is a function, set service property with it - * - * If a service member is a property, not a function, - * set it with the config value - * If a service member name is not a key in config, - * follow the same logic as above to set its members - * using the config._default value (which is `undefined` if omitted) - * - * If there is a config entry that is NOT a member of the service - * add mocked function to the service using the config value - */ - function mockService(service: any, config: any): any; - - /** - * Replaces the accented characters of many European languages w/ unaccented chars - * Use it in JavaScript string sorts where such characters may be encountered - * Matches the default string comparers of most databases. - * Ex: replaceAccentChars(a.Name) < replaceAccentChars(b.Name) - * instead of: a.Name < b.Name - */ - function replaceAccentChars(text: string): string; - - /** - * Assert that there are no outstanding HTTP requests after test is complete - * For use with ngMocks; doesn't work for async server integration tests - */ - function verifyNoOutstandingHttpRequests(): void; - - /** - * Returns a function that execute a callback function - * (typically a fn making asserts) within a try/catch - * The try/catch then calls the ambient "done" function - * in the appropriate way for both success and failure - */ - function wrapWithDone(callback: Function, done: Function): Function; -} diff --git a/bardjs/index.d.ts b/bardjs/index.d.ts new file mode 100644 index 0000000000..c2e9a76a06 --- /dev/null +++ b/bardjs/index.d.ts @@ -0,0 +1,174 @@ +// Type definitions for bardjs 0.1.4 +// Project: https://github.com/wardbell/bardjs +// Definitions by: Andrew Archibald +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + +/** + * Module for bardjs functions + */ +declare namespace bard { + /** + * Replaces the ngMock'ed $httpBackend with the real one from ng thus + * restoring the ability to issue AJAX calls to the backend with $http. + * + * Note that $q remains ngMocked so you must flush $http calls ($rootScope.$digest). + * Use $rootScope.$apply() for this purpose. + * + * Could restore $q with $qReal in which case don't need to flush. + */ + function $httpBackend($provide: angular.auto.IProvideService): any; + + /** + * Replaces the ngMock'ed $q with the real one from ng thus + * obviating the need to flush $http and $q queues + * at the expense of ability to control $q timing. + */ + function $q($provide: angular.auto.IProvideService): any; + + /** + * Add names of globals to list of OK globals for this mocha spec + * NB: Call this method ONLY if you're using mocha! + * NB: Turn off browser-sync else mocha detects the browser-sync globals + * like ` ___browserSync___` + */ + function addGlobals(...globals: any[]): void; + + /** + * Prepare ngMocked application feature module + * along with faked toastr, routehelper, + * and faked router services. + * Especially useful for controller testing + * Use it as you would the ngMocks#module method + * + * DO NOT USE IF YOU NEED THE REAL ROUTER SERVICES! + * Fall back to `angular.mock.module(...)` or just `module(...)` + */ + function appModule(...fns: (string | Function | Object)[]): () => void; + + /** + * Assert a failure in mocha, without condition + */ + function assertFail(message: string): Chai.AssertionError; + + /** + * Prepare ngMocked module definition that makes real $http and $q calls + * Also adds fakeLogger to the end of the definition + * Use it as you would the ngMocks#module method + */ + function asyncModule(...fns: (string | Function | Object)[]): () => void; + + /** + * Get or set bard debugging flag + */ + function debugging(newFlag?: any): boolean; + + /** + * Registers a fake logger service that you can spy on + */ + function fakeLogger($provide: angular.auto.IProvideService): void; + + /** + * Registers a fake route helper provider service that you can spy on + */ + function fakeRouteHelperProvider($provide: angular.auto.IProvideService): void; + + /** + * Stub out the $routeProvider so we avoid + * all routing calls, including the default route + * which runs on every test otherwise. + * Make sure this goes before the inject in the spec. + */ + function fakeRouteProvider($provide: angular.auto.IProvideService): void; + + /** + * Stub out the $stateProvider so we avoid + * all routing calls, including the default state + * which runs on every test otherwise. + * Make sure this goes before the inject in the spec. + */ + function fakeStateProvider($provide: angular.auto.IProvideService): void; + + /** + * Registers a fake toastr service that you can spy on + */ + function fakeToastr($provide: angular.auto.IProvideService): void; + + /** + * Inject selected services into the windows object during test + * then remove them when test ends with an `afterEach`. + * + * spares us the repetition of creating common service vars and injecting them + * + * Option: the first argument may be the mocha spec context object (`this`) + * It MUST be `this` if you what to check for mocha global leaks. + * Do NOT supply `this` as the first arg if you're not running mocha specs. + * + * remaining inject arguments may take one of 3 forms : + * + * function - This fn will be passed to ngMocks.inject. + * Annotations extracted after inject does its thing. + * [strings] - same string array you'd use to set fn.$inject + * (...string) - string arguments turned into a string array + */ + function inject(context?: Function, ...args: string[]): void; + + /** + * Write to console if bard debugging flag is on + */ + function log(message: any): void; + + /** + * Listen to mocha test runner events + * Usage in browser: + * var runner = mocha.run(); + * bard.mochaRunnerListener(runner); + */ + function mochaRunnerListener(runner: Mocha.IRunner): void; + + /** + * Mocks out a service with sinon stubbed functions + * that return the values specified in the config + * + * If the config value is `undefined`, + * stub the service method with a dummy that doesn't return a value + * + * If the config value is a function, set service property with it + * + * If a service member is a property, not a function, + * set it with the config value + * If a service member name is not a key in config, + * follow the same logic as above to set its members + * using the config._default value (which is `undefined` if omitted) + * + * If there is a config entry that is NOT a member of the service + * add mocked function to the service using the config value + */ + function mockService(service: any, config: any): any; + + /** + * Replaces the accented characters of many European languages w/ unaccented chars + * Use it in JavaScript string sorts where such characters may be encountered + * Matches the default string comparers of most databases. + * Ex: replaceAccentChars(a.Name) < replaceAccentChars(b.Name) + * instead of: a.Name < b.Name + */ + function replaceAccentChars(text: string): string; + + /** + * Assert that there are no outstanding HTTP requests after test is complete + * For use with ngMocks; doesn't work for async server integration tests + */ + function verifyNoOutstandingHttpRequests(): void; + + /** + * Returns a function that execute a callback function + * (typically a fn making asserts) within a try/catch + * The try/catch then calls the ambient "done" function + * in the appropriate way for both success and failure + */ + function wrapWithDone(callback: Function, done: Function): Function; +} diff --git a/bardjs/tsconfig.json b/bardjs/tsconfig.json new file mode 100644 index 0000000000..e3d00cc1ed --- /dev/null +++ b/bardjs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bardjs-tests.ts" + ] +} \ No newline at end of file diff --git a/base-x/base-x-tests.ts b/base-x/base-x-tests.ts index 3e082c45ba..44e302d2d5 100644 --- a/base-x/base-x-tests.ts +++ b/base-x/base-x-tests.ts @@ -1,8 +1,7 @@ -/// import * as basex from 'base-x'; -let bs16: BaseX.BaseConverter = basex('0123456789ABCDEF'); +let bs16 = basex('0123456789ABCDEF'); { let encoded: string; diff --git a/base-x/base-x.d.ts b/base-x/base-x.d.ts deleted file mode 100644 index b6b764befe..0000000000 --- a/base-x/base-x.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Type definitions for base-x v1.0.1 -// Project: https://github.com/cryptocoinjs/base-x -// Definitions by: Ilya Mochalov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace BaseX { - interface EncodeBuffer { - [index: number]: number; - length: number; - } - - interface BaseConverter { - encode: (buffer: EncodeBuffer) => string; - decode: (string: string) => number[]; - } - - interface Base { - (ALPHABET: string): BaseX.BaseConverter - } -} - -declare module "base-x" { - namespace base {} - - let base: BaseX.Base; - - export = base; -} diff --git a/base-x/index.d.ts b/base-x/index.d.ts new file mode 100644 index 0000000000..19af3aa993 --- /dev/null +++ b/base-x/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for base-x v1.0.1 +// Project: https://github.com/cryptocoinjs/base-x +// Definitions by: Ilya Mochalov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var base: BaseX.Base; +export = base; + +declare namespace BaseX { + interface EncodeBuffer { + [index: number]: number; + length: number; + } + + interface BaseConverter { + encode: (buffer: EncodeBuffer) => string; + decode: (string: string) => number[]; + } + + interface Base { + (ALPHABET: string): BaseX.BaseConverter + } +} diff --git a/base-x/tsconfig.json b/base-x/tsconfig.json new file mode 100644 index 0000000000..e18efdf2c7 --- /dev/null +++ b/base-x/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "base-x-tests.ts" + ] +} \ No newline at end of file diff --git a/basic-auth/basic-auth-tests.ts b/basic-auth/basic-auth-tests.ts index 54be7af1f4..1fab9c10e2 100644 --- a/basic-auth/basic-auth-tests.ts +++ b/basic-auth/basic-auth-tests.ts @@ -1,4 +1,3 @@ -/// import auth = require('basic-auth'); diff --git a/basic-auth/basic-auth.d.ts b/basic-auth/basic-auth.d.ts deleted file mode 100644 index 911299a6c6..0000000000 --- a/basic-auth/basic-auth.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Type definitions for basic-auth -// Project: https://github.com/jshttp/basic-auth -// Definitions by: Clément Bourgeois -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "basic-auth" { - function auth(req: Express.Request): auth.BasicAuthResult; - - namespace auth { - interface BasicAuthResult { - name: string; - pass: string; - } - } - - export = auth; -} diff --git a/basic-auth/index.d.ts b/basic-auth/index.d.ts new file mode 100644 index 0000000000..3dc19b3046 --- /dev/null +++ b/basic-auth/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for basic-auth +// Project: https://github.com/jshttp/basic-auth +// Definitions by: Clément Bourgeois +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Express from 'express'; + +declare function auth(req: Express.Request): auth.BasicAuthResult; + +declare namespace auth { + interface BasicAuthResult { + name: string; + pass: string; + } +} + +export = auth; diff --git a/basic-auth/tsconfig.json b/basic-auth/tsconfig.json new file mode 100644 index 0000000000..06eb0913cf --- /dev/null +++ b/basic-auth/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "basic-auth-tests.ts" + ] +} \ No newline at end of file diff --git a/batch-stream/batch-stream-tests.ts b/batch-stream/batch-stream-tests.ts index 2271e67e57..d3195466e8 100644 --- a/batch-stream/batch-stream-tests.ts +++ b/batch-stream/batch-stream-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// import fs = require('fs'); import BatchStream = require('batch-stream'); diff --git a/batch-stream/batch-stream.d.ts b/batch-stream/batch-stream.d.ts deleted file mode 100644 index 5b27050104..0000000000 --- a/batch-stream/batch-stream.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Type definitions for batch-stream 0.1.2 -// Project: https://github.com/segmentio/batch-stream -// Definitions by: Nicholas Penree -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "batch-stream" { - import stream = require('stream'); - - interface Options { - size?: number; - highWaterMark?: number; - } - - class BatchStream extends stream.Transform { - size: number; - batch: any[]; - - constructor(options: Options); - } - - export = BatchStream; -} \ No newline at end of file diff --git a/batch-stream/index.d.ts b/batch-stream/index.d.ts new file mode 100644 index 0000000000..26c433a04b --- /dev/null +++ b/batch-stream/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for batch-stream 0.1.2 +// Project: https://github.com/segmentio/batch-stream +// Definitions by: Nicholas Penree +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import stream = require('stream'); + +interface Options { + size?: number; + highWaterMark?: number; +} + +declare class BatchStream extends stream.Transform { + size: number; + batch: any[]; + + constructor(options: Options); +} + +export = BatchStream; diff --git a/batch-stream/tsconfig.json b/batch-stream/tsconfig.json new file mode 100644 index 0000000000..377af76001 --- /dev/null +++ b/batch-stream/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "batch-stream-tests.ts" + ] +} \ No newline at end of file diff --git a/bcrypt-nodejs/bcrypt-nodejs-tests.ts b/bcrypt-nodejs/bcrypt-nodejs-tests.ts index 2a151c1c7e..a1a2944d52 100644 --- a/bcrypt-nodejs/bcrypt-nodejs-tests.ts +++ b/bcrypt-nodejs/bcrypt-nodejs-tests.ts @@ -1,4 +1,3 @@ -/// import bCrypt = require("bcrypt-nodejs"); diff --git a/bcrypt-nodejs/bcrypt-nodejs.d.ts b/bcrypt-nodejs/bcrypt-nodejs.d.ts deleted file mode 100644 index 6df662346a..0000000000 --- a/bcrypt-nodejs/bcrypt-nodejs.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -// Type definitions for bcrypt-nodejs -// Project: https://github.com/shaneGirish/bcrypt-nodejs -// Definitions by: David Broder-Rodgers -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "bcrypt-nodejs" { - /** - * Generate a salt synchronously - * @param rounds Number of rounds to process the data for (default - 10) - * @return Generated salt - */ - export function genSaltSync(rounds?: number): string; - - /** - * Generate a salt asynchronously - * @param rounds Number of rounds to process the data for (default - 10) - * @param callback Callback with error and resulting salt, to be fired once the salt has been generated - */ - export function genSalt(rounds: number, callback: (error: Error, result: string) => void): void; - - /** - * Generate a hash synchronously - * @param data Data to be encrypted - * @param salt Salt to be used in encryption (default - new salt generated with 10 rounds) - * @return Generated hash - */ - export function hashSync(data: string, salt?: string): string; - - /** - * Generate a hash asynchronously - * @param data Data to be encrypted - * @param salt Salt to be used in encryption - * @param callback Callback with error and hashed result, to be fired once the data has been encrypted - */ - export function hash(data: string, salt: string, callback: (error: Error, result: string) => void): void; - - /** - * Generate a hash asynchronously - * @param data Data to be encrypted - * @param salt Salt to be used in encryption - * @param progressCallback Callback to be fired multiple times during the hash calculation to signify progress - * @param callback Callback with error and hashed result, to be fired once the data has been encrypted - */ - export function hash(data: string, salt: string, progressCallback: () => void, callback: (error: Error, result: string) => void): void; - - /** - * Compares data with a hash synchronously - * @param data Data to be compared - * @param hash Hash to be compared to - * @return true if matching, false otherwise - */ - export function compareSync(data: string, hash: string): boolean; - - /** - * Compares data with a hash asynchronously - * @param data Data to be compared - * @param hash Hash to be compared to - * @param callback Callback with error and match result, to be fired once the data has been compared - */ - export function compare(data: string, hash: string, callback: (error: Error, result: boolean) => void): void; - - /** - * Get number of rounds used for hash - * @param hash Hash from which the number of rounds used should be extracted - * @return number of rounds used to encrypt a given hash - */ - export function getRounds(hash: string): number; -} diff --git a/bcrypt-nodejs/index.d.ts b/bcrypt-nodejs/index.d.ts new file mode 100644 index 0000000000..d6baffaffa --- /dev/null +++ b/bcrypt-nodejs/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for bcrypt-nodejs +// Project: https://github.com/shaneGirish/bcrypt-nodejs +// Definitions by: David Broder-Rodgers +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/** + * Generate a salt synchronously + * @param rounds Number of rounds to process the data for (default - 10) + * @return Generated salt + */ +export declare function genSaltSync(rounds?: number): string; + +/** + * Generate a salt asynchronously + * @param rounds Number of rounds to process the data for (default - 10) + * @param callback Callback with error and resulting salt, to be fired once the salt has been generated + */ +export declare function genSalt(rounds: number, callback: (error: Error, result: string) => void): void; + +/** + * Generate a hash synchronously + * @param data Data to be encrypted + * @param salt Salt to be used in encryption (default - new salt generated with 10 rounds) + * @return Generated hash + */ +export declare function hashSync(data: string, salt?: string): string; + +/** + * Generate a hash asynchronously + * @param data Data to be encrypted + * @param salt Salt to be used in encryption + * @param callback Callback with error and hashed result, to be fired once the data has been encrypted + */ +export declare function hash(data: string, salt: string, callback: (error: Error, result: string) => void): void; + +/** + * Generate a hash asynchronously + * @param data Data to be encrypted + * @param salt Salt to be used in encryption + * @param progressCallback Callback to be fired multiple times during the hash calculation to signify progress + * @param callback Callback with error and hashed result, to be fired once the data has been encrypted + */ +export declare function hash(data: string, salt: string, progressCallback: () => void, callback: (error: Error, result: string) => void): void; + +/** + * Compares data with a hash synchronously + * @param data Data to be compared + * @param hash Hash to be compared to + * @return true if matching, false otherwise + */ +export declare function compareSync(data: string, hash: string): boolean; + +/** + * Compares data with a hash asynchronously + * @param data Data to be compared + * @param hash Hash to be compared to + * @param callback Callback with error and match result, to be fired once the data has been compared + */ +export declare function compare(data: string, hash: string, callback: (error: Error, result: boolean) => void): void; + +/** + * Get number of rounds used for hash + * @param hash Hash from which the number of rounds used should be extracted + * @return number of rounds used to encrypt a given hash + */ +export declare function getRounds(hash: string): number; diff --git a/bcrypt-nodejs/tsconfig.json b/bcrypt-nodejs/tsconfig.json new file mode 100644 index 0000000000..2db80659fc --- /dev/null +++ b/bcrypt-nodejs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bcrypt-nodejs-tests.ts" + ] +} \ No newline at end of file diff --git a/bcrypt/bcrypt-tests.ts b/bcrypt/bcrypt-tests.ts index b88d4fb7aa..ec4701dab2 100644 --- a/bcrypt/bcrypt-tests.ts +++ b/bcrypt/bcrypt-tests.ts @@ -1,4 +1,3 @@ -/// import bcrypt = require("bcrypt"); diff --git a/bcrypt/bcrypt.d.ts b/bcrypt/bcrypt.d.ts deleted file mode 100644 index 38d9604b44..0000000000 --- a/bcrypt/bcrypt.d.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Type definitions for bcrypt -// Project: https://www.npmjs.org/package/bcrypt -// Definitions by: Peter Harris -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "bcrypt" { - /** - * @param rounds The cost of processing the data. Default 10. - */ - export function genSaltSync(rounds?: number): string; - - /** - * @param rounds The cost of processing the data. Default 10. - * @param callback A callback to be fire once the sald has been generated. Uses eio making it asynchronous. - */ - export function genSalt(rounds: number, callback: (err: Error, salt: string) => void): void; - /** - * @param callback A callback to be fire once the sald has been generated. Uses eio making it asynchronous. - */ - export function genSalt(callback: (err: Error, salt: string) => void): void; - - /** - * @param data The data to be encrypted. - * @param salt The salt to be used in encryption. - */ - export function hashSync(data: any, salt: string): string; - /** - * @param data The data to be encrypted. - * @param rounds A salt will be generated using the rounds specified. - */ - export function hashSync(data: any, rounds: number): string; - - /** - * @param data The data to be encrypted. - * @param salt The salt to be used in encryption. - * @param callback A callback to be fired once the data has been encrypted. Uses eio making it asynchronous. - */ - export function hash(data: any, salt: string, callback: (err: Error, encrypted: string) => void): void; - /** - * @param data The data to be encrypted. - * @param rounds A salt will be generated using the rounds specified. - * @param callback A callback to be fired once the data has been encrypted. Uses eio making it asynchronous. - */ - export function hash(data: any, rounds: number, callback: (err: Error, encrypted: string) => void): void; - - /** - * @param data The data to be encrypted. - * @param encrypted The data to be compared against. - */ - export function compareSync(data: any, encrypted: string): boolean; - - /** - * @param data The data to be encrypted. - * @param encrypted The data to be compared against. - * @param callback A callback to be fire once the data has been compared. Uses eio making it asynchronous. - */ - export function compare(data: any, encrypted: string, callback: (err: Error, same: boolean) => void): void; - - /** - * Return the number of rounds used to encrypt a given hash - * - * @param encrypted Hash from which the number of rounds used should be extracted. - */ - export function getRounds(encrypted: string): number; -} diff --git a/bcrypt/index.d.ts b/bcrypt/index.d.ts new file mode 100644 index 0000000000..d9eafce4ef --- /dev/null +++ b/bcrypt/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for bcrypt +// Project: https://www.npmjs.org/package/bcrypt +// Definitions by: Peter Harris +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/** + * @param rounds The cost of processing the data. Default 10. + */ +export declare function genSaltSync(rounds?: number): string; + +/** + * @param rounds The cost of processing the data. Default 10. + * @param callback A callback to be fire once the sald has been generated. Uses eio making it asynchronous. + */ +export declare function genSalt(rounds: number, callback: (err: Error, salt: string) => void): void; +/** + * @param callback A callback to be fire once the sald has been generated. Uses eio making it asynchronous. + */ +export declare function genSalt(callback: (err: Error, salt: string) => void): void; + +/** + * @param data The data to be encrypted. + * @param salt The salt to be used in encryption. + */ +export declare function hashSync(data: any, salt: string): string; +/** + * @param data The data to be encrypted. + * @param rounds A salt will be generated using the rounds specified. + */ +export declare function hashSync(data: any, rounds: number): string; + +/** + * @param data The data to be encrypted. + * @param salt The salt to be used in encryption. + * @param callback A callback to be fired once the data has been encrypted. Uses eio making it asynchronous. + */ +export declare function hash(data: any, salt: string, callback: (err: Error, encrypted: string) => void): void; +/** + * @param data The data to be encrypted. + * @param rounds A salt will be generated using the rounds specified. + * @param callback A callback to be fired once the data has been encrypted. Uses eio making it asynchronous. + */ +export declare function hash(data: any, rounds: number, callback: (err: Error, encrypted: string) => void): void; + +/** + * @param data The data to be encrypted. + * @param encrypted The data to be compared against. + */ +export declare function compareSync(data: any, encrypted: string): boolean; + +/** + * @param data The data to be encrypted. + * @param encrypted The data to be compared against. + * @param callback A callback to be fire once the data has been compared. Uses eio making it asynchronous. + */ +export declare function compare(data: any, encrypted: string, callback: (err: Error, same: boolean) => void): void; + +/** + * Return the number of rounds used to encrypt a given hash + * + * @param encrypted Hash from which the number of rounds used should be extracted. + */ +export declare function getRounds(encrypted: string): number; diff --git a/bcrypt/tsconfig.json b/bcrypt/tsconfig.json new file mode 100644 index 0000000000..70a619adc7 --- /dev/null +++ b/bcrypt/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bcrypt-tests.ts" + ] +} \ No newline at end of file diff --git a/bcryptjs/bcryptjs-tests.ts b/bcryptjs/bcryptjs-tests.ts index acfc48e439..83b67c17cc 100644 --- a/bcryptjs/bcryptjs-tests.ts +++ b/bcryptjs/bcryptjs-tests.ts @@ -1,5 +1,3 @@ -/// - import bcryptjs = require("bcryptjs"); let str: string; diff --git a/bcryptjs/bcryptjs.d.ts b/bcryptjs/bcryptjs.d.ts deleted file mode 100644 index 3d3128d022..0000000000 --- a/bcryptjs/bcryptjs.d.ts +++ /dev/null @@ -1,82 +0,0 @@ -// Type definitions for bcryptjs v2.3.0 -// Project: https://github.com/dcodeIO/bcrypt.js -// Definitions by: Joshua Filby -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "bcryptjs" { - - /** - * Sets the pseudo random number generator to use as a fallback if neither node's crypto module nor the Web Crypto API is available. - * Please note: It is highly important that the PRNG used is cryptographically secure and that it is seeded properly! - * @param random Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values. - */ - export function setRandomFallback(random: (random: number) => number[]): void; - - /** - * Synchronously generates a salt. - * @param rounds Number of rounds to use, defaults to 10 if omitted - * @return Resulting salt - */ - export function genSaltSync(rounds?: number): string; - - /** - * Asynchronously generates a salt. - * @param callback Callback receiving the error, if any, and the resulting salt - */ - export function genSalt(callback: (err: Error, salt: string) => void): void; - - /** - * Asynchronously generates a salt. - * @param rounds Number of rounds to use, defaults to 10 if omitted - * @param callback Callback receiving the error, if any, and the resulting salt - */ - export function genSalt(rounds: number, callback: (err: Error, salt: string) => void): void; - - /** - * Synchronously generates a hash for the given string. - * @param s String to hash - * @param salt Salt length to generate or salt to use, default to 10 - * @return Resulting hash - */ - export function hashSync(s: string, salt?: number | string): string; - - /** - * Asynchronously generates a hash for the given string. - * @param s String to hash - * @param salt Salt length to generate or salt to use - * @param callback Callback receiving the error, if any, and the resulting hash - * @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms. - */ - export function hash(s: string, salt: number | string, callback: (err: Error, hash: string) => void, progressCallback?: (percent: number) => void): void; - - /** - * Synchronously tests a string against a hash. - * @param s String to compare - * @param hash Hash to test against - * @return true if matching, otherwise false - */ - export function compareSync(s: string, hash: string): boolean; - - /** - * Asynchronously compares the given data against the given hash. - * @param s Data to compare - * @param hash Data to be compared to - * @param callback Callback receiving the error, if any, otherwise the result - * @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms. - */ - export function compare(s: string, hash: string, callback: (err: Error, success: boolean) => void, progressCallback?: (percent: number) => void): void; - - /** - * Gets the number of rounds used to encrypt the specified hash. - * @param hash Hash to extract the used number of rounds from - * @return Number of rounds used - */ - export function getRounds(hash: string): number; - - /** - * Gets the salt portion from a hash. Does not validate the hash. - * @param hash Hash to extract the salt from - * @return Extracted salt part - */ - export function getSalt(hash: string): string; -} diff --git a/bcryptjs/index.d.ts b/bcryptjs/index.d.ts new file mode 100644 index 0000000000..fd1c0d7903 --- /dev/null +++ b/bcryptjs/index.d.ts @@ -0,0 +1,81 @@ +// Type definitions for bcryptjs v2.3.0 +// Project: https://github.com/dcodeIO/bcrypt.js +// Definitions by: Joshua Filby +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + +/** + * Sets the pseudo random number generator to use as a fallback if neither node's crypto module nor the Web Crypto API is available. + * Please note: It is highly important that the PRNG used is cryptographically secure and that it is seeded properly! + * @param random Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values. + */ +export declare function setRandomFallback(random: (random: number) => number[]): void; + +/** + * Synchronously generates a salt. + * @param rounds Number of rounds to use, defaults to 10 if omitted + * @return Resulting salt + */ +export declare function genSaltSync(rounds?: number): string; + +/** + * Asynchronously generates a salt. + * @param callback Callback receiving the error, if any, and the resulting salt + */ +export declare function genSalt(callback: (err: Error, salt: string) => void): void; + +/** + * Asynchronously generates a salt. + * @param rounds Number of rounds to use, defaults to 10 if omitted + * @param callback Callback receiving the error, if any, and the resulting salt + */ +export declare function genSalt(rounds: number, callback: (err: Error, salt: string) => void): void; + +/** + * Synchronously generates a hash for the given string. + * @param s String to hash + * @param salt Salt length to generate or salt to use, default to 10 + * @return Resulting hash + */ +export declare function hashSync(s: string, salt?: number | string): string; + +/** + * Asynchronously generates a hash for the given string. + * @param s String to hash + * @param salt Salt length to generate or salt to use + * @param callback Callback receiving the error, if any, and the resulting hash + * @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms. + */ +export declare function hash(s: string, salt: number | string, callback: (err: Error, hash: string) => void, progressCallback?: (percent: number) => void): void; + +/** + * Synchronously tests a string against a hash. + * @param s String to compare + * @param hash Hash to test against + * @return true if matching, otherwise false + */ +export declare function compareSync(s: string, hash: string): boolean; + +/** + * Asynchronously compares the given data against the given hash. + * @param s Data to compare + * @param hash Data to be compared to + * @param callback Callback receiving the error, if any, otherwise the result + * @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms. + */ +export declare function compare(s: string, hash: string, callback: (err: Error, success: boolean) => void, progressCallback?: (percent: number) => void): void; + +/** + * Gets the number of rounds used to encrypt the specified hash. + * @param hash Hash to extract the used number of rounds from + * @return Number of rounds used + */ +export declare function getRounds(hash: string): number; + +/** + * Gets the salt portion from a hash. Does not validate the hash. + * @param hash Hash to extract the salt from + * @return Extracted salt part + */ +export declare function getSalt(hash: string): string; diff --git a/bcryptjs/tsconfig.json b/bcryptjs/tsconfig.json new file mode 100644 index 0000000000..ebf1b81515 --- /dev/null +++ b/bcryptjs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bcryptjs-tests.ts" + ] +} \ No newline at end of file diff --git a/benchmark/benchmark-tests.ts b/benchmark/benchmark-tests.ts index 363e522b0b..8fbe2b1d92 100644 --- a/benchmark/benchmark-tests.ts +++ b/benchmark/benchmark-tests.ts @@ -1,4 +1,3 @@ -/// import Benchmark = require("benchmark"); var suite = new Benchmark.Suite; diff --git a/benchmark/benchmark.d.ts b/benchmark/benchmark.d.ts deleted file mode 100644 index c5c257aaaa..0000000000 --- a/benchmark/benchmark.d.ts +++ /dev/null @@ -1,192 +0,0 @@ -// Type definitions for Benchmark v1.0.0 -// Project: http://benchmarkjs.com -// Definitions by: Asana -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "benchmark" { - class Benchmark { - static deepClone(value: T): T; - static each(obj: Object | any[], callback: Function, thisArg?: any): void; - static extend(destination: Object, ...sources: Object[]): Object; - static filter(arr: T[], callback: (value: T) => any, thisArg?: any): T[]; - static filter(arr: T[], filter: string, thisArg?: any): T[]; - static forEach(arr: T[], callback: (value: T) => any, thisArg?: any): void; - static formatNumber(num: number): string; - static forOwn(obj: Object, callback: Function, thisArg?: any): void; - static hasKey(obj: Object, key: string): boolean; - static indexOf(arr: T[], value: T, fromIndex?: number): number; - static interpolate(template: string, values: Object): string; - static invoke(benches: Benchmark[], name: string | Object, ...args: any[]): any[]; - static join(obj: Object, separator1?: string, separator2?: string): string; - static map(arr: T[], callback: (value: T) => K, thisArg?: any): K[]; - static pluck(arr: T[], key: string): K[]; - static reduce(arr: T[], callback: (accumulator: K, value: T) => K, thisArg?: any): K; - - static options: Benchmark.Options; - static platform: Benchmark.Platform; - static support: Benchmark.Support; - static version: string; - - constructor(fn: Function | string, options?: Benchmark.Options); - constructor(name: string, fn: Function | string, options?: Benchmark.Options); - constructor(name: string, options?: Benchmark.Options); - constructor(options: Benchmark.Options); - - aborted: boolean; - compiled: Function | string; - count: number; - cycles: number; - error: Error; - fn: Function | string; - hz: number; - running: boolean; - setup: Function | string; - teardown: Function | string; - - stats: Benchmark.Stats; - times: Benchmark.Times; - - abort(): Benchmark; - clone(options: Benchmark.Options): Benchmark; - compare(benchmark: Benchmark): number; - emit(type: string | Object): any; - listeners(type: string): Function[]; - off(type?: string, listener?: Function): Benchmark; - off(types: string[]): Benchmark; - on(type?: string, listener?: Function): Benchmark; - on(types: string[]): Benchmark; - reset(): Benchmark; - run(options?: Benchmark.Options): Benchmark; - toString(): string; - } - - namespace Benchmark { - export interface Options { - async?: boolean; - defer?: boolean; - delay?: number; - id?: string; - initCount?: number; - maxTime?: number; - minSamples?: number; - minTime?: number; - name?: string; - onAbort?: Function; - onComplete?: Function; - onCycle?: Function; - onError?: Function; - onReset?: Function; - onStart?: Function; - setup?: Function | string; - teardown?: Function | string; - fn?: Function | string; - queued?: boolean; - } - - export interface Platform { - description: string; - layout: string; - manufacturer: string; - name: string; - os: string; - prerelease: string; - product: string; - version: string; - toString(): string; - } - - export interface Support { - air: boolean; - argumentsClass: boolean; - browser: boolean; - charByIndex: boolean; - charByOwnIndex: boolean; - decompilation: boolean; - descriptors: boolean; - getAllKeys: boolean; - iteratesOwnFirst: boolean; - java: boolean; - nodeClass: boolean; - timeout: boolean; - } - - export interface Stats { - deviation: number; - mean: number; - moe: number; - rme: number; - sample: any[]; - sem: number; - variance: number; - } - - export interface Times { - cycle: number; - elapsed: number; - period: number; - timeStamp: number; - } - - export class Deferred { - constructor(clone: Benchmark); - - benchmark: Benchmark; - cycles: number; - elapsed: number; - timeStamp: number; - } - - export class Event { - constructor(type: string | Object); - - aborted: boolean; - cancelled: boolean; - currentTarget: Object; - result: any; - target: Object; - timeStamp: number; - type: string; - } - - export class Suite { - static options: { name: string }; - - constructor(name?: string, options?: Options); - - aborted: boolean; - length: number; - running: boolean; - abort(): Suite; - add(name: string, fn: Function | string, options?: Options): Suite; - add(fn: Function | string, options?: Options): Suite; - add(name: string, options?: Options): Suite; - add(options: Options): Suite; - clone(options: Options): Suite; - emit(type: string | Object): any; - filter(callback: Function | string): Suite; - forEach(callback: Function): Suite; - indexOf(value: any): number; - invoke(name: string, ...args: any[]): any[]; - join(separator?: string): string; - listeners(type: string): Function[]; - map(callback: Function): any[]; - off(type?: string, callback?: Function): Benchmark; - off(types: string[]): Benchmark; - on(type?: string, callback?: Function): Benchmark; - on(types: string[]): Benchmark; - pluck(property: string): any[]; - pop(): Function; - push(benchmark: Benchmark): number; - reduce(callback: Function, accumulator: T): T; - reset(): Suite; - reverse(): any[]; - run(options?: Options): Suite; - shift(): Benchmark; - slice(start: number, end: number): any[]; - slice(start: number, deleteCount: number, ...values: any[]): any[]; - unshift(benchmark: Benchmark): number; - } - } - - export = Benchmark; -} diff --git a/benchmark/index.d.ts b/benchmark/index.d.ts new file mode 100644 index 0000000000..01bb379a48 --- /dev/null +++ b/benchmark/index.d.ts @@ -0,0 +1,191 @@ +// Type definitions for Benchmark v1.0.0 +// Project: http://benchmarkjs.com +// Definitions by: Asana +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare class Benchmark { + static deepClone(value: T): T; + static each(obj: Object | any[], callback: Function, thisArg?: any): void; + static extend(destination: Object, ...sources: Object[]): Object; + static filter(arr: T[], callback: (value: T) => any, thisArg?: any): T[]; + static filter(arr: T[], filter: string, thisArg?: any): T[]; + static forEach(arr: T[], callback: (value: T) => any, thisArg?: any): void; + static formatNumber(num: number): string; + static forOwn(obj: Object, callback: Function, thisArg?: any): void; + static hasKey(obj: Object, key: string): boolean; + static indexOf(arr: T[], value: T, fromIndex?: number): number; + static interpolate(template: string, values: Object): string; + static invoke(benches: Benchmark[], name: string | Object, ...args: any[]): any[]; + static join(obj: Object, separator1?: string, separator2?: string): string; + static map(arr: T[], callback: (value: T) => K, thisArg?: any): K[]; + static pluck(arr: T[], key: string): K[]; + static reduce(arr: T[], callback: (accumulator: K, value: T) => K, thisArg?: any): K; + + static options: Benchmark.Options; + static platform: Benchmark.Platform; + static support: Benchmark.Support; + static version: string; + + constructor(fn: Function | string, options?: Benchmark.Options); + constructor(name: string, fn: Function | string, options?: Benchmark.Options); + constructor(name: string, options?: Benchmark.Options); + constructor(options: Benchmark.Options); + + aborted: boolean; + compiled: Function | string; + count: number; + cycles: number; + error: Error; + fn: Function | string; + hz: number; + running: boolean; + setup: Function | string; + teardown: Function | string; + + stats: Benchmark.Stats; + times: Benchmark.Times; + + abort(): Benchmark; + clone(options: Benchmark.Options): Benchmark; + compare(benchmark: Benchmark): number; + emit(type: string | Object): any; + listeners(type: string): Function[]; + off(type?: string, listener?: Function): Benchmark; + off(types: string[]): Benchmark; + on(type?: string, listener?: Function): Benchmark; + on(types: string[]): Benchmark; + reset(): Benchmark; + run(options?: Benchmark.Options): Benchmark; + toString(): string; +} + +declare namespace Benchmark { + export interface Options { + async?: boolean; + defer?: boolean; + delay?: number; + id?: string; + initCount?: number; + maxTime?: number; + minSamples?: number; + minTime?: number; + name?: string; + onAbort?: Function; + onComplete?: Function; + onCycle?: Function; + onError?: Function; + onReset?: Function; + onStart?: Function; + setup?: Function | string; + teardown?: Function | string; + fn?: Function | string; + queued?: boolean; + } + + export interface Platform { + description: string; + layout: string; + manufacturer: string; + name: string; + os: string; + prerelease: string; + product: string; + version: string; + toString(): string; + } + + export interface Support { + air: boolean; + argumentsClass: boolean; + browser: boolean; + charByIndex: boolean; + charByOwnIndex: boolean; + decompilation: boolean; + descriptors: boolean; + getAllKeys: boolean; + iteratesOwnFirst: boolean; + java: boolean; + nodeClass: boolean; + timeout: boolean; + } + + export interface Stats { + deviation: number; + mean: number; + moe: number; + rme: number; + sample: any[]; + sem: number; + variance: number; + } + + export interface Times { + cycle: number; + elapsed: number; + period: number; + timeStamp: number; + } + + export class Deferred { + constructor(clone: Benchmark); + + benchmark: Benchmark; + cycles: number; + elapsed: number; + timeStamp: number; + } + + export class Event { + constructor(type: string | Object); + + aborted: boolean; + cancelled: boolean; + currentTarget: Object; + result: any; + target: Object; + timeStamp: number; + type: string; + } + + export class Suite { + static options: { name: string }; + + constructor(name?: string, options?: Options); + + aborted: boolean; + length: number; + running: boolean; + abort(): Suite; + add(name: string, fn: Function | string, options?: Options): Suite; + add(fn: Function | string, options?: Options): Suite; + add(name: string, options?: Options): Suite; + add(options: Options): Suite; + clone(options: Options): Suite; + emit(type: string | Object): any; + filter(callback: Function | string): Suite; + forEach(callback: Function): Suite; + indexOf(value: any): number; + invoke(name: string, ...args: any[]): any[]; + join(separator?: string): string; + listeners(type: string): Function[]; + map(callback: Function): any[]; + off(type?: string, callback?: Function): Benchmark; + off(types: string[]): Benchmark; + on(type?: string, callback?: Function): Benchmark; + on(types: string[]): Benchmark; + pluck(property: string): any[]; + pop(): Function; + push(benchmark: Benchmark): number; + reduce(callback: Function, accumulator: T): T; + reset(): Suite; + reverse(): any[]; + run(options?: Options): Suite; + shift(): Benchmark; + slice(start: number, end: number): any[]; + slice(start: number, deleteCount: number, ...values: any[]): any[]; + unshift(benchmark: Benchmark): number; + } +} + +export = Benchmark; diff --git a/benchmark/tsconfig.json b/benchmark/tsconfig.json new file mode 100644 index 0000000000..85df6e1ab3 --- /dev/null +++ b/benchmark/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "benchmark-tests.ts" + ] +} \ No newline at end of file diff --git a/better-curry/better-curry-tests.ts b/better-curry/better-curry-tests.ts index 36e4936e0d..48c9c7f0ca 100644 --- a/better-curry/better-curry-tests.ts +++ b/better-curry/better-curry-tests.ts @@ -1,4 +1,4 @@ -/// + import bc = require('better-curry'); bc.flatten([1,2,3,[1,2],['a']]) === []; diff --git a/better-curry/better-curry.d.ts b/better-curry/index.d.ts similarity index 100% rename from better-curry/better-curry.d.ts rename to better-curry/index.d.ts diff --git a/better-curry/tsconfig.json b/better-curry/tsconfig.json new file mode 100644 index 0000000000..2098c89392 --- /dev/null +++ b/better-curry/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "better-curry-tests.ts" + ] +} \ No newline at end of file diff --git a/bezier-easing/bezier-easing-tests.ts b/bezier-easing/bezier-easing-tests.ts index f928fa62de..6cf2b28bf2 100644 --- a/bezier-easing/bezier-easing-tests.ts +++ b/bezier-easing/bezier-easing-tests.ts @@ -1,4 +1,4 @@ -/// + function get_easing() { let easing: Easing = BezierEasing(0, 0, 1, 0.5); diff --git a/bezier-easing/bezier-easing.d.ts b/bezier-easing/index.d.ts similarity index 100% rename from bezier-easing/bezier-easing.d.ts rename to bezier-easing/index.d.ts diff --git a/bezier-easing/tsconfig.json b/bezier-easing/tsconfig.json new file mode 100644 index 0000000000..ab6fb82af9 --- /dev/null +++ b/bezier-easing/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bezier-easing-tests.ts" + ] +} \ No newline at end of file diff --git a/bgiframe/typescript.bgiframe.d.ts b/bgiframe/index.d.ts similarity index 100% rename from bgiframe/typescript.bgiframe.d.ts rename to bgiframe/index.d.ts diff --git a/bgiframe/tsconfig.json b/bgiframe/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/bgiframe/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/big-integer/big-integer-tests.ts b/big-integer/big-integer-tests.ts index fd08f89a14..2ab3c1fad5 100644 --- a/big-integer/big-integer-tests.ts +++ b/big-integer/big-integer-tests.ts @@ -1,4 +1,4 @@ -/// + // constructor tests var noArgument = bigInt(), diff --git a/big-integer/big-integer.d.ts b/big-integer/index.d.ts similarity index 100% rename from big-integer/big-integer.d.ts rename to big-integer/index.d.ts diff --git a/big-integer/tsconfig.json b/big-integer/tsconfig.json new file mode 100644 index 0000000000..ff891f65a2 --- /dev/null +++ b/big-integer/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "big-integer-tests.ts" + ] +} \ No newline at end of file diff --git a/big.js/big.js-tests.ts b/big.js/big.js-tests.ts index 0067a0b4f5..10a1f44a0f 100644 --- a/big.js/big.js-tests.ts +++ b/big.js/big.js-tests.ts @@ -2,7 +2,6 @@ // Project: https://github.com/MikeMcl/big.js/ // Definitions by: Steve Ognibene // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// /* diff --git a/big.js/big.js.d.ts b/big.js/index.d.ts similarity index 100% rename from big.js/big.js.d.ts rename to big.js/index.d.ts diff --git a/big.js/tsconfig.json b/big.js/tsconfig.json new file mode 100644 index 0000000000..102ae72e67 --- /dev/null +++ b/big.js/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "big.js-tests.ts" + ] +} \ No newline at end of file diff --git a/bigint/bigint-tests.ts b/bigint/bigint-tests.ts index 14cdd5b12c..35d118a8a1 100644 --- a/bigint/bigint-tests.ts +++ b/bigint/bigint-tests.ts @@ -1,4 +1,4 @@ -/// + var bi: BigInt.BigInt; var num: number; diff --git a/bigint/bigint.d.ts b/bigint/index.d.ts similarity index 100% rename from bigint/bigint.d.ts rename to bigint/index.d.ts diff --git a/bigint/tsconfig.json b/bigint/tsconfig.json new file mode 100644 index 0000000000..3e25ecb967 --- /dev/null +++ b/bigint/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bigint-tests.ts" + ] +} \ No newline at end of file diff --git a/bignum/bignum-tests.ts b/bignum/bignum-tests.ts index 363fad886b..0803ac00ea 100644 --- a/bignum/bignum-tests.ts +++ b/bignum/bignum-tests.ts @@ -1,4 +1,4 @@ -/// + var bignum = require('bignum'); diff --git a/bignum/bignum.d.ts b/bignum/bignum.d.ts deleted file mode 100644 index b9e653e189..0000000000 --- a/bignum/bignum.d.ts +++ /dev/null @@ -1,269 +0,0 @@ -// Type definitions for BigNum -// Project: https://github.com/justmoon/node-BigNum -// Definitions by: Pat Smuk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare class BigNum { - /** Create a new BigNum from n. */ - constructor(n: number|BigNum); - - /** Create a new BigNum from n and a base. */ - constructor(n: string, base?: number); - - /** - * Create a new BigNum from a Buffer. - * - * The default options are: {endian: 'big', size: 1}. - */ - static fromBuffer(buffer: Buffer, options?: BigNum.BufferOptions): BigNum; - - /** - * Generate a probable prime of length bits. - * - * If safe is true, it will be a "safe" prime of the form p=2p'+1 where p' is also prime. - */ - static prime(bits: number, safe?: boolean): BigNum; - - /** Return true if num is identified as a BigNum instance. Otherwise, return false. */ - static isBigNum(num: any): boolean; - - /** Print out the BigNum instance in the requested base as a string. Default: base 10 */ - toString(base?: number): string; - - /** - * Turn a BigNum into a Number. - * - * If the BigNum is too big you'll lose precision or you'll get ±Infinity. - */ - toNumber(): number; - - /** - * Return a new Buffer with the data from the BigNum. - * - * The default options are: {endian: 'big', size: 1}. - */ - toBuffer(options?: BigNum.BufferOptions): Buffer; - - /** Return a new BigNum containing the instance value plus n. */ - add(n: BigNum.BigNumCompatible): BigNum; - - /** Return a new BigNum containing the instance value minus n. */ - sub(n: BigNum.BigNumCompatible): BigNum; - - /** Return a new BigNum containing the instance value multiplied by n. */ - mul(n: BigNum.BigNumCompatible): BigNum; - - /** Return a new BigNum containing the instance value integrally divided by n. */ - div(n: BigNum.BigNumCompatible): BigNum; - - /** Return a new BigNum with the absolute value of the instance. */ - abs(): BigNum; - - /** Return a new BigNum with the negative of the instance value. */ - neg(): BigNum; - - /** - * Compare the instance value to n. - * - * Return a positive integer if > n, a negative integer if < n, and 0 if == n. - */ - cmp(n: BigNum.BigNumCompatible): number; - - /** Return a boolean: whether the instance value is greater than n (> n). */ - gt(n: BigNum.BigNumCompatible): boolean; - - /** Return a boolean: whether the instance value is greater than or equal to n (>= n). */ - ge(n: BigNum.BigNumCompatible): boolean; - - /** Return a boolean: whether the instance value is equal to n (== n). */ - eq(n: BigNum.BigNumCompatible): boolean; - - /** Return a boolean: whether the instance value is less than n (< n). */ - lt(n: BigNum.BigNumCompatible): boolean; - - /** Return a boolean: whether the instance value is less than or equal to n (<= n). */ - le(n: BigNum.BigNumCompatible): boolean; - - /** Return a new BigNum with the instance value bitwise AND (&)-ed with n. */ - and(n: BigNum.BigNumCompatible): BigNum; - - /** Return a new BigNum with the instance value bitwise inclusive-OR (|)-ed with n. */ - or(n: BigNum.BigNumCompatible): BigNum; - - /** Return a new BigNum with the instance value bitwise exclusive-OR (^)-ed with n. */ - xor(n: BigNum.BigNumCompatible): BigNum; - - /** Return a new BigNum with the instance value modulo n. */ - mod(n: BigNum.BigNumCompatible): BigNum; - - /** Return a new BigNum with the instance value raised to the nth power. */ - pow(n: BigNum.BigNumCompatible): BigNum; - - /** Return a new BigNum with the instance value raised to the nth power modulo m. */ - powm(n: BigNum.BigNumCompatible, m: BigNum.BigNumCompatible): BigNum; - - /** Compute the multiplicative inverse modulo m. */ - invertm(m: BigNum.BigNumCompatible): BigNum; - - /** - * If upperBound is supplied, return a random BigNum between the instance value and upperBound - 1, inclusive. - * Otherwise, return a random BigNum between 0 and the instance value - 1, inclusive. - */ - rand(upperBound?: BigNum.BigNumCompatible): BigNum; - - /** - * Return whether the BigNum is: - * - certainly prime (true) - * - probably prime ('maybe') - * - certainly composite (false) - */ - probPrime(): boolean | string; - - /** Return a new BigNum that is the 2^n multiple. Equivalent of the << operator. */ - shiftLeft(n: BigNum.BigNumCompatible): BigNum; - - /** Return a new BigNum of the value integer divided by 2^n. Equivalent of the >> operator. */ - shiftRight(n: BigNum.BigNumCompatible): BigNum; - - /** Return the greatest common divisor of the current BigNum with n as a new BigNum. */ - gcd(n: BigNum): BigNum; - - /** - * Return the Jacobi symbol (or Legendre symbol if n is prime) of the current BigNum (= a) over n. - * Note that n must be odd and >= 3. 0 <= a < n. - * - * Returns -1 or 1 as an int (NOT a BigNum). Throws an error on failure. - */ - jacobi(n: BigNum): number; - - /** Return the number of bits used to represent the current BigNum. */ - bitLength(): number; -} - -declare namespace BigNum { - /** Anything that can be converted to BigNum. */ - type BigNumCompatible = BigNum | number | string; - - export interface BufferOptions { - /** Can be either 'big' or 'little'. Also accepts 1 for big and -1 for little. Doesn't matter when size = 1. */ - endian: string | number; - - /** Number of bytes per word, or 'auto' to flip entire Buffer. */ - size: number | string; - } - - /** - * Turn a BigNum into a Number. - * - * If the BigNum is too big you'll lose precision or you'll get ±Infinity. - */ - export function toNumber(n: BigNumCompatible): number; - - /** - * Return a new Buffer with the data from the BigNum. - * - * The default options are: {endian: 'big', size: 1}. - */ - export function toBuffer(n: BigNumCompatible, options?: BufferOptions): Buffer; - - /** Return a new BigNum containing the instance value plus n. */ - export function add(left: BigNumCompatible, right: BigNumCompatible): BigNum; - - /** Return a new BigNum containing the instance value minus n. */ - export function sub(left: BigNumCompatible, right: BigNumCompatible): BigNum; - - /** Return a new BigNum containing the instance value multiplied by n. */ - export function mul(left: BigNumCompatible, right: BigNumCompatible): BigNum; - - /** Return a new BigNum containing the instance value integrally divided by n. */ - export function div(dividend: BigNumCompatible, divisor: BigNumCompatible): BigNum; - - /** Return a new BigNum with the absolute value of the instance. */ - export function abs(n: BigNumCompatible): BigNum; - - /** Return a new BigNum with the negative of the instance value. */ - export function neg(n: BigNumCompatible): BigNum; - - /** - * Compare the instance value to n. - * - * Return a positive integer if > n, a negative integer if < n, and 0 if == n. - */ - export function cmp(left: BigNumCompatible, right: BigNumCompatible): number; - - /** Return a boolean: whether the instance value is greater than n (> n). */ - export function gt(left: BigNumCompatible, right: BigNumCompatible): boolean; - - /** Return a boolean: whether the instance value is greater than or equal to n (>= n). */ - export function ge(left: BigNumCompatible, right: BigNumCompatible): boolean; - - /** Return a boolean: whether the instance value is equal to n (== n). */ - export function eq(left: BigNumCompatible, right: BigNumCompatible): boolean; - - /** Return a boolean: whether the instance value is less than n (< n). */ - export function lt(left: BigNumCompatible, right: BigNumCompatible): boolean; - - /** Return a boolean: whether the instance value is less than or equal to n (<= n). */ - export function le(left: BigNumCompatible, right: BigNumCompatible): boolean; - - /** Return a new BigNum with the instance value bitwise AND (&)-ed with n. */ - export function and(left: BigNumCompatible, right: BigNumCompatible): BigNum; - - /** Return a new BigNum with the instance value bitwise inclusive-OR (|)-ed with n. */ - export function or(left: BigNumCompatible, right: BigNumCompatible): BigNum; - - /** Return a new BigNum with the instance value bitwise exclusive-OR (^)-ed with n. */ - export function xor(left: BigNumCompatible, right: BigNumCompatible): BigNum; - - /** Return a new BigNum with the instance value modulo n. */ - export function mod(left: BigNumCompatible, right: BigNumCompatible): BigNum; - - /** Return a new BigNum with the instance value raised to the nth power. */ - export function pow(base: BigNumCompatible, exponent: BigNumCompatible): BigNum; - - /** Return a new BigNum with the instance value raised to the nth power modulo m. */ - export function powm(base: BigNumCompatible, exponent: BigNumCompatible, m: BigNumCompatible): BigNum; - - /** Compute the multiplicative inverse modulo m. */ - export function invertm(n: BigNumCompatible, m: BigNumCompatible): BigNum; - - /** - * If upperBound is supplied, return a random BigNum between the instance value and upperBound - 1, inclusive. - * Otherwise, return a random BigNum between 0 and the instance value - 1, inclusive. - */ - export function rand(n: BigNumCompatible, upperBound?: BigNumCompatible): BigNum; - - /** - * Return whether the BigNum is: - * - certainly prime (true) - * - probably prime ('maybe') - * - certainly composite (false) - */ - export function probPrime(n: BigNumCompatible): boolean | string; - - /** Return a new BigNum that is the 2^bits multiple. Equivalent of the << operator. */ - export function shiftLeft(n: BigNumCompatible, bits: BigNumCompatible): BigNum; - - /** Return a new BigNum of the value integer divided by 2^bits. Equivalent of the >> operator. */ - export function shiftRight(n: BigNumCompatible, bits: BigNumCompatible): BigNum; - - /** Return the greatest common divisor of the current BigNum with n as a new BigNum. */ - export function gcd(left: BigNumCompatible, right: BigNum): BigNum; - - /** - * Return the Jacobi symbol (or Legendre symbol if n is prime) of the current BigNum (= a) over n. - * Note that n must be odd and >= 3. 0 <= a < n. - * - * Returns -1 or 1 as an int (NOT a BigNum). Throws an error on failure. - */ - export function jacobi(a: BigNumCompatible, n: BigNum): number; - - /** Return the number of bits used to represent the current BigNum. */ - export function bitLength(n: BigNumCompatible): number; -} - -declare module "bignum" { - export = BigNum; -} diff --git a/bignum/index.d.ts b/bignum/index.d.ts new file mode 100644 index 0000000000..ae556d00fe --- /dev/null +++ b/bignum/index.d.ts @@ -0,0 +1,267 @@ +// Type definitions for BigNum +// Project: https://github.com/justmoon/node-BigNum +// Definitions by: Pat Smuk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = BigNum; + +declare class BigNum { + /** Create a new BigNum from n. */ + constructor(n: number|BigNum); + + /** Create a new BigNum from n and a base. */ + constructor(n: string, base?: number); + + /** + * Create a new BigNum from a Buffer. + * + * The default options are: {endian: 'big', size: 1}. + */ + static fromBuffer(buffer: Buffer, options?: BigNum.BufferOptions): BigNum; + + /** + * Generate a probable prime of length bits. + * + * If safe is true, it will be a "safe" prime of the form p=2p'+1 where p' is also prime. + */ + static prime(bits: number, safe?: boolean): BigNum; + + /** Return true if num is identified as a BigNum instance. Otherwise, return false. */ + static isBigNum(num: any): boolean; + + /** Print out the BigNum instance in the requested base as a string. Default: base 10 */ + toString(base?: number): string; + + /** + * Turn a BigNum into a Number. + * + * If the BigNum is too big you'll lose precision or you'll get ±Infinity. + */ + toNumber(): number; + + /** + * Return a new Buffer with the data from the BigNum. + * + * The default options are: {endian: 'big', size: 1}. + */ + toBuffer(options?: BigNum.BufferOptions): Buffer; + + /** Return a new BigNum containing the instance value plus n. */ + add(n: BigNum.BigNumCompatible): BigNum; + + /** Return a new BigNum containing the instance value minus n. */ + sub(n: BigNum.BigNumCompatible): BigNum; + + /** Return a new BigNum containing the instance value multiplied by n. */ + mul(n: BigNum.BigNumCompatible): BigNum; + + /** Return a new BigNum containing the instance value integrally divided by n. */ + div(n: BigNum.BigNumCompatible): BigNum; + + /** Return a new BigNum with the absolute value of the instance. */ + abs(): BigNum; + + /** Return a new BigNum with the negative of the instance value. */ + neg(): BigNum; + + /** + * Compare the instance value to n. + * + * Return a positive integer if > n, a negative integer if < n, and 0 if == n. + */ + cmp(n: BigNum.BigNumCompatible): number; + + /** Return a boolean: whether the instance value is greater than n (> n). */ + gt(n: BigNum.BigNumCompatible): boolean; + + /** Return a boolean: whether the instance value is greater than or equal to n (>= n). */ + ge(n: BigNum.BigNumCompatible): boolean; + + /** Return a boolean: whether the instance value is equal to n (== n). */ + eq(n: BigNum.BigNumCompatible): boolean; + + /** Return a boolean: whether the instance value is less than n (< n). */ + lt(n: BigNum.BigNumCompatible): boolean; + + /** Return a boolean: whether the instance value is less than or equal to n (<= n). */ + le(n: BigNum.BigNumCompatible): boolean; + + /** Return a new BigNum with the instance value bitwise AND (&)-ed with n. */ + and(n: BigNum.BigNumCompatible): BigNum; + + /** Return a new BigNum with the instance value bitwise inclusive-OR (|)-ed with n. */ + or(n: BigNum.BigNumCompatible): BigNum; + + /** Return a new BigNum with the instance value bitwise exclusive-OR (^)-ed with n. */ + xor(n: BigNum.BigNumCompatible): BigNum; + + /** Return a new BigNum with the instance value modulo n. */ + mod(n: BigNum.BigNumCompatible): BigNum; + + /** Return a new BigNum with the instance value raised to the nth power. */ + pow(n: BigNum.BigNumCompatible): BigNum; + + /** Return a new BigNum with the instance value raised to the nth power modulo m. */ + powm(n: BigNum.BigNumCompatible, m: BigNum.BigNumCompatible): BigNum; + + /** Compute the multiplicative inverse modulo m. */ + invertm(m: BigNum.BigNumCompatible): BigNum; + + /** + * If upperBound is supplied, return a random BigNum between the instance value and upperBound - 1, inclusive. + * Otherwise, return a random BigNum between 0 and the instance value - 1, inclusive. + */ + rand(upperBound?: BigNum.BigNumCompatible): BigNum; + + /** + * Return whether the BigNum is: + * - certainly prime (true) + * - probably prime ('maybe') + * - certainly composite (false) + */ + probPrime(): boolean | string; + + /** Return a new BigNum that is the 2^n multiple. Equivalent of the << operator. */ + shiftLeft(n: BigNum.BigNumCompatible): BigNum; + + /** Return a new BigNum of the value integer divided by 2^n. Equivalent of the >> operator. */ + shiftRight(n: BigNum.BigNumCompatible): BigNum; + + /** Return the greatest common divisor of the current BigNum with n as a new BigNum. */ + gcd(n: BigNum): BigNum; + + /** + * Return the Jacobi symbol (or Legendre symbol if n is prime) of the current BigNum (= a) over n. + * Note that n must be odd and >= 3. 0 <= a < n. + * + * Returns -1 or 1 as an int (NOT a BigNum). Throws an error on failure. + */ + jacobi(n: BigNum): number; + + /** Return the number of bits used to represent the current BigNum. */ + bitLength(): number; +} + +declare namespace BigNum { + /** Anything that can be converted to BigNum. */ + type BigNumCompatible = BigNum | number | string; + + export interface BufferOptions { + /** Can be either 'big' or 'little'. Also accepts 1 for big and -1 for little. Doesn't matter when size = 1. */ + endian: string | number; + + /** Number of bytes per word, or 'auto' to flip entire Buffer. */ + size: number | string; + } + + /** + * Turn a BigNum into a Number. + * + * If the BigNum is too big you'll lose precision or you'll get ±Infinity. + */ + export function toNumber(n: BigNumCompatible): number; + + /** + * Return a new Buffer with the data from the BigNum. + * + * The default options are: {endian: 'big', size: 1}. + */ + export function toBuffer(n: BigNumCompatible, options?: BufferOptions): Buffer; + + /** Return a new BigNum containing the instance value plus n. */ + export function add(left: BigNumCompatible, right: BigNumCompatible): BigNum; + + /** Return a new BigNum containing the instance value minus n. */ + export function sub(left: BigNumCompatible, right: BigNumCompatible): BigNum; + + /** Return a new BigNum containing the instance value multiplied by n. */ + export function mul(left: BigNumCompatible, right: BigNumCompatible): BigNum; + + /** Return a new BigNum containing the instance value integrally divided by n. */ + export function div(dividend: BigNumCompatible, divisor: BigNumCompatible): BigNum; + + /** Return a new BigNum with the absolute value of the instance. */ + export function abs(n: BigNumCompatible): BigNum; + + /** Return a new BigNum with the negative of the instance value. */ + export function neg(n: BigNumCompatible): BigNum; + + /** + * Compare the instance value to n. + * + * Return a positive integer if > n, a negative integer if < n, and 0 if == n. + */ + export function cmp(left: BigNumCompatible, right: BigNumCompatible): number; + + /** Return a boolean: whether the instance value is greater than n (> n). */ + export function gt(left: BigNumCompatible, right: BigNumCompatible): boolean; + + /** Return a boolean: whether the instance value is greater than or equal to n (>= n). */ + export function ge(left: BigNumCompatible, right: BigNumCompatible): boolean; + + /** Return a boolean: whether the instance value is equal to n (== n). */ + export function eq(left: BigNumCompatible, right: BigNumCompatible): boolean; + + /** Return a boolean: whether the instance value is less than n (< n). */ + export function lt(left: BigNumCompatible, right: BigNumCompatible): boolean; + + /** Return a boolean: whether the instance value is less than or equal to n (<= n). */ + export function le(left: BigNumCompatible, right: BigNumCompatible): boolean; + + /** Return a new BigNum with the instance value bitwise AND (&)-ed with n. */ + export function and(left: BigNumCompatible, right: BigNumCompatible): BigNum; + + /** Return a new BigNum with the instance value bitwise inclusive-OR (|)-ed with n. */ + export function or(left: BigNumCompatible, right: BigNumCompatible): BigNum; + + /** Return a new BigNum with the instance value bitwise exclusive-OR (^)-ed with n. */ + export function xor(left: BigNumCompatible, right: BigNumCompatible): BigNum; + + /** Return a new BigNum with the instance value modulo n. */ + export function mod(left: BigNumCompatible, right: BigNumCompatible): BigNum; + + /** Return a new BigNum with the instance value raised to the nth power. */ + export function pow(base: BigNumCompatible, exponent: BigNumCompatible): BigNum; + + /** Return a new BigNum with the instance value raised to the nth power modulo m. */ + export function powm(base: BigNumCompatible, exponent: BigNumCompatible, m: BigNumCompatible): BigNum; + + /** Compute the multiplicative inverse modulo m. */ + export function invertm(n: BigNumCompatible, m: BigNumCompatible): BigNum; + + /** + * If upperBound is supplied, return a random BigNum between the instance value and upperBound - 1, inclusive. + * Otherwise, return a random BigNum between 0 and the instance value - 1, inclusive. + */ + export function rand(n: BigNumCompatible, upperBound?: BigNumCompatible): BigNum; + + /** + * Return whether the BigNum is: + * - certainly prime (true) + * - probably prime ('maybe') + * - certainly composite (false) + */ + export function probPrime(n: BigNumCompatible): boolean | string; + + /** Return a new BigNum that is the 2^bits multiple. Equivalent of the << operator. */ + export function shiftLeft(n: BigNumCompatible, bits: BigNumCompatible): BigNum; + + /** Return a new BigNum of the value integer divided by 2^bits. Equivalent of the >> operator. */ + export function shiftRight(n: BigNumCompatible, bits: BigNumCompatible): BigNum; + + /** Return the greatest common divisor of the current BigNum with n as a new BigNum. */ + export function gcd(left: BigNumCompatible, right: BigNum): BigNum; + + /** + * Return the Jacobi symbol (or Legendre symbol if n is prime) of the current BigNum (= a) over n. + * Note that n must be odd and >= 3. 0 <= a < n. + * + * Returns -1 or 1 as an int (NOT a BigNum). Throws an error on failure. + */ + export function jacobi(a: BigNumCompatible, n: BigNum): number; + + /** Return the number of bits used to represent the current BigNum. */ + export function bitLength(n: BigNumCompatible): number; +} diff --git a/bignum/tsconfig.json b/bignum/tsconfig.json new file mode 100644 index 0000000000..09ac5b622d --- /dev/null +++ b/bignum/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bignum-tests.ts" + ] +} \ No newline at end of file diff --git a/bigscreen/bigscreen-tests.ts b/bigscreen/bigscreen-tests.ts index 9e0c9fda8c..459e7cd449 100644 --- a/bigscreen/bigscreen-tests.ts +++ b/bigscreen/bigscreen-tests.ts @@ -1,5 +1,3 @@ -/// - import BigScreen = require("bigscreen"); BigScreen.onchange = function(element: Element) { diff --git a/bigscreen/bigscreen.d.ts b/bigscreen/index.d.ts similarity index 100% rename from bigscreen/bigscreen.d.ts rename to bigscreen/index.d.ts diff --git a/bigscreen/tsconfig.json b/bigscreen/tsconfig.json new file mode 100644 index 0000000000..c449fb1ae0 --- /dev/null +++ b/bigscreen/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bigscreen-tests.ts" + ] +} \ No newline at end of file diff --git a/bingmaps/Microsoft.Maps.AdvancedShapes.d.ts b/bingmaps/Microsoft.Maps.AdvancedShapes.d.ts index a677cd2a4d..32ac20a874 100644 --- a/bingmaps/Microsoft.Maps.AdvancedShapes.d.ts +++ b/bingmaps/Microsoft.Maps.AdvancedShapes.d.ts @@ -3,8 +3,6 @@ // Definitions by: Eric Todd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare namespace Microsoft.Maps.AdvancedShapes { export class EntityCollection { diff --git a/bingmaps/Microsoft.Maps.Directions.d.ts b/bingmaps/Microsoft.Maps.Directions.d.ts index fd0622f880..e9f2fa9cf1 100644 --- a/bingmaps/Microsoft.Maps.Directions.d.ts +++ b/bingmaps/Microsoft.Maps.Directions.d.ts @@ -3,8 +3,6 @@ // Definitions by: Eric Todd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare namespace Microsoft.Maps.Directions { export interface BusinessDetails { diff --git a/bingmaps/Microsoft.Maps.Search.d.ts b/bingmaps/Microsoft.Maps.Search.d.ts index d13163ef25..21011ab1cd 100644 --- a/bingmaps/Microsoft.Maps.Search.d.ts +++ b/bingmaps/Microsoft.Maps.Search.d.ts @@ -3,8 +3,6 @@ // Definitions by: Eric Todd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare namespace Microsoft.Maps.Search { export interface Address { diff --git a/bingmaps/Microsoft.Maps.Traffic.d.ts b/bingmaps/Microsoft.Maps.Traffic.d.ts index 1451c09000..353ec39b7c 100644 --- a/bingmaps/Microsoft.Maps.Traffic.d.ts +++ b/bingmaps/Microsoft.Maps.Traffic.d.ts @@ -3,8 +3,6 @@ // Definitions by: Eric Todd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare namespace Microsoft.Maps.Traffic { export class TrafficManager { diff --git a/bingmaps/Microsoft.Maps.VenueMaps.d.ts b/bingmaps/Microsoft.Maps.VenueMaps.d.ts index 2d67bb3e69..51b41815f5 100644 --- a/bingmaps/Microsoft.Maps.VenueMaps.d.ts +++ b/bingmaps/Microsoft.Maps.VenueMaps.d.ts @@ -3,8 +3,6 @@ // Definitions by: Eric Todd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare namespace Microsoft.Maps.VenueMaps { export interface MouseResponse { diff --git a/bingmaps/bingmaps-tests.ts b/bingmaps/bingmaps-tests.ts index 08b3decd5b..d50efb0e62 100644 --- a/bingmaps/bingmaps-tests.ts +++ b/bingmaps/bingmaps-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// /// /// /// diff --git a/bingmaps/Microsoft.Maps.d.ts b/bingmaps/index.d.ts similarity index 100% rename from bingmaps/Microsoft.Maps.d.ts rename to bingmaps/index.d.ts diff --git a/bingmaps/tsconfig.json b/bingmaps/tsconfig.json new file mode 100644 index 0000000000..54cd61be88 --- /dev/null +++ b/bingmaps/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bingmaps-tests.ts" + ] +} \ No newline at end of file diff --git a/bip21/bip21-tests.ts b/bip21/bip21-tests.ts index e685eca102..ef200719a8 100644 --- a/bip21/bip21-tests.ts +++ b/bip21/bip21-tests.ts @@ -1,5 +1,4 @@ -/// - +import bip21 = require('bip21'); let decoded:any = bip21.decode('bitcoin:1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH?amount=20.3&label=Foobar'); let encoded:string = bip21.encode('1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH', { diff --git a/bip21/bip21.d.ts b/bip21/bip21.d.ts deleted file mode 100644 index 7dc6223164..0000000000 --- a/bip21/bip21.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Type definitions for bip21 v1.1.2 -// Project: https://github.com/bitcoinjs/bip21 -// Definitions by: Stefan Huber -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace bip21 { - export function decode(uri:string) : {address:string,amount?:number}; - export function encode(address:string,options?:any) : string; -} - -declare module "bip21" { - export = bip21; -} diff --git a/bip21/index.d.ts b/bip21/index.d.ts new file mode 100644 index 0000000000..06e61a6944 --- /dev/null +++ b/bip21/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for bip21 v1.1.2 +// Project: https://github.com/bitcoinjs/bip21 +// Definitions by: Stefan Huber +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace bip21 { + export function decode(uri:string) : {address:string,amount?:number}; + export function encode(address:string,options?:any) : string; +} + +export = bip21; diff --git a/bip21/tsconfig.json b/bip21/tsconfig.json new file mode 100644 index 0000000000..0fc323b52d --- /dev/null +++ b/bip21/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bip21-tests.ts" + ] +} \ No newline at end of file diff --git a/bitwise-xor/bitwise-xor-tests.ts b/bitwise-xor/bitwise-xor-tests.ts index e55670b85f..b19768f11f 100644 --- a/bitwise-xor/bitwise-xor-tests.ts +++ b/bitwise-xor/bitwise-xor-tests.ts @@ -1,5 +1,4 @@ -/// "use strict"; diff --git a/bitwise-xor/bitwise-xor.d.ts b/bitwise-xor/bitwise-xor.d.ts deleted file mode 100644 index 09f104b9af..0000000000 --- a/bitwise-xor/bitwise-xor.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Type definitions for bitwise-xor 0.0.0 -// Project: https://github.com/czzarr/node-bitwise-xor -// Definitions by: Rogier Schouten -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -declare module "bitwise-xor" { - - /** - * Bitwise XOR between two Buffers or Strings, returns a Buffer - */ - function xor(b1: Buffer, b2: Buffer): Buffer; - function xor(s1: string, s2: string): Buffer; - - export = xor; -} - diff --git a/bitwise-xor/index.d.ts b/bitwise-xor/index.d.ts new file mode 100644 index 0000000000..c0a129fa70 --- /dev/null +++ b/bitwise-xor/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for bitwise-xor 0.0.0 +// Project: https://github.com/czzarr/node-bitwise-xor +// Definitions by: Rogier Schouten +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +/** + * Bitwise XOR between two Buffers or Strings, returns a Buffer + */ +declare function xor(b1: Buffer, b2: Buffer): Buffer; +declare function xor(s1: string, s2: string): Buffer; + +export = xor; diff --git a/bitwise-xor/tsconfig.json b/bitwise-xor/tsconfig.json new file mode 100644 index 0000000000..5b7c28f898 --- /dev/null +++ b/bitwise-xor/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bitwise-xor-tests.ts" + ] +} \ No newline at end of file diff --git a/bl/bl-tests.ts b/bl/bl-tests.ts index b8435911de..084cf1925a 100644 --- a/bl/bl-tests.ts +++ b/bl/bl-tests.ts @@ -1,4 +1,3 @@ -/// import BufferList = require('bl'); diff --git a/bl/bl.d.ts b/bl/bl.d.ts deleted file mode 100644 index b3b97b3983..0000000000 --- a/bl/bl.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -// Type definitions for BufferList v0.8.0 -// Project: https://github.com/rvagg/bl -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'bl' { - import stream = require('stream'); - - class BufferList extends stream.Duplex { - new (callback?:(err:Error, buffer:Buffer) => void): void; - - append(buffer: Buffer):void; - get(index: number): number; - slice(start?: number, end?: number): Buffer; - copy(dest: Buffer, destStart?: number, srcStart?: number, srcEnd?: number): void; - duplicate(): BufferList; - consume(bytes?: number): void; - toString(encoding?: string, start?: number, end?: number): string; - length: number; - - readDoubleBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - } - - export = BufferList; -} diff --git a/bl/index.d.ts b/bl/index.d.ts new file mode 100644 index 0000000000..12bbf0bec5 --- /dev/null +++ b/bl/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for BufferList v0.8.0 +// Project: https://github.com/rvagg/bl +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import stream = require('stream'); + +declare class BufferList extends stream.Duplex { + new(callback?: (err: Error, buffer: Buffer) => void): void; + + append(buffer: Buffer): void; + get(index: number): number; + slice(start?: number, end?: number): Buffer; + copy(dest: Buffer, destStart?: number, srcStart?: number, srcEnd?: number): void; + duplicate(): BufferList; + consume(bytes?: number): void; + toString(encoding?: string, start?: number, end?: number): string; + length: number; + + readDoubleBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; +} + +export = BufferList; diff --git a/bl/tsconfig.json b/bl/tsconfig.json new file mode 100644 index 0000000000..da713a32d9 --- /dev/null +++ b/bl/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bl-tests.ts" + ] +} \ No newline at end of file diff --git a/blazy/blazy-tests.ts b/blazy/blazy-tests.ts index 6e95801e9e..835b0e6472 100644 --- a/blazy/blazy-tests.ts +++ b/blazy/blazy-tests.ts @@ -1,4 +1,4 @@ -/// + /* Constructor test */ var tester: BlazyInstance = new Blazy({ diff --git a/blazy/blazy.d.ts b/blazy/index.d.ts similarity index 100% rename from blazy/blazy.d.ts rename to blazy/index.d.ts diff --git a/blazy/tsconfig.json b/blazy/tsconfig.json new file mode 100644 index 0000000000..5f8097bb18 --- /dev/null +++ b/blazy/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "blazy-tests.ts" + ] +} \ No newline at end of file diff --git a/blissfuljs/blissfuljs-tests.ts b/blissfuljs/blissfuljs-tests.ts index 55085f00ae..1601ce9457 100644 --- a/blissfuljs/blissfuljs-tests.ts +++ b/blissfuljs/blissfuljs-tests.ts @@ -1,5 +1,3 @@ -/// - function test_overview() { /*Bliss includes several static methods (on the Bliss or $ object). For example, to copy all properties of an object onto another object, you would call $.extend():*/ diff --git a/blissfuljs/blissfuljs.d.ts b/blissfuljs/blissfuljs.d.ts deleted file mode 100644 index 9338929f16..0000000000 --- a/blissfuljs/blissfuljs.d.ts +++ /dev/null @@ -1,670 +0,0 @@ -// Type definitions for bliss -// Project: http://blissfuljs.com/ -// Definitions by: François Skorzec -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -interface Element { - _: BlissNS.BlissBindedElement; -} - -interface Array { - _: BlissNS.BlissBindedArray & BlissNS.BlissCollectionArray; -} - -declare namespace BlissNS { - export type BlissDecoratedElement = Element & T; - export type BlissDecoratedArrayElement = Array & BlissNS.BlissCollectionArray; - - interface BlissStatic { - (selector: string, context?: Element): BlissDecoratedElement; - - classProps: Object; - - create(tag: "a"): HTMLAnchorElement; - create(tag: "applet"): HTMLAppletElement; - create(tag: "area"):HTMLAreaElement; - create(tag: "audio"): HTMLAudioElement; - create(tag: "base"): HTMLBaseElement; - create(tag: "basefont"): HTMLBaseFontElement; - create(tag: "blockquote"): HTMLBlockElement; - create(tag: "body"): HTMLBodyElement; - create(tag: "br"): HTMLBRElement; - create(tag: "button"): HTMLButtonElement; - create(tag: "canvas"): HTMLCanvasElement; - create(tag: "datalist"): HTMLDataListElement; - create(tag: "dd"): HTMLDDElement; - create(tag: "directory"): HTMLDirectoryElement; - create(tag: "div"): HTMLDivElement; - create(tag: "embeded"): HTMLEmbedElement; - create(tag: "fieldset"): HTMLFieldSetElement; - create(tag: "form"): HTMLFormElement; - create(tag: "frame"): HTMLFrameElement; - create(tag: "frameset"): HTMLFrameSetElement; - create(tag: "iframe"): HTMLDListElement; - create(tag: "image"): HTMLImageElement; - create(tag: "input"): HTMLInputElement; - create(tag: "i"): HTMLLIElement; - create(tag: "label"): HTMLLabelElement; - create(tag: "legend"): HTMLLegendElement; - create(tag: "li"): HTMLLIElement; - create(tag: "link"): HTMLLinkElement; - create(tag: "map"): HTMLMapElement; - create(tag: "mark"): HTMLMarqueeElement; - create(tag: "menu"): HTMLMenuElement; - create(tag: "meta"): HTMLMetaElement; - create(tag: "object"): HTMLObjectElement; - create(tag: "ol"): HTMLOListElement; - create(tag: "optgroup"): HTMLOptGroupElement; - create(tag: "option"): HTMLOptionElement; - create(tag: "p"): HTMLParagraphElement; - create(tag: "param"): HTMLParamElement; - create(tag: "pre"): HTMLPreElement; - create(tag: "progress"): HTMLProgressElement; - create(tag: "q"): HTMLQuoteElement; - create(tag: "script"): HTMLScriptElement; - create(tag: "select"): HTMLSelectElement; - create(tag: "source"): HTMLSourceElement; - create(tag: "span"): HTMLSpanElement; - create(tag: "style"): HTMLStyleElement; - create(tag: "table"): HTMLTableElement; - create(tag: "thead"): HTMLTableHeaderCellElement; - create(tag: "ul"): HTMLUListElement; - create(tag: "video"): HTMLVideoElement; - create(tag: string): BlissDecoratedElement; - - create(options: Object): BlissDecoratedElement; - - create(tag: "a", options: Object): HTMLAnchorElement; - create(tag: "applet", options: Object): HTMLAppletElement; - create(tag: "area", options: Object): HTMLAreaElement; - create(tag: "audio", options: Object): HTMLAudioElement; - create(tag: "base", options: Object): HTMLBaseElement; - create(tag: "basefont", options: Object): HTMLBaseFontElement; - create(tag: "blockquote", options: Object): HTMLBlockElement; - create(tag: "body", options: Object): HTMLBodyElement; - create(tag: "br", options: Object): HTMLBRElement; - create(tag: "button", options: Object): HTMLButtonElement; - create(tag: "canvas", options: Object): HTMLCanvasElement; - create(tag: "datalist", options: Object): HTMLDataListElement; - create(tag: "dd", options: Object): HTMLDDElement; - create(tag: "directory", options: Object): HTMLDirectoryElement; - create(tag: "div", options: Object): HTMLDivElement; - create(tag: "embeded", options: Object): HTMLEmbedElement; - create(tag: "fieldset", options: Object): HTMLFieldSetElement; - create(tag: "form", options: Object): HTMLFormElement; - create(tag: "frame", options: Object): HTMLFrameElement; - create(tag: "frameset", options: Object): HTMLFrameSetElement; - create(tag: "iframe", options: Object): HTMLDListElement; - create(tag: "image", options: Object): HTMLImageElement; - create(tag: "input", options: Object): HTMLInputElement; - create(tag: "i", options: Object): HTMLLIElement; - create(tag: "label", options: Object): HTMLLabelElement; - create(tag: "legend", options: Object): HTMLLegendElement; - create(tag: "li", options: Object): HTMLLIElement; - create(tag: "link", options: Object): HTMLLinkElement; - create(tag: "map", options: Object): HTMLMapElement; - create(tag: "mark", options: Object): HTMLMarqueeElement; - create(tag: "menu", options: Object): HTMLMenuElement; - create(tag: "meta", options: Object): HTMLMetaElement; - create(tag: "object", options: Object): HTMLObjectElement; - create(tag: "ol", options: Object): HTMLOListElement; - create(tag: "optgroup", options: Object): HTMLOptGroupElement; - create(tag: "option", options: Object): HTMLOptionElement; - create(tag: "p", options: Object): HTMLParagraphElement; - create(tag: "param", options: Object): HTMLParamElement; - create(tag: "pre", options: Object): HTMLPreElement; - create(tag: "progress", options: Object): HTMLProgressElement; - create(tag: "q", options: Object): HTMLQuoteElement; - create(tag: "script", options: Object): HTMLScriptElement; - create(tag: "select", options: Object): HTMLSelectElement; - create(tag: "source", options: Object): HTMLSourceElement; - create(tag: "span", options: Object): HTMLSpanElement; - create(tag: "style", options: Object): HTMLStyleElement; - create(tag: "table", options: Object): HTMLTableElement; - create(tag: "thead", options: Object): HTMLTableHeaderCellElement; - create(tag: "ul", options: Object): HTMLUListElement; - create(tag: "video", options: Object): HTMLVideoElement; - create(tag: string, options: Object): BlissDecoratedElement; - - create(...args:any[]): BlissDecoratedElement; - - set(subject: BlissDecoratedElement, options: Object): BlissDecoratedElement; - contents(subject: BlissDecoratedElement , elements: Object | Array | string | Number | Node): BlissDecoratedElement; - contents(subject: BlissDecoratedElement[], elements: Object | Array | string | Number | Node): BlissDecoratedElement[]; - clone(subject:BlissDecoratedElement) : BlissDecoratedElement; - after(subject:BlissDecoratedElement, element: Element) : BlissDecoratedElement; - around(subject:BlissDecoratedElement, element: Element) : BlissDecoratedElement; - attributes(subject:BlissDecoratedElement, attrs: Object) : BlissDecoratedElement; - attributes(subject:BlissDecoratedElement[], attrs: Object) : BlissDecoratedElement[]; - before(subject:BlissDecoratedElement, element: Element) : BlissDecoratedElement; - inside(subject:BlissDecoratedElement, element: Element) : BlissDecoratedElement; - properties(subject:BlissDecoratedElement, props: Object) : BlissDecoratedElement; - properties(subject:BlissDecoratedElement[], props: Object) : BlissDecoratedElement[]; - start(subject:BlissDecoratedElement, element: Element) : BlissDecoratedElement; - style(subject:BlissDecoratedElement, properties: Object) : BlissDecoratedElement; - style(subject:BlissDecoratedElement[], properties: Object) : BlissDecoratedElement[]; - transition(subject:BlissDecoratedElement | BlissDecoratedElement[], properties: Object, duration?: number) : Promise; - delegate(subject:BlissDecoratedElement , type: string, selector: string, callback: (event: Event) => void): BlissDecoratedElement; - delegate(subject: BlissDecoratedElement[], type: string, selector: string, callback: (event: Event) => void): BlissDecoratedElement[]; - delegate(subject:BlissDecoratedElement , type: string, selectorsToCallbacks: {[selector: string] : (event: Event) => void}): BlissDecoratedElement; - delegate(subject:BlissDecoratedElement[], type: string, selectorsToCallbacks: {[selector: string] : (event: Event) => void}): BlissDecoratedElement[]; - delegate(subject:BlissDecoratedElement , typesToSelectorsToCallbacks: {[type: string] : {[selector: string] : (event: Event) => void}}): BlissDecoratedElement; - delegate(subject:BlissDecoratedElement[], typesToSelectorsToCallbacks: {[type: string] : {[selector: string] : (event: Event) => void}}): BlissDecoratedElement[]; - events(subject:BlissDecoratedElement , handlers: {[eventName:string] : (event: Event) => void} | Element): BlissDecoratedElement; - events(subject: BlissDecoratedElement[], handlers: {[eventName:string] : (event: Event) => void} | Element): BlissDecoratedElement[]; - fire(subject:BlissDecoratedElement, type: string, properties?: {[propertyName: string] : any}): BlissDecoratedElement; - fire(subject:BlissDecoratedElement[], type: string, properties?: {[propertyName: string] : any}): BlissDecoratedElement[]; - once(subject:BlissDecoratedElement, handlers: {[eventName:string] : (event: Event) => void} | Element): BlissDecoratedElement; - once(subject:BlissDecoratedElement[], handlers: {[eventName:string] : (event: Event) => void} | Element): BlissDecoratedElement[]; - ready(context?: Document): Promise; - - remove(subject:Element | BlissStatic): void; - - all(array: Array, method: string, ...args: Array): Array; - all(array: Array, method: string, ...args: Array): Array; - - Class(options: { - constructor?: Function; - extends?: Function; - abstract?: boolean; - lazy?: Object; - live?: Object; - static?: Object; - [propertyName: string]:any; - }): T; - - Class(options: { - constructor?: Function; - extends?: Function; - abstract?: boolean; - lazy?: Object; - live?: Object; - static?: Object; - [propertyName: string]:any; - }): Object; - - each(obj: {[propertyName: string] : any}, callback: Function, ret?: Object): T; - each(obj: {[propertyName: string] : any}, callback: Function, ret?: Object): Object; - - extend(target: Object, source: any, whitelist? : string[] | string | Function | RegExp): Object; - extend(target: Object, source: any, whitelist? : string[] | string | Function | RegExp): T; - - lazy(object: Object, property: string, getter: () => any): Object; - lazy(object:Object, property: string, getter:() => any): T; - - lazy(object: Object, properties: {[propertyName:string]: () => any}): Object; - lazy(object: Object, properties: {[propertyName:string]: () => any}): T; - - live(object: Object, property: string, descriptor: Object | Function): Object; - live(object: Object, property: string, descriptor: Object | Function): T; - - live(object: Object, properties: {[propertyName: string]: Object | Function}): Object; - live(object: Object, properties: {[propertyName: string]: Object | Function}): T; - - type(object: Object): string; - - value(obj: Object, ...properties: string[]): any; - value(obj: Object, ...properties: string[]): T; - - value(property: string, ...properties: string[]): any; - value(property: string , ...properties: string[]): T; - - fetch(url: string, options?: { - method?: string; - data?: string; - headers?:{[key:string]:string}; - - onreadystatechange?: (ev: ProgressEvent) => any; - readyState?: number; - response?: any; - responseBody?: any; - responseText?: string; - responseType?: string; - responseXML?: any; - status?: number; - statusText?: string; - timeout?: number; - upload?: XMLHttpRequestUpload; - withCredentials?: boolean; - - [propertyName: string]: any; - }): Promise; - - include(condition: any, url: string ): Promise; - include(url: string ): Promise; - - add(name: string, callback: Function, on?: BlissStatic | BlissStaticCollection | Element | Array): void; - add(callbacks:{[callbackName: string]: Function}, on?: BlissStatic | BlissStaticCollection | Element | Array): void; - - hooks: { - add(name: string, callback: Function): void; - run(name: string, env: Object): void; - }; - - $: BlissStaticCollection; - } - - interface BlissStaticCollection extends BlissStatic { - (selector: string, context?: Element): BlissDecoratedArrayElement; - (expr: Object, context?: Element): Array; - (expr: Window, context?: Element): [Window]; - (expr: Node, context?: Element): [Node]; - } - - // Native methods added into "_" property, but methods that return "void" now return thi stype in order to be chainables - // Methods are All HTMLElement a ELement methods - interface BlissNativeExtentions { - blur(): T; - click(): T; - contains(child: HTMLElement): boolean; - dragDrop(): boolean; - focus(): T; - insertAdjacentElement(position: string, insertedElement: Element): Element; - insertAdjacentHTML(where: string, html: string): T; - insertAdjacentText(where: string, text: string): T; - msGetInputContext(): MSInputMethodContext; - scrollIntoView(top?: boolean): T; - setActive(): T; - addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): T; - addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): T; - addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): T; - addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): T; - addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): T; - addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): T; - addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; - addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): T; - addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; - addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): T; - addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): T; - addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): T; - addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): T; - addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): T; - addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): T; - addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; - addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; - addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; - addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; - addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; - addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; - addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; - addEventListener(type: "mousewheel", listener: (ev: MouseWheelEvent) => any, useCapture?: boolean): T; - addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): T; - addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): T; - addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): T; - addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; - addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; - addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; - addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; - addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): T; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): T; - getAttribute(name?: string): string; - getAttributeNS(namespaceURI: string, localName: string): string; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; - getElementsByTagName(name: "a"): NodeListOf; - getElementsByTagName(name: "abbr"): NodeListOf; - getElementsByTagName(name: "acronym"): NodeListOf; - getElementsByTagName(name: "address"): NodeListOf; - getElementsByTagName(name: "applet"): NodeListOf; - getElementsByTagName(name: "area"): NodeListOf; - getElementsByTagName(name: "article"): NodeListOf; - getElementsByTagName(name: "aside"): NodeListOf; - getElementsByTagName(name: "audio"): NodeListOf; - getElementsByTagName(name: "b"): NodeListOf; - getElementsByTagName(name: "base"): NodeListOf; - getElementsByTagName(name: "basefont"): NodeListOf; - getElementsByTagName(name: "bdo"): NodeListOf; - getElementsByTagName(name: "big"): NodeListOf; - getElementsByTagName(name: "blockquote"): NodeListOf; - getElementsByTagName(name: "body"): NodeListOf; - getElementsByTagName(name: "br"): NodeListOf; - getElementsByTagName(name: "button"): NodeListOf; - getElementsByTagName(name: "canvas"): NodeListOf; - getElementsByTagName(name: "caption"): NodeListOf; - getElementsByTagName(name: "center"): NodeListOf; - getElementsByTagName(name: "circle"): NodeListOf; - getElementsByTagName(name: "cite"): NodeListOf; - getElementsByTagName(name: "clippath"): NodeListOf; - getElementsByTagName(name: "code"): NodeListOf; - getElementsByTagName(name: "col"): NodeListOf; - getElementsByTagName(name: "colgroup"): NodeListOf; - getElementsByTagName(name: "datalist"): NodeListOf; - getElementsByTagName(name: "dd"): NodeListOf; - getElementsByTagName(name: "defs"): NodeListOf; - getElementsByTagName(name: "del"): NodeListOf; - getElementsByTagName(name: "desc"): NodeListOf; - getElementsByTagName(name: "dfn"): NodeListOf; - getElementsByTagName(name: "dir"): NodeListOf; - getElementsByTagName(name: "div"): NodeListOf; - getElementsByTagName(name: "dl"): NodeListOf; - getElementsByTagName(name: "dt"): NodeListOf; - getElementsByTagName(name: "ellipse"): NodeListOf; - getElementsByTagName(name: "em"): NodeListOf; - getElementsByTagName(name: "embed"): NodeListOf; - getElementsByTagName(name: "feblend"): NodeListOf; - getElementsByTagName(name: "fecolormatrix"): NodeListOf; - getElementsByTagName(name: "fecomponenttransfer"): NodeListOf; - getElementsByTagName(name: "fecomposite"): NodeListOf; - getElementsByTagName(name: "feconvolvematrix"): NodeListOf; - getElementsByTagName(name: "fediffuselighting"): NodeListOf; - getElementsByTagName(name: "fedisplacementmap"): NodeListOf; - getElementsByTagName(name: "fedistantlight"): NodeListOf; - getElementsByTagName(name: "feflood"): NodeListOf; - getElementsByTagName(name: "fefunca"): NodeListOf; - getElementsByTagName(name: "fefuncb"): NodeListOf; - getElementsByTagName(name: "fefuncg"): NodeListOf; - getElementsByTagName(name: "fefuncr"): NodeListOf; - getElementsByTagName(name: "fegaussianblur"): NodeListOf; - getElementsByTagName(name: "feimage"): NodeListOf; - getElementsByTagName(name: "femerge"): NodeListOf; - getElementsByTagName(name: "femergenode"): NodeListOf; - getElementsByTagName(name: "femorphology"): NodeListOf; - getElementsByTagName(name: "feoffset"): NodeListOf; - getElementsByTagName(name: "fepointlight"): NodeListOf; - getElementsByTagName(name: "fespecularlighting"): NodeListOf; - getElementsByTagName(name: "fespotlight"): NodeListOf; - getElementsByTagName(name: "fetile"): NodeListOf; - getElementsByTagName(name: "feturbulence"): NodeListOf; - getElementsByTagName(name: "fieldset"): NodeListOf; - getElementsByTagName(name: "figcaption"): NodeListOf; - getElementsByTagName(name: "figure"): NodeListOf; - getElementsByTagName(name: "filter"): NodeListOf; - getElementsByTagName(name: "font"): NodeListOf; - getElementsByTagName(name: "footer"): NodeListOf; - getElementsByTagName(name: "foreignobject"): NodeListOf; - getElementsByTagName(name: "form"): NodeListOf; - getElementsByTagName(name: "frame"): NodeListOf; - getElementsByTagName(name: "frameset"): NodeListOf; - getElementsByTagName(name: "g"): NodeListOf; - getElementsByTagName(name: "h1"): NodeListOf; - getElementsByTagName(name: "h2"): NodeListOf; - getElementsByTagName(name: "h3"): NodeListOf; - getElementsByTagName(name: "h4"): NodeListOf; - getElementsByTagName(name: "h5"): NodeListOf; - getElementsByTagName(name: "h6"): NodeListOf; - getElementsByTagName(name: "head"): NodeListOf; - getElementsByTagName(name: "header"): NodeListOf; - getElementsByTagName(name: "hgroup"): NodeListOf; - getElementsByTagName(name: "hr"): NodeListOf; - getElementsByTagName(name: "html"): NodeListOf; - getElementsByTagName(name: "i"): NodeListOf; - getElementsByTagName(name: "iframe"): NodeListOf; - getElementsByTagName(name: "image"): NodeListOf; - getElementsByTagName(name: "img"): NodeListOf; - getElementsByTagName(name: "input"): NodeListOf; - getElementsByTagName(name: "ins"): NodeListOf; - getElementsByTagName(name: "isindex"): NodeListOf; - getElementsByTagName(name: "kbd"): NodeListOf; - getElementsByTagName(name: "keygen"): NodeListOf; - getElementsByTagName(name: "label"): NodeListOf; - getElementsByTagName(name: "legend"): NodeListOf; - getElementsByTagName(name: "li"): NodeListOf; - getElementsByTagName(name: "line"): NodeListOf; - getElementsByTagName(name: "lineargradient"): NodeListOf; - getElementsByTagName(name: "link"): NodeListOf; - getElementsByTagName(name: "listing"): NodeListOf; - getElementsByTagName(name: "map"): NodeListOf; - getElementsByTagName(name: "mark"): NodeListOf; - getElementsByTagName(name: "marker"): NodeListOf; - getElementsByTagName(name: "marquee"): NodeListOf; - getElementsByTagName(name: "mask"): NodeListOf; - getElementsByTagName(name: "menu"): NodeListOf; - getElementsByTagName(name: "meta"): NodeListOf; - getElementsByTagName(name: "metadata"): NodeListOf; - getElementsByTagName(name: "nav"): NodeListOf; - getElementsByTagName(name: "nextid"): NodeListOf; - getElementsByTagName(name: "nobr"): NodeListOf; - getElementsByTagName(name: "noframes"): NodeListOf; - getElementsByTagName(name: "noscript"): NodeListOf; - getElementsByTagName(name: "object"): NodeListOf; - getElementsByTagName(name: "ol"): NodeListOf; - getElementsByTagName(name: "optgroup"): NodeListOf; - getElementsByTagName(name: "option"): NodeListOf; - getElementsByTagName(name: "p"): NodeListOf; - getElementsByTagName(name: "param"): NodeListOf; - getElementsByTagName(name: "path"): NodeListOf; - getElementsByTagName(name: "pattern"): NodeListOf; - getElementsByTagName(name: "plaintext"): NodeListOf; - getElementsByTagName(name: "polygon"): NodeListOf; - getElementsByTagName(name: "polyline"): NodeListOf; - getElementsByTagName(name: "pre"): NodeListOf; - getElementsByTagName(name: "progress"): NodeListOf; - getElementsByTagName(name: "q"): NodeListOf; - getElementsByTagName(name: "radialgradient"): NodeListOf; - getElementsByTagName(name: "rect"): NodeListOf; - getElementsByTagName(name: "rt"): NodeListOf; - getElementsByTagName(name: "ruby"): NodeListOf; - getElementsByTagName(name: "s"): NodeListOf; - getElementsByTagName(name: "samp"): NodeListOf; - getElementsByTagName(name: "script"): NodeListOf; - getElementsByTagName(name: "section"): NodeListOf; - getElementsByTagName(name: "select"): NodeListOf; - getElementsByTagName(name: "small"): NodeListOf; - getElementsByTagName(name: "source"): NodeListOf; - getElementsByTagName(name: "span"): NodeListOf; - getElementsByTagName(name: "stop"): NodeListOf; - getElementsByTagName(name: "strike"): NodeListOf; - getElementsByTagName(name: "strong"): NodeListOf; - getElementsByTagName(name: "style"): NodeListOf; - getElementsByTagName(name: "sub"): NodeListOf; - getElementsByTagName(name: "sup"): NodeListOf; - getElementsByTagName(name: "svg"): NodeListOf; - getElementsByTagName(name: "switch"): NodeListOf; - getElementsByTagName(name: "symbol"): NodeListOf; - getElementsByTagName(name: "table"): NodeListOf; - getElementsByTagName(name: "tbody"): NodeListOf; - getElementsByTagName(name: "td"): NodeListOf; - getElementsByTagName(name: "text"): NodeListOf; - getElementsByTagName(name: "textpath"): NodeListOf; - getElementsByTagName(name: "textarea"): NodeListOf; - getElementsByTagName(name: "tfoot"): NodeListOf; - getElementsByTagName(name: "th"): NodeListOf; - getElementsByTagName(name: "thead"): NodeListOf; - getElementsByTagName(name: "title"): NodeListOf; - getElementsByTagName(name: "tr"): NodeListOf; - getElementsByTagName(name: "track"): NodeListOf; - getElementsByTagName(name: "tspan"): NodeListOf; - getElementsByTagName(name: "tt"): NodeListOf; - getElementsByTagName(name: "u"): NodeListOf; - getElementsByTagName(name: "ul"): NodeListOf; - getElementsByTagName(name: "use"): NodeListOf; - getElementsByTagName(name: "var"): NodeListOf; - getElementsByTagName(name: "video"): NodeListOf; - getElementsByTagName(name: "view"): NodeListOf; - getElementsByTagName(name: "wbr"): NodeListOf; - getElementsByTagName(name: "x-ms-webview"): NodeListOf; - getElementsByTagName(name: "xmp"): NodeListOf; - getElementsByTagName(name: string): NodeListOf; - getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf; - hasAttribute(name: string): boolean; - hasAttributeNS(namespaceURI: string, localName: string): boolean; - msGetRegionContent(): MSRangeCollection; - msGetUntransformedBounds(): ClientRect; - msMatchesSelector(selectors: string): boolean; - msReleasePointerCapture(pointerId: number): T; - msSetPointerCapture(pointerId: number): T; - msZoomTo(args: MsZoomToOptions): T; - releasePointerCapture(pointerId: number): T; - removeAttribute(name?: string): T; - removeAttributeNS(namespaceURI: string, localName: string): T; - removeAttributeNode(oldAttr: Attr): Attr; - requestFullscreen(): T; - requestPointerLock(): T; - setAttribute(name?: string, value?: string): T; - setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): T; - setAttributeNode(newAttr: Attr): Attr; - setAttributeNodeNS(newAttr: Attr): Attr; - setPointerCapture(pointerId: number): T; - webkitMatchesSelector(selectors: string): boolean; - webkitRequestFullScreen(): T; - webkitRequestFullscreen(): T; - getElementsByClassName(classNames: string): NodeListOf; - addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): T; - addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): T; - addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; - addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; - addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; - addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; - addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; - addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): T; - addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): T; - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): T; - } - - interface BlissBindedElement extends BlissNativeExtentions { - set(options: Object): BlissDecoratedElement - contents(elements: Object | Array | string | Number | Node): BlissDecoratedElement - clone(): BlissDecoratedElement; - after(element:Element) : BlissDecoratedElement; - around(element:Element) : BlissDecoratedElement; - attributes(attrs: Object) : BlissDecoratedElement; - before(element:Element) : BlissDecoratedElement; - inside(element:Element) : BlissDecoratedElement; - properties(props: Object) : BlissDecoratedElement; - start(element:Element) : BlissDecoratedElement; - style(properties: Object) : BlissDecoratedElement; - transition(properties: Object, duration?: number) : Promise; - delegate(type: string, selector: string, callback: (event: Event) => void): BlissDecoratedElement; - delegate(type: string, selectorsToCallbacks: {[selector: string] : (event: Event) => void}): BlissDecoratedElement; - delegate(typesToSelectorsToCallbacks: {[type: string] : {[selector: string] : (event: Event) => void}}): BlissDecoratedElement; - events(handlers: {[eventName:string] : (event: Event) => void} | Element): BlissDecoratedElement; - fire(type: string, properties?: {[propertyName: string] : any}): BlissDecoratedElement; - once(handlers: {[eventName:string] : (event: Event) => void} | Element): BlissDecoratedElement; - - remove(): BlissDecoratedElement; - } - - interface BlissBindedArray { - all(method: string, ...args: Array): Array; - all(method: string, ...args: Array): Array; - } - - interface BlissCollectionArray { - set(options: Object): BlissCollectionArray - contents(elements: Object | Array | string | Number | Node): BlissCollectionArray - clone(): BlissCollectionArray; - after(element:Element) : BlissCollectionArray; - around(element:Element) : BlissCollectionArray; - attributes(attrs: Object) : BlissCollectionArray; - before(element:Element) : BlissCollectionArray; - inside(element:Element) : BlissCollectionArray; - properties(props: Object) : BlissCollectionArray; - start(element:Element) : BlissCollectionArray; - style(properties: Object) : BlissCollectionArray; - transition(properties: Object, duration?: number) : Promise[]; - delegate(type: string, selector: string, callback: (event: Event) => void): BlissCollectionArray; - delegate(type: string, selectorsToCallbacks: {[selector: string] : (event: Event) => void}): BlissCollectionArray; - delegate(typesToSelectorsToCallbacks: {[type: string] : {[selector: string] : (event: Event) => void}}): BlissCollectionArray; - events(handlers: {[eventName:string] : (event: Event) => void} | Element): BlissCollectionArray; - fire(type: string, properties?: {[propertyName: string] : any}): BlissCollectionArray; - once(handlers: {[eventName:string] : (event: Event) => void} | Element): BlissCollectionArray; - - addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): BlissCollectionArray; - - remove(): BlissCollectionArray; - } -} - -declare var Bliss: BlissNS.BlissStatic; -declare var $: BlissNS.BlissStatic; -declare var $$: BlissNS.BlissStaticCollection; diff --git a/blissfuljs/index.d.ts b/blissfuljs/index.d.ts new file mode 100644 index 0000000000..76061c1391 --- /dev/null +++ b/blissfuljs/index.d.ts @@ -0,0 +1,670 @@ +// Type definitions for bliss +// Project: http://blissfuljs.com/ +// Definitions by: François Skorzec +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Element { + _: BlissNS.BlissBindedElement; +} + +interface Array { + _: BlissNS.BlissBindedArray & BlissNS.BlissCollectionArray; +} + +declare namespace BlissNS { + export type BlissDecoratedElement = Element & T; + export type BlissDecoratedArrayElement = Array & BlissNS.BlissCollectionArray; + + interface BlissStatic { + (selector: string, context?: Element): BlissDecoratedElement; + + classProps: Object; + + create(tag: "a"): HTMLAnchorElement; + create(tag: "applet"): HTMLAppletElement; + create(tag: "area"):HTMLAreaElement; + create(tag: "audio"): HTMLAudioElement; + create(tag: "base"): HTMLBaseElement; + create(tag: "basefont"): HTMLBaseFontElement; + create(tag: "blockquote"): HTMLQuoteElement; + create(tag: "body"): HTMLBodyElement; + create(tag: "br"): HTMLBRElement; + create(tag: "button"): HTMLButtonElement; + create(tag: "canvas"): HTMLCanvasElement; + create(tag: "datalist"): HTMLDataListElement; + create(tag: "dd"): HTMLElement; + create(tag: "directory"): HTMLDirectoryElement; + create(tag: "div"): HTMLDivElement; + create(tag: "embeded"): HTMLEmbedElement; + create(tag: "fieldset"): HTMLFieldSetElement; + create(tag: "form"): HTMLFormElement; + create(tag: "frame"): HTMLFrameElement; + create(tag: "frameset"): HTMLFrameSetElement; + create(tag: "iframe"): HTMLDListElement; + create(tag: "image"): HTMLImageElement; + create(tag: "input"): HTMLInputElement; + create(tag: "i"): HTMLLIElement; + create(tag: "label"): HTMLLabelElement; + create(tag: "legend"): HTMLLegendElement; + create(tag: "li"): HTMLLIElement; + create(tag: "link"): HTMLLinkElement; + create(tag: "map"): HTMLMapElement; + create(tag: "mark"): HTMLMarqueeElement; + create(tag: "menu"): HTMLMenuElement; + create(tag: "meta"): HTMLMetaElement; + create(tag: "object"): HTMLObjectElement; + create(tag: "ol"): HTMLOListElement; + create(tag: "optgroup"): HTMLOptGroupElement; + create(tag: "option"): HTMLOptionElement; + create(tag: "p"): HTMLParagraphElement; + create(tag: "param"): HTMLParamElement; + create(tag: "pre"): HTMLPreElement; + create(tag: "progress"): HTMLProgressElement; + create(tag: "q"): HTMLQuoteElement; + create(tag: "script"): HTMLScriptElement; + create(tag: "select"): HTMLSelectElement; + create(tag: "source"): HTMLSourceElement; + create(tag: "span"): HTMLSpanElement; + create(tag: "style"): HTMLStyleElement; + create(tag: "table"): HTMLTableElement; + create(tag: "thead"): HTMLTableHeaderCellElement; + create(tag: "ul"): HTMLUListElement; + create(tag: "video"): HTMLVideoElement; + create(tag: string): BlissDecoratedElement; + + create(options: Object): BlissDecoratedElement; + + create(tag: "a", options: Object): HTMLAnchorElement; + create(tag: "applet", options: Object): HTMLAppletElement; + create(tag: "area", options: Object): HTMLAreaElement; + create(tag: "audio", options: Object): HTMLAudioElement; + create(tag: "base", options: Object): HTMLBaseElement; + create(tag: "basefont", options: Object): HTMLBaseFontElement; + create(tag: "blockquote", options: Object): HTMLQuoteElement; + create(tag: "body", options: Object): HTMLBodyElement; + create(tag: "br", options: Object): HTMLBRElement; + create(tag: "button", options: Object): HTMLButtonElement; + create(tag: "canvas", options: Object): HTMLCanvasElement; + create(tag: "datalist", options: Object): HTMLDataListElement; + create(tag: "dd", options: Object): HTMLElement; + create(tag: "directory", options: Object): HTMLDirectoryElement; + create(tag: "div", options: Object): HTMLDivElement; + create(tag: "embeded", options: Object): HTMLEmbedElement; + create(tag: "fieldset", options: Object): HTMLFieldSetElement; + create(tag: "form", options: Object): HTMLFormElement; + create(tag: "frame", options: Object): HTMLFrameElement; + create(tag: "frameset", options: Object): HTMLFrameSetElement; + create(tag: "iframe", options: Object): HTMLDListElement; + create(tag: "image", options: Object): HTMLImageElement; + create(tag: "input", options: Object): HTMLInputElement; + create(tag: "i", options: Object): HTMLLIElement; + create(tag: "label", options: Object): HTMLLabelElement; + create(tag: "legend", options: Object): HTMLLegendElement; + create(tag: "li", options: Object): HTMLLIElement; + create(tag: "link", options: Object): HTMLLinkElement; + create(tag: "map", options: Object): HTMLMapElement; + create(tag: "mark", options: Object): HTMLMarqueeElement; + create(tag: "menu", options: Object): HTMLMenuElement; + create(tag: "meta", options: Object): HTMLMetaElement; + create(tag: "object", options: Object): HTMLObjectElement; + create(tag: "ol", options: Object): HTMLOListElement; + create(tag: "optgroup", options: Object): HTMLOptGroupElement; + create(tag: "option", options: Object): HTMLOptionElement; + create(tag: "p", options: Object): HTMLParagraphElement; + create(tag: "param", options: Object): HTMLParamElement; + create(tag: "pre", options: Object): HTMLPreElement; + create(tag: "progress", options: Object): HTMLProgressElement; + create(tag: "q", options: Object): HTMLQuoteElement; + create(tag: "script", options: Object): HTMLScriptElement; + create(tag: "select", options: Object): HTMLSelectElement; + create(tag: "source", options: Object): HTMLSourceElement; + create(tag: "span", options: Object): HTMLSpanElement; + create(tag: "style", options: Object): HTMLStyleElement; + create(tag: "table", options: Object): HTMLTableElement; + create(tag: "thead", options: Object): HTMLTableHeaderCellElement; + create(tag: "ul", options: Object): HTMLUListElement; + create(tag: "video", options: Object): HTMLVideoElement; + create(tag: string, options: Object): BlissDecoratedElement; + + create(...args:any[]): BlissDecoratedElement; + + set(subject: BlissDecoratedElement, options: Object): BlissDecoratedElement; + contents(subject: BlissDecoratedElement , elements: Object | Array | string | Number | Node): BlissDecoratedElement; + contents(subject: BlissDecoratedElement[], elements: Object | Array | string | Number | Node): BlissDecoratedElement[]; + clone(subject:BlissDecoratedElement) : BlissDecoratedElement; + after(subject:BlissDecoratedElement, element: Element) : BlissDecoratedElement; + around(subject:BlissDecoratedElement, element: Element) : BlissDecoratedElement; + attributes(subject:BlissDecoratedElement, attrs: Object) : BlissDecoratedElement; + attributes(subject:BlissDecoratedElement[], attrs: Object) : BlissDecoratedElement[]; + before(subject:BlissDecoratedElement, element: Element) : BlissDecoratedElement; + inside(subject:BlissDecoratedElement, element: Element) : BlissDecoratedElement; + properties(subject:BlissDecoratedElement, props: Object) : BlissDecoratedElement; + properties(subject:BlissDecoratedElement[], props: Object) : BlissDecoratedElement[]; + start(subject:BlissDecoratedElement, element: Element) : BlissDecoratedElement; + style(subject:BlissDecoratedElement, properties: Object) : BlissDecoratedElement; + style(subject:BlissDecoratedElement[], properties: Object) : BlissDecoratedElement[]; + transition(subject:BlissDecoratedElement | BlissDecoratedElement[], properties: Object, duration?: number) : Promise; + delegate(subject:BlissDecoratedElement , type: string, selector: string, callback: (event: Event) => void): BlissDecoratedElement; + delegate(subject: BlissDecoratedElement[], type: string, selector: string, callback: (event: Event) => void): BlissDecoratedElement[]; + delegate(subject:BlissDecoratedElement , type: string, selectorsToCallbacks: {[selector: string] : (event: Event) => void}): BlissDecoratedElement; + delegate(subject:BlissDecoratedElement[], type: string, selectorsToCallbacks: {[selector: string] : (event: Event) => void}): BlissDecoratedElement[]; + delegate(subject:BlissDecoratedElement , typesToSelectorsToCallbacks: {[type: string] : {[selector: string] : (event: Event) => void}}): BlissDecoratedElement; + delegate(subject:BlissDecoratedElement[], typesToSelectorsToCallbacks: {[type: string] : {[selector: string] : (event: Event) => void}}): BlissDecoratedElement[]; + events(subject:BlissDecoratedElement , handlers: {[eventName:string] : (event: Event) => void} | Element): BlissDecoratedElement; + events(subject: BlissDecoratedElement[], handlers: {[eventName:string] : (event: Event) => void} | Element): BlissDecoratedElement[]; + fire(subject:BlissDecoratedElement, type: string, properties?: {[propertyName: string] : any}): BlissDecoratedElement; + fire(subject:BlissDecoratedElement[], type: string, properties?: {[propertyName: string] : any}): BlissDecoratedElement[]; + once(subject:BlissDecoratedElement, handlers: {[eventName:string] : (event: Event) => void} | Element): BlissDecoratedElement; + once(subject:BlissDecoratedElement[], handlers: {[eventName:string] : (event: Event) => void} | Element): BlissDecoratedElement[]; + ready(context?: Document): Promise; + + remove(subject:Element | BlissStatic): void; + + all(array: Array, method: string, ...args: Array): Array; + all(array: Array, method: string, ...args: Array): Array; + + Class(options: { + constructor?: Function; + extends?: Function; + abstract?: boolean; + lazy?: Object; + live?: Object; + static?: Object; + [propertyName: string]:any; + }): T; + + Class(options: { + constructor?: Function; + extends?: Function; + abstract?: boolean; + lazy?: Object; + live?: Object; + static?: Object; + [propertyName: string]:any; + }): Object; + + each(obj: {[propertyName: string] : any}, callback: Function, ret?: Object): T; + each(obj: {[propertyName: string] : any}, callback: Function, ret?: Object): Object; + + extend(target: Object, source: any, whitelist? : string[] | string | Function | RegExp): Object; + extend(target: Object, source: any, whitelist? : string[] | string | Function | RegExp): T; + + lazy(object: Object, property: string, getter: () => any): Object; + lazy(object:Object, property: string, getter:() => any): T; + + lazy(object: Object, properties: {[propertyName:string]: () => any}): Object; + lazy(object: Object, properties: {[propertyName:string]: () => any}): T; + + live(object: Object, property: string, descriptor: Object | Function): Object; + live(object: Object, property: string, descriptor: Object | Function): T; + + live(object: Object, properties: {[propertyName: string]: Object | Function}): Object; + live(object: Object, properties: {[propertyName: string]: Object | Function}): T; + + type(object: Object): string; + + value(obj: Object, ...properties: string[]): any; + value(obj: Object, ...properties: string[]): T; + + value(property: string, ...properties: string[]): any; + value(property: string , ...properties: string[]): T; + + fetch(url: string, options?: { + method?: string; + data?: string; + headers?:{[key:string]:string}; + + onreadystatechange?: (ev: ProgressEvent) => any; + readyState?: number; + response?: any; + responseBody?: any; + responseText?: string; + responseType?: string; + responseXML?: any; + status?: number; + statusText?: string; + timeout?: number; + upload?: XMLHttpRequestUpload; + withCredentials?: boolean; + + [propertyName: string]: any; + }): Promise; + + include(condition: any, url: string ): Promise; + include(url: string ): Promise; + + add(name: string, callback: Function, on?: BlissStatic | BlissStaticCollection | Element | Array): void; + add(callbacks:{[callbackName: string]: Function}, on?: BlissStatic | BlissStaticCollection | Element | Array): void; + + hooks: { + add(name: string, callback: Function): void; + run(name: string, env: Object): void; + }; + + $: BlissStaticCollection; + } + + interface BlissStaticCollection extends BlissStatic { + (selector: string, context?: Element): BlissDecoratedArrayElement; + (expr: Object, context?: Element): Array; + (expr: Window, context?: Element): [Window]; + (expr: Node, context?: Element): [Node]; + } + + // Native methods added into "_" property, but methods that return "void" now return thi stype in order to be chainables + // Methods are All HTMLElement a ELement methods + interface BlissNativeExtentions { + blur(): T; + click(): T; + contains(child: HTMLElement): boolean; + dragDrop(): boolean; + focus(): T; + insertAdjacentElement(position: string, insertedElement: Element): Element; + insertAdjacentHTML(where: string, html: string): T; + insertAdjacentText(where: string, text: string): T; + msGetInputContext(): MSInputMethodContext; + scrollIntoView(top?: boolean): T; + setActive(): T; + addEventListener(type: "MSContentZoom", listener: (ev: UIEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSManipulationStateChanged", listener: (ev: MSManipulationEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "abort", listener: (ev: UIEvent) => any, useCapture?: boolean): T; + addEventListener(type: "activate", listener: (ev: UIEvent) => any, useCapture?: boolean): T; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): T; + addEventListener(type: "beforeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): T; + addEventListener(type: "beforecopy", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "beforecut", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "beforedeactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): T; + addEventListener(type: "beforepaste", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "blur", listener: (ev: FocusEvent) => any, useCapture?: boolean): T; + addEventListener(type: "canplay", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "canplaythrough", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "change", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "click", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): T; + addEventListener(type: "contextmenu", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "copy", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "cuechange", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "cut", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "dblclick", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; + addEventListener(type: "deactivate", listener: (ev: UIEvent) => any, useCapture?: boolean): T; + addEventListener(type: "drag", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "dragend", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "dragenter", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "dragleave", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "dragover", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "dragstart", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "drop", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "durationchange", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "emptied", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): T; + addEventListener(type: "focus", listener: (ev: FocusEvent) => any, useCapture?: boolean): T; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "input", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): T; + addEventListener(type: "keypress", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): T; + addEventListener(type: "keyup", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): T; + addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "loadeddata", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "loadedmetadata", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "mousedown", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; + addEventListener(type: "mouseenter", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; + addEventListener(type: "mouseleave", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; + addEventListener(type: "mousemove", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; + addEventListener(type: "mouseout", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; + addEventListener(type: "mouseover", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; + addEventListener(type: "mouseup", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; + addEventListener(type: "mousewheel", listener: (ev: MouseEvent) => any, useCapture?: boolean): T; + addEventListener(type: "paste", listener: (ev: DragEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "play", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "playing", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): T; + addEventListener(type: "ratechange", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "reset", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "scroll", listener: (ev: UIEvent) => any, useCapture?: boolean): T; + addEventListener(type: "seeked", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "seeking", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "select", listener: (ev: UIEvent) => any, useCapture?: boolean): T; + addEventListener(type: "selectstart", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "stalled", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "submit", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "suspend", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "timeupdate", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; + addEventListener(type: "volumechange", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): T; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): T; + getAttribute(name?: string): string; + getAttributeNS(namespaceURI: string, localName: string): string; + getAttributeNode(name: string): Attr; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getBoundingClientRect(): ClientRect; + getClientRects(): ClientRectList; + getElementsByTagName(name: "a"): NodeListOf; + getElementsByTagName(name: "abbr"): NodeListOf; + getElementsByTagName(name: "acronym"): NodeListOf; + getElementsByTagName(name: "address"): NodeListOf; + getElementsByTagName(name: "applet"): NodeListOf; + getElementsByTagName(name: "area"): NodeListOf; + getElementsByTagName(name: "article"): NodeListOf; + getElementsByTagName(name: "aside"): NodeListOf; + getElementsByTagName(name: "audio"): NodeListOf; + getElementsByTagName(name: "b"): NodeListOf; + getElementsByTagName(name: "base"): NodeListOf; + getElementsByTagName(name: "basefont"): NodeListOf; + getElementsByTagName(name: "bdo"): NodeListOf; + getElementsByTagName(name: "big"): NodeListOf; + getElementsByTagName(name: "blockquote"): NodeListOf; + getElementsByTagName(name: "body"): NodeListOf; + getElementsByTagName(name: "br"): NodeListOf; + getElementsByTagName(name: "button"): NodeListOf; + getElementsByTagName(name: "canvas"): NodeListOf; + getElementsByTagName(name: "caption"): NodeListOf; + getElementsByTagName(name: "center"): NodeListOf; + getElementsByTagName(name: "circle"): NodeListOf; + getElementsByTagName(name: "cite"): NodeListOf; + getElementsByTagName(name: "clippath"): NodeListOf; + getElementsByTagName(name: "code"): NodeListOf; + getElementsByTagName(name: "col"): NodeListOf; + getElementsByTagName(name: "colgroup"): NodeListOf; + getElementsByTagName(name: "datalist"): NodeListOf; + getElementsByTagName(name: "dd"): NodeListOf; + getElementsByTagName(name: "defs"): NodeListOf; + getElementsByTagName(name: "del"): NodeListOf; + getElementsByTagName(name: "desc"): NodeListOf; + getElementsByTagName(name: "dfn"): NodeListOf; + getElementsByTagName(name: "dir"): NodeListOf; + getElementsByTagName(name: "div"): NodeListOf; + getElementsByTagName(name: "dl"): NodeListOf; + getElementsByTagName(name: "dt"): NodeListOf; + getElementsByTagName(name: "ellipse"): NodeListOf; + getElementsByTagName(name: "em"): NodeListOf; + getElementsByTagName(name: "embed"): NodeListOf; + getElementsByTagName(name: "feblend"): NodeListOf; + getElementsByTagName(name: "fecolormatrix"): NodeListOf; + getElementsByTagName(name: "fecomponenttransfer"): NodeListOf; + getElementsByTagName(name: "fecomposite"): NodeListOf; + getElementsByTagName(name: "feconvolvematrix"): NodeListOf; + getElementsByTagName(name: "fediffuselighting"): NodeListOf; + getElementsByTagName(name: "fedisplacementmap"): NodeListOf; + getElementsByTagName(name: "fedistantlight"): NodeListOf; + getElementsByTagName(name: "feflood"): NodeListOf; + getElementsByTagName(name: "fefunca"): NodeListOf; + getElementsByTagName(name: "fefuncb"): NodeListOf; + getElementsByTagName(name: "fefuncg"): NodeListOf; + getElementsByTagName(name: "fefuncr"): NodeListOf; + getElementsByTagName(name: "fegaussianblur"): NodeListOf; + getElementsByTagName(name: "feimage"): NodeListOf; + getElementsByTagName(name: "femerge"): NodeListOf; + getElementsByTagName(name: "femergenode"): NodeListOf; + getElementsByTagName(name: "femorphology"): NodeListOf; + getElementsByTagName(name: "feoffset"): NodeListOf; + getElementsByTagName(name: "fepointlight"): NodeListOf; + getElementsByTagName(name: "fespecularlighting"): NodeListOf; + getElementsByTagName(name: "fespotlight"): NodeListOf; + getElementsByTagName(name: "fetile"): NodeListOf; + getElementsByTagName(name: "feturbulence"): NodeListOf; + getElementsByTagName(name: "fieldset"): NodeListOf; + getElementsByTagName(name: "figcaption"): NodeListOf; + getElementsByTagName(name: "figure"): NodeListOf; + getElementsByTagName(name: "filter"): NodeListOf; + getElementsByTagName(name: "font"): NodeListOf; + getElementsByTagName(name: "footer"): NodeListOf; + getElementsByTagName(name: "foreignobject"): NodeListOf; + getElementsByTagName(name: "form"): NodeListOf; + getElementsByTagName(name: "frame"): NodeListOf; + getElementsByTagName(name: "frameset"): NodeListOf; + getElementsByTagName(name: "g"): NodeListOf; + getElementsByTagName(name: "h1"): NodeListOf; + getElementsByTagName(name: "h2"): NodeListOf; + getElementsByTagName(name: "h3"): NodeListOf; + getElementsByTagName(name: "h4"): NodeListOf; + getElementsByTagName(name: "h5"): NodeListOf; + getElementsByTagName(name: "h6"): NodeListOf; + getElementsByTagName(name: "head"): NodeListOf; + getElementsByTagName(name: "header"): NodeListOf; + getElementsByTagName(name: "hgroup"): NodeListOf; + getElementsByTagName(name: "hr"): NodeListOf; + getElementsByTagName(name: "html"): NodeListOf; + getElementsByTagName(name: "i"): NodeListOf; + getElementsByTagName(name: "iframe"): NodeListOf; + getElementsByTagName(name: "image"): NodeListOf; + getElementsByTagName(name: "img"): NodeListOf; + getElementsByTagName(name: "input"): NodeListOf; + getElementsByTagName(name: "ins"): NodeListOf; + getElementsByTagName(name: "isindex"): NodeListOf; + getElementsByTagName(name: "kbd"): NodeListOf; + getElementsByTagName(name: "keygen"): NodeListOf; + getElementsByTagName(name: "label"): NodeListOf; + getElementsByTagName(name: "legend"): NodeListOf; + getElementsByTagName(name: "li"): NodeListOf; + getElementsByTagName(name: "line"): NodeListOf; + getElementsByTagName(name: "lineargradient"): NodeListOf; + getElementsByTagName(name: "link"): NodeListOf; + getElementsByTagName(name: "listing"): NodeListOf; + getElementsByTagName(name: "map"): NodeListOf; + getElementsByTagName(name: "mark"): NodeListOf; + getElementsByTagName(name: "marker"): NodeListOf; + getElementsByTagName(name: "marquee"): NodeListOf; + getElementsByTagName(name: "mask"): NodeListOf; + getElementsByTagName(name: "menu"): NodeListOf; + getElementsByTagName(name: "meta"): NodeListOf; + getElementsByTagName(name: "metadata"): NodeListOf; + getElementsByTagName(name: "nav"): NodeListOf; + getElementsByTagName(name: "nextid"): NodeListOf; + getElementsByTagName(name: "nobr"): NodeListOf; + getElementsByTagName(name: "noframes"): NodeListOf; + getElementsByTagName(name: "noscript"): NodeListOf; + getElementsByTagName(name: "object"): NodeListOf; + getElementsByTagName(name: "ol"): NodeListOf; + getElementsByTagName(name: "optgroup"): NodeListOf; + getElementsByTagName(name: "option"): NodeListOf; + getElementsByTagName(name: "p"): NodeListOf; + getElementsByTagName(name: "param"): NodeListOf; + getElementsByTagName(name: "path"): NodeListOf; + getElementsByTagName(name: "pattern"): NodeListOf; + getElementsByTagName(name: "plaintext"): NodeListOf; + getElementsByTagName(name: "polygon"): NodeListOf; + getElementsByTagName(name: "polyline"): NodeListOf; + getElementsByTagName(name: "pre"): NodeListOf; + getElementsByTagName(name: "progress"): NodeListOf; + getElementsByTagName(name: "q"): NodeListOf; + getElementsByTagName(name: "radialgradient"): NodeListOf; + getElementsByTagName(name: "rect"): NodeListOf; + getElementsByTagName(name: "rt"): NodeListOf; + getElementsByTagName(name: "ruby"): NodeListOf; + getElementsByTagName(name: "s"): NodeListOf; + getElementsByTagName(name: "samp"): NodeListOf; + getElementsByTagName(name: "script"): NodeListOf; + getElementsByTagName(name: "section"): NodeListOf; + getElementsByTagName(name: "select"): NodeListOf; + getElementsByTagName(name: "small"): NodeListOf; + getElementsByTagName(name: "source"): NodeListOf; + getElementsByTagName(name: "span"): NodeListOf; + getElementsByTagName(name: "stop"): NodeListOf; + getElementsByTagName(name: "strike"): NodeListOf; + getElementsByTagName(name: "strong"): NodeListOf; + getElementsByTagName(name: "style"): NodeListOf; + getElementsByTagName(name: "sub"): NodeListOf; + getElementsByTagName(name: "sup"): NodeListOf; + getElementsByTagName(name: "svg"): NodeListOf; + getElementsByTagName(name: "switch"): NodeListOf; + getElementsByTagName(name: "symbol"): NodeListOf; + getElementsByTagName(name: "table"): NodeListOf; + getElementsByTagName(name: "tbody"): NodeListOf; + getElementsByTagName(name: "td"): NodeListOf; + getElementsByTagName(name: "text"): NodeListOf; + getElementsByTagName(name: "textpath"): NodeListOf; + getElementsByTagName(name: "textarea"): NodeListOf; + getElementsByTagName(name: "tfoot"): NodeListOf; + getElementsByTagName(name: "th"): NodeListOf; + getElementsByTagName(name: "thead"): NodeListOf; + getElementsByTagName(name: "title"): NodeListOf; + getElementsByTagName(name: "tr"): NodeListOf; + getElementsByTagName(name: "track"): NodeListOf; + getElementsByTagName(name: "tspan"): NodeListOf; + getElementsByTagName(name: "tt"): NodeListOf; + getElementsByTagName(name: "u"): NodeListOf; + getElementsByTagName(name: "ul"): NodeListOf; + getElementsByTagName(name: "use"): NodeListOf; + getElementsByTagName(name: "var"): NodeListOf; + getElementsByTagName(name: "video"): NodeListOf; + getElementsByTagName(name: "view"): NodeListOf; + getElementsByTagName(name: "wbr"): NodeListOf; + getElementsByTagName(name: "x-ms-webview"): NodeListOf; + getElementsByTagName(name: "xmp"): NodeListOf; + getElementsByTagName(name: string): NodeListOf; + getElementsByTagNameNS(namespaceURI: string, localName: string): NodeListOf; + hasAttribute(name: string): boolean; + hasAttributeNS(namespaceURI: string, localName: string): boolean; + msGetRegionContent(): MSRangeCollection; + msGetUntransformedBounds(): ClientRect; + msMatchesSelector(selectors: string): boolean; + msReleasePointerCapture(pointerId: number): T; + msSetPointerCapture(pointerId: number): T; + msZoomTo(args: MsZoomToOptions): T; + releasePointerCapture(pointerId: number): T; + removeAttribute(name?: string): T; + removeAttributeNS(namespaceURI: string, localName: string): T; + removeAttributeNode(oldAttr: Attr): Attr; + requestFullscreen(): T; + requestPointerLock(): T; + setAttribute(name?: string, value?: string): T; + setAttributeNS(namespaceURI: string, qualifiedName: string, value: string): T; + setAttributeNode(newAttr: Attr): Attr; + setAttributeNodeNS(newAttr: Attr): Attr; + setPointerCapture(pointerId: number): T; + webkitMatchesSelector(selectors: string): boolean; + webkitRequestFullScreen(): T; + webkitRequestFullscreen(): T; + getElementsByClassName(classNames: string): NodeListOf; + addEventListener(type: "MSGestureChange", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGestureDoubleTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGestureEnd", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGestureHold", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGestureStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGestureTap", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSGotPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSInertiaStart", listener: (ev: MSGestureEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSLostPointerCapture", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerCancel", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerDown", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerEnter", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerLeave", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerMove", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerOut", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerOver", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "MSPointerUp", listener: (ev: MSPointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "ariarequest", listener: (ev: AriaRequestEvent) => any, useCapture?: boolean): T; + addEventListener(type: "command", listener: (ev: CommandEvent) => any, useCapture?: boolean): T; + addEventListener(type: "gotpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "lostpointercapture", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): T; + addEventListener(type: "touchcancel", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; + addEventListener(type: "touchend", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; + addEventListener(type: "touchmove", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; + addEventListener(type: "touchstart", listener: (ev: TouchEvent) => any, useCapture?: boolean): T; + addEventListener(type: "webkitfullscreenchange", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "webkitfullscreenerror", listener: (ev: Event) => any, useCapture?: boolean): T; + addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): T; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): T; + } + + interface BlissBindedElement extends BlissNativeExtentions { + set(options: Object): BlissDecoratedElement + contents(elements: Object | Array | string | Number | Node): BlissDecoratedElement + clone(): BlissDecoratedElement; + after(element:Element) : BlissDecoratedElement; + around(element:Element) : BlissDecoratedElement; + attributes(attrs: Object) : BlissDecoratedElement; + before(element:Element) : BlissDecoratedElement; + inside(element:Element) : BlissDecoratedElement; + properties(props: Object) : BlissDecoratedElement; + start(element:Element) : BlissDecoratedElement; + style(properties: Object) : BlissDecoratedElement; + transition(properties: Object, duration?: number) : Promise; + delegate(type: string, selector: string, callback: (event: Event) => void): BlissDecoratedElement; + delegate(type: string, selectorsToCallbacks: {[selector: string] : (event: Event) => void}): BlissDecoratedElement; + delegate(typesToSelectorsToCallbacks: {[type: string] : {[selector: string] : (event: Event) => void}}): BlissDecoratedElement; + events(handlers: {[eventName:string] : (event: Event) => void} | Element): BlissDecoratedElement; + fire(type: string, properties?: {[propertyName: string] : any}): BlissDecoratedElement; + once(handlers: {[eventName:string] : (event: Event) => void} | Element): BlissDecoratedElement; + + remove(): BlissDecoratedElement; + } + + interface BlissBindedArray { + all(method: string, ...args: Array): Array; + all(method: string, ...args: Array): Array; + } + + interface BlissCollectionArray { + set(options: Object): BlissCollectionArray + contents(elements: Object | Array | string | Number | Node): BlissCollectionArray + clone(): BlissCollectionArray; + after(element:Element) : BlissCollectionArray; + around(element:Element) : BlissCollectionArray; + attributes(attrs: Object) : BlissCollectionArray; + before(element:Element) : BlissCollectionArray; + inside(element:Element) : BlissCollectionArray; + properties(props: Object) : BlissCollectionArray; + start(element:Element) : BlissCollectionArray; + style(properties: Object) : BlissCollectionArray; + transition(properties: Object, duration?: number) : Promise[]; + delegate(type: string, selector: string, callback: (event: Event) => void): BlissCollectionArray; + delegate(type: string, selectorsToCallbacks: {[selector: string] : (event: Event) => void}): BlissCollectionArray; + delegate(typesToSelectorsToCallbacks: {[type: string] : {[selector: string] : (event: Event) => void}}): BlissCollectionArray; + events(handlers: {[eventName:string] : (event: Event) => void} | Element): BlissCollectionArray; + fire(type: string, properties?: {[propertyName: string] : any}): BlissCollectionArray; + once(handlers: {[eventName:string] : (event: Event) => void} | Element): BlissCollectionArray; + + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): BlissCollectionArray; + + remove(): BlissCollectionArray; + } +} + +declare var Bliss: BlissNS.BlissStatic; +declare var $: BlissNS.BlissStatic; +declare var $$: BlissNS.BlissStaticCollection; diff --git a/blissfuljs/tsconfig.json b/blissfuljs/tsconfig.json new file mode 100644 index 0000000000..26de24f582 --- /dev/null +++ b/blissfuljs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "blissfuljs-tests.ts" + ] +} \ No newline at end of file diff --git a/blob-stream/blob-stream-tests.ts b/blob-stream/blob-stream-tests.ts index fab0932068..b9174859f9 100644 --- a/blob-stream/blob-stream-tests.ts +++ b/blob-stream/blob-stream-tests.ts @@ -1,5 +1,5 @@ -/// -/// + +/// var bl = require('blob-stream'); diff --git a/blob-stream/blob-stream.d.ts b/blob-stream/blob-stream.d.ts deleted file mode 100644 index cb7c6c1146..0000000000 --- a/blob-stream/blob-stream.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// Type definitions for blob-stream v0.1.3 -// Project: https://github.com/devongovett/blob-stream -// Definitions by: Eric Hillah -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare function BlobStream(): BlobStream.IBlobStream; - -declare namespace BlobStream { - - interface IBlobStream extends NodeJS.WritableStream{ - toBlob(type?: string): Blob; - toBlobURL(type?: string): string; - } -} - -declare module "blob-stream" { - export = BlobStream; -} diff --git a/blob-stream/index.d.ts b/blob-stream/index.d.ts new file mode 100644 index 0000000000..c7452a3242 --- /dev/null +++ b/blob-stream/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for blob-stream v0.1.3 +// Project: https://github.com/devongovett/blob-stream +// Definitions by: Eric Hillah +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare function BlobStream(): BlobStream.IBlobStream; + +declare namespace BlobStream { + + interface IBlobStream extends NodeJS.WritableStream{ + toBlob(type?: string): Blob; + toBlobURL(type?: string): string; + } +} + +export = BlobStream; \ No newline at end of file diff --git a/blob-stream/tsconfig.json b/blob-stream/tsconfig.json new file mode 100644 index 0000000000..67b9cd7761 --- /dev/null +++ b/blob-stream/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "blob-stream-tests.ts" + ] +} \ No newline at end of file diff --git a/blocks/blocks-tests.ts b/blocks/blocks-tests.ts index 7b83b52a61..3fa24b4d83 100644 --- a/blocks/blocks-tests.ts +++ b/blocks/blocks-tests.ts @@ -1,4 +1,4 @@ -/// + function test_blocks_methods() { var extended: Object; diff --git a/blocks/blocks.d.ts b/blocks/index.d.ts similarity index 100% rename from blocks/blocks.d.ts rename to blocks/index.d.ts diff --git a/blocks/tsconfig.json b/blocks/tsconfig.json new file mode 100644 index 0000000000..cea3804db6 --- /dev/null +++ b/blocks/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "blocks-tests.ts" + ] +} \ No newline at end of file diff --git a/blue-tape/blue-tape-tests.ts b/blue-tape/blue-tape-tests.ts index a01675a1c5..92b2641115 100644 --- a/blue-tape/blue-tape-tests.ts +++ b/blue-tape/blue-tape-tests.ts @@ -1,6 +1,5 @@ -/// -/// -/// +/// +/// import tape = require('blue-tape'); import P = require('bluebird'); diff --git a/blue-tape/blue-tape.d.ts b/blue-tape/blue-tape.d.ts deleted file mode 100644 index 1216600cab..0000000000 --- a/blue-tape/blue-tape.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Type definitions for blue-tape v0.1.11 -// Project: https://github.com/spion/blue-tape -// Definitions by: Haoqun Jiang -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare module 'blue-tape' { - import tape = require('tape'); - export = tape; -} diff --git a/blue-tape/index.d.ts b/blue-tape/index.d.ts new file mode 100644 index 0000000000..133968a165 --- /dev/null +++ b/blue-tape/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for blue-tape v0.1.11 +// Project: https://github.com/spion/blue-tape +// Definitions by: Haoqun Jiang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import tape = require('tape'); +export = tape; diff --git a/blue-tape/tsconfig.json b/blue-tape/tsconfig.json new file mode 100644 index 0000000000..04302d1e28 --- /dev/null +++ b/blue-tape/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "blue-tape-tests.ts" + ] +} \ No newline at end of file diff --git a/bluebird-retry/bluebird-retry-tests.ts b/bluebird-retry/bluebird-retry-tests.ts index 5d8c32dfcb..b63b360160 100644 --- a/bluebird-retry/bluebird-retry-tests.ts +++ b/bluebird-retry/bluebird-retry-tests.ts @@ -1,5 +1,5 @@ -/// -/// + +/// import Promise = require('bluebird'); import retry = require('bluebird-retry'); diff --git a/bluebird-retry/bluebird-retry.d.ts b/bluebird-retry/bluebird-retry.d.ts deleted file mode 100644 index 1210bf3b53..0000000000 --- a/bluebird-retry/bluebird-retry.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -// Type definitions for bluebird-retry -// Project: https://github.com/jut-io/bluebird-retry -// Definitions by: Pascal Vomhoff -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -declare module "bluebird-retry" { - import Promise = require('bluebird'); - - function retry(func:(param:T)=>void, options?:retry.Options):Promise; - - namespace retry { - export interface Options { - interval?:number; - backoff?:number; - max_interval?:number; - timeout?:number; - max_tries?:number; - } - - } - - export = retry; -} diff --git a/bluebird-retry/index.d.ts b/bluebird-retry/index.d.ts new file mode 100644 index 0000000000..2881d2065c --- /dev/null +++ b/bluebird-retry/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for bluebird-retry +// Project: https://github.com/jut-io/bluebird-retry +// Definitions by: Pascal Vomhoff +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import Promise = require('bluebird'); + +declare function retry(func: (param: T) => void, options?: retry.Options): Promise; + +declare namespace retry { + export interface Options { + interval?: number; + backoff?: number; + max_interval?: number; + timeout?: number; + max_tries?: number; + } + +} + +export = retry; diff --git a/bluebird-retry/tsconfig.json b/bluebird-retry/tsconfig.json new file mode 100644 index 0000000000..ab290b6e3b --- /dev/null +++ b/bluebird-retry/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bluebird-retry-tests.ts" + ] +} \ No newline at end of file diff --git a/bluebird/bluebird-1.0-tests.ts b/bluebird/bluebird-1.0-tests.ts index 2aa795a4f3..6f6df3a978 100644 --- a/bluebird/bluebird-1.0-tests.ts +++ b/bluebird/bluebird-1.0-tests.ts @@ -1,4 +1,4 @@ -/// + // Tests by: Bart van der Schoor diff --git a/bluebird/bluebird-1.0-tests.ts.tscparams b/bluebird/bluebird-1.0-tests.ts.tscparams deleted file mode 100644 index 1f3d85fb3b..0000000000 --- a/bluebird/bluebird-1.0-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ ---target es5 --noImplicitAny diff --git a/bluebird/bluebird-1.0.d.ts.tscparams b/bluebird/bluebird-1.0.d.ts.tscparams deleted file mode 100644 index 1f3d85fb3b..0000000000 --- a/bluebird/bluebird-1.0.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ ---target es5 --noImplicitAny diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts index a24cdfd7ee..8acdcb44bd 100644 --- a/bluebird/bluebird-tests.ts +++ b/bluebird/bluebird-tests.ts @@ -1,5 +1,3 @@ -/// - // Tests by: Bart van der Schoor // Note: replicate changes to all overloads in both definition and test file diff --git a/bluebird/bluebird.d.ts b/bluebird/index.d.ts similarity index 100% rename from bluebird/bluebird.d.ts rename to bluebird/index.d.ts diff --git a/bluebird/tsconfig.json b/bluebird/tsconfig.json new file mode 100644 index 0000000000..b7544420b6 --- /dev/null +++ b/bluebird/tsconfig.json @@ -0,0 +1,17 @@ +{ + "files": [ + "index.d.ts", + "bluebird-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/blueimp-md5/blueimp-md5-tests.ts b/blueimp-md5/blueimp-md5-tests.ts index 5e38083097..18edc69b57 100644 --- a/blueimp-md5/blueimp-md5-tests.ts +++ b/blueimp-md5/blueimp-md5-tests.ts @@ -1,4 +1,3 @@ -/// import blueimp = require('blueimp-md5'); diff --git a/blueimp-md5/blueimp-md5.d.ts b/blueimp-md5/blueimp-md5.d.ts deleted file mode 100644 index 99880ba0d6..0000000000 --- a/blueimp-md5/blueimp-md5.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// Type definitions for blueimp-md5 v1.1.0 -// Project: https://github.com/blueimp/JavaScript-MD5 -// Definitions by: Ray Martone -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'blueimp-md5' { - export function md5(value: string, key?: string, raw?: boolean): string; -} diff --git a/blueimp-md5/index.d.ts b/blueimp-md5/index.d.ts new file mode 100644 index 0000000000..b51f554e32 --- /dev/null +++ b/blueimp-md5/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for blueimp-md5 v1.1.0 +// Project: https://github.com/blueimp/JavaScript-MD5 +// Definitions by: Ray Martone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export declare function md5(value: string, key?: string, raw?: boolean): string; diff --git a/blueimp-md5/tsconfig.json b/blueimp-md5/tsconfig.json new file mode 100644 index 0000000000..0c7840bbdf --- /dev/null +++ b/blueimp-md5/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "blueimp-md5-tests.ts" + ] +} \ No newline at end of file diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts deleted file mode 100644 index 16f639dfaf..0000000000 --- a/body-parser/body-parser.d.ts +++ /dev/null @@ -1,138 +0,0 @@ -// Type definitions for body-parser -// Project: http://expressjs.com -// Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "body-parser" { - import * as express from "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; - - namespace 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. - */ - extended: boolean; - }): express.RequestHandler; - } - - export = bodyParser; -} diff --git a/body-parser/index.d.ts b/body-parser/index.d.ts new file mode 100644 index 0000000000..13976bbb69 --- /dev/null +++ b/body-parser/index.d.ts @@ -0,0 +1,137 @@ +// Type definitions for body-parser +// Project: http://expressjs.com +// Definitions by: Santi Albo , VILIC VANE , Jonathan Häberle +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + + +import * as express from "express"; + +/** + * bodyParser: use individual json/urlencoded middlewares + * @deprecated + */ + +declare 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; + +declare namespace 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. + */ + extended: boolean; + }): express.RequestHandler; +} + +export = bodyParser; diff --git a/body-parser/tsconfig.json b/body-parser/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/body-parser/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/bookshelf/bookshelf-tests.ts b/bookshelf/bookshelf-tests.ts index 42faf0909e..59c20bb686 100644 --- a/bookshelf/bookshelf-tests.ts +++ b/bookshelf/bookshelf-tests.ts @@ -1,5 +1,4 @@ -/// -/// + import * as Knex from 'knex'; import * as Bookshelf from 'bookshelf'; @@ -15,6 +14,9 @@ var knex = Knex({ var bookshelf = Bookshelf(knex); +bookshelf.plugin('registry'); +bookshelf.plugin(['virtuals']); + class User extends bookshelf.Model { get tableName() { return 'users'; } messages() : Bookshelf.Collection { diff --git a/bookshelf/bookshelf.d.ts b/bookshelf/bookshelf.d.ts deleted file mode 100644 index 74f5e83d4a..0000000000 --- a/bookshelf/bookshelf.d.ts +++ /dev/null @@ -1,314 +0,0 @@ -// Type definitions for bookshelfjs v0.8.2 -// Project: http://bookshelfjs.org/ -// Definitions by: Andrew Schurman -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// -/// - -declare module 'bookshelf' { - import knex = require('knex'); - import Promise = require('bluebird'); - import Lodash = require('lodash'); - - interface Bookshelf extends Bookshelf.Events { - VERSION : string; - knex : knex; - Model : typeof Bookshelf.Model; - Collection : typeof Bookshelf.Collection; - - plugin(name: string) : Bookshelf; - transaction(callback : (transaction : knex.Transaction) => T) : Promise; - } - - function Bookshelf(knex : knex) : Bookshelf; - - namespace Bookshelf { - abstract class Events { - on(event? : string, callback? : EventFunction, context? : any) : void; - off(event? : string) : void; - trigger(event? : string, ...args : any[]) : void; - triggerThen(name : string, ...args : any[]) : Promise; - once(event : string, callback : EventFunction, context? : any) : void; - } - - interface IModelBase { - /** Should be declared as a getter instead of a plain property. */ - hasTimestamps? : boolean|string[]; - /** Should be declared as a getter instead of a plain property. Should be required, but cannot have abstract properties yet. */ - tableName? : string; - } - - abstract class ModelBase> extends Events> implements IModelBase { - /** If overriding, must use a getter instead of a plain property. */ - idAttribute : string; - - constructor(attributes? : any, options? : ModelOptions); - - clear() : T; - clone() : T; - escape(attribute : string) : string; - format(attributes : any) : any; - get(attribute : string) : any; - has(attribute : string) : boolean; - hasChanged(attribute? : string) : boolean; - isNew() : boolean; - parse(response : any) : any; - previousAttributes() : any; - previous(attribute : string) : any; - related>(relation : string) : R | Collection; - serialize(options? : SerializeOptions) : any; - set(attribute?: {[key : string] : any}, options? : SetOptions) : T; - set(attribute : string, value? : any, options? : SetOptions) : T; - timestamp(options? : TimestampOptions) : any; - toJSON(options? : SerializeOptions) : any; - unset(attribute : string) : T; - - // lodash methods - invert() : R; - keys() : string[]; - omit(predicate? : Lodash.ObjectIterator, thisArg? : any) : R; - omit(...attributes : string[]) : R; - pairs() : any[][]; - pick(predicate? : Lodash.ObjectIterator, thisArg? : any) : R; - pick(...attributes : string[]) : R; - values() : any[]; - } - - class Model> extends ModelBase { - static collection>(models? : T[], options? : CollectionOptions) : Collection; - static count(column? : string, options? : SyncOptions) : Promise; - /** @deprecated use Typescript classes */ - static extend>(prototypeProperties? : any, classProperties? : any) : Function; // should return a type - static fetchAll>() : Promise>; - /** @deprecated should use `new` objects instead. */ - static forge(attributes? : any, options? : ModelOptions) : T; - - belongsTo>(target : {new(...args : any[]) : R}, foreignKey? : string) : R; - belongsToMany>(target : {new(...args : any[]) : R}, table? : string, foreignKey? : string, otherKey? : string) : Collection; - count(column? : string, options? : SyncOptions) : Promise; - destroy(options? : SyncOptions) : Promise; - fetch(options? : FetchOptions) : Promise; - fetchAll(options? : FetchAllOptions) : Promise>; - hasMany>(target : {new(...args : any[]) : R}, foreignKey? : string) : Collection; - hasOne>(target : {new(...args : any[]) : R}, foreignKey? : string) : R; - load(relations : string|string[], options? : LoadOptions) : Promise; - morphMany>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : Collection; - morphOne>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : R; - morphTo(name : string, columnNames? : string[], ...target : typeof Model[]) : T; - morphTo(name : string, ...target : typeof Model[]) : T; - query(...query : string[]) : T; - query(query : {[key : string] : any}) : T; - query(callback : (qb : knex.QueryBuilder) => void) : T; - query() : knex.QueryBuilder; - refresh(options? : FetchOptions) : Promise; - resetQuery() : T; - save(key? : string, val? : string, options? : SaveOptions) : Promise; - save(attrs? : {[key : string] : any}, options? : SaveOptions) : Promise; - through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; - where(properties : {[key : string] : any}) : T; - where(key : string, operatorOrValue : string|number|boolean, valueIfOperator? : string|number|boolean) : T; - } - - abstract class CollectionBase> extends Events { - add(models : T[]|{[key : string] : any}[], options? : CollectionAddOptions) : Collection; - at(index : number) : T; - clone() : Collection; - fetch(options? : CollectionFetchOptions) : Promise>; - findWhere(match : {[key : string] : any}) : T; - get(id : any) : T; - invokeThen(name : string, ...args : any[]) : Promise; - parse(response : any) : any; - pluck(attribute : string) : any[]; - pop() : void; - push(model : any) : Collection; - reduceThen(iterator : (prev : R, cur : T, idx : number, array : T[]) => R, initialValue : R, context : any) : Promise; - remove(model : T, options? : EventOptions) : T; - remove(model : T[], options? : EventOptions) : T[]; - reset(model : any[], options? : CollectionAddOptions) : T[]; - serialize(options? : SerializeOptions) : any; - set(models : T[]|{[key : string] : any}[], options? : CollectionSetOptions) : Collection; - shift(options? : EventOptions) : void; - slice(begin? : number, end? : number) : void; - toJSON(options? : SerializeOptions) : any; - unshift(model : any, options? : CollectionAddOptions) : void; - where(match : {[key : string] : any}, firstOnly : boolean) : T|Collection; - - // lodash methods - all(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; - all(predicate? : R) : boolean; - any(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; - any(predicate? : R) : boolean; - chain() : Lodash.LoDashExplicitObjectWrapper; - collect(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - collect(predicate? : R) : T[]; - contains(value : any, fromIndex? : number) : boolean; - countBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : Lodash.Dictionary; - countBy(predicate? : R) : Lodash.Dictionary; - detect(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T; - detect(predicate? : R) : T; - difference(...values : T[]) : T[]; - drop(n? : number) : T[]; - each(callback? : Lodash.ListIterator, thisArg? : any) : Lodash.List; - each(callback? : Lodash.DictionaryIterator, thisArg? : any) : Lodash.Dictionary; - each(callback? : Lodash.ObjectIterator, thisArg? : any) : T; - every(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; - every(predicate? : R) : boolean; - filter(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - filter(predicate? : R) : T[]; - find(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T; - find(predicate? : R) : T; - first() : T; - foldl(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - foldr(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - forEach(callback? : Lodash.ListIterator, thisArg? : any) : Lodash.List; - forEach(callback? : Lodash.DictionaryIterator, thisArg? : any) : Lodash.Dictionary; - forEach(callback? : Lodash.ObjectIterator, thisArg? : any) : T; - groupBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : Lodash.Dictionary; - groupBy(predicate? : R) : Lodash.Dictionary; - head() : T; - include(value : any, fromIndex? : number) : boolean; - indexOf(value : any, fromIndex? : number) : number; - initial() : T[]; - inject(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - invoke(methodName : string|Function, ...args : any[]) : any; - isEmpty() : boolean; - keys() : string[]; - last() : T; - lastIndexOf(value : any, fromIndex? : number) : number; - map(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - map(predicate? : R) : T[]; - max(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; - max(predicate? : R) : T; - min(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; - min(predicate? : R) : T; - reduce(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - reduceRight(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - reject(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - reject(predicate? : R) : T[]; - rest() : T[]; - select(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - select(predicate? : R) : T[]; - shuffle() : T[]; - size() : number; - some(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; - some(predicate? : R) : boolean; - sortBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - sortBy(predicate? : R) : T[]; - tail() : T[]; - take(n? : number) : T[]; - toArray() : T[]; - without(...values : any[]) : T[]; - } - - class Collection> extends CollectionBase { - /** @deprecated use Typescript classes */ - static extend(prototypeProperties? : any, classProperties? : any) : Function; - /** @deprecated should use `new` objects instead. */ - static forge(attributes? : any, options? : ModelOptions) : T; - - attach(ids : any[], options? : SyncOptions) : Promise>; - count(column? : string, options? : SyncOptions) : Promise; - create(model : {[key : string] : any}, options? : CollectionCreateOptions) : Promise; - detach(ids : any[], options? : SyncOptions) : Promise; - fetchOne(options? : CollectionFetchOneOptions) : Promise; - load(relations : string|string[], options? : SyncOptions) : Promise>; - query(...query : string[]) : Collection; - query(query : {[key : string] : any}) : Collection; - query(callback : (qb : knex.QueryBuilder) => void) : Collection; - query() : knex.QueryBuilder; - resetQuery() : Collection; - through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; - updatePivot(attributes : any, options? : PivotOptions) : Promise; - withPivot(columns : string[]) : Collection; - } - - interface ModelOptions { - tableName? : string; - hasTimestamps? : boolean; - parse? : boolean; - } - - interface LoadOptions extends SyncOptions { - withRelated: string|any|any[]; - } - - interface FetchOptions extends SyncOptions { - require? : boolean; - columns? : string|string[]; - withRelated? : string|any|any[]; - } - - interface FetchAllOptions extends SyncOptions { - require? : boolean; - } - - interface SaveOptions extends SyncOptions { - method? : string; - defaults? : string; - patch? : boolean; - require? : boolean; - } - - interface SerializeOptions { - shallow? : boolean; - omitPivot? : boolean; - } - - interface SetOptions { - unset? : boolean; - } - - interface TimestampOptions { - method? : string; - } - - interface SyncOptions { - transacting? : knex.Transaction; - debug? : boolean; - } - - interface CollectionOptions { - comparator? : boolean|string|((a : T, b : T) => number); - } - - interface CollectionAddOptions extends EventOptions { - at? : number; - merge? : boolean; - } - - interface CollectionFetchOptions { - require? : boolean; - withRelated? : string|string[]; - } - - interface CollectionFetchOneOptions { - require? : boolean; - columns? : string|string[]; - } - - interface CollectionSetOptions extends EventOptions { - add? : boolean; - remove? : boolean; - merge?: boolean; - } - - interface PivotOptions { - query? : Function|any; - require? : boolean; - } - - interface EventOptions { - silent? : boolean; - } - - interface EventFunction { - (model: T, attrs: any, options: any) : Promise|void; - } - - interface CollectionCreateOptions extends ModelOptions, SyncOptions, CollectionAddOptions, SaveOptions {} - } - - export = Bookshelf; -} diff --git a/bookshelf/index.d.ts b/bookshelf/index.d.ts new file mode 100644 index 0000000000..34a94dd3e8 --- /dev/null +++ b/bookshelf/index.d.ts @@ -0,0 +1,312 @@ +// Type definitions for bookshelfjs v0.8.2 +// Project: http://bookshelfjs.org/ +// Definitions by: Andrew Schurman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +import knex = require('knex'); +import Promise = require('bluebird'); +import Lodash = require('lodash'); + +interface Bookshelf extends Bookshelf.Events { + VERSION : string; + knex : knex; + Model : typeof Bookshelf.Model; + Collection : typeof Bookshelf.Collection; + + plugin(name: string | string[] | Function, options?: any) : Bookshelf; + transaction(callback : (transaction : knex.Transaction) => T) : Promise; +} + +declare function Bookshelf(knex : knex) : Bookshelf; + +declare namespace Bookshelf { + abstract class Events { + on(event? : string, callback? : EventFunction, context? : any) : void; + off(event? : string) : void; + trigger(event? : string, ...args : any[]) : void; + triggerThen(name : string, ...args : any[]) : Promise; + once(event : string, callback : EventFunction, context? : any) : void; + } + + interface IModelBase { + /** Should be declared as a getter instead of a plain property. */ + hasTimestamps? : boolean|string[]; + /** Should be declared as a getter instead of a plain property. Should be required, but cannot have abstract properties yet. */ + tableName? : string; + } + + abstract class ModelBase> extends Events> implements IModelBase { + /** If overriding, must use a getter instead of a plain property. */ + idAttribute : string; + + constructor(attributes? : any, options? : ModelOptions); + + clear() : T; + clone() : T; + escape(attribute : string) : string; + format(attributes : any) : any; + get(attribute : string) : any; + has(attribute : string) : boolean; + hasChanged(attribute? : string) : boolean; + isNew() : boolean; + parse(response : any) : any; + previousAttributes() : any; + previous(attribute : string) : any; + related>(relation : string) : R | Collection; + serialize(options? : SerializeOptions) : any; + set(attribute?: {[key : string] : any}, options? : SetOptions) : T; + set(attribute : string, value? : any, options? : SetOptions) : T; + timestamp(options? : TimestampOptions) : any; + toJSON(options? : SerializeOptions) : any; + unset(attribute : string) : T; + + // lodash methods + invert() : R; + keys() : string[]; + omit(predicate? : Lodash.ObjectIterator, thisArg? : any) : R; + omit(...attributes : string[]) : R; + pairs() : any[][]; + pick(predicate? : Lodash.ObjectIterator, thisArg? : any) : R; + pick(...attributes : string[]) : R; + values() : any[]; + } + + class Model> extends ModelBase { + static collection>(models? : T[], options? : CollectionOptions) : Collection; + static count(column? : string, options? : SyncOptions) : Promise; + /** @deprecated use Typescript classes */ + static extend>(prototypeProperties? : any, classProperties? : any) : Function; // should return a type + static fetchAll>() : Promise>; + /** @deprecated should use `new` objects instead. */ + static forge(attributes? : any, options? : ModelOptions) : T; + + belongsTo>(target : {new(...args : any[]) : R}, foreignKey? : string) : R; + belongsToMany>(target : {new(...args : any[]) : R}, table? : string, foreignKey? : string, otherKey? : string) : Collection; + count(column? : string, options? : SyncOptions) : Promise; + destroy(options? : SyncOptions) : Promise; + fetch(options? : FetchOptions) : Promise; + fetchAll(options? : FetchAllOptions) : Promise>; + hasMany>(target : {new(...args : any[]) : R}, foreignKey? : string) : Collection; + hasOne>(target : {new(...args : any[]) : R}, foreignKey? : string) : R; + load(relations : string|string[], options? : LoadOptions) : Promise; + morphMany>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : Collection; + morphOne>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : R; + morphTo(name : string, columnNames? : string[], ...target : typeof Model[]) : T; + morphTo(name : string, ...target : typeof Model[]) : T; + query(...query : string[]) : T; + query(query : {[key : string] : any}) : T; + query(callback : (qb : knex.QueryBuilder) => void) : T; + query() : knex.QueryBuilder; + refresh(options? : FetchOptions) : Promise; + resetQuery() : T; + save(key? : string, val? : string, options? : SaveOptions) : Promise; + save(attrs? : {[key : string] : any}, options? : SaveOptions) : Promise; + through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; + where(properties : {[key : string] : any}) : T; + where(key : string, operatorOrValue : string|number|boolean, valueIfOperator? : string|number|boolean) : T; + } + + abstract class CollectionBase> extends Events { + add(models : T[]|{[key : string] : any}[], options? : CollectionAddOptions) : Collection; + at(index : number) : T; + clone() : Collection; + fetch(options? : CollectionFetchOptions) : Promise>; + findWhere(match : {[key : string] : any}) : T; + get(id : any) : T; + invokeThen(name : string, ...args : any[]) : Promise; + parse(response : any) : any; + pluck(attribute : string) : any[]; + pop() : void; + push(model : any) : Collection; + reduceThen(iterator : (prev : R, cur : T, idx : number, array : T[]) => R, initialValue : R, context : any) : Promise; + remove(model : T, options? : EventOptions) : T; + remove(model : T[], options? : EventOptions) : T[]; + reset(model : any[], options? : CollectionAddOptions) : T[]; + serialize(options? : SerializeOptions) : any; + set(models : T[]|{[key : string] : any}[], options? : CollectionSetOptions) : Collection; + shift(options? : EventOptions) : void; + slice(begin? : number, end? : number) : void; + toJSON(options? : SerializeOptions) : any; + unshift(model : any, options? : CollectionAddOptions) : void; + where(match : {[key : string] : any}, firstOnly : boolean) : T|Collection; + + // lodash methods + all(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; + all(predicate? : R) : boolean; + any(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; + any(predicate? : R) : boolean; + chain() : Lodash.LoDashExplicitObjectWrapper; + collect(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; + collect(predicate? : R) : T[]; + contains(value : any, fromIndex? : number) : boolean; + countBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : Lodash.Dictionary; + countBy(predicate? : R) : Lodash.Dictionary; + detect(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T; + detect(predicate? : R) : T; + difference(...values : T[]) : T[]; + drop(n? : number) : T[]; + each(callback? : Lodash.ListIterator, thisArg? : any) : Lodash.List; + each(callback? : Lodash.DictionaryIterator, thisArg? : any) : Lodash.Dictionary; + each(callback? : Lodash.ObjectIterator, thisArg? : any) : T; + every(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; + every(predicate? : R) : boolean; + filter(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; + filter(predicate? : R) : T[]; + find(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T; + find(predicate? : R) : T; + first() : T; + foldl(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; + foldr(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; + forEach(callback? : Lodash.ListIterator, thisArg? : any) : Lodash.List; + forEach(callback? : Lodash.DictionaryIterator, thisArg? : any) : Lodash.Dictionary; + forEach(callback? : Lodash.ObjectIterator, thisArg? : any) : T; + groupBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : Lodash.Dictionary; + groupBy(predicate? : R) : Lodash.Dictionary; + head() : T; + include(value : any, fromIndex? : number) : boolean; + indexOf(value : any, fromIndex? : number) : number; + initial() : T[]; + inject(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; + invoke(methodName : string|Function, ...args : any[]) : any; + isEmpty() : boolean; + keys() : string[]; + last() : T; + lastIndexOf(value : any, fromIndex? : number) : number; + map(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; + map(predicate? : R) : T[]; + max(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; + max(predicate? : R) : T; + min(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; + min(predicate? : R) : T; + reduce(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; + reduceRight(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; + reject(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; + reject(predicate? : R) : T[]; + rest() : T[]; + select(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; + select(predicate? : R) : T[]; + shuffle() : T[]; + size() : number; + some(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; + some(predicate? : R) : boolean; + sortBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; + sortBy(predicate? : R) : T[]; + tail() : T[]; + take(n? : number) : T[]; + toArray() : T[]; + without(...values : any[]) : T[]; + } + + class Collection> extends CollectionBase { + /** @deprecated use Typescript classes */ + static extend(prototypeProperties? : any, classProperties? : any) : Function; + /** @deprecated should use `new` objects instead. */ + static forge(attributes? : any, options? : ModelOptions) : T; + + attach(ids : any[], options? : SyncOptions) : Promise>; + count(column? : string, options? : SyncOptions) : Promise; + create(model : {[key : string] : any}, options? : CollectionCreateOptions) : Promise; + detach(ids : any[], options? : SyncOptions) : Promise; + fetchOne(options? : CollectionFetchOneOptions) : Promise; + load(relations : string|string[], options? : SyncOptions) : Promise>; + query(...query : string[]) : Collection; + query(query : {[key : string] : any}) : Collection; + query(callback : (qb : knex.QueryBuilder) => void) : Collection; + query() : knex.QueryBuilder; + resetQuery() : Collection; + through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; + updatePivot(attributes : any, options? : PivotOptions) : Promise; + withPivot(columns : string[]) : Collection; + } + + interface ModelOptions { + tableName? : string; + hasTimestamps? : boolean; + parse? : boolean; + } + + interface LoadOptions extends SyncOptions { + withRelated: string|any|any[]; + } + + interface FetchOptions extends SyncOptions { + require? : boolean; + columns? : string|string[]; + withRelated? : string|any|any[]; + } + + interface FetchAllOptions extends SyncOptions { + require? : boolean; + } + + interface SaveOptions extends SyncOptions { + method? : string; + defaults? : string; + patch? : boolean; + require? : boolean; + } + + interface SerializeOptions { + shallow? : boolean; + omitPivot? : boolean; + } + + interface SetOptions { + unset? : boolean; + } + + interface TimestampOptions { + method? : string; + } + + interface SyncOptions { + transacting? : knex.Transaction; + debug? : boolean; + } + + interface CollectionOptions { + comparator? : boolean|string|((a : T, b : T) => number); + } + + interface CollectionAddOptions extends EventOptions { + at? : number; + merge? : boolean; + } + + interface CollectionFetchOptions { + require? : boolean; + withRelated? : string|string[]; + } + + interface CollectionFetchOneOptions { + require? : boolean; + columns? : string|string[]; + } + + interface CollectionSetOptions extends EventOptions { + add? : boolean; + remove? : boolean; + merge?: boolean; + } + + interface PivotOptions { + query? : Function|any; + require? : boolean; + } + + interface EventOptions { + silent? : boolean; + } + + interface EventFunction { + (model: T, attrs: any, options: any) : Promise|void; + } + + interface CollectionCreateOptions extends ModelOptions, SyncOptions, CollectionAddOptions, SaveOptions {} +} + +export = Bookshelf; + diff --git a/bookshelf/tsconfig.json b/bookshelf/tsconfig.json new file mode 100644 index 0000000000..c789d28f14 --- /dev/null +++ b/bookshelf/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bookshelf-tests.ts" + ] +} \ No newline at end of file diff --git a/boolify-string/boolify-string-tests.ts b/boolify-string/boolify-string-tests.ts index 1436a1aeae..80a68375a9 100644 --- a/boolify-string/boolify-string-tests.ts +++ b/boolify-string/boolify-string-tests.ts @@ -1,4 +1,3 @@ -/// import boolifyString = require('boolify-string'); diff --git a/boolify-string/boolify-string.d.ts b/boolify-string/boolify-string.d.ts deleted file mode 100644 index d4ab286a5e..0000000000 --- a/boolify-string/boolify-string.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for boolify-string -// Project: https://github.com/sanemat/node-boolify-string -// Definitions by: Tobias Henöckl -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "boolify-string" { - function boolifyString(obj: any): boolean; - export = boolifyString; -} diff --git a/boolify-string/index.d.ts b/boolify-string/index.d.ts new file mode 100644 index 0000000000..8d405fe032 --- /dev/null +++ b/boolify-string/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for boolify-string +// Project: https://github.com/sanemat/node-boolify-string +// Definitions by: Tobias Henöckl +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function boolifyString(obj: any): boolean; +export = boolifyString; diff --git a/boolify-string/tsconfig.json b/boolify-string/tsconfig.json new file mode 100644 index 0000000000..c25af627ad --- /dev/null +++ b/boolify-string/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "boolify-string-tests.ts" + ] +} \ No newline at end of file diff --git a/boom/boom-tests.ts b/boom/boom-tests.ts index 67c7786273..4c2f23ed64 100644 --- a/boom/boom-tests.ts +++ b/boom/boom-tests.ts @@ -1,4 +1,4 @@ -/// + import Boom = require('boom'); diff --git a/boom/boom.d.ts b/boom/boom.d.ts deleted file mode 100644 index 85c2e22b35..0000000000 --- a/boom/boom.d.ts +++ /dev/null @@ -1,59 +0,0 @@ -// Type definitions for boom -// Project: http://github.com/hapijs/boom -// Definitions by: Igor Rogatty -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Boom { - - export interface BoomError { - data: any; - reformat: () => void; - isBoom: boolean; - isServer: boolean; - message: string; - output: Output; - } - - export interface Output { - statusCode: number; - headers: any; - payload: any; - } - - export function wrap(error: Error, statusCode?: number, message?: string): BoomError; - export function create(statusCode: number, message?: string, data?: any): BoomError; - - // 4xx - export function badRequest(message?: string, data?: any): BoomError; - export function unauthorized(message?: string, scheme?: any, attributes?: any): BoomError; - export function forbidden(message?: string, data?: any): BoomError; - export function notFound(message?: string, data?: any): BoomError; - export function methodNotAllowed(message?: string, data?: any): BoomError; - export function notAcceptable(message?: string, data?: any): BoomError; - export function proxyAuthRequired(message?: string, data?: any): BoomError; - export function clientTimeout(message?: string, data?: any): BoomError; - export function conflict(message?: string, data?: any): BoomError; - export function resourceGone(message?: string, data?: any): BoomError; - export function lengthRequired(message?: string, data?: any): BoomError; - export function preconditionFailed(message?: string, data?: any): BoomError; - export function entityTooLarge(message?: string, data?: any): BoomError; - export function uriTooLong(message?: string, data?: any): BoomError; - export function unsupportedMediaType(message?: string, data?: any): BoomError; - export function rangeNotSatisfiable(message?: string, data?: any): BoomError; - export function expectationFailed(message?: string, data?: any): BoomError; - export function badData(message?: string, data?: any): BoomError; - export function tooManyRequests(message?: string, data?: any): BoomError; - - // 5xx - export function notImplemented(message?: string, data?: any): BoomError; - export function badGateway(message?: string, data?: any): BoomError; - export function serverTimeout(message?: string, data?: any): BoomError; - export function gatewayTimeout(message?: string, data?: any): BoomError; - export function badImplementation(message?: string, data?: any): BoomError; -} - -declare module "boom" { - export = Boom; -} diff --git a/boom/index.d.ts b/boom/index.d.ts new file mode 100644 index 0000000000..6945673678 --- /dev/null +++ b/boom/index.d.ts @@ -0,0 +1,57 @@ +// Type definitions for boom +// Project: http://github.com/hapijs/boom +// Definitions by: Igor Rogatty +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = Boom; + +declare namespace Boom { + + export interface BoomError { + data: any; + reformat: () => void; + isBoom: boolean; + isServer: boolean; + message: string; + output: Output; + } + + export interface Output { + statusCode: number; + headers: any; + payload: any; + } + + export function wrap(error: Error, statusCode?: number, message?: string): BoomError; + export function create(statusCode: number, message?: string, data?: any): BoomError; + + // 4xx + export function badRequest(message?: string, data?: any): BoomError; + export function unauthorized(message?: string, scheme?: any, attributes?: any): BoomError; + export function forbidden(message?: string, data?: any): BoomError; + export function notFound(message?: string, data?: any): BoomError; + export function methodNotAllowed(message?: string, data?: any): BoomError; + export function notAcceptable(message?: string, data?: any): BoomError; + export function proxyAuthRequired(message?: string, data?: any): BoomError; + export function clientTimeout(message?: string, data?: any): BoomError; + export function conflict(message?: string, data?: any): BoomError; + export function resourceGone(message?: string, data?: any): BoomError; + export function lengthRequired(message?: string, data?: any): BoomError; + export function preconditionFailed(message?: string, data?: any): BoomError; + export function entityTooLarge(message?: string, data?: any): BoomError; + export function uriTooLong(message?: string, data?: any): BoomError; + export function unsupportedMediaType(message?: string, data?: any): BoomError; + export function rangeNotSatisfiable(message?: string, data?: any): BoomError; + export function expectationFailed(message?: string, data?: any): BoomError; + export function badData(message?: string, data?: any): BoomError; + export function tooManyRequests(message?: string, data?: any): BoomError; + + // 5xx + export function notImplemented(message?: string, data?: any): BoomError; + export function badGateway(message?: string, data?: any): BoomError; + export function serverTimeout(message?: string, data?: any): BoomError; + export function gatewayTimeout(message?: string, data?: any): BoomError; + export function badImplementation(message?: string, data?: any): BoomError; +} diff --git a/boom/tsconfig.json b/boom/tsconfig.json new file mode 100644 index 0000000000..0ca34d3a08 --- /dev/null +++ b/boom/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "boom-tests.ts" + ] +} \ No newline at end of file diff --git a/bootbox/bootbox-tests.ts b/bootbox/bootbox-tests.ts index 83837d41fa..92a079f456 100644 --- a/bootbox/bootbox-tests.ts +++ b/bootbox/bootbox-tests.ts @@ -1,5 +1,5 @@ // QUnit Tests for Bootbox 4.4.0 -/// + bootbox.alert("Are we ok?"); bootbox.alert("Are we ok with callback?", function () { diff --git a/bootbox/bootbox.d.ts b/bootbox/bootbox.d.ts deleted file mode 100644 index ce422de880..0000000000 --- a/bootbox/bootbox.d.ts +++ /dev/null @@ -1,105 +0,0 @@ -// Type definitions for Bootbox 4.4.0 -// Project: https://github.com/makeusabrew/bootbox -// Definitions by: Vincent Bortone , Kon Pik , Anup Kattel , Dominik Schroeter , Troy McKinnon -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -/** Bootbox options shared by all modal types */ -interface BootboxBaseOptions { - title?: string | Element; - callback?: (result: boolean | string) => any; - onEscape?: () => any | boolean; - show?: boolean; - backdrop?: boolean; - closeButton?: boolean; - animate?: boolean; - className?: string; - size?: string; - buttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton -} - -/** Bootbox options available for custom modals */ -interface BootboxDialogOptions extends BootboxBaseOptions { - message: string | Element; -} - -/** Bootbox options available for alert modals */ -interface BootboxAlertOptions extends BootboxDialogOptions { - callback?: () => any; - buttons?: BootboxAlertButtonMap; -} - -/** Bootbox options available for confirm modals */ -interface BootboxConfirmOptions extends BootboxDialogOptions { - callback: (result: boolean) => any; - buttons?: BootboxConfirmPromptButtonMap; -} - -/** Bootbox options available for prompt modals */ -interface BootboxPromptOptions extends BootboxBaseOptions { - title: string; - value?: string; - callback: (result: string) => any; - buttons?: BootboxConfirmPromptButtonMap; -} - -/** Bootbox options available when setting defaults for modals */ -interface BootboxDefaultOptions { - locale?: string; - show?: boolean; - backdrop?: boolean; - closeButton?: boolean; - animate?: boolean; - className?: string; -} - -interface BootboxButton { - label?: string; - className?: string; - callback?: () => any; -} - -interface BootboxButtonMap { - [key: string]: BootboxButton | Function; -} - -/** ButtonMap options for alerts modals */ -interface BootboxAlertButtonMap extends BootboxButtonMap { - ok: BootboxButton | Function; -} - -/** ButtonMap options for confirm and prompt modals */ -interface BootboxConfirmPromptButtonMap extends BootboxButtonMap { - confirm: BootboxButton | Function; - cancel: BootboxButton | Function; -} - -interface BootboxLocaleValues { - OK: string; - CANCEL: string; - CONFIRM: string; -} - -interface BootboxStatic { - alert(message: string, callback?: () => void): JQuery; - alert(options: BootboxAlertOptions): JQuery; - confirm(message: string, callback: (result: boolean) => void): JQuery; - confirm(options: BootboxConfirmOptions): JQuery; - prompt(message: string, callback: (result: string) => void): JQuery; - prompt(options: BootboxPromptOptions): JQuery; - dialog(message: string, callback?: (result: string) => void): JQuery; - dialog(options: BootboxDialogOptions): JQuery; - setDefaults(options: BootboxDefaultOptions): void; - hideAll(): void; - - addLocale(name: string, values: BootboxLocaleValues): void; - removeLocale(name: string): void; - setLocale(name: string): void; -} - -declare var bootbox: BootboxStatic; - -declare module "bootbox" { - export = bootbox; -} diff --git a/bootbox/index.d.ts b/bootbox/index.d.ts new file mode 100644 index 0000000000..28ba5072d1 --- /dev/null +++ b/bootbox/index.d.ts @@ -0,0 +1,105 @@ +// Type definitions for Bootbox 4.4.0 +// Project: https://github.com/makeusabrew/bootbox +// Definitions by: Vincent Bortone , Kon Pik , Anup Kattel , Dominik Schroeter , Troy McKinnon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** Bootbox options shared by all modal types */ +interface BootboxBaseOptions { + title?: string | Element; + callback?: (result: boolean | string) => any; + onEscape?: () => any | boolean; + show?: boolean; + backdrop?: boolean; + closeButton?: boolean; + animate?: boolean; + className?: string; + size?: string; + buttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton +} + +/** Bootbox options available for custom modals */ +interface BootboxDialogOptions extends BootboxBaseOptions { + message: string | Element; +} + +/** Bootbox options available for alert modals */ +interface BootboxAlertOptions extends BootboxDialogOptions { + callback?: () => any; + buttons?: BootboxAlertButtonMap; +} + +/** Bootbox options available for confirm modals */ +interface BootboxConfirmOptions extends BootboxDialogOptions { + callback: (result: boolean) => any; + buttons?: BootboxConfirmPromptButtonMap; +} + +/** Bootbox options available for prompt modals */ +interface BootboxPromptOptions extends BootboxBaseOptions { + title: string; + value?: string; + callback: (result: string) => any; + buttons?: BootboxConfirmPromptButtonMap; +} + +/** Bootbox options available when setting defaults for modals */ +interface BootboxDefaultOptions { + locale?: string; + show?: boolean; + backdrop?: boolean; + closeButton?: boolean; + animate?: boolean; + className?: string; +} + +interface BootboxButton { + label?: string; + className?: string; + callback?: () => any; +} + +interface BootboxButtonMap { + [key: string]: BootboxButton | Function; +} + +/** ButtonMap options for alerts modals */ +interface BootboxAlertButtonMap extends BootboxButtonMap { + ok: BootboxButton | Function; +} + +/** ButtonMap options for confirm and prompt modals */ +interface BootboxConfirmPromptButtonMap extends BootboxButtonMap { + confirm: BootboxButton | Function; + cancel: BootboxButton | Function; +} + +interface BootboxLocaleValues { + OK: string; + CANCEL: string; + CONFIRM: string; +} + +interface BootboxStatic { + alert(message: string, callback?: () => void): JQuery; + alert(options: BootboxAlertOptions): JQuery; + confirm(message: string, callback: (result: boolean) => void): JQuery; + confirm(options: BootboxConfirmOptions): JQuery; + prompt(message: string, callback: (result: string) => void): JQuery; + prompt(options: BootboxPromptOptions): JQuery; + dialog(message: string, callback?: (result: string) => void): JQuery; + dialog(options: BootboxDialogOptions): JQuery; + setDefaults(options: BootboxDefaultOptions): void; + hideAll(): void; + + addLocale(name: string, values: BootboxLocaleValues): void; + removeLocale(name: string): void; + setLocale(name: string): void; +} + +declare var bootbox: BootboxStatic; + +declare module "bootbox" { + export = bootbox; +} diff --git a/bootbox/tsconfig.json b/bootbox/tsconfig.json new file mode 100644 index 0000000000..4c5702a4ce --- /dev/null +++ b/bootbox/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bootbox-tests.ts" + ] +} \ No newline at end of file diff --git a/bootpag/bootpag-tests.ts b/bootpag/bootpag-tests.ts index a0986e74cc..6a5503f9f8 100644 --- a/bootpag/bootpag-tests.ts +++ b/bootpag/bootpag-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// var pagerSelector = ".bootpager"; var $pager = $(pagerSelector); diff --git a/bootpag/bootpag.d.ts b/bootpag/bootpag.d.ts deleted file mode 100644 index fef37711cd..0000000000 --- a/bootpag/bootpag.d.ts +++ /dev/null @@ -1,126 +0,0 @@ -// Type definitions for jQuery-Bootpag 1.0.7 -// Project: http://botmonster.com/jquery-bootpag/ -// Definitions by: MAF.DAP / Romain Deneau -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace JqueryBootpag { - /** - * Bootpag plugin interface options - */ - export interface Options { - /** - * number of pages - */ - total: number; - - /** - * maximum number of visible pages - */ - maxVisible: number; - - /** - * page to show on start - */ - page?: number; - - /** - * next/prev buttons move over one page or maximum visible pages (default true) - */ - leaps?: boolean; - - /** - * next button text (default "�") - */ - next?: string; - - /** - * prev button text (default "�") - */ - prev?: string; - - /** - * template for pagination links (default "javascript:void(0);") - */ - href?: string; - - /** - * variable name in href template for page number (default "{{number}}") - */ - hrefVariable?: string; - - /** - * do we ant first and last (default true) - */ - firstLastUse?: boolean; - - /** - * name of first (default 'FIRST') - */ - first?: string; - - /** - * name of last (default 'LAST') - */ - last?: string; - - /** - * css class for wrap (default 'pagination') - */ - wrapClass?: string; - - /** - * css class for active (default 'active') - */ - activeClass?: string; - - /** - * css class for disabled (default 'disabled') - */ - disabledClass?: string; - - /** - * css class for next (default 'next') - */ - nextClass?: string; - - /** - * css class for prev (default 'prev') - */ - prevClass?: string; - - /** - * css class for last (default 'last') - */ - lastClass?: string; - - /** - * css class for first (default 'first') - */ - firstClass?: string; - } - - /** - * Event handler on page click. - * @param event : JQueryEventObject - * @param pageNumber : number of the clicked page - */ - interface PageEventHandler { - (event: JQueryEventObject, pageNumber: number): any; - } -} - -interface JQuery { - /** - * jQuery Bootpag plugin main method - */ - bootpag(options: JqueryBootpag.Options): JQuery; - - /** - * jQuery Bootpag "page" event occurring on page click. - * @param eventName : always "page" - * @param handler : A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(eventName: "page", handler: JqueryBootpag.PageEventHandler): JQuery; -} diff --git a/bootpag/index.d.ts b/bootpag/index.d.ts new file mode 100644 index 0000000000..2063cf5b93 --- /dev/null +++ b/bootpag/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for jQuery-Bootpag 1.0.7 +// Project: http://botmonster.com/jquery-bootpag/ +// Definitions by: MAF.DAP / Romain Deneau +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace JqueryBootpag { + /** + * Bootpag plugin interface options + */ + export interface Options { + /** + * number of pages + */ + total: number; + + /** + * maximum number of visible pages + */ + maxVisible: number; + + /** + * page to show on start + */ + page?: number; + + /** + * next/prev buttons move over one page or maximum visible pages (default true) + */ + leaps?: boolean; + + /** + * next button text (default "�") + */ + next?: string; + + /** + * prev button text (default "�") + */ + prev?: string; + + /** + * template for pagination links (default "javascript:void(0);") + */ + href?: string; + + /** + * variable name in href template for page number (default "{{number}}") + */ + hrefVariable?: string; + + /** + * do we ant first and last (default true) + */ + firstLastUse?: boolean; + + /** + * name of first (default 'FIRST') + */ + first?: string; + + /** + * name of last (default 'LAST') + */ + last?: string; + + /** + * css class for wrap (default 'pagination') + */ + wrapClass?: string; + + /** + * css class for active (default 'active') + */ + activeClass?: string; + + /** + * css class for disabled (default 'disabled') + */ + disabledClass?: string; + + /** + * css class for next (default 'next') + */ + nextClass?: string; + + /** + * css class for prev (default 'prev') + */ + prevClass?: string; + + /** + * css class for last (default 'last') + */ + lastClass?: string; + + /** + * css class for first (default 'first') + */ + firstClass?: string; + } + + /** + * Event handler on page click. + * @param event : JQueryEventObject + * @param pageNumber : number of the clicked page + */ + interface PageEventHandler { + (event: JQueryEventObject, pageNumber: number): any; + } +} + +interface JQuery { + /** + * jQuery Bootpag plugin main method + */ + bootpag(options: JqueryBootpag.Options): JQuery; + + /** + * jQuery Bootpag "page" event occurring on page click. + * @param eventName : always "page" + * @param handler : A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(eventName: "page", handler: JqueryBootpag.PageEventHandler): JQuery; +} diff --git a/bootpag/tsconfig.json b/bootpag/tsconfig.json new file mode 100644 index 0000000000..9b2a07d1b1 --- /dev/null +++ b/bootpag/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bootpag-tests.ts" + ] +} \ No newline at end of file diff --git a/bootstrap-maxlength/bootstrap-maxlength-tests.ts b/bootstrap-maxlength/bootstrap-maxlength-tests.ts index 8a17cc7ff9..32255bc66b 100644 --- a/bootstrap-maxlength/bootstrap-maxlength-tests.ts +++ b/bootstrap-maxlength/bootstrap-maxlength-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// // Examples from the projects github page $('input[maxlength]').maxlength(); diff --git a/bootstrap-maxlength/bootstrap-maxlength.d.ts b/bootstrap-maxlength/bootstrap-maxlength.d.ts deleted file mode 100644 index 024ebcba5f..0000000000 --- a/bootstrap-maxlength/bootstrap-maxlength.d.ts +++ /dev/null @@ -1,158 +0,0 @@ -// Type definitions for bootstrap-maxlength v1.7.0 -// Project: https://github.com/mimo84/bootstrap-maxlength -// Definitions by: Dan Manastireanu -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace BootstrapMaxlength { - - /** - * Possible options for the position of the counter. (passed to $.fn.css) - */ - interface PlacementOptions { - /** - * The top position of the counter (Number of pixels, or a px or percent string) - */ - top?: Number | string, - /** - * The right position of the counter (Number of pixels, or a px or percent string) - */ - right?: Number | string, - /** - * The bottom position of the counter (Number of pixels, or a px or percent string) - */ - bottom?: Number | string, - /** - * The left position of the counter (Number of pixels, or a px or percent string) - */ - left?: Number | string, - /** - * The positioning to use. For example 'relative', 'absolute' - */ - position?: string - } - - /** - * Representation of the current input position - */ - interface PositionParam { - top: Number, - right: Number, - bottom: Number, - left: Number, - width: Number, - height: Number - } - - export interface Options { - /** - * If true the threshold will be ignored and the remaining length indication will be always showing up while typing or on focus on the input - * @default false - */ - alwaysShow?: Boolean, - /** - * This is a number indicating how many chars are left to start displaying the indications - * @default 10 - */ - threshold?: Number, - /** - * It's the class of the element with the indicator. By default is the bootstrap "label label-success" but can be changed to anything you'd like. - * @default 'label label-success' - */ - warningClass?: string, - /** - * It's the class the element gets when the limit is reached. Default is "label label-important label-danger" (to support Bootstrap 2 and 3). - * @default 'label label-important label-danger' - */ - limitReachedClass?: string, - /** - * Represents the separator between the number of typed chars and total number of available chars. - * @default ' / ' - */ - separator?: string, - /** - * Is a string of text that can be outputted in front of the indicator. - * @default '' - */ - preText?: string, - /** - * Is a string outputted after the indicator. - * @default '' - */ - postText?: string, - /** - * If false, will display just the number of typed characters, e.g. will not display the max length. - * @default true - */ - showMaxLength?: Boolean, - /** - * If false, will display just the remaining length, e.g. will display remaining lenght instead of number of typed characters. - * @default true - */ - showCharsTyped?: Boolean, - /** - * Is a string, define where to output the counter. - * Options: bottom, left, top, right, bottom-right, top-right, top-left, bottom-left and centered-right - * @default 'bottom' - */ - placement?: string | PlacementOptions | ((currentInput: JQuery, maxLengthIndicator: JQuery, currentInputPosition: PositionParam) => void), - /** - * Appends the maxlength indicator badge to the parent of the input rather than to the body. - * @default false - */ - appendToParent?: boolean, - /** - * An alternative way to provide the message text. - * String example: 'You have typed %charsTyped% chars, %charsRemaining% of %charsTotal% remaining'. - * %charsTyped%, %charsRemaining% and %charsTotal% will be replaced by the actual values. This overrides the options separator, preText, postText and showMaxLength. - * Alternatively you may supply a function that the current text and max length and returns the string to be displayed. - * Function example: function(currentText, maxLength) { return '' + Math.ceil(currentText.length / 160) + ' SMS Message(s)'; } - * @default null - */ - message?: string | ((currentText : string, maxLength: Number) => string), - /** - * If true the input will count using utf8 bytesize/encoding. For example: the '�' character is counted as two characters. - * @default false - */ - utf8?: boolean, - /** - * Shows the badge as soon as it is added to the page, similar to alwaysShow - * @default false - */ - showOnReady?: boolean, - /** - * Count linebreak as 2 characters to match IE/Chrome textarea validation. As well as DB storage. - * @default true - */ - twoCharLinebreak?: boolean, - /** - * Allows a custom attribute to display indicator without triggering native maxlength behaviour. - * Ignored if value greater than a native maxlength attribute. - * 'overmax' class gets added when exceeded to allow user to implement form validation. - * @default null (use the maxlength attribute and browser functionality) - */ - customMaxAttribute?: string, - /** - * Will allow the input to be over the customMaxLength. Useful in soft max situations. - * @default false - */ - allowOverMax?: boolean, - /** - * If the browser doesn't support the maxlength attribute, attempt to type more than - * the indicated chars, will be prevented. - * @default false - */ - validate?: boolean - } -} - - -interface JQuery { - /** Apply the maxlength plugin on the selected elemens */ - maxlength(options?: BootstrapMaxlength.Options): JQuery; - on(events: 'maxlength.shown', handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - on(events: 'maxlength.hidden', handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - trigger(eventType: 'maxlength.reposition', extraParameters?: any[]|Object): JQuery; - -} diff --git a/bootstrap-maxlength/index.d.ts b/bootstrap-maxlength/index.d.ts new file mode 100644 index 0000000000..fefe196dff --- /dev/null +++ b/bootstrap-maxlength/index.d.ts @@ -0,0 +1,158 @@ +// Type definitions for bootstrap-maxlength v1.7.0 +// Project: https://github.com/mimo84/bootstrap-maxlength +// Definitions by: Dan Manastireanu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace BootstrapMaxlength { + + /** + * Possible options for the position of the counter. (passed to $.fn.css) + */ + interface PlacementOptions { + /** + * The top position of the counter (Number of pixels, or a px or percent string) + */ + top?: Number | string, + /** + * The right position of the counter (Number of pixels, or a px or percent string) + */ + right?: Number | string, + /** + * The bottom position of the counter (Number of pixels, or a px or percent string) + */ + bottom?: Number | string, + /** + * The left position of the counter (Number of pixels, or a px or percent string) + */ + left?: Number | string, + /** + * The positioning to use. For example 'relative', 'absolute' + */ + position?: string + } + + /** + * Representation of the current input position + */ + interface PositionParam { + top: Number, + right: Number, + bottom: Number, + left: Number, + width: Number, + height: Number + } + + export interface Options { + /** + * If true the threshold will be ignored and the remaining length indication will be always showing up while typing or on focus on the input + * @default false + */ + alwaysShow?: Boolean, + /** + * This is a number indicating how many chars are left to start displaying the indications + * @default 10 + */ + threshold?: Number, + /** + * It's the class of the element with the indicator. By default is the bootstrap "label label-success" but can be changed to anything you'd like. + * @default 'label label-success' + */ + warningClass?: string, + /** + * It's the class the element gets when the limit is reached. Default is "label label-important label-danger" (to support Bootstrap 2 and 3). + * @default 'label label-important label-danger' + */ + limitReachedClass?: string, + /** + * Represents the separator between the number of typed chars and total number of available chars. + * @default ' / ' + */ + separator?: string, + /** + * Is a string of text that can be outputted in front of the indicator. + * @default '' + */ + preText?: string, + /** + * Is a string outputted after the indicator. + * @default '' + */ + postText?: string, + /** + * If false, will display just the number of typed characters, e.g. will not display the max length. + * @default true + */ + showMaxLength?: Boolean, + /** + * If false, will display just the remaining length, e.g. will display remaining lenght instead of number of typed characters. + * @default true + */ + showCharsTyped?: Boolean, + /** + * Is a string, define where to output the counter. + * Options: bottom, left, top, right, bottom-right, top-right, top-left, bottom-left and centered-right + * @default 'bottom' + */ + placement?: string | PlacementOptions | ((currentInput: JQuery, maxLengthIndicator: JQuery, currentInputPosition: PositionParam) => void), + /** + * Appends the maxlength indicator badge to the parent of the input rather than to the body. + * @default false + */ + appendToParent?: boolean, + /** + * An alternative way to provide the message text. + * String example: 'You have typed %charsTyped% chars, %charsRemaining% of %charsTotal% remaining'. + * %charsTyped%, %charsRemaining% and %charsTotal% will be replaced by the actual values. This overrides the options separator, preText, postText and showMaxLength. + * Alternatively you may supply a function that the current text and max length and returns the string to be displayed. + * Function example: function(currentText, maxLength) { return '' + Math.ceil(currentText.length / 160) + ' SMS Message(s)'; } + * @default null + */ + message?: string | ((currentText : string, maxLength: Number) => string), + /** + * If true the input will count using utf8 bytesize/encoding. For example: the '�' character is counted as two characters. + * @default false + */ + utf8?: boolean, + /** + * Shows the badge as soon as it is added to the page, similar to alwaysShow + * @default false + */ + showOnReady?: boolean, + /** + * Count linebreak as 2 characters to match IE/Chrome textarea validation. As well as DB storage. + * @default true + */ + twoCharLinebreak?: boolean, + /** + * Allows a custom attribute to display indicator without triggering native maxlength behaviour. + * Ignored if value greater than a native maxlength attribute. + * 'overmax' class gets added when exceeded to allow user to implement form validation. + * @default null (use the maxlength attribute and browser functionality) + */ + customMaxAttribute?: string, + /** + * Will allow the input to be over the customMaxLength. Useful in soft max situations. + * @default false + */ + allowOverMax?: boolean, + /** + * If the browser doesn't support the maxlength attribute, attempt to type more than + * the indicated chars, will be prevented. + * @default false + */ + validate?: boolean + } +} + + +interface JQuery { + /** Apply the maxlength plugin on the selected elemens */ + maxlength(options?: BootstrapMaxlength.Options): JQuery; + on(events: 'maxlength.shown', handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + on(events: 'maxlength.hidden', handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + trigger(eventType: 'maxlength.reposition', extraParameters?: any[]|Object): JQuery; + +} diff --git a/bootstrap-maxlength/tsconfig.json b/bootstrap-maxlength/tsconfig.json new file mode 100644 index 0000000000..d482e7b7d1 --- /dev/null +++ b/bootstrap-maxlength/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bootstrap-maxlength-tests.ts" + ] +} \ No newline at end of file diff --git a/bootstrap-notify/bootstrap-notify-tests.ts b/bootstrap-notify/bootstrap-notify-tests.ts index 8461da8e48..5ae4f2ffc1 100644 --- a/bootstrap-notify/bootstrap-notify-tests.ts +++ b/bootstrap-notify/bootstrap-notify-tests.ts @@ -1,5 +1,5 @@ -/// -/// + +/// //Test for bootstrap-notify v3.1.3 //Copied example directly from Bootstrap-notify site diff --git a/bootstrap-notify/bootstrap-notify.d.ts b/bootstrap-notify/bootstrap-notify.d.ts deleted file mode 100644 index acdb83b9fd..0000000000 --- a/bootstrap-notify/bootstrap-notify.d.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Type definitions for bootstrap-notify v3.1.3 -// Project: http://bootstrap-notify.remabledesigns.com/ -// Definitions by: Blake Niemyjski , Robert McIntosh , Robert Voica -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -/* tslint:disable: interface-name no-any */ - -interface JQueryStatic { - /* tslint:enable: interface-name */ - notify(message: string): NotifyReturn; - notify(opts: NotifyOptions, settings?: NotifySettings): NotifyReturn; - notifyDefaults(settings: NotifySettings): void; - notifyClose(): void; - notifyClose(command: string): void; -} - -interface NotifyOptions { - message: string; - title?: string; - icon?: string; - url?: string; - target?: string; -} - -interface NotifySettings { - element?: string; - position?: string; - type?: string; - allow_dismiss?: boolean; - allow_duplicates?: boolean; - newest_on_top?: boolean; - showProgressbar?: boolean; - placement?: { - from?: string; - align?: string; - }; - offset?: number; - spacing?: number; - z_index?: number; - delay?: number; - timer?: number; - url_target?: string; - mouse_over?: string; - animate?: { - enter?: string; - exit?: string; - }; - onShow?: () => void; - onShown?: () => void; - onClose?: () => void; - onClosed?: () => void; - icon_type?: string; - template?: string; -} - -interface NotifyReturn { - $ele: JQueryStatic; - close: () => void; - update: (command: string, update: any) => void; -} \ No newline at end of file diff --git a/bootstrap-notify/index.d.ts b/bootstrap-notify/index.d.ts new file mode 100644 index 0000000000..afc7913273 --- /dev/null +++ b/bootstrap-notify/index.d.ts @@ -0,0 +1,62 @@ +// Type definitions for bootstrap-notify v3.1.3 +// Project: http://bootstrap-notify.remabledesigns.com/ +// Definitions by: Blake Niemyjski , Robert McIntosh , Robert Voica +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/* tslint:disable: interface-name no-any */ + +interface JQueryStatic { + /* tslint:enable: interface-name */ + notify(message: string): NotifyReturn; + notify(opts: NotifyOptions, settings?: NotifySettings): NotifyReturn; + notifyDefaults(settings: NotifySettings): void; + notifyClose(): void; + notifyClose(command: string): void; +} + +interface NotifyOptions { + message: string; + title?: string; + icon?: string; + url?: string; + target?: string; +} + +interface NotifySettings { + element?: string; + position?: string; + type?: string; + allow_dismiss?: boolean; + allow_duplicates?: boolean; + newest_on_top?: boolean; + showProgressbar?: boolean; + placement?: { + from?: string; + align?: string; + }; + offset?: number; + spacing?: number; + z_index?: number; + delay?: number; + timer?: number; + url_target?: string; + mouse_over?: string; + animate?: { + enter?: string; + exit?: string; + }; + onShow?: () => void; + onShown?: () => void; + onClose?: () => void; + onClosed?: () => void; + icon_type?: string; + template?: string; +} + +interface NotifyReturn { + $ele: JQueryStatic; + close: () => void; + update: (command: string, update: any) => void; +} \ No newline at end of file diff --git a/bootstrap-notify/tsconfig.json b/bootstrap-notify/tsconfig.json new file mode 100644 index 0000000000..b27df7f92c --- /dev/null +++ b/bootstrap-notify/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bootstrap-notify-tests.ts" + ] +} \ No newline at end of file diff --git a/bootstrap-slider/bootstrap-slider-tests.ts b/bootstrap-slider/bootstrap-slider-tests.ts index 548d909a62..749d8dc137 100644 --- a/bootstrap-slider/bootstrap-slider-tests.ts +++ b/bootstrap-slider/bootstrap-slider-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + $(function() { // examples from http://seiyria.github.io/bootstrap-slider/ diff --git a/bootstrap-slider/bootstrap-slider.d.ts b/bootstrap-slider/bootstrap-slider.d.ts deleted file mode 100644 index 77a5177fa0..0000000000 --- a/bootstrap-slider/bootstrap-slider.d.ts +++ /dev/null @@ -1,207 +0,0 @@ -// Type definitions for bootstrap-slider.js 4.8.3 -// Project: https://github.com/seiyria/bootstrap-slider -// Definitions by: Daniel Beckwith -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface SliderOptions { - /** - * Default: '' - * set the id of the slider element when it's created - */ - id?: string; - /** - * Default: 0 - * minimum possible value - */ - min?: number; - /** - * Default: 10 - * maximum possible value - */ - max?: number; - /** - * Default: 1 - * increment step - */ - step?: number; - /** - * Default: number of digits after the decimal of step value - * The number of digits shown after the decimal. Defaults to the number of digits after the decimal of step value. - */ - precision?: number; - /** - * Default: 'horizontal' - * set the orientation. Accepts 'vertical' or 'horizontal' - */ - orientation?: number; - /** - * Default: 5 - * initial value. Use array to have a range slider. - */ - value?: number|number[]; - /** - * Default: false - * make range slider. Optional if initial value is an array. If initial value is scalar, max will be used for second value. - */ - range?: boolean; - /** - * Default: 'before' - * selection placement. Accepts: 'before', 'after' or 'none'. In case of a range slider, the selection will be placed between the handles - */ - selection?: string; - /** - * Default: 'show' - * whether to show the tooltip on drag, hide the tooltip, or always show the tooltip. Accepts: 'show', 'hide', or 'always' - */ - tooltip?: string; - /** - * Default: false - * if false show one tootip if true show two tooltips one for each handler - */ - tooltip_split?: boolean; - /** - * Default: 'round' - * handle shape. Accepts: 'round', 'square', 'triangle' or 'custom' - */ - handle?: string; - /** - * Default: false - * whether or not the slider should be reversed - */ - reversed?: boolean; - /** - * Default: true - * whether or not the slider is initially enabled - */ - enabled?: boolean; - /** - * Default: returns the plain value - * formatter callback. Return the value wanted to be displayed in the tooltip - * @param val the current value to display - */ - formatter?(val:number): string; - /** - * Default: false - * The natural order is used for the arrow keys. Arrow up select the upper slider value for vertical sliders, arrow right the righter slider value for a horizontal slider - no matter if the slider was reversed or not. By default the arrow keys are oriented by arrow up/right to the higher slider value, arrow down/left to the lower slider value. - */ - natural_arrow_keys?: boolean; - /** - * Default: [ ] - * Used to define the values of ticks. Tick marks are indicators to denote special values in the range. This option overwrites min and max options. - */ - ticks?: number[]; - /** - * Default: [ ] - * Defines the positions of the tick values in percentages. The first value should alwasy be 0, the last value should always be 100 percent. - */ - ticks_positions?: number[]; - /** - * Default: [ ] - * Defines the labels below the tick marks. Accepts HTML input. - */ - ticks_labels?: string[]; - /** - * Default: 0 - * Used to define the snap bounds of a tick. Snaps to the tick if value is within these bounds. - */ - ticks_snap_bounds?: number; - /** - * Default: 'linear' - * Set to 'logarithmic' to use a logarithmic scale. - */ - scale?: string; - /** - * Default: false - * Focus the appropriate slider handle after a value change. - */ - focus?: boolean; -} - -interface JQuery { - /** - * Creates a slider from the current element. - * @param options - */ - slider(options?:SliderOptions): JQuery; - slider(methodName:string, ...args:any[]): JQuery; -} - -interface ChangeValue { - oldValue: number; - newValue: number; -} - -interface JQueryEventObject { - value: number|ChangeValue; -} - -interface SliderStatics { - new (selector: string, opts: SliderOptions): Slider; - prototype: Slider; -} - -declare var Slider: SliderStatics; - -/** - * This class is actually not used when using the jQuery version of bootstrap-slider - * The method documentation is still here thouh. - * When using jQuery, slider methods like setValue(3, true) have to be called like $slider.slider('setValue', 3, true) - */ -interface Slider extends JQuery { - /** - * Get the current value from the slider - */ - getValue(): number; - /** - * Set a new value for the slider. If optional triggerSlideEvent parameter is true, 'slide' events will be triggered. If optional triggerChangeEvent parameter is true, 'change' events will be triggered. - * @param newValue - * @param triggerSlideEvent - * @param triggerChangeEvent - */ - setValue(newValue:number, triggerSlideEvent?:boolean, triggerChangeEvent?:boolean): void; - /** - * Properly clean up and remove the slider instance - */ - destroy(): void; - /** - * Disables the slider and prevents the user from changing the value - */ - disable(): void; - /** - * Enables the slider - */ - enable(): void; - /** - * Returns true if enabled, false if disabled - */ - isEnabled(): boolean; - /** - * Updates the slider's attributes - * @param attribute - * @param value - */ - setAttribute(attribute:string, value:any): void; - /** - * Get the slider's attributes - * @param attribute - */ - getAttribute(attribute:string): any; - /** - * Refreshes the current slider - */ - refresh(): void; - /** - * Renders the tooltip again, after initialization. Useful in situations when the slider and tooltip are initially hidden. - */ - relayout(): void; - on: { - (eventType:string, callback:(eventObject:JQueryEventObject, ...args:any[]) => any): Slider; - (eventType:string, data:any, callback:(eventObject:JQueryEventObject, ...args:any[]) => any): Slider; - (eventType:string, selector:string, callback:(eventObject:JQueryEventObject, ...eventData:any[]) => any): Slider; - (eventType:string, selector:string, data:any, callback:(eventObject:JQueryEventObject, ...eventData:any[]) => any): Slider; - (eventType:{ [key: string]: any; }, selector?:string, data?:any): Slider; - (eventType:{ [key: string]: any; }, data?:any): Slider; - } -} diff --git a/bootstrap-slider/index.d.ts b/bootstrap-slider/index.d.ts new file mode 100644 index 0000000000..0d704c0dfc --- /dev/null +++ b/bootstrap-slider/index.d.ts @@ -0,0 +1,207 @@ +// Type definitions for bootstrap-slider.js 4.8.3 +// Project: https://github.com/seiyria/bootstrap-slider +// Definitions by: Daniel Beckwith +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface SliderOptions { + /** + * Default: '' + * set the id of the slider element when it's created + */ + id?: string; + /** + * Default: 0 + * minimum possible value + */ + min?: number; + /** + * Default: 10 + * maximum possible value + */ + max?: number; + /** + * Default: 1 + * increment step + */ + step?: number; + /** + * Default: number of digits after the decimal of step value + * The number of digits shown after the decimal. Defaults to the number of digits after the decimal of step value. + */ + precision?: number; + /** + * Default: 'horizontal' + * set the orientation. Accepts 'vertical' or 'horizontal' + */ + orientation?: number; + /** + * Default: 5 + * initial value. Use array to have a range slider. + */ + value?: number|number[]; + /** + * Default: false + * make range slider. Optional if initial value is an array. If initial value is scalar, max will be used for second value. + */ + range?: boolean; + /** + * Default: 'before' + * selection placement. Accepts: 'before', 'after' or 'none'. In case of a range slider, the selection will be placed between the handles + */ + selection?: string; + /** + * Default: 'show' + * whether to show the tooltip on drag, hide the tooltip, or always show the tooltip. Accepts: 'show', 'hide', or 'always' + */ + tooltip?: string; + /** + * Default: false + * if false show one tootip if true show two tooltips one for each handler + */ + tooltip_split?: boolean; + /** + * Default: 'round' + * handle shape. Accepts: 'round', 'square', 'triangle' or 'custom' + */ + handle?: string; + /** + * Default: false + * whether or not the slider should be reversed + */ + reversed?: boolean; + /** + * Default: true + * whether or not the slider is initially enabled + */ + enabled?: boolean; + /** + * Default: returns the plain value + * formatter callback. Return the value wanted to be displayed in the tooltip + * @param val the current value to display + */ + formatter?(val:number): string; + /** + * Default: false + * The natural order is used for the arrow keys. Arrow up select the upper slider value for vertical sliders, arrow right the righter slider value for a horizontal slider - no matter if the slider was reversed or not. By default the arrow keys are oriented by arrow up/right to the higher slider value, arrow down/left to the lower slider value. + */ + natural_arrow_keys?: boolean; + /** + * Default: [ ] + * Used to define the values of ticks. Tick marks are indicators to denote special values in the range. This option overwrites min and max options. + */ + ticks?: number[]; + /** + * Default: [ ] + * Defines the positions of the tick values in percentages. The first value should alwasy be 0, the last value should always be 100 percent. + */ + ticks_positions?: number[]; + /** + * Default: [ ] + * Defines the labels below the tick marks. Accepts HTML input. + */ + ticks_labels?: string[]; + /** + * Default: 0 + * Used to define the snap bounds of a tick. Snaps to the tick if value is within these bounds. + */ + ticks_snap_bounds?: number; + /** + * Default: 'linear' + * Set to 'logarithmic' to use a logarithmic scale. + */ + scale?: string; + /** + * Default: false + * Focus the appropriate slider handle after a value change. + */ + focus?: boolean; +} + +interface JQuery { + /** + * Creates a slider from the current element. + * @param options + */ + slider(options?:SliderOptions): JQuery; + slider(methodName:string, ...args:any[]): JQuery; +} + +interface ChangeValue { + oldValue: number; + newValue: number; +} + +interface JQueryEventObject { + value: number|ChangeValue; +} + +interface SliderStatics { + new (selector: string, opts: SliderOptions): Slider; + prototype: Slider; +} + +declare var Slider: SliderStatics; + +/** + * This class is actually not used when using the jQuery version of bootstrap-slider + * The method documentation is still here thouh. + * When using jQuery, slider methods like setValue(3, true) have to be called like $slider.slider('setValue', 3, true) + */ +interface Slider extends JQuery { + /** + * Get the current value from the slider + */ + getValue(): number; + /** + * Set a new value for the slider. If optional triggerSlideEvent parameter is true, 'slide' events will be triggered. If optional triggerChangeEvent parameter is true, 'change' events will be triggered. + * @param newValue + * @param triggerSlideEvent + * @param triggerChangeEvent + */ + setValue(newValue:number, triggerSlideEvent?:boolean, triggerChangeEvent?:boolean): void; + /** + * Properly clean up and remove the slider instance + */ + destroy(): void; + /** + * Disables the slider and prevents the user from changing the value + */ + disable(): void; + /** + * Enables the slider + */ + enable(): void; + /** + * Returns true if enabled, false if disabled + */ + isEnabled(): boolean; + /** + * Updates the slider's attributes + * @param attribute + * @param value + */ + setAttribute(attribute:string, value:any): void; + /** + * Get the slider's attributes + * @param attribute + */ + getAttribute(attribute:string): any; + /** + * Refreshes the current slider + */ + refresh(): void; + /** + * Renders the tooltip again, after initialization. Useful in situations when the slider and tooltip are initially hidden. + */ + relayout(): void; + on: { + (eventType:string, callback:(eventObject:JQueryEventObject, ...args:any[]) => any): Slider; + (eventType:string, data:any, callback:(eventObject:JQueryEventObject, ...args:any[]) => any): Slider; + (eventType:string, selector:string, callback:(eventObject:JQueryEventObject, ...eventData:any[]) => any): Slider; + (eventType:string, selector:string, data:any, callback:(eventObject:JQueryEventObject, ...eventData:any[]) => any): Slider; + (eventType:{ [key: string]: any; }, selector?:string, data?:any): Slider; + (eventType:{ [key: string]: any; }, data?:any): Slider; + } +} diff --git a/bootstrap-slider/tsconfig.json b/bootstrap-slider/tsconfig.json new file mode 100644 index 0000000000..afed31c049 --- /dev/null +++ b/bootstrap-slider/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bootstrap-slider-tests.ts" + ] +} \ No newline at end of file diff --git a/bootstrap-switch/bootstrap-switch-tests.ts b/bootstrap-switch/bootstrap-switch-tests.ts index 542f71ebd4..17bc0fd561 100644 --- a/bootstrap-switch/bootstrap-switch-tests.ts +++ b/bootstrap-switch/bootstrap-switch-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + function test_cases() { $('#switch').bootstrapSwitch(); diff --git a/bootstrap-switch/bootstrap-switch.d.ts b/bootstrap-switch/bootstrap-switch.d.ts deleted file mode 100644 index b6738a9b8d..0000000000 --- a/bootstrap-switch/bootstrap-switch.d.ts +++ /dev/null @@ -1,102 +0,0 @@ -// Type definitions for Bootstrap Switch -// Project: http://www.bootstrap-switch.org/ -// Definitions by: John M. Baughman -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/** - * bootstrap-switch - v3.3.2 Copyright (c) 2012-2013 Mattia Larentis - * Available via the Apache license. - * see: http://www.bootstrap-switch.org/ or https://github.com/nostalgiaz/bootstrap-switch for details. - */ - -/// - -declare namespace BootstrapSwitch { - interface BootstrapSwitchChangeEventObject extends JQueryEventObject { - state: boolean - } - - interface BootstrapSwitchEventObject extends JQueryEventObject { } - - interface BootstrapSwitchOptions { - state?: boolean; - size?: string; - animate?: boolean; - disabled?: boolean; - readonly?: boolean; - indeterminate?: boolean; - invers?: boolean; - radioAllOff?: boolean; - onColor?: string; - offColor?: string; - onText?: string; - offText?: string; - labelText?: string; - handleWidth?: string; - labelWidth?: string; - baseClass?: string; - wrapperClass?: string; - onInit?: any; - onSwitchChange?: any; - } - - interface Switch { - toggleAnimate(): JQuery; - toggleDisabled(): JQuery; - toggleReadonly(): JQuery; - toggleIndeterminate(): JQuery; - toggleInverse(): JQuery; - destroy(): JQuery; - - state(): boolean; - state(value: any): JQuery; - state(value: any, skip: boolean): JQuery; - toggleState(skip?: boolean): JQuery; - radioAllOff(): boolean; - radioAllOff(state: boolean): JQuery; - size(): string; - size(size: string): JQuery; - animate(): boolean; - animate(state: boolean): JQuery; - disabled(): boolean; - disabled(state: boolean): JQuery; - toggleDisabled(): JQuery; - readonly(): boolean; - readonly(state: boolean): JQuery; - toggleReadOnly(): JQuery; - onColor(): string; - onColor(color: string): JQuery; - offColor(): string; - offColor(color: string): JQuery; - onText(): string; - onText(text: string): JQuery; - offText(): string; - offText(text: string): JQuery; - labelText(): string; - labelText(text: string): JQuery; - baseClass(): string; - baseClass(text: string): JQuery; - wrapperClass(): string; - wrapperClass(text: string): JQuery; - } -} - -interface JQuery { - bootstrapSwitch(): JQuery; - bootstrapSwitch(options: BootstrapSwitch.BootstrapSwitchOptions): JQuery; - bootstrapSwitch(method: string): JQuery; - bootstrapSwitch(method: string, param: any): JQuery; - bootstrapSwitch(method: string, param1: any, param2: any): JQuery; - - off(events: "init.bootstrapSwitch", selector?: string, handler?: (eventobject: BootstrapSwitch.BootstrapSwitchEventObject) => any): JQuery; - off(events: "init.bootstrapSwitch", handler?: (eventobject: BootstrapSwitch.BootstrapSwitchEventObject) => any): JQuery; - - off(events: "switchChange.bootstrapSwitch", selector?: string, handler?: (eventobject: BootstrapSwitch.BootstrapSwitchChangeEventObject) => any): JQuery; - off(events: "switchChange.bootstrapSwitch", handler?: (eventobject: BootstrapSwitch.BootstrapSwitchChangeEventObject) => any): JQuery; - - on(events: "init.bootstrapSwitch", selector?: string, handler?: (eventobject: BootstrapSwitch.BootstrapSwitchEventObject) => any): JQuery; - on(events: "init.bootstrapSwitch", handler?: (eventobject: BootstrapSwitch.BootstrapSwitchEventObject) => any): JQuery; - - on(events: "switchChange.bootstrapSwitch", selector?: string, handler?: (eventobject: BootstrapSwitch.BootstrapSwitchChangeEventObject) => any): JQuery; - on(events: "switchChange.bootstrapSwitch", handler?: (eventobject: BootstrapSwitch.BootstrapSwitchChangeEventObject) => any): JQuery; -} diff --git a/bootstrap-switch/index.d.ts b/bootstrap-switch/index.d.ts new file mode 100644 index 0000000000..fe6d5f5a0c --- /dev/null +++ b/bootstrap-switch/index.d.ts @@ -0,0 +1,102 @@ +// Type definitions for Bootstrap Switch +// Project: http://www.bootstrap-switch.org/ +// Definitions by: John M. Baughman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * bootstrap-switch - v3.3.2 Copyright (c) 2012-2013 Mattia Larentis + * Available via the Apache license. + * see: http://www.bootstrap-switch.org/ or https://github.com/nostalgiaz/bootstrap-switch for details. + */ + +/// + +declare namespace BootstrapSwitch { + interface BootstrapSwitchChangeEventObject extends JQueryEventObject { + state: boolean + } + + interface BootstrapSwitchEventObject extends JQueryEventObject { } + + interface BootstrapSwitchOptions { + state?: boolean; + size?: string; + animate?: boolean; + disabled?: boolean; + readonly?: boolean; + indeterminate?: boolean; + invers?: boolean; + radioAllOff?: boolean; + onColor?: string; + offColor?: string; + onText?: string; + offText?: string; + labelText?: string; + handleWidth?: string; + labelWidth?: string; + baseClass?: string; + wrapperClass?: string; + onInit?: any; + onSwitchChange?: any; + } + + interface Switch { + toggleAnimate(): JQuery; + toggleDisabled(): JQuery; + toggleReadonly(): JQuery; + toggleIndeterminate(): JQuery; + toggleInverse(): JQuery; + destroy(): JQuery; + + state(): boolean; + state(value: any): JQuery; + state(value: any, skip: boolean): JQuery; + toggleState(skip?: boolean): JQuery; + radioAllOff(): boolean; + radioAllOff(state: boolean): JQuery; + size(): string; + size(size: string): JQuery; + animate(): boolean; + animate(state: boolean): JQuery; + disabled(): boolean; + disabled(state: boolean): JQuery; + toggleDisabled(): JQuery; + readonly(): boolean; + readonly(state: boolean): JQuery; + toggleReadOnly(): JQuery; + onColor(): string; + onColor(color: string): JQuery; + offColor(): string; + offColor(color: string): JQuery; + onText(): string; + onText(text: string): JQuery; + offText(): string; + offText(text: string): JQuery; + labelText(): string; + labelText(text: string): JQuery; + baseClass(): string; + baseClass(text: string): JQuery; + wrapperClass(): string; + wrapperClass(text: string): JQuery; + } +} + +interface JQuery { + bootstrapSwitch(): JQuery; + bootstrapSwitch(options: BootstrapSwitch.BootstrapSwitchOptions): JQuery; + bootstrapSwitch(method: string): JQuery; + bootstrapSwitch(method: string, param: any): JQuery; + bootstrapSwitch(method: string, param1: any, param2: any): JQuery; + + off(events: "init.bootstrapSwitch", selector?: string, handler?: (eventobject: BootstrapSwitch.BootstrapSwitchEventObject) => any): JQuery; + off(events: "init.bootstrapSwitch", handler?: (eventobject: BootstrapSwitch.BootstrapSwitchEventObject) => any): JQuery; + + off(events: "switchChange.bootstrapSwitch", selector?: string, handler?: (eventobject: BootstrapSwitch.BootstrapSwitchChangeEventObject) => any): JQuery; + off(events: "switchChange.bootstrapSwitch", handler?: (eventobject: BootstrapSwitch.BootstrapSwitchChangeEventObject) => any): JQuery; + + on(events: "init.bootstrapSwitch", selector?: string, handler?: (eventobject: BootstrapSwitch.BootstrapSwitchEventObject) => any): JQuery; + on(events: "init.bootstrapSwitch", handler?: (eventobject: BootstrapSwitch.BootstrapSwitchEventObject) => any): JQuery; + + on(events: "switchChange.bootstrapSwitch", selector?: string, handler?: (eventobject: BootstrapSwitch.BootstrapSwitchChangeEventObject) => any): JQuery; + on(events: "switchChange.bootstrapSwitch", handler?: (eventobject: BootstrapSwitch.BootstrapSwitchChangeEventObject) => any): JQuery; +} diff --git a/bootstrap-switch/tsconfig.json b/bootstrap-switch/tsconfig.json new file mode 100644 index 0000000000..1ac64e6a95 --- /dev/null +++ b/bootstrap-switch/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bootstrap-switch-tests.ts" + ] +} \ No newline at end of file diff --git a/bootstrap-touchspin/bootstrap-touchspin-tests.ts b/bootstrap-touchspin/bootstrap-touchspin-tests.ts index 552c26f52f..d3c37d87d7 100644 --- a/bootstrap-touchspin/bootstrap-touchspin-tests.ts +++ b/bootstrap-touchspin/bootstrap-touchspin-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + $(function () { // Example 1 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ diff --git a/bootstrap-touchspin/bootstrap-touchspin.d.ts b/bootstrap-touchspin/bootstrap-touchspin.d.ts deleted file mode 100644 index 7334e37bbb..0000000000 --- a/bootstrap-touchspin/bootstrap-touchspin.d.ts +++ /dev/null @@ -1,130 +0,0 @@ -// Type definitions for Bootstrap TouchSpin -// Project: http://www.virtuosoft.eu/code/bootstrap-touchspin/ -// Definitions by: Albin Sunnanbo -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -/** - * TouchSpinOptions. All options are optional - */ -interface TouchSpinOptions { - /** - * Applied when no explicit value is set on the input with the value attribute. - * Empty string means that the value remains empty on initialization. - */ - initval?: number | string; - - /** - * Minimum value. - */ - min?: number; - - /** - * Maximum value. - */ - max?: number; - - /** - * Incremental/decremental step on up/down change. - */ - step?: number; - - /** - * How to force the value to be divisible by step value: 'none' | 'round' | 'floor' | 'ceil' - */ - forcestepdivisibility?: string; - - /** - * Number of decimal points. - */ - decimals?: number; - - /** - * Refresh rate of the spinner in milliseconds. - */ - stepinterval?: number; - - /** - * Time in milliseconds before the spinner starts to spin. - */ - stepintervaldelay?: number; - - /** - * Enables the traditional up/down buttons. - */ - verticalbuttons?: boolean; - - /** - * Class of the up button with vertical buttons mode enabled. - */ - verticalupclass?: string; - - /** - * Class of the down button with vertical buttons mode enabled. - */ - verticaldownclass?: string; - - /** - * Text before the input. - */ - prefix?: string; - - /** - * Text after the input. - */ - postfix?: string; - - /** - * Extra class(es) for prefix. - */ - prefix_extraclass?: string; - - /** - * Extra class(es) for postfix. - */ - postfix_extraclass?: string; - - /** - * If enabled, the the spinner is continually becoming faster as holding the button. - */ - booster?: boolean; - - /** - * Boost at every nth step. - */ - boostat?: number; - - /** - * Maximum step when boosted. - */ - maxboostedstep?: number | boolean; - - /** - * Enables the mouse wheel to change the value of the input. - */ - mousewheel?: boolean; - - /** - * Class(es) of down button. - */ - buttondown_class?: string; - - /** - * Class(es) of up button. - */ - buttonup_class?: string; -} - -interface JQuery { - /** - * Initialize TouchSpin - */ - TouchSpin(): JQuery; - - /** - * Inialize TouchSpin with options - * @param options a TouchSpinOptions object with one or more options - */ - TouchSpin(options: TouchSpinOptions): JQuery; -} diff --git a/bootstrap-touchspin/index.d.ts b/bootstrap-touchspin/index.d.ts new file mode 100644 index 0000000000..268a33df38 --- /dev/null +++ b/bootstrap-touchspin/index.d.ts @@ -0,0 +1,130 @@ +// Type definitions for Bootstrap TouchSpin +// Project: http://www.virtuosoft.eu/code/bootstrap-touchspin/ +// Definitions by: Albin Sunnanbo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * TouchSpinOptions. All options are optional + */ +interface TouchSpinOptions { + /** + * Applied when no explicit value is set on the input with the value attribute. + * Empty string means that the value remains empty on initialization. + */ + initval?: number | string; + + /** + * Minimum value. + */ + min?: number; + + /** + * Maximum value. + */ + max?: number; + + /** + * Incremental/decremental step on up/down change. + */ + step?: number; + + /** + * How to force the value to be divisible by step value: 'none' | 'round' | 'floor' | 'ceil' + */ + forcestepdivisibility?: string; + + /** + * Number of decimal points. + */ + decimals?: number; + + /** + * Refresh rate of the spinner in milliseconds. + */ + stepinterval?: number; + + /** + * Time in milliseconds before the spinner starts to spin. + */ + stepintervaldelay?: number; + + /** + * Enables the traditional up/down buttons. + */ + verticalbuttons?: boolean; + + /** + * Class of the up button with vertical buttons mode enabled. + */ + verticalupclass?: string; + + /** + * Class of the down button with vertical buttons mode enabled. + */ + verticaldownclass?: string; + + /** + * Text before the input. + */ + prefix?: string; + + /** + * Text after the input. + */ + postfix?: string; + + /** + * Extra class(es) for prefix. + */ + prefix_extraclass?: string; + + /** + * Extra class(es) for postfix. + */ + postfix_extraclass?: string; + + /** + * If enabled, the the spinner is continually becoming faster as holding the button. + */ + booster?: boolean; + + /** + * Boost at every nth step. + */ + boostat?: number; + + /** + * Maximum step when boosted. + */ + maxboostedstep?: number | boolean; + + /** + * Enables the mouse wheel to change the value of the input. + */ + mousewheel?: boolean; + + /** + * Class(es) of down button. + */ + buttondown_class?: string; + + /** + * Class(es) of up button. + */ + buttonup_class?: string; +} + +interface JQuery { + /** + * Initialize TouchSpin + */ + TouchSpin(): JQuery; + + /** + * Inialize TouchSpin with options + * @param options a TouchSpinOptions object with one or more options + */ + TouchSpin(options: TouchSpinOptions): JQuery; +} diff --git a/bootstrap-touchspin/tsconfig.json b/bootstrap-touchspin/tsconfig.json new file mode 100644 index 0000000000..a046a7d843 --- /dev/null +++ b/bootstrap-touchspin/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bootstrap-touchspin-tests.ts" + ] +} \ No newline at end of file diff --git a/bootstrap.datepicker/bootstrap.datepicker-tests.ts b/bootstrap.datepicker/bootstrap.datepicker-tests.ts index b275ee25a8..5e084697a2 100644 --- a/bootstrap.datepicker/bootstrap.datepicker-tests.ts +++ b/bootstrap.datepicker/bootstrap.datepicker-tests.ts @@ -1,6 +1,4 @@ -/// - -function tests_simple() { +function tests_simple() { $('#datepicker').datepicker(); $('#datepicker').datepicker({ format: 'mm-dd-yyyy' diff --git a/bootstrap.datepicker/bootstrap.datepicker.d.ts b/bootstrap.datepicker/bootstrap.datepicker.d.ts deleted file mode 100644 index 0633db5358..0000000000 --- a/bootstrap.datepicker/bootstrap.datepicker.d.ts +++ /dev/null @@ -1,57 +0,0 @@ -// Type definitions for bootstrap.datepicker -// Project: https://github.com/eternicode/bootstrap-datepicker -// Definitions by: Boris Yankov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -/** - * All options that take a “Date” can handle a Date object; a String - * formatted according to the given format; or a timedelta relative - * to today, eg “-1d”, “+6m +1y”, etc, where valid units are “d” (day), - * “w” (week), “m” (month), and “y” (year). - * - * See online docs for more info: - * http://bootstrap-datepicker.readthedocs.org/en/release/options.html - */ -interface DatepickerOptions { - format?: string; - weekStart?: number; - startDate?: any; - endDate?: any; - autoclose?: boolean; - startView?: number; - todayBtn?: any; - todayHighlight?: boolean; - keyboardNavigation?: boolean; - language?: string; - beforeShowDay?: (date: any) => any; - calendarWeeks?: boolean; - clearBtn?: boolean; - daysOfWeekDisabled?: number[]; - forceParse?: boolean; - inputs?: any[]; - minViewMode?: any; - multidate?: any; - multidateSeparator?: string; - orientation?: string; -} - -interface DatepickerEventObject extends JQueryEventObject { - date: Date; - format(format?: string): string; -} - -interface JQuery { - datepicker(): JQuery; - datepicker(methodName: string): any; - datepicker(methodName: string, params: any): any; - datepicker(options: DatepickerOptions): JQuery; - - off(events: "changeDate", selector?: string, handler?: (eventObject: DatepickerEventObject) => any): JQuery; - off(events: "changeDate", handler: (eventObject: DatepickerEventObject) => any): JQuery; - - on(events: "changeDate", selector: string, data: any, handler?: (eventObject: DatepickerEventObject) => any): JQuery; - on(events: "changeDate", selector: string, handler: (eventObject: DatepickerEventObject) => any): JQuery; - on(events: 'changeDate', handler: (eventObject: DatepickerEventObject) => any): JQuery; -} diff --git a/bootstrap.datepicker/index.d.ts b/bootstrap.datepicker/index.d.ts new file mode 100644 index 0000000000..107a3d536c --- /dev/null +++ b/bootstrap.datepicker/index.d.ts @@ -0,0 +1,57 @@ +// Type definitions for bootstrap.datepicker +// Project: https://github.com/eternicode/bootstrap-datepicker +// Definitions by: Boris Yankov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * All options that take a “Date” can handle a Date object; a String + * formatted according to the given format; or a timedelta relative + * to today, eg “-1d”, “+6m +1y”, etc, where valid units are “d” (day), + * “w” (week), “m” (month), and “y” (year). + * + * See online docs for more info: + * http://bootstrap-datepicker.readthedocs.org/en/release/options.html + */ +interface DatepickerOptions { + format?: string; + weekStart?: number; + startDate?: any; + endDate?: any; + autoclose?: boolean; + startView?: number; + todayBtn?: any; + todayHighlight?: boolean; + keyboardNavigation?: boolean; + language?: string; + beforeShowDay?: (date: any) => any; + calendarWeeks?: boolean; + clearBtn?: boolean; + daysOfWeekDisabled?: number[]; + forceParse?: boolean; + inputs?: any[]; + minViewMode?: any; + multidate?: any; + multidateSeparator?: string; + orientation?: string; +} + +interface DatepickerEventObject extends JQueryEventObject { + date: Date; + format(format?: string): string; +} + +interface JQuery { + datepicker(): JQuery; + datepicker(methodName: string): any; + datepicker(methodName: string, params: any): any; + datepicker(options: DatepickerOptions): JQuery; + + off(events: "changeDate", selector?: string, handler?: (eventObject: DatepickerEventObject) => any): JQuery; + off(events: "changeDate", handler: (eventObject: DatepickerEventObject) => any): JQuery; + + on(events: "changeDate", selector: string, data: any, handler?: (eventObject: DatepickerEventObject) => any): JQuery; + on(events: "changeDate", selector: string, handler: (eventObject: DatepickerEventObject) => any): JQuery; + on(events: 'changeDate', handler: (eventObject: DatepickerEventObject) => any): JQuery; +} diff --git a/bootstrap.datepicker/tsconfig.json b/bootstrap.datepicker/tsconfig.json new file mode 100644 index 0000000000..7c242b10d7 --- /dev/null +++ b/bootstrap.datepicker/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bootstrap.datepicker-tests.ts" + ] +} \ No newline at end of file diff --git a/bootstrap.paginator/bootstrap.paginator.d.ts b/bootstrap.paginator/bootstrap.paginator.d.ts deleted file mode 100644 index 805850c88d..0000000000 --- a/bootstrap.paginator/bootstrap.paginator.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Type definitions for bootstrap.paginator -// Project: https://github.com/lyonlai/bootstrap-paginator -// Definitions by: derikwhittaker -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface PaginatorOptions{ - alignment?: string; - size?: string; - itemContainerClass?: (type, page, current) => string; - currentPage?: number; - numberOfPages?: number; - totalPages?: number; - pageUrl?: (type, page, current) => string; - shouldShowPage?: boolean; - itemTexts?: (type:string, page:number, current:number) => string; - tooltipTitles?: (type, page, current) => string; - useBootstrapTooltip?: boolean; - bootstrapTooltipOptions?: {}; - bootstrapMajorVersion?: number; - onPageClicked?: (event, originalEvent, type, page) => void; - onPageChanged?: (event, originalEvent, type, page) => void; -} - -interface JQuery { - bootstrapPaginator(): JQuery; - bootstrapPaginator(options: PaginatorOptions): JQuery; -} diff --git a/bootstrap.paginator/bootstrap.paginator.d.ts.tscparams b/bootstrap.paginator/bootstrap.paginator.d.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/bootstrap.paginator/bootstrap.paginator.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/bootstrap.paginator/index.d.ts b/bootstrap.paginator/index.d.ts new file mode 100644 index 0000000000..52aedd0656 --- /dev/null +++ b/bootstrap.paginator/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for bootstrap.paginator +// Project: https://github.com/lyonlai/bootstrap-paginator +// Definitions by: derikwhittaker +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface PaginatorOptions { + alignment?: string; + size?: string; + itemContainerClass?: (type: string, page: number, current: number) => string; + currentPage?: number; + numberOfPages?: number; + totalPages?: number; + pageUrl?: (type: string, page: number, current: number) => string; + shouldShowPage?: boolean; + itemTexts?: (type: string, page: number, current: number) => string; + tooltipTitles?: (type: string, page: number, current: number) => string; + useBootstrapTooltip?: boolean; + bootstrapTooltipOptions?: {}; + bootstrapMajorVersion?: number; + onPageClicked?: (event: any, originalEvent: any, type: string, page: number) => void; + onPageChanged?: (event: any, originalEvent: any, type: string, page: number) => void; +} + +interface JQuery { + bootstrapPaginator(options?: PaginatorOptions): JQuery; +} diff --git a/bootstrap.paginator/tsconfig.json b/bootstrap.paginator/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/bootstrap.paginator/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/bootstrap.timepicker/bootstrap.timepicker.d.ts b/bootstrap.timepicker/bootstrap.timepicker.d.ts deleted file mode 100644 index 70a48184e6..0000000000 --- a/bootstrap.timepicker/bootstrap.timepicker.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Type definitions for bootstrap.timepicker -// Project: https://github.com/jdewit/bootstrap-timepicker -// Definitions by: derikwhittaker -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface TimeickerOptions { - defaultTime?: string; - disableFocus?: boolean; - isOpen?: boolean; - minuteStep?: number; - modalBackdrop?: boolean; - secondStep?: number; - showSeconds?: boolean; - showInputs?: boolean; - showMeridian?: boolean; - template?: string; - appendWidgetTo?: string; -} - -interface JQuery { - timepicker(): JQuery; - timepicker(methodName: string): JQuery; - timepicker(methodName: string, params: any): JQuery; - timepicker(options: TimeickerOptions): JQuery; -} diff --git a/bootstrap.timepicker/index.d.ts b/bootstrap.timepicker/index.d.ts new file mode 100644 index 0000000000..b1325323af --- /dev/null +++ b/bootstrap.timepicker/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for bootstrap.timepicker +// Project: https://github.com/jdewit/bootstrap-timepicker +// Definitions by: derikwhittaker +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface TimeickerOptions { + defaultTime?: string; + disableFocus?: boolean; + isOpen?: boolean; + minuteStep?: number; + modalBackdrop?: boolean; + secondStep?: number; + showSeconds?: boolean; + showInputs?: boolean; + showMeridian?: boolean; + template?: string; + appendWidgetTo?: string; +} + +interface JQuery { + timepicker(): JQuery; + timepicker(methodName: string): JQuery; + timepicker(methodName: string, params: any): JQuery; + timepicker(options: TimeickerOptions): JQuery; +} diff --git a/bootstrap.timepicker/tsconfig.json b/bootstrap.timepicker/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/bootstrap.timepicker/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-3.0.0.d.ts b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-3.0.0.d.ts index 1412ad47eb..2f9a25cb1e 100644 --- a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-3.0.0.d.ts +++ b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-3.0.0.d.ts @@ -9,105 +9,105 @@ * see: http://eonasdan.github.io/bootstrap-datetimepicker or https://github.com/Eonasdan/bootstrap-datetimepicker for details. */ -/// -/// +/// -declare namespace BootstrapV3DatetimePicker { - interface DatetimepickerChangeEventObject extends DatetimepickerEventObject { - oldDate: moment.Moment; - } +import * as moment from '../moment'; - interface DatetimepickerEventObject extends JQueryEventObject { - date: moment.Moment; - } - - interface DatetimepickerIcons { - time?: string; - date?: string; - up?: string; - down?: string; - } - - interface DatetimepickerOptions { - pickDate?: boolean; - pickTime?: boolean; - useMinutes?: boolean; - useSeconds?: boolean; - useCurrent?: boolean; - minuteStepping?: number; - minDate?: moment.Moment | Date | string; - maxDate?: moment.Moment | Date | string; - showToday?: boolean; - collapse?: boolean; - language?: string; - defaultDate?: moment.Moment | Date | string; - disabledDates?: Array; - enabledDates?: Array; - icons?: DatetimepickerIcons; - useStrict?: boolean; - direction?: string; - sideBySide?: boolean; - daysOfWeekDisabled?: Array; - calendarWeeks?: boolean; - format?: string | boolean; - locale?: string; - showTodayButton?: boolean; - viewMode?: string; - inline?: boolean; - toolbarPlacement?: string; - showClear?: boolean; - ignoreReadonly?: boolean; - } - - interface Datetimepicker { - date(date: moment.Moment | Date | string): void; - date(): moment.Moment; - minDate(date: moment.Moment | Date | string): void; - minDate(): moment.Moment | boolean; - maxDate(date: moment.Moment | Date | string): void; - maxDate(): moment.Moment | boolean; - show(): void; - disable(): void; - enable(): void; - destroy(): void; - toggle(): void; - } +export as namespace BootstrapV3DatetimePicker; +export interface DatetimepickerChangeEventObject extends DatetimepickerEventObject { + oldDate: moment.Moment; } +export interface DatetimepickerEventObject extends JQueryEventObject { + date: moment.Moment; +} -interface JQuery { +export interface DatetimepickerIcons { + time?: string; + date?: string; + up?: string; + down?: string; +} - datetimepicker(): JQuery; - datetimepicker(options: BootstrapV3DatetimePicker.DatetimepickerOptions): JQuery; +export interface DatetimepickerOptions { + pickDate?: boolean; + pickTime?: boolean; + useMinutes?: boolean; + useSeconds?: boolean; + useCurrent?: boolean; + minuteStepping?: number; + minDate?: moment.Moment | Date | string; + maxDate?: moment.Moment | Date | string; + showToday?: boolean; + collapse?: boolean; + language?: string; + defaultDate?: moment.Moment | Date | string; + disabledDates?: Array; + enabledDates?: Array; + icons?: DatetimepickerIcons; + useStrict?: boolean; + direction?: string; + sideBySide?: boolean; + daysOfWeekDisabled?: Array; + calendarWeeks?: boolean; + format?: string | boolean; + locale?: string; + showTodayButton?: boolean; + viewMode?: string; + inline?: boolean; + toolbarPlacement?: string; + showClear?: boolean; + ignoreReadonly?: boolean; +} - off(events: "dp.change", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; - off(events: "dp.change", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; +export interface Datetimepicker { + date(date: moment.Moment | Date | string): void; + date(): moment.Moment; + minDate(date: moment.Moment | Date | string): void; + minDate(): moment.Moment | boolean; + maxDate(date: moment.Moment | Date | string): void; + maxDate(): moment.Moment | boolean; + show(): void; + disable(): void; + enable(): void; + destroy(): void; + toggle(): void; +} - on(events: "dp.change", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; - on(events: "dp.change", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; - on(events: 'dp.change', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerChangeEventObject) => any): JQuery; +declare global { + interface JQuery { + datetimepicker(): JQuery; + datetimepicker(options: DatetimepickerOptions): JQuery; - off(events: "dp.show", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - off(events: "dp.show", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + off(events: "dp.change", selector?: string, handler?: (eventobject: DatetimepickerChangeEventObject) => any): JQuery; + off(events: "dp.change", handler: (eventobject: DatetimepickerChangeEventObject) => any): JQuery; - on(events: "dp.show", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: "dp.show", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: 'dp.show', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: "dp.change", selector: string, data: any, handler?: (eventobject: DatetimepickerChangeEventObject) => any): JQuery; + on(events: "dp.change", selector: string, handler: (eventobject: DatetimepickerChangeEventObject) => any): JQuery; + on(events: 'dp.change', handler: (eventObject: DatetimepickerChangeEventObject) => any): JQuery; - off(events: "dp.hide", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - off(events: "dp.hide", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + off(events: "dp.show", selector?: string, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; + off(events: "dp.show", handler: (eventobject: DatetimepickerEventObject) => any): JQuery; - on(events: "dp.hide", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: "dp.hide", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: 'dp.hide', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: "dp.show", selector: string, data: any, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; + on(events: "dp.show", selector: string, handler: (eventobject: DatetimepickerEventObject) => any): JQuery; + on(events: 'dp.show', handler: (eventObject: DatetimepickerEventObject) => any): JQuery; - off(events: "dp.error", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - off(events: "dp.error", handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + off(events: "dp.hide", selector?: string, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; + off(events: "dp.hide", handler: (eventobject: DatetimepickerEventObject) => any): JQuery; - on(events: "dp.error", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: "dp.error", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; - on(events: 'dp.error', handler: (eventObject: BootstrapV3DatetimePicker.DatetimepickerEventObject) => any): JQuery; + on(events: "dp.hide", selector: string, data: any, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; + on(events: "dp.hide", selector: string, handler: (eventobject: DatetimepickerEventObject) => any): JQuery; + on(events: 'dp.hide', handler: (eventObject: DatetimepickerEventObject) => any): JQuery; - data(key: 'DateTimePicker'): BootstrapV3DatetimePicker.Datetimepicker; + off(events: "dp.error", selector?: string, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; + off(events: "dp.error", handler: (eventobject: DatetimepickerEventObject) => any): JQuery; + + on(events: "dp.error", selector: string, data: any, handler?: (eventobject: DatetimepickerEventObject) => any): JQuery; + on(events: "dp.error", selector: string, handler: (eventobject: DatetimepickerEventObject) => any): JQuery; + on(events: 'dp.error', handler: (eventObject: DatetimepickerEventObject) => any): JQuery; + + data(key: 'DateTimePicker'): Datetimepicker; + } } diff --git a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts index 137e84720d..4306bf97c7 100644 --- a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts +++ b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts @@ -1,5 +1,6 @@ -/// -/// +/// + +import * as moment from 'moment'; function test_cases() { $('#datetimepicker').datetimepicker(); diff --git a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts deleted file mode 100644 index d49a0d8814..0000000000 --- a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts +++ /dev/null @@ -1,588 +0,0 @@ -// Type definitions for Bootstrap 3 Datepicker v4.17.37 -// Project: http://eonasdan.github.io/bootstrap-datetimepicker -// Definitions by: Katona Péter -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// based on the previous version created by Jesica N. Fera - -/** - * bootstrap-datetimepicker.js 4.17.37 Copyright (c) 2015 Jonathan Peterson - * Available via the MIT license. - * see: http://eonasdan.github.io/bootstrap-datetimepicker or https://github.com/Eonasdan/bootstrap-datetimepicker for details. - */ - -/// -/// - -declare namespace BootstrapV3DatetimePicker { - - interface Datetimepicker { - /**Clears the datepicker by setting the value to null */ - clear(): void; - /**Returns the component's model current date, a moment object or null if not set. */ - date(): moment.Moment; - /**Takes string, Date, moment, null parameter and sets the components model current moment to it. - * Passing a null value unsets the components model current moment. - * Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration. - * Throws: - * - TypeError - in case the newDate cannot be parsed - * - * Emits: - * - dp.change - In case newDate is different from current moment - */ - date(date: moment.Moment | Date | string): void; - /**Destroys the widget and removes all attached event listeners */ - destroy(): void; - /**Disables the input element, the component is attached to, by adding a disabled="true" attribute to it. If the widget was visible before that call it is hidden. - * Emits: - * - dp.hide - if the widget was visible before that call - */ - disable(): void; - /**Enables the input element, the component is attached to, by removing disabled attribute from it. */ - enable(): void; - /**Hides the widget - * Emits: - * - dp.hide - if the widget was visible before that call - */ - hide(): void; - /**Returns the components current options object. - * Note that the changing the values of the returned object does not change the components actual configuration. */ - options(): DatetimepickerOptions - /**Takes an object variable with option key:value properties and configures the component. Use this to update multiple options on the component. */ - options(options: DatetimepickerOptions): void - /**Shows the widget - * Emits: - * - dp.show - if the widget was hidden before that call - * - dp.change - if the widget is opened for the first time and the useCurrent is set to true or to a granularity value and the input element the component is attached to has an empty value - */ - show(): void; - /**Shows or hides the widget - * Emits: - * - dp.hide - if the widget is hidden after the toggle call - * - dp.show - if the widget is show after the toggle call - * - dp.change - if the widget is opened for the first time and the input element is empty and options.useCurrent != false - */ - toggle(): void; - - //////////////////////////////////////////////////////////////////////////////////////////////////// - //// Below are the getters/setters for the properties of the 'options(): DatetimepickerOptions' //// - //////////////////////////////////////////////////////////////////////////////////////////////////// - - /**Returns the options.allowInputToggle option. */ - allowInputToggle(): boolean; - /**If true, the picker will show on textbox focus and icon click when used in a button group */ - allowInputToggle(value: boolean): void; - /**Returns the current options.calendarWeeks option configuration */ - calendarWeeks(): boolean; - /**Set if the week numbers will appear to the left on the days view */ - calendarWeeks(value: boolean): void; - /**Returns the options.collapse option configuration */ - collapse(): boolean; - /**If set to false the picker will display similar to sideBySide except vertical. */ - collapse(value: boolean): void; - /**Returns the options.daysOfWeekDisabled configuration - * IMPORTANT! Throws exception if not set explicitly https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1459 - */ - daysOfWeekDisabled(): Array; - /**Takes an [ Number:0 to 6 ] and disallow the user to select weekdays that exist in this array. - * This has lower priority over the options.minDate, options.maxDate, options.disabledDates and options.enabledDates configuration settings. - * Emits: - * - dp.change - if the currently selected moment falls in the values passed on the daysOfWeek parameter. - * - dp.error - if the currently selected moment falls in the values passed on the daysOfWeek parameter. - */ - daysOfWeekDisabled(days: Array): void; - /**Returns the options.dayViewHeaderFormat option. */ - dayViewHeaderFormat(): string; - /**Used to customize the header of the day view. */ - dayViewHeaderFormat(value: string): void; - /**Returns a moment with the options.defaultDate option configuration or false if not set */ - defaultDate(): moment.Moment | boolean; - /**Will set the picker's inital date. - * If a boolean:false value is passed the options.defaultDate parameter is cleared. - * Throws: - * - TypeError - if the provided date doesn't pass validation, including disabledDates, enabledDates, minDate, maxDate, and daysOfWeekDisabled - * - TypeError - if the provided date cannot be parsed by momentjs - */ - defaultDate(date: string | Date | moment.Moment | boolean): void; - /**Returns the options.disabledDates option. - * NOTES: probably should be: disabledDates(): boolean | Array; see: DatetimepickerOptions - */ - disabledDates(): boolean | any; - /**Takes an array of values and disallows the user to select those days. - * Setting this takes precedence over options.minDate, options.maxDate configuration. - * Also calling this function removes the configuration of options.enabledDates if such exist. - * Note: These values are matched with Day granularity. - */ - disabledDates(dates: boolean | Array): void; - /**Returns the options.disabledHours option. - * NOTES: probably should be: disabledHours(): boolean | Array; see: DatetimepickerOptions - */ - disabledHours(): boolean | any; - /**Must be in 24 hour format. Will disallow hour selections (much like disabledTimeIntervals) but will affect all days. - * Like en/disabledDates, the en/disabledHours options are mutually exclusive and will reset one of the options back to false. */ - disabledHours(value: boolean | Array): void; - /**Returns the options.disabledTimeIntervals option, or... not exactly - * IMPORTANT! Creates an object from the options.disabledTimeIntervals with the keys being numbers, the values being the moment arrays. - * eg { "0": [, ], "1": [...] } - * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1498 - */ - disabledTimeIntervals(): boolean | Array>; - /**Disables time selection between the given moments - * eg: [[moment({ h: 0 }), moment({ h: 8 })], [moment({ h: 18 }), moment({ h: 24 })]] - */ - disabledTimeIntervals(value: boolean | Array>): void; - /**Returns the options.enabledDates option - * NOTES: probably should be: enabledDates(): boolean | Array; see: DatetimepickerOptions - */ - enabledDates(): boolean | any; - /**Takes an array of values and allows the user to select only from those days. - * Setting this takes precedence over options.minDate, options.maxDate configuration. - * Also calling this function removes the configuration of options.disabledDates if such exist. - * Note: These values are matched with Day granularity. - */ - enabledDates(dates: boolean | Array): void; - /**Returns the options.enabledHours option. - * NOTES: probably should be: enabledHours(): boolean | Array; see: DatetimepickerOptions - */ - enabledHours(): boolean | any; - /**Must be in 24 hour format. Will allow hour selections (much like enabledTimeIntervals) but will affect all days. - * Like en/disabledDates, the en/disabledHours options are mutually exclusive and will reset one of the options back to false. */ - enabledHours(value: boolean | Array): void; - /**Returns a boolean or array with the options.extraFormats option configuration */ - extraFormats(): boolean | Array; - /**Takes an array of valid input moment format options, or boolean:false */ - extraFormats(formats: boolean | Array): void; - /**Returns the options.focusOnShow option. */ - focusOnShow(): boolean; - /**If false, the textbox will not be given focus when the picker is shown */ - focusOnShow(value: boolean): void; - /**Returns the component's options.format string */ - format(): boolean | string; - /**Takes a moment.js format string and sets the components options.format. - * This is used for displaying and also for parsing input strings either from the input element the component is attached to or the date() function. - * The parameter can also be a boolean:false in which case the format is set to the locale's L LT. - * Note: this is also used to determine if the TimePicker sub component will display the hours in 12 or 24 format. (if "a" or "h" exists in the passed string then a 12 hour mode is set) - */ - format(format: boolean | string): void; - /**Returns options.icons */ - icons(): Icons; - /**Takes an Object of strings. - * Throws: - * - TypeError - if icons parameter is not an Object - */ - icons(icons: Icons): void; - /**Returns the options.ignoreReadonly option. */ - ignoreReadonly(): boolean; - /**Set this to true to allow the picker to be used even if the input field is readonly. This will not bypass the disabled property */ - ignoreReadonly(value: boolean): void; - /**Returns the options.inline option. */ - inline(): boolean; - /**Used to customize the header of the day view. */ - inline(value: boolean): void; - /**Returns the options.keepInvalid option. */ - keepInvalid(): boolean; - /**If true, invalid dates will not be reverted to a previous selection or changed. */ - keepInvalid(value: boolean): void; - /**Returns a string variable with the currently set options.keyBinds option. */ - keyBinds(): any; - /**Allows for several keyBinding functions to be specified for ease of access or accessibility. For defaults see {@link http://eonasdan.github.io/bootstrap-datetimepicker/Options/#keybinds}. - */ - keyBinds(value: any): void; - /**Returns the currently set locale of the options.locale */ - locale(): string; - /**Takes a string of any valid moment locale e.g. de for German. - * Throws: - * - TypeError - if the locale is not loaded via a separate script or moment-with-locale - */ - locale(newLocale: string): void; - /**Returns the currently set moment of the options.maxDate or false if not set */ - maxDate(): moment.Moment | boolean; - /**Takes a parameter and disallows the user to select a moment that is after that moment. - * If a boolean:false value is passed options.maxDate is cleared and there is no restriction to the maximum moment the user can select. - * Note: If the parameter is before the currently selected moment the currently selected moment changes to maxDate - * Throws: - * - TypeError - if the parameter cannot be parsed using the options.format and options.useStrict configuration settings - * - TypeError - if the parameter is before options.minDate - * - * Emits: - * - dp.change - if the new maxDate is after currently selected moment - * - dp.error - if the new maxDate is after currently selected moment - */ - maxDate(date: moment.Moment | Date | string | boolean): void; - /**Returns the currently set moment of the options.minDate or false if not set */ - minDate(): moment.Moment | boolean; - /**Takes a parameter and disallows the user to select a moment that is before that moment. - * If a boolean:false value is passed the options.minDate parameter is cleared and there is no restriction to the miminum moment the user can select. - * Note: If the parameter is after the currently selected moment the currently selected moment changes to minDate parameter - * Throws: - * - TypeError - if the parameter cannot be parsed using the options.format and options.useStrict configuration settings - * - TypeError - if the parameter is after options.maxDate - * - * Emits: - * - dp.change - if the new minDate is after currently selected moment - * - dp.error - if the new minDate is after currently selected moment - */ - minDate(date: moment.Moment | Date | string | boolean): void; - /**Returns the options.parseInputDate option */ - parseInputDate(): Function; - /**Allows custom input formatting For example: the user can enter "yesterday"" or "30 days ago". - * {@link http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#parseinputdate} - */ - parseInputDate(value: (input: string) => moment.Moment): void; - /**Returns the options.showClear option. */ - showClear(): boolean; - /**Set if the clear date button will appear on the widget */ - showClear(value: boolean): void; - /**Returns the options.showClose option. */ - showClose(): boolean; - /**If true, an icon will be displayed on the toolbar that will hide the picker */ - showClose(value: boolean): void; - /**Returns the options.showTodayButton option. */ - showTodayButton(): boolean; - /**Set if the Today button will appear on the widget */ - showTodayButton(value: boolean): void; - /**Returns a boolean of the options.sideBySide. */ - sideBySide(): boolean; - /**If sideBySide is true and the time picker is used, both components will display side by side instead of collapsing. */ - sideBySide(value: boolean): void; - /**Returns a number with the options.stepping option configuration */ - stepping(): number; - /**This will be the amount the up/down arrows move the minute value with a time picker. */ - stepping(step: number): void; - /**Returns the options.toolbarplacement option. */ - toolbarPlacement(): string; - /**Changes the placement of the toolbar where the today, clear, component switch icon are located. - * See valid values at DatetimepickerOptions.toolbarplacement - * Throws: - * - TypeError if the parameter is not a valid value - */ - toolbarPlacement(value: string): void; - /**Returns the options.tooltips option */ - tooltips(): Tooltips; - /**Sets the tooltips for icons. - * Throws: - * - TypeError - if tooltips parameter is not an Object - */ - tooltips(value: Tooltips): void; - /**Returns the options.useCurrent option configuration */ - useCurrent(): boolean | string; - /**Takes a boolean or string. - * If a boolean true is passed and the components model moment is not set (either through setDate or through a valid value on the input element the component is attached to) then the first time the user opens the datetimepicker widget the value is initialized to the current moment of the action. - * If a false boolean is passed then no initialization happens on the input element. - * You can select the granularity on the initialized moment by passing one of the following strings ("year", "month", "day", "hour", "minute") in the variable. - * If for example you pass "day" to the useCurrent function and the input field is empty the first time the user opens the datetimepicker widget the input text will be initialized to the current datetime with day granularity (ie if currentTime = 2014-08-10 13:32:33 the input value will be initialized to 2014-08-10 00:00:00) - * Note: If the options.defaultDate is set or the input element the component is attached to has already a value that takes precedence and the functionality of useCurrent is not triggered! - */ - useCurrent(value: boolean | string): void; - /**Returns the options.useStrict */ - useStrict(): boolean; - /**If useStrict is true, momentjs parsing rules will be stricter when determining if a date is valid or not. */ - useStrict(value: boolean): void; - /**Returns the options.viewDate option. */ - viewDate(): boolean | moment.Moment; - /**This will change the viewDate without changing or setting the selected date. */ - viewDate(value: string | Date | moment.Moment | boolean): void; - /**Returns the options.viewMode. */ - viewMode(): string; - /**Takes a string. See valid values at DatetimepickerOptions.viewMode - * Throws: - * - TypeError - if the parameter is not a string or not a valid value - */ - viewMode(value: string): void; - /**Returns the options.widgetPositioning object */ - widgetPositioning(): WidgetPositioningOptions; - /**WidgetPositioning defines where the dropdown with the widget will appear relative to the input element the component is attached to. - * "auto" is the default value for both horizontal and vertical keys and it tries to automatically place the dropdown in a position that is visible to the user. - * Usually you should not override those options unless you have a special need in your layout. - */ - widgetPositioning(value: WidgetPositioningOptions): void; - } - - interface DatetimepickerOptions { - /**If true, the picker will show on textbox focus and icon click when used in a button group - * @default: false - */ - allowInputToggle?: boolean; - /**Shows the week of the year to the left of first day of the week. - * @default: false - */ - calendarWeeks?: boolean; - /**Using a Bootstraps collapse to switch between date/time pickers. - * @default: true - */ - collapse?: boolean; - /**Disables the section of days of the week, e.g. weekends. - * Accepts: array of numbers from 0-6 - * @default: false - */ - daysOfWeekDisabled?: Array | boolean; - /**Changes the heading of the datepicker when in "days" view. - * @default: "MMMM YYYY" - */ - dayViewHeaderFormat?: string; - /**Will cause the date picker to stay open after a blur event. - * @default: false - */ - debug?: boolean; - /**Sets the picker default date/time. Overrides useCurrent - * @default: false - */ - defaultDate?: boolean | moment.Moment | Date | string; - /**Disables selection of dates in the array, e.g. holidays - * @default: false - * IMPORTANT! The getter returns an Object NOT an Array, with keys being the dates, values being true. - * eg disabledDates = ["2010-10-10"]; -> disabledDated will be { "2010-01-01": true } - * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 - */ - disabledDates?: boolean | Array | any; - /**Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days - * @default: false - * IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true. - * eg disabledHours = [0, 1]; -> disabledHours will be { "0": true, "1": true } - * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 - */ - disabledHours?: boolean | Array | any; - /**Disables time selection between the given moments - * eg: [[moment({ h: 0 }), moment({ h: 8 })], [moment({ h: 18 }), moment({ h: 24 })]] - * @default: false - */ - disabledTimeIntervals?: boolean | Array>; - /**Disables selection of dates NOT in the array, e.g. holidays - * @default: false - * IMPORTANT! The getter returns an Object NOT an Array, with keys being the dates, values being true. - * eg enabledDates = ["2010-10-10"]; -> enabledDated will be { "2010-01-01": true } - * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 - */ - enabledDates?: boolean | Array | any; - /**Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days - * @default: false - * IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true. - * eg enabledHours = [0, 1]; -> enabledHours will be { "0": true, "1": true } - * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 - */ - enabledHours?: boolean | Array; - /**Allows for several input formats to be valid. See: https://github.com/Eonasdan/bootstrap-datetimepicker/pull/666 - * @default: false - */ - extraFormats?: boolean | Array; - /**If false, the textbox will not be given focus when the picker is shown - * @default: true - */ - focusOnShow?: boolean; - /**See momentjs' docs for valid formats. Format also dictates what components are shown, e.g. MM/dd/YYYY will not display the time picker. - * @default: false - */ - format?: boolean | string; - /**Change the default icons for the pickers functions. */ - icons?: Icons; - /**Allow date picker show event to fire even when the associated input element has the readonly="readonly"property. - * @default: false - */ - ignoreReadonly?: boolean; - /**Will display the picker inline without the need of a input field. This will also hide borders and shadows. - * @default: false - */ - inline?: boolean; - /**Allows for custom events to fire on keyboard press. - * eg: keybinds: { - * up: (widget) => console.log(widget), - * "control up": (widget) => console.log(widget) - * } - * The widget parameter is false, if the datepicker is closed. - */ - keyBinds?: { [key: string]: (widget: boolean | JQuery) => void }; - /**Will cause the date picker to not revert or overwrite invalid dates. - * @default: false - */ - keepInvalid?: boolean; - /**Will cause the date picker to stay open after selecting a date if no time components are being used. - * @default: false - */ - keepOpen?: boolean; - /**See momentjs for valid locales. You must include moment-with-locales.js or a local js file. - * @default: moment.locale() - */ - locale?: string; - /**Prevents date/time selections after this date. - * maxDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected. - * @default: false - */ - maxDate?: boolean | moment.Moment | Date | string; - /**Prevents date/time selections before this date. - * minDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected. - * @default: false - */ - minDate?: boolean | moment.Moment | Date | string; - /**Allows custom input formatting For example: the user can enter "yesterday"" or "30 days ago". - * {@link http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#parseinputdate} - */ - parseInputDate?: (input: string) => moment.Moment; - /**Show the "Clear" button in the icon toolbar. - * Clicking the "Clear" button will set the calendar to null. - * @default: false - */ - showClear?: boolean; - /**Show the "Close" button in the icon toolbar. - * Clicking the "Close" button will call hide() - * @default: false - */ - showClose?: boolean; - /**Show the "Today" button in the icon toolbar. - * Clicking the "Today" button will set the calendar view and set the date to now. - * @default: false - */ - showTodayButton?: boolean; - /**Shows the picker side by side when using the time and date together. - * @default: false - */ - sideBySide?: boolean; - /**Number of minutes the up/down arrow's will move the minutes value in the time picker - * @default: 1 - */ - stepping?: number; - /**Changes the placement of the icon toolbar. - * @default: "default" - */ - toolbarPlacement?: "default" | "top" | "bottom"; - /**This will change the tooltips over each icon to a custom string */ - tooltips?: Tooltips; - /**On show, will set the picker to the current date/time - * @default: true - */ - useCurrent?: boolean; - /**Defines if moment should use strict date parsing when considering a date to be valid - * @default: false - */ - useStrict?: boolean; - /**This will change the viewDate without changing or setting the selected date. - * @default: false - */ - viewDate?: boolean | moment.Moment | Date | string; - /**The default view to display when the picker is shown. - * Note: To limit the picker to selecting, for instance the year and month, use format: MM/YYYY - * @default: "days" - */ - viewMode?: "decades" | "years" | "months" | "days"; - /**On picker show, places the widget at the identifier (string) or jQuery object if the element has css position: "relative" - * @default: null - */ - widgetParent?: string | JQuery; - widgetPositioning?: WidgetPositioningOptions; - } - - interface Icons { - /**default: "glyphicon glyphicon-trash" */ - clear?: string; - /**default: "glyphicon glyphicon-remove" */ - close?: string; - /**default: "glyphicon glyphicon-calendar" */ - date?: string; - /**default: "glyphicon glyphicon-time" */ - down?: string; - /**default: "glyphicon glyphicon-chevron-left" */ - next?: string; - /**default: "glyphicon glyphicon-screenshot" */ - previous?: string; - /**default: "glyphicon glyphicon-chevron-right" */ - time?: string; - /**default: "glyphicon glyphicon-chevron-down" */ - today?: string; - /**default: "glyphicon glyphicon-chevron-up" */ - up?: string; - } - - interface Tooltips { - today?: string; - clear?: string; - close?: string; - selectMonth?: string; - prevMonth?: string; - nextMonth?: string; - selectYear?: string; - prevYear?: string; - nextYear?: string; - selectDecade?: string; - prevDecade?: string; - nextDecade?: string; - prevCentury?: string; - nextCentury?: string; - selectTime?: string; - pickHour?: string; - incrementHour?: string; - decrementHour?: string; - pickMinute?: string; - incrementMinute?: string; - decrementMinute?: string; - togglePeriod?: string; - pickSecond?: string; - incrementSecond?: string; - decrementSecond?: string; - } - - interface WidgetPositioningOptions { - horizontal?: "auto" | "left" | "right"; - vertical?: "auto" | "top" | "bottom"; - } - - interface Event extends JQueryEventObject { - date: moment.Moment; - } - - interface ChangeEvent extends Event { - /**Previous date. False if the previous date is null. */ - oldDate: moment.Moment | boolean; - } - - interface UpdateEvent extends JQueryEventObject { - /**Change type as a momentjs format token. e.g. yyyy on year change */ - change: string; - /**New viewDate. */ - viewDate: moment.Moment; - } -} - -interface JQuery { - - datetimepicker(): JQuery; - datetimepicker(options: BootstrapV3DatetimePicker.DatetimepickerOptions): JQuery; - - data(key: "DateTimePicker"): BootstrapV3DatetimePicker.Datetimepicker; - - on(events: "dp.change", handler: (eventObject: BootstrapV3DatetimePicker.ChangeEvent) => any): JQuery; - on(events: "dp.change", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.ChangeEvent) => any): JQuery; - on(events: "dp.change", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.ChangeEvent) => any): JQuery; - - off(events: "dp.change", handler: (eventobject: BootstrapV3DatetimePicker.ChangeEvent) => any): JQuery; - off(events: "dp.change", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.ChangeEvent) => any): JQuery; - - - on(events: "dp.show", handler: (eventObject: BootstrapV3DatetimePicker.Event) => any): JQuery; - on(events: "dp.show", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - on(events: "dp.show", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - - off(events: "dp.show", handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - off(events: "dp.show", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - - - on(events: "dp.hide", handler: (eventObject: BootstrapV3DatetimePicker.Event) => any): JQuery; - on(events: "dp.hide", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - on(events: "dp.hide", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - - off(events: "dp.hide", handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - off(events: "dp.hide", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - - - on(events: "dp.error", handler: (eventObject: BootstrapV3DatetimePicker.Event) => any): JQuery; - on(events: "dp.error", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - on(events: "dp.error", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - - off(events: "dp.error", handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - off(events: "dp.error", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - - - on(events: "dp.update", handler: (eventObject: BootstrapV3DatetimePicker.UpdateEvent) => any): JQuery; - on(events: "dp.update", selector: string, handler: (eventobject: BootstrapV3DatetimePicker.UpdateEvent) => any): JQuery; - on(events: "dp.update", selector: string, data: any, handler?: (eventobject: BootstrapV3DatetimePicker.UpdateEvent) => any): JQuery; - - off(events: "dp.update", handler: (eventobject: BootstrapV3DatetimePicker.Event) => any): JQuery; - off(events: "dp.update", selector?: string, handler?: (eventobject: BootstrapV3DatetimePicker.UpdateEvent) => any): JQuery; -} diff --git a/bootstrap.v3.datetimepicker/index.d.ts b/bootstrap.v3.datetimepicker/index.d.ts new file mode 100644 index 0000000000..cb8f8d0e47 --- /dev/null +++ b/bootstrap.v3.datetimepicker/index.d.ts @@ -0,0 +1,591 @@ +// Type definitions for Bootstrap 3 Datepicker v4.17.37 +// Project: http://eonasdan.github.io/bootstrap-datetimepicker +// Definitions by: Katona Péter +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// based on the previous version created by Jesica N. Fera + +/** + * bootstrap-datetimepicker.js 4.17.37 Copyright (c) 2015 Jonathan Peterson + * Available via the MIT license. + * see: http://eonasdan.github.io/bootstrap-datetimepicker or https://github.com/Eonasdan/bootstrap-datetimepicker for details. + */ + +/// + +import * as moment from '../moment'; + +export as namespace BootstrapV3DatetimePicker; + +export interface Datetimepicker { + /**Clears the datepicker by setting the value to null */ + clear(): void; + /**Returns the component's model current date, a moment object or null if not set. */ + date(): moment.Moment; + /**Takes string, Date, moment, null parameter and sets the components model current moment to it. + * Passing a null value unsets the components model current moment. + * Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration. + * Throws: + * - TypeError - in case the newDate cannot be parsed + * + * Emits: + * - dp.change - In case newDate is different from current moment + */ + date(date: moment.Moment | Date | string): void; + /**Destroys the widget and removes all attached event listeners */ + destroy(): void; + /**Disables the input element, the component is attached to, by adding a disabled="true" attribute to it. If the widget was visible before that call it is hidden. + * Emits: + * - dp.hide - if the widget was visible before that call + */ + disable(): void; + /**Enables the input element, the component is attached to, by removing disabled attribute from it. */ + enable(): void; + /**Hides the widget + * Emits: + * - dp.hide - if the widget was visible before that call + */ + hide(): void; + /**Returns the components current options object. + * Note that the changing the values of the returned object does not change the components actual configuration. */ + options(): DatetimepickerOptions + /**Takes an object variable with option key:value properties and configures the component. Use this to update multiple options on the component. */ + options(options: DatetimepickerOptions): void + /**Shows the widget + * Emits: + * - dp.show - if the widget was hidden before that call + * - dp.change - if the widget is opened for the first time and the useCurrent is set to true or to a granularity value and the input element the component is attached to has an empty value + */ + show(): void; + /**Shows or hides the widget + * Emits: + * - dp.hide - if the widget is hidden after the toggle call + * - dp.show - if the widget is show after the toggle call + * - dp.change - if the widget is opened for the first time and the input element is empty and options.useCurrent != false + */ + toggle(): void; + + //////////////////////////////////////////////////////////////////////////////////////////////////// + //// Below are the getters/setters for the properties of the 'options(): DatetimepickerOptions' //// + //////////////////////////////////////////////////////////////////////////////////////////////////// + + /**Returns the options.allowInputToggle option. */ + allowInputToggle(): boolean; + /**If true, the picker will show on textbox focus and icon click when used in a button group */ + allowInputToggle(value: boolean): void; + /**Returns the current options.calendarWeeks option configuration */ + calendarWeeks(): boolean; + /**Set if the week numbers will appear to the left on the days view */ + calendarWeeks(value: boolean): void; + /**Returns the options.collapse option configuration */ + collapse(): boolean; + /**If set to false the picker will display similar to sideBySide except vertical. */ + collapse(value: boolean): void; + /**Returns the options.daysOfWeekDisabled configuration + * IMPORTANT! Throws exception if not set explicitly https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1459 + */ + daysOfWeekDisabled(): Array; + /**Takes an [ Number:0 to 6 ] and disallow the user to select weekdays that exist in this array. + * This has lower priority over the options.minDate, options.maxDate, options.disabledDates and options.enabledDates configuration settings. + * Emits: + * - dp.change - if the currently selected moment falls in the values passed on the daysOfWeek parameter. + * - dp.error - if the currently selected moment falls in the values passed on the daysOfWeek parameter. + */ + daysOfWeekDisabled(days: Array): void; + /**Returns the options.dayViewHeaderFormat option. */ + dayViewHeaderFormat(): string; + /**Used to customize the header of the day view. */ + dayViewHeaderFormat(value: string): void; + /**Returns a moment with the options.defaultDate option configuration or false if not set */ + defaultDate(): moment.Moment | boolean; + /**Will set the picker's inital date. + * If a boolean:false value is passed the options.defaultDate parameter is cleared. + * Throws: + * - TypeError - if the provided date doesn't pass validation, including disabledDates, enabledDates, minDate, maxDate, and daysOfWeekDisabled + * - TypeError - if the provided date cannot be parsed by momentjs + */ + defaultDate(date: string | Date | moment.Moment | boolean): void; + /**Returns the options.disabledDates option. + * NOTES: probably should be: disabledDates(): boolean | Array; see: DatetimepickerOptions + */ + disabledDates(): boolean | any; + /**Takes an array of values and disallows the user to select those days. + * Setting this takes precedence over options.minDate, options.maxDate configuration. + * Also calling this function removes the configuration of options.enabledDates if such exist. + * Note: These values are matched with Day granularity. + */ + disabledDates(dates: boolean | Array): void; + /**Returns the options.disabledHours option. + * NOTES: probably should be: disabledHours(): boolean | Array; see: DatetimepickerOptions + */ + disabledHours(): boolean | any; + /**Must be in 24 hour format. Will disallow hour selections (much like disabledTimeIntervals) but will affect all days. + * Like en/disabledDates, the en/disabledHours options are mutually exclusive and will reset one of the options back to false. */ + disabledHours(value: boolean | Array): void; + /**Returns the options.disabledTimeIntervals option, or... not exactly + * IMPORTANT! Creates an object from the options.disabledTimeIntervals with the keys being numbers, the values being the moment arrays. + * eg { "0": [, ], "1": [...] } + * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1498 + */ + disabledTimeIntervals(): boolean | Array>; + /**Disables time selection between the given moments + * eg: [[moment({ h: 0 }), moment({ h: 8 })], [moment({ h: 18 }), moment({ h: 24 })]] + */ + disabledTimeIntervals(value: boolean | Array>): void; + /**Returns the options.enabledDates option + * NOTES: probably should be: enabledDates(): boolean | Array; see: DatetimepickerOptions + */ + enabledDates(): boolean | any; + /**Takes an array of values and allows the user to select only from those days. + * Setting this takes precedence over options.minDate, options.maxDate configuration. + * Also calling this function removes the configuration of options.disabledDates if such exist. + * Note: These values are matched with Day granularity. + */ + enabledDates(dates: boolean | Array): void; + /**Returns the options.enabledHours option. + * NOTES: probably should be: enabledHours(): boolean | Array; see: DatetimepickerOptions + */ + enabledHours(): boolean | any; + /**Must be in 24 hour format. Will allow hour selections (much like enabledTimeIntervals) but will affect all days. + * Like en/disabledDates, the en/disabledHours options are mutually exclusive and will reset one of the options back to false. */ + enabledHours(value: boolean | Array): void; + /**Returns a boolean or array with the options.extraFormats option configuration */ + extraFormats(): boolean | Array; + /**Takes an array of valid input moment format options, or boolean:false */ + extraFormats(formats: boolean | Array): void; + /**Returns the options.focusOnShow option. */ + focusOnShow(): boolean; + /**If false, the textbox will not be given focus when the picker is shown */ + focusOnShow(value: boolean): void; + /**Returns the component's options.format string */ + format(): boolean | string; + /**Takes a moment.js format string and sets the components options.format. + * This is used for displaying and also for parsing input strings either from the input element the component is attached to or the date() function. + * The parameter can also be a boolean:false in which case the format is set to the locale's L LT. + * Note: this is also used to determine if the TimePicker sub component will display the hours in 12 or 24 format. (if "a" or "h" exists in the passed string then a 12 hour mode is set) + */ + format(format: boolean | string): void; + /**Returns options.icons */ + icons(): Icons; + /**Takes an Object of strings. + * Throws: + * - TypeError - if icons parameter is not an Object + */ + icons(icons: Icons): void; + /**Returns the options.ignoreReadonly option. */ + ignoreReadonly(): boolean; + /**Set this to true to allow the picker to be used even if the input field is readonly. This will not bypass the disabled property */ + ignoreReadonly(value: boolean): void; + /**Returns the options.inline option. */ + inline(): boolean; + /**Used to customize the header of the day view. */ + inline(value: boolean): void; + /**Returns the options.keepInvalid option. */ + keepInvalid(): boolean; + /**If true, invalid dates will not be reverted to a previous selection or changed. */ + keepInvalid(value: boolean): void; + /**Returns a string variable with the currently set options.keyBinds option. */ + keyBinds(): any; + /**Allows for several keyBinding functions to be specified for ease of access or accessibility. For defaults see {@link http://eonasdan.github.io/bootstrap-datetimepicker/Options/#keybinds}. + */ + keyBinds(value: any): void; + /**Returns the currently set locale of the options.locale */ + locale(): string; + /**Takes a string of any valid moment locale e.g. de for German. + * Throws: + * - TypeError - if the locale is not loaded via a separate script or moment-with-locale + */ + locale(newLocale: string): void; + /**Returns the currently set moment of the options.maxDate or false if not set */ + maxDate(): moment.Moment | boolean; + /**Takes a parameter and disallows the user to select a moment that is after that moment. + * If a boolean:false value is passed options.maxDate is cleared and there is no restriction to the maximum moment the user can select. + * Note: If the parameter is before the currently selected moment the currently selected moment changes to maxDate + * Throws: + * - TypeError - if the parameter cannot be parsed using the options.format and options.useStrict configuration settings + * - TypeError - if the parameter is before options.minDate + * + * Emits: + * - dp.change - if the new maxDate is after currently selected moment + * - dp.error - if the new maxDate is after currently selected moment + */ + maxDate(date: moment.Moment | Date | string | boolean): void; + /**Returns the currently set moment of the options.minDate or false if not set */ + minDate(): moment.Moment | boolean; + /**Takes a parameter and disallows the user to select a moment that is before that moment. + * If a boolean:false value is passed the options.minDate parameter is cleared and there is no restriction to the miminum moment the user can select. + * Note: If the parameter is after the currently selected moment the currently selected moment changes to minDate parameter + * Throws: + * - TypeError - if the parameter cannot be parsed using the options.format and options.useStrict configuration settings + * - TypeError - if the parameter is after options.maxDate + * + * Emits: + * - dp.change - if the new minDate is after currently selected moment + * - dp.error - if the new minDate is after currently selected moment + */ + minDate(date: moment.Moment | Date | string | boolean): void; + /**Returns the options.parseInputDate option */ + parseInputDate(): Function; + /**Allows custom input formatting For example: the user can enter "yesterday"" or "30 days ago". + * {@link http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#parseinputdate} + */ + parseInputDate(value: (input: string) => moment.Moment): void; + /**Returns the options.showClear option. */ + showClear(): boolean; + /**Set if the clear date button will appear on the widget */ + showClear(value: boolean): void; + /**Returns the options.showClose option. */ + showClose(): boolean; + /**If true, an icon will be displayed on the toolbar that will hide the picker */ + showClose(value: boolean): void; + /**Returns the options.showTodayButton option. */ + showTodayButton(): boolean; + /**Set if the Today button will appear on the widget */ + showTodayButton(value: boolean): void; + /**Returns a boolean of the options.sideBySide. */ + sideBySide(): boolean; + /**If sideBySide is true and the time picker is used, both components will display side by side instead of collapsing. */ + sideBySide(value: boolean): void; + /**Returns a number with the options.stepping option configuration */ + stepping(): number; + /**This will be the amount the up/down arrows move the minute value with a time picker. */ + stepping(step: number): void; + /**Returns the options.toolbarplacement option. */ + toolbarPlacement(): string; + /**Changes the placement of the toolbar where the today, clear, component switch icon are located. + * See valid values at DatetimepickerOptions.toolbarplacement + * Throws: + * - TypeError if the parameter is not a valid value + */ + toolbarPlacement(value: string): void; + /**Returns the options.tooltips option */ + tooltips(): Tooltips; + /**Sets the tooltips for icons. + * Throws: + * - TypeError - if tooltips parameter is not an Object + */ + tooltips(value: Tooltips): void; + /**Returns the options.useCurrent option configuration */ + useCurrent(): boolean | string; + /**Takes a boolean or string. + * If a boolean true is passed and the components model moment is not set (either through setDate or through a valid value on the input element the component is attached to) then the first time the user opens the datetimepicker widget the value is initialized to the current moment of the action. + * If a false boolean is passed then no initialization happens on the input element. + * You can select the granularity on the initialized moment by passing one of the following strings ("year", "month", "day", "hour", "minute") in the variable. + * If for example you pass "day" to the useCurrent function and the input field is empty the first time the user opens the datetimepicker widget the input text will be initialized to the current datetime with day granularity (ie if currentTime = 2014-08-10 13:32:33 the input value will be initialized to 2014-08-10 00:00:00) + * Note: If the options.defaultDate is set or the input element the component is attached to has already a value that takes precedence and the functionality of useCurrent is not triggered! + */ + useCurrent(value: boolean | string): void; + /**Returns the options.useStrict */ + useStrict(): boolean; + /**If useStrict is true, momentjs parsing rules will be stricter when determining if a date is valid or not. */ + useStrict(value: boolean): void; + /**Returns the options.viewDate option. */ + viewDate(): boolean | moment.Moment; + /**This will change the viewDate without changing or setting the selected date. */ + viewDate(value: string | Date | moment.Moment | boolean): void; + /**Returns the options.viewMode. */ + viewMode(): string; + /**Takes a string. See valid values at DatetimepickerOptions.viewMode + * Throws: + * - TypeError - if the parameter is not a string or not a valid value + */ + viewMode(value: string): void; + /**Returns the options.widgetPositioning object */ + widgetPositioning(): WidgetPositioningOptions; + /**WidgetPositioning defines where the dropdown with the widget will appear relative to the input element the component is attached to. + * "auto" is the default value for both horizontal and vertical keys and it tries to automatically place the dropdown in a position that is visible to the user. + * Usually you should not override those options unless you have a special need in your layout. + */ + widgetPositioning(value: WidgetPositioningOptions): void; +} + +export interface DatetimepickerOptions { + /**If true, the picker will show on textbox focus and icon click when used in a button group + * @default: false + */ + allowInputToggle?: boolean; + /**Shows the week of the year to the left of first day of the week. + * @default: false + */ + calendarWeeks?: boolean; + /**Using a Bootstraps collapse to switch between date/time pickers. + * @default: true + */ + collapse?: boolean; + /**Disables the section of days of the week, e.g. weekends. + * Accepts: array of numbers from 0-6 + * @default: false + */ + daysOfWeekDisabled?: Array | boolean; + /**Changes the heading of the datepicker when in "days" view. + * @default: "MMMM YYYY" + */ + dayViewHeaderFormat?: string; + /**Will cause the date picker to stay open after a blur event. + * @default: false + */ + debug?: boolean; + /**Sets the picker default date/time. Overrides useCurrent + * @default: false + */ + defaultDate?: boolean | moment.Moment | Date | string; + /**Disables selection of dates in the array, e.g. holidays + * @default: false + * IMPORTANT! The getter returns an Object NOT an Array, with keys being the dates, values being true. + * eg disabledDates = ["2010-10-10"]; -> disabledDated will be { "2010-01-01": true } + * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 + */ + disabledDates?: boolean | Array | any; + /**Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days + * @default: false + * IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true. + * eg disabledHours = [0, 1]; -> disabledHours will be { "0": true, "1": true } + * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 + */ + disabledHours?: boolean | Array | any; + /**Disables time selection between the given moments + * eg: [[moment({ h: 0 }), moment({ h: 8 })], [moment({ h: 18 }), moment({ h: 24 })]] + * @default: false + */ + disabledTimeIntervals?: boolean | Array>; + /**Disables selection of dates NOT in the array, e.g. holidays + * @default: false + * IMPORTANT! The getter returns an Object NOT an Array, with keys being the dates, values being true. + * eg enabledDates = ["2010-10-10"]; -> enabledDated will be { "2010-01-01": true } + * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 + */ + enabledDates?: boolean | Array | any; + /**Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days + * @default: false + * IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true. + * eg enabledHours = [0, 1]; -> enabledHours will be { "0": true, "1": true } + * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 + */ + enabledHours?: boolean | Array; + /**Allows for several input formats to be valid. See: https://github.com/Eonasdan/bootstrap-datetimepicker/pull/666 + * @default: false + */ + extraFormats?: boolean | Array; + /**If false, the textbox will not be given focus when the picker is shown + * @default: true + */ + focusOnShow?: boolean; + /**See momentjs' docs for valid formats. Format also dictates what components are shown, e.g. MM/dd/YYYY will not display the time picker. + * @default: false + */ + format?: boolean | string; + /**Change the default icons for the pickers functions. */ + icons?: Icons; + /**Allow date picker show event to fire even when the associated input element has the readonly="readonly"property. + * @default: false + */ + ignoreReadonly?: boolean; + /**Will display the picker inline without the need of a input field. This will also hide borders and shadows. + * @default: false + */ + inline?: boolean; + /**Allows for custom events to fire on keyboard press. + * eg: keybinds: { + * up: (widget) => console.log(widget), + * "control up": (widget) => console.log(widget) + * } + * The widget parameter is false, if the datepicker is closed. + */ + keyBinds?: { [key: string]: (widget: boolean | JQuery) => void }; + /**Will cause the date picker to not revert or overwrite invalid dates. + * @default: false + */ + keepInvalid?: boolean; + /**Will cause the date picker to stay open after selecting a date if no time components are being used. + * @default: false + */ + keepOpen?: boolean; + /**See momentjs for valid locales. You must include moment-with-locales.js or a local js file. + * @default: moment.locale() + */ + locale?: string; + /**Prevents date/time selections after this date. + * maxDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected. + * @default: false + */ + maxDate?: boolean | moment.Moment | Date | string; + /**Prevents date/time selections before this date. + * minDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected. + * @default: false + */ + minDate?: boolean | moment.Moment | Date | string; + /**Allows custom input formatting For example: the user can enter "yesterday"" or "30 days ago". + * {@link http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#parseinputdate} + */ + parseInputDate?: (input: string) => moment.Moment; + /**Show the "Clear" button in the icon toolbar. + * Clicking the "Clear" button will set the calendar to null. + * @default: false + */ + showClear?: boolean; + /**Show the "Close" button in the icon toolbar. + * Clicking the "Close" button will call hide() + * @default: false + */ + showClose?: boolean; + /**Show the "Today" button in the icon toolbar. + * Clicking the "Today" button will set the calendar view and set the date to now. + * @default: false + */ + showTodayButton?: boolean; + /**Shows the picker side by side when using the time and date together. + * @default: false + */ + sideBySide?: boolean; + /**Number of minutes the up/down arrow's will move the minutes value in the time picker + * @default: 1 + */ + stepping?: number; + /**Changes the placement of the icon toolbar. + * @default: "default" + */ + toolbarPlacement?: "default" | "top" | "bottom"; + /**This will change the tooltips over each icon to a custom string */ + tooltips?: Tooltips; + /**On show, will set the picker to the current date/time + * @default: true + */ + useCurrent?: boolean; + /**Defines if moment should use strict date parsing when considering a date to be valid + * @default: false + */ + useStrict?: boolean; + /**This will change the viewDate without changing or setting the selected date. + * @default: false + */ + viewDate?: boolean | moment.Moment | Date | string; + /**The default view to display when the picker is shown. + * Note: To limit the picker to selecting, for instance the year and month, use format: MM/YYYY + * @default: "days" + */ + viewMode?: "decades" | "years" | "months" | "days"; + /**On picker show, places the widget at the identifier (string) or jQuery object if the element has css position: "relative" + * @default: null + */ + widgetParent?: string | JQuery; + widgetPositioning?: WidgetPositioningOptions; +} + +export interface Icons { + /**default: "glyphicon glyphicon-trash" */ + clear?: string; + /**default: "glyphicon glyphicon-remove" */ + close?: string; + /**default: "glyphicon glyphicon-calendar" */ + date?: string; + /**default: "glyphicon glyphicon-time" */ + down?: string; + /**default: "glyphicon glyphicon-chevron-left" */ + next?: string; + /**default: "glyphicon glyphicon-screenshot" */ + previous?: string; + /**default: "glyphicon glyphicon-chevron-right" */ + time?: string; + /**default: "glyphicon glyphicon-chevron-down" */ + today?: string; + /**default: "glyphicon glyphicon-chevron-up" */ + up?: string; +} + +export interface Tooltips { + today?: string; + clear?: string; + close?: string; + selectMonth?: string; + prevMonth?: string; + nextMonth?: string; + selectYear?: string; + prevYear?: string; + nextYear?: string; + selectDecade?: string; + prevDecade?: string; + nextDecade?: string; + prevCentury?: string; + nextCentury?: string; + selectTime?: string; + pickHour?: string; + incrementHour?: string; + decrementHour?: string; + pickMinute?: string; + incrementMinute?: string; + decrementMinute?: string; + togglePeriod?: string; + pickSecond?: string; + incrementSecond?: string; + decrementSecond?: string; +} + +export interface WidgetPositioningOptions { + horizontal?: "auto" | "left" | "right"; + vertical?: "auto" | "top" | "bottom"; +} + +export interface Event extends JQueryEventObject { + date: moment.Moment; +} + +export interface ChangeEvent extends Event { + /**Previous date. False if the previous date is null. */ + oldDate: moment.Moment | boolean; +} + +export interface UpdateEvent extends JQueryEventObject { + /**Change type as a momentjs format token. e.g. yyyy on year change */ + change: string; + /**New viewDate. */ + viewDate: moment.Moment; +} + + +declare global { + interface JQuery { + + datetimepicker(): JQuery; + datetimepicker(options: DatetimepickerOptions): JQuery; + + data(key: "DateTimePicker"): Datetimepicker; + + on(events: "dp.change", handler: (eventObject: ChangeEvent) => any): JQuery; + on(events: "dp.change", selector: string, handler: (eventobject: ChangeEvent) => any): JQuery; + on(events: "dp.change", selector: string, data: any, handler?: (eventobject: ChangeEvent) => any): JQuery; + + off(events: "dp.change", handler: (eventobject: ChangeEvent) => any): JQuery; + off(events: "dp.change", selector?: string, handler?: (eventobject: ChangeEvent) => any): JQuery; + + + on(events: "dp.show", handler: (eventObject: Event) => any): JQuery; + on(events: "dp.show", selector: string, handler: (eventobject: Event) => any): JQuery; + on(events: "dp.show", selector: string, data: any, handler?: (eventobject: Event) => any): JQuery; + + off(events: "dp.show", handler: (eventobject: Event) => any): JQuery; + off(events: "dp.show", selector?: string, handler?: (eventobject: Event) => any): JQuery; + + + on(events: "dp.hide", handler: (eventObject: Event) => any): JQuery; + on(events: "dp.hide", selector: string, handler: (eventobject: Event) => any): JQuery; + on(events: "dp.hide", selector: string, data: any, handler?: (eventobject: Event) => any): JQuery; + + off(events: "dp.hide", handler: (eventobject: Event) => any): JQuery; + off(events: "dp.hide", selector?: string, handler?: (eventobject: Event) => any): JQuery; + + + on(events: "dp.error", handler: (eventObject: Event) => any): JQuery; + on(events: "dp.error", selector: string, handler: (eventobject: Event) => any): JQuery; + on(events: "dp.error", selector: string, data: any, handler?: (eventobject: Event) => any): JQuery; + + off(events: "dp.error", handler: (eventobject: Event) => any): JQuery; + off(events: "dp.error", selector?: string, handler?: (eventobject: Event) => any): JQuery; + + + on(events: "dp.update", handler: (eventObject: UpdateEvent) => any): JQuery; + on(events: "dp.update", selector: string, handler: (eventobject: UpdateEvent) => any): JQuery; + on(events: "dp.update", selector: string, data: any, handler?: (eventobject: UpdateEvent) => any): JQuery; + + off(events: "dp.update", handler: (eventobject: Event) => any): JQuery; + off(events: "dp.update", selector?: string, handler?: (eventobject: UpdateEvent) => any): JQuery; + } +} diff --git a/bootstrap.v3.datetimepicker/tsconfig.json b/bootstrap.v3.datetimepicker/tsconfig.json new file mode 100644 index 0000000000..4b93d0b7ae --- /dev/null +++ b/bootstrap.v3.datetimepicker/tsconfig.json @@ -0,0 +1,17 @@ +{ + "files": [ + "index.d.ts", + "bootstrap.v3.datetimepicker-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/bootstrap/bootstrap-tests.ts b/bootstrap/bootstrap-tests.ts index c497e0abcd..a3633e5d12 100644 --- a/bootstrap/bootstrap-tests.ts +++ b/bootstrap/bootstrap-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + $('body').off('.data-api'); $('body').off('.alert.data-api'); diff --git a/bootstrap/bootstrap.d.ts b/bootstrap/bootstrap.d.ts deleted file mode 100644 index b0e8fbf858..0000000000 --- a/bootstrap/bootstrap.d.ts +++ /dev/null @@ -1,120 +0,0 @@ -// Type definitions for Bootstrap 3.3.5 -// Project: http://twitter.github.com/bootstrap/ -// Definitions by: Boris Yankov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -/// - -interface ModalOptions { - backdrop?: boolean|string; - keyboard?: boolean; - show?: boolean; - remote?: string; -} - -interface ModalOptionsBackdropString { - backdrop?: string; // for "static" - keyboard?: boolean; - show?: boolean; - remote?: string; -} - -interface ScrollSpyOptions { - offset?: number; - target?: string; -} - -interface TooltipOptions { - animation?: boolean; - html?: boolean; - placement?: string | Function; - selector?: string; - title?: string | Function; - trigger?: string; - template?: string; - delay?: number | Object; - container?: string | boolean; - viewport?: string | Function | Object; -} - -interface PopoverOptions { - animation?: boolean; - html?: boolean; - placement?: string | Function; - selector?: string; - trigger?: string; - title?: string | Function; - template?: string; - content?: any; - delay?: number | Object; - container?: string | boolean; - viewport?: string | Function | Object; -} - -interface CollapseOptions { - parent?: any; - toggle?: boolean; -} - -interface CarouselOptions { - interval?: number; - pause?: string; - wrap?: boolean; - keybord?: boolean; -} - -interface TypeaheadOptions { - source?: any; - items?: number; - minLength?: number; - matcher?: (item: any) => boolean; - sorter?: (items: any[]) => any[]; - updater?: (item: any) => any; - highlighter?: (item: any) => string; -} - -interface AffixOptions { - offset?: number | Function | Object; - target?: any; -} - -interface JQuery { - modal(options?: ModalOptions): JQuery; - modal(options?: ModalOptionsBackdropString): JQuery; - modal(command: string): JQuery; - - dropdown(): JQuery; - dropdown(command: string): JQuery; - - scrollspy(command: string): JQuery; - scrollspy(options?: ScrollSpyOptions): JQuery; - - tab(): JQuery; - tab(command: string): JQuery; - - tooltip(options?: TooltipOptions): JQuery; - tooltip(command: string): JQuery; - - popover(options?: PopoverOptions): JQuery; - popover(command: string): JQuery; - - alert(): JQuery; - alert(command: string): JQuery; - - button(): JQuery; - button(command: string): JQuery; - - collapse(options?: CollapseOptions): JQuery; - collapse(command: string): JQuery; - - carousel(options?: CarouselOptions): JQuery; - carousel(command: string): JQuery; - - typeahead(options?: TypeaheadOptions): JQuery; - - affix(options?: AffixOptions): JQuery; -} - -declare module "bootstrap" { -} diff --git a/bootstrap/index.d.ts b/bootstrap/index.d.ts new file mode 100644 index 0000000000..c9c264defa --- /dev/null +++ b/bootstrap/index.d.ts @@ -0,0 +1,120 @@ +// Type definitions for Bootstrap 3.3.5 +// Project: http://twitter.github.com/bootstrap/ +// Definitions by: Boris Yankov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +interface ModalOptions { + backdrop?: boolean|string; + keyboard?: boolean; + show?: boolean; + remote?: string; +} + +interface ModalOptionsBackdropString { + backdrop?: string; // for "static" + keyboard?: boolean; + show?: boolean; + remote?: string; +} + +interface ScrollSpyOptions { + offset?: number; + target?: string; +} + +interface TooltipOptions { + animation?: boolean; + html?: boolean; + placement?: string | Function; + selector?: string; + title?: string | Function; + trigger?: string; + template?: string; + delay?: number | Object; + container?: string | boolean; + viewport?: string | Function | Object; +} + +interface PopoverOptions { + animation?: boolean; + html?: boolean; + placement?: string | Function; + selector?: string; + trigger?: string; + title?: string | Function; + template?: string; + content?: any; + delay?: number | Object; + container?: string | boolean; + viewport?: string | Function | Object; +} + +interface CollapseOptions { + parent?: any; + toggle?: boolean; +} + +interface CarouselOptions { + interval?: number; + pause?: string; + wrap?: boolean; + keybord?: boolean; +} + +interface TypeaheadOptions { + source?: any; + items?: number; + minLength?: number; + matcher?: (item: any) => boolean; + sorter?: (items: any[]) => any[]; + updater?: (item: any) => any; + highlighter?: (item: any) => string; +} + +interface AffixOptions { + offset?: number | Function | Object; + target?: any; +} + +interface JQuery { + modal(options?: ModalOptions): JQuery; + modal(options?: ModalOptionsBackdropString): JQuery; + modal(command: string): JQuery; + + dropdown(): JQuery; + dropdown(command: string): JQuery; + + scrollspy(command: string): JQuery; + scrollspy(options?: ScrollSpyOptions): JQuery; + + tab(): JQuery; + tab(command: string): JQuery; + + tooltip(options?: TooltipOptions): JQuery; + tooltip(command: string): JQuery; + + popover(options?: PopoverOptions): JQuery; + popover(command: string): JQuery; + + alert(): JQuery; + alert(command: string): JQuery; + + button(): JQuery; + button(command: string): JQuery; + + collapse(options?: CollapseOptions): JQuery; + collapse(command: string): JQuery; + + carousel(options?: CarouselOptions): JQuery; + carousel(command: string): JQuery; + + typeahead(options?: TypeaheadOptions): JQuery; + + affix(options?: AffixOptions): JQuery; +} + +declare module "bootstrap" { +} diff --git a/bootstrap/tsconfig.json b/bootstrap/tsconfig.json new file mode 100644 index 0000000000..7202bd75f5 --- /dev/null +++ b/bootstrap/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bootstrap-tests.ts" + ] +} \ No newline at end of file diff --git a/bounce/bounce-tests.ts b/bounce.js/bounce-tests.ts similarity index 94% rename from bounce/bounce-tests.ts rename to bounce.js/bounce-tests.ts index bd90bfe4c1..afa0cdcae2 100644 --- a/bounce/bounce-tests.ts +++ b/bounce.js/bounce-tests.ts @@ -1,5 +1,5 @@ -/// -/// + + import Bounce from 'bounce.js'; import * as $ from 'jquery'; diff --git a/bounce.js/index.d.ts b/bounce.js/index.d.ts new file mode 100644 index 0000000000..250fef1a51 --- /dev/null +++ b/bounce.js/index.d.ts @@ -0,0 +1,65 @@ +// Type definitions for Bounce.js v0.8.2 +// Project: http://github.com/tictail/bounce.js +// Definitions by: Cherry +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +export default Bounce + +interface Point2D { + x: number + y: number +} + +interface BounceOptions { + from: T + to: T + duration?: number + delay?: number + easing?: string + bounces?: number + stiffness?: number +} + +interface AnimationOptions { + loop?: boolean + remove?: boolean + onComplete?: () => void +} + +interface SerailizedComponent { + type: string + from: T + to: T + duration: number + delay: number + easing: string + bounces: number + stiffness: number +} + +declare class Bounce { + static FPS: number + static counter: number + + static isSupported(): boolean + + constructor(); + + scale(options: BounceOptions): Bounce + rotate(options: BounceOptions): Bounce + translate(options: BounceOptions): Bounce + skew(options: BounceOptions): Bounce + + serialize(): SerailizedComponent[] + deserialize(serailized: SerailizedComponent[]): Bounce + + applyTo(element: Element, options?: AnimationOptions): void + applyTo(elements: Element[], options?: AnimationOptions): void + applyTo(elements: JQuery, options?: AnimationOptions): JQueryPromise + + define(name: string): Bounce + remove(): void +} diff --git a/bounce.js/tsconfig.json b/bounce.js/tsconfig.json new file mode 100644 index 0000000000..8bf7f47534 --- /dev/null +++ b/bounce.js/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bounce-tests.ts" + ] +} \ No newline at end of file diff --git a/bounce/bounce.d.ts b/bounce/bounce.d.ts deleted file mode 100644 index 54fe897638..0000000000 --- a/bounce/bounce.d.ts +++ /dev/null @@ -1,66 +0,0 @@ -// Type definitions for Bounce.js v0.8.2 -// Project: http://github.com/tictail/bounce.js -// Definitions by: Cherry -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'bounce.js' { - export default Bounce - - interface Point2D { - x: number - y: number - } - - interface BounceOptions { - from: T - to: T - duration?: number - delay?: number - easing?: string - bounces?: number - stiffness?: number - } - - interface AnimationOptions { - loop?: boolean - remove?: boolean - onComplete?: () => void - } - - interface SerailizedComponent { - type: string - from: T - to: T - duration: number - delay: number - easing: string - bounces: number - stiffness: number - } - - class Bounce { - static FPS: number - static counter: number - - static isSupported(): boolean - - constructor(); - - scale(options: BounceOptions): Bounce - rotate(options: BounceOptions): Bounce - translate(options: BounceOptions): Bounce - skew(options: BounceOptions): Bounce - - serialize(): SerailizedComponent[] - deserialize(serailized: SerailizedComponent[]): Bounce - - applyTo(element: Element, options?: AnimationOptions): void - applyTo(elements: Element[], options?: AnimationOptions): void - applyTo(elements: JQuery, options?: AnimationOptions): JQueryPromise - - define(name: string): Bounce - remove(): void - } -} diff --git a/bowser/bowser-tests.ts b/bowser/bowser-tests.ts index 2f7cb8904c..c70ab4da05 100644 --- a/bowser/bowser-tests.ts +++ b/bowser/bowser-tests.ts @@ -1,4 +1,4 @@ -/// + import Bowser = require('bowser'); diff --git a/bowser/bowser.d.ts b/bowser/bowser.d.ts deleted file mode 100644 index 2bf1b3d510..0000000000 --- a/bowser/bowser.d.ts +++ /dev/null @@ -1,54 +0,0 @@ -// Type definitions for Bowser 1.x -// Project: https://github.com/ded/bowser -// Definitions by: Paulo Cesar -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module 'bowser' { - var def: BowserModule.IBowser; - export = def; -} - -declare namespace BowserModule { - - export interface IBowserUA { - msie: boolean; - chrome: boolean; - webkit: boolean; - phantom: boolean; - opera: boolean; - safari: boolean; - android: boolean; - ios: boolean; - webos: boolean; - msedge: boolean; - seamonkey: boolean; - firefox: boolean; - yandexbrowser: boolean; - blackberry: boolean; - tablet: boolean; - mobile: boolean; - silk: boolean; - bada: boolean; - tizen: boolean; - windowsphone: boolean; - firefoxos: boolean; - gecko: boolean; - sailfish: boolean; - chromeBook: boolean; - /** Grade A browser */ - a: boolean; - /** Grade C browser */ - c: boolean; - /** Grade X browser */ - x: boolean; - name: string; - version: string|number; - osversion: string|number; - } - - export interface IBowser extends IBowserUA { - test(browserList: string[]): boolean; - _detect(ua: string): IBowser; - } - -} diff --git a/bowser/index.d.ts b/bowser/index.d.ts new file mode 100644 index 0000000000..1a9fa4bf70 --- /dev/null +++ b/bowser/index.d.ts @@ -0,0 +1,53 @@ +// Type definitions for Bowser 1.x +// Project: https://github.com/ded/bowser +// Definitions by: Paulo Cesar +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var def: BowserModule.IBowser; +export = def; +export as namespace bowser; + +declare namespace BowserModule { + + export interface IBowserUA { + msie: boolean; + chrome: boolean; + webkit: boolean; + phantom: boolean; + opera: boolean; + safari: boolean; + android: boolean; + ios: boolean; + webos: boolean; + msedge: boolean; + seamonkey: boolean; + firefox: boolean; + yandexbrowser: boolean; + blackberry: boolean; + tablet: boolean; + mobile: boolean; + silk: boolean; + bada: boolean; + tizen: boolean; + windowsphone: boolean; + firefoxos: boolean; + gecko: boolean; + sailfish: boolean; + chromeBook: boolean; + /** Grade A browser */ + a: boolean; + /** Grade C browser */ + c: boolean; + /** Grade X browser */ + x: boolean; + name: string; + version: string|number; + osversion: string|number; + } + + export interface IBowser extends IBowserUA { + test(browserList: string[]): boolean; + _detect(ua: string): IBowser; + } + +} diff --git a/bowser/tsconfig.json b/bowser/tsconfig.json new file mode 100644 index 0000000000..da76d06764 --- /dev/null +++ b/bowser/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bowser-tests.ts" + ] +} \ No newline at end of file diff --git a/box2d/README.md b/box2d/README.md index 251b20ced4..9a775a1962 100644 --- a/box2d/README.md +++ b/box2d/README.md @@ -16,7 +16,7 @@ Import Statements Reference the box2dweb.d.ts file in your project and in an appropriate location include the following import statements to reduce the amount of typing you will need to do to acccess deeply nested modules. ```typescript -/// + // Include the following imports, or add more/less, to reduce the module nesting. import b2Common = Box2D.Common; diff --git a/box2d/box2dweb-tests.ts b/box2d/box2dweb-tests.ts index 5a5f44f24c..776e0df68f 100644 --- a/box2d/box2dweb-tests.ts +++ b/box2d/box2dweb-tests.ts @@ -1,4 +1,4 @@ -/// + import b2Common = Box2D.Common; import b2Math = Box2D.Common.Math; diff --git a/box2d/box2dweb.d.ts b/box2d/index.d.ts similarity index 100% rename from box2d/box2dweb.d.ts rename to box2d/index.d.ts diff --git a/box2d/tsconfig.json b/box2d/tsconfig.json new file mode 100644 index 0000000000..676c2c42a3 --- /dev/null +++ b/box2d/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "box2dweb-tests.ts" + ] +} \ No newline at end of file diff --git a/breeze/breeze-tests.ts b/breeze/breeze-tests.ts index 022f4e3c16..1606e6f591 100644 --- a/breeze/breeze-tests.ts +++ b/breeze/breeze-tests.ts @@ -1,4 +1,4 @@ -/// + import core = breeze.core; import config = breeze.config; @@ -133,7 +133,7 @@ function test_entityManager() { metadataStore: metadataStore }); - return new breeze.QueryOptions({ + new breeze.QueryOptions({ mergeStrategy: null, fetchStrategy: this.fetchStrategy }); @@ -415,25 +415,25 @@ function test_entityQuery() { function test_entityState() { var anEntity: breeze.Entity; var es = anEntity.entityAspect.entityState; - return es.isAdded(); - return es === breeze.EntityState.Added; + es.isAdded(); + es === breeze.EntityState.Added; var es = anEntity.entityAspect.entityState; - return es.isAddedModifiedOrDeleted(); - return es === breeze.EntityState.Added || es === breeze.EntityState.Modified || es === breeze.EntityState.Deleted; + es.isAddedModifiedOrDeleted(); + es === breeze.EntityState.Added || es === breeze.EntityState.Modified || es === breeze.EntityState.Deleted; var es = anEntity.entityAspect.entityState; - return es.isDeleted(); - return es === breeze.EntityState.Deleted; + es.isDeleted(); + es === breeze.EntityState.Deleted; var es = anEntity.entityAspect.entityState; - return es.isDetached(); - return es === breeze.EntityState.Detached; + es.isDetached(); + es === breeze.EntityState.Detached; var es = anEntity.entityAspect.entityState; - return es.isModified(); - return es === breeze.EntityState.Modified; + es.isModified(); + es === breeze.EntityState.Modified; var es = anEntity.entityAspect.entityState; - return es.isUnchanged(); - return es === breeze.EntityState.Unchanged; + es.isUnchanged(); + es === breeze.EntityState.Unchanged; var es = anEntity.entityAspect.entityState; - return es.isUnchangedOrModified(); + es.isUnchangedOrModified(); return es === breeze.EntityState.Unchanged || es === breeze.EntityState.Modified; } diff --git a/breeze/breeze.d.ts b/breeze/index.d.ts similarity index 100% rename from breeze/breeze.d.ts rename to breeze/index.d.ts diff --git a/breeze/tsconfig.json b/breeze/tsconfig.json new file mode 100644 index 0000000000..78821385f8 --- /dev/null +++ b/breeze/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "breeze-tests.ts" + ] +} \ No newline at end of file diff --git a/brorand/brorand-tests.ts b/brorand/brorand-tests.ts index 1adb7b1144..ac090e8724 100644 --- a/brorand/brorand-tests.ts +++ b/brorand/brorand-tests.ts @@ -1,4 +1,3 @@ -/// import * as brorand from 'brorand'; diff --git a/brorand/brorand.d.ts b/brorand/brorand.d.ts deleted file mode 100644 index efef9baa3f..0000000000 --- a/brorand/brorand.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Type definitions for Brorand v1.0.5 -// Project: https://github.com/indutny/brorand -// Definitions by: Ilya Mochalov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "brorand" { - type rand = {getByte: () => number}; - - interface RandStatic { - new (rand: rand): RandInstance; - } - - interface RandInstance { - rand: rand; - generate(len: number): Buffer|Uint8Array; - } - - interface BrorandStatic { - (len: number): Buffer|Uint8Array; - Rand: RandStatic; - } - - namespace Brorand {} - - let Brorand: BrorandStatic; - - export = Brorand; -} diff --git a/brorand/index.d.ts b/brorand/index.d.ts new file mode 100644 index 0000000000..b7e21ed284 --- /dev/null +++ b/brorand/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for Brorand v1.0.5 +// Project: https://github.com/indutny/brorand +// Definitions by: Ilya Mochalov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +type rand = { getByte: () => number }; + +interface RandStatic { + new (rand: rand): RandInstance; +} + +interface RandInstance { + rand: rand; + generate(len: number): Buffer | Uint8Array; +} + +interface BrorandStatic { + (len: number): Buffer | Uint8Array; + Rand: RandStatic; +} + +declare namespace Brorand { } + +declare let Brorand: BrorandStatic; + +export = Brorand; diff --git a/brorand/tsconfig.json b/brorand/tsconfig.json new file mode 100644 index 0000000000..cd2bb44f8f --- /dev/null +++ b/brorand/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "brorand-tests.ts" + ] +} \ No newline at end of file diff --git a/browser-harness/browser-harness-tests.ts b/browser-harness/browser-harness-tests.ts index 71001ba9b0..4215c847d0 100644 --- a/browser-harness/browser-harness-tests.ts +++ b/browser-harness/browser-harness-tests.ts @@ -1,4 +1,3 @@ -/// import harness = require('browser-harness'); diff --git a/browser-harness/browser-harness-tests.ts.tscparams b/browser-harness/browser-harness-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/browser-harness/browser-harness-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/browser-harness/browser-harness.d.ts b/browser-harness/browser-harness.d.ts deleted file mode 100644 index c57311b1f8..0000000000 --- a/browser-harness/browser-harness.d.ts +++ /dev/null @@ -1,133 +0,0 @@ -// Type definitions for Browser Harness -// Project: https://github.com/scriby/browser-harness -// Definitions by: Chris Scribner -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "browser-harness" { - import _events = require('events'); - - interface HarnessEvents extends _events.EventEmitter { - once(event: string, listener: (driver: Driver) => void): this; - once(event: 'ready', listener: (driver: Driver) => void): this; - - on(event: string, listener: (driver: Driver) => void): this; - on(event: 'ready', listener: (driver: Driver) => void): this; - } - - interface DriverEvents extends _events.EventEmitter { - once(event: string, listener: (text: string) => void): this; - once(event: 'console.log', listener: (text: string) => void): this; - once(event: 'console.warn', listener: (text: string) => void): this; - once(event: 'console.error', listener: (text: string) => void): this; - once(event: 'window.onerror', listener: (text: string) => void): this; - - on(event: string, listener: (text: string) => void): this; - on(event: 'console.log', listener: (text: string) => void): this; - on(event: 'console.warn', listener: (text: string) => void): this; - on(event: 'console.error', listener: (text: string) => void): this; - on(event: 'window.onerror', listener: (text: string) => void): this; - } - - export interface Driver { - exec(args: { func: Function; args?: any[]}, callback?: Function) : any; - exec(func: Function, callback?: Function) : any; - - setUrl(url: string, callback?: Function); - - waitFor(args: { condition: Function; exec?: Function; timeoutMS?: number }, callback?: Function); - waitFor(condition: Function, callback?: Function); - - findElement(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy; - findElements(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy; - - findVisible(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy; - findVisibles(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy; - find(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy; - - events: DriverEvents; - } - - export interface ElementProxy { - click(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - focus(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - blur(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - val(value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - attr(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - removeAttr(name: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - prop(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - removeProp(name: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - html(value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - text(value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - hasClass(className: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - addClass(className: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - removeClass(className: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - toggleClass(className: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - - trigger(event: string, extraParameters?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - triggerHandler(event: string, extraParameters?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - - css(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - height(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - innerHeight(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - outerHeight(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - width(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - innerWidth(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - outerWidth(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - offset(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - position(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - scrollLeft(value?: number, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - scrollTop(value?: number, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - - hide(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - show(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - toggle(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - - children(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - closest(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - contents(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - find(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - findElements(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - findElement(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - findVisible(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - findVisibles(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - isActionable(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - first(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - has(arg: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - is(arg: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - last(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - next(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - nextAll(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - nextUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - offsetParent(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - parent(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - parents(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - parentsUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - prev(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - prevAll(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - prevUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - siblings(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - - - data(name: string, value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - removeData(name: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - - filter(selector: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - } - - export class Browser { - //constructor(args: { type: string; location?: string; args?: string[] }); - constructor(args: { type: string; location?: string; args?: any; }); - - open(harnessUrl: string, serverUrl?: string); - close(); - } - - export function listen(port: number, callback?: Function) - export var events: HarnessEvents; - export var config: { - timeoutMS: number; - retryMS: number; - }; -} diff --git a/browser-harness/browser-harness.d.ts.tscparams b/browser-harness/browser-harness.d.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/browser-harness/browser-harness.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/browser-harness/index.d.ts b/browser-harness/index.d.ts new file mode 100644 index 0000000000..d2c49be3e9 --- /dev/null +++ b/browser-harness/index.d.ts @@ -0,0 +1,132 @@ +// Type definitions for Browser Harness +// Project: https://github.com/scriby/browser-harness +// Definitions by: Chris Scribner +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import _events = require('events'); + +interface HarnessEvents extends _events.EventEmitter { + once(event: string, listener: (driver: Driver) => void): this; + once(event: 'ready', listener: (driver: Driver) => void): this; + + on(event: string, listener: (driver: Driver) => void): this; + on(event: 'ready', listener: (driver: Driver) => void): this; +} + +interface DriverEvents extends _events.EventEmitter { + once(event: string, listener: (text: string) => void): this; + once(event: 'console.log', listener: (text: string) => void): this; + once(event: 'console.warn', listener: (text: string) => void): this; + once(event: 'console.error', listener: (text: string) => void): this; + once(event: 'window.onerror', listener: (text: string) => void): this; + + on(event: string, listener: (text: string) => void): this; + on(event: 'console.log', listener: (text: string) => void): this; + on(event: 'console.warn', listener: (text: string) => void): this; + on(event: 'console.error', listener: (text: string) => void): this; + on(event: 'window.onerror', listener: (text: string) => void): this; +} + +export interface Driver { + exec(args: { func: Function; args?: any[] }, callback?: Function): any; + exec(func: Function, callback?: Function): any; + + setUrl(url: string, callback?: Function); + + waitFor(args: { condition: Function; exec?: Function; timeoutMS?: number }, callback?: Function); + waitFor(condition: Function, callback?: Function); + + findElement(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy; + findElements(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy; + + findVisible(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy; + findVisibles(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy; + find(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy; + + events: DriverEvents; +} + +export interface ElementProxy { + click(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + focus(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + blur(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + val(value?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + attr(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + removeAttr(name: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + prop(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + removeProp(name: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + html(value?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + text(value?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + hasClass(className: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + addClass(className: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + removeClass(className: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + toggleClass(className: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + + trigger(event: string, extraParameters?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + triggerHandler(event: string, extraParameters?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + + css(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + height(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + innerHeight(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + outerHeight(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + width(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + innerWidth(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + outerWidth(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + offset(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + position(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + scrollLeft(value?: number, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + scrollTop(value?: number, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + + hide(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + show(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + toggle(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + + children(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + closest(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + contents(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + find(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + findElements(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + findElement(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + findVisible(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + findVisibles(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + isActionable(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + first(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + has(arg: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + is(arg: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + last(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + next(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + nextAll(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + nextUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + offsetParent(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + parent(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + parents(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + parentsUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + prev(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + prevAll(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + prevUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + siblings(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + + + data(name: string, value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + removeData(name: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + + filter(selector: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy +} + +export declare class Browser { + //constructor(args: { type: string; location?: string; args?: string[] }); + constructor(args: { type: string; location?: string; args?: any; }); + + open(harnessUrl: string, serverUrl?: string); + close(); +} + +export declare function listen(port: number, callback?: Function) +export declare var events: HarnessEvents; +export declare var config: { + timeoutMS: number; + retryMS: number; +}; diff --git a/browser-harness/tsconfig.json b/browser-harness/tsconfig.json new file mode 100644 index 0000000000..a0732be20a --- /dev/null +++ b/browser-harness/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "browser-harness-tests.ts" + ] +} \ No newline at end of file diff --git a/browser-sync/browser-sync-tests.ts b/browser-sync/browser-sync-tests.ts index 822c941d9f..45cfd11c30 100644 --- a/browser-sync/browser-sync-tests.ts +++ b/browser-sync/browser-sync-tests.ts @@ -1,4 +1,3 @@ -/// import browserSync = require("browser-sync"); (() => { diff --git a/browser-sync/browser-sync.d.ts b/browser-sync/browser-sync.d.ts deleted file mode 100644 index 3bc083d1f1..0000000000 --- a/browser-sync/browser-sync.d.ts +++ /dev/null @@ -1,422 +0,0 @@ -// Type definitions for browser-sync -// Project: http://www.browsersync.io/ -// Definitions by: Asana , Joe Skeen -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// -/// - -declare module "browser-sync" { - import chokidar = require("chokidar"); - import fs = require("fs"); - import http = require("http"); - import mm = require("micromatch"); - - namespace browserSync { - interface Options { - /** - * Browsersync includes a user-interface that is accessed via a separate port. The UI allows to controls - * all devices, push sync updates and much more. - * - * port - Default: 3001 - * weinre.port - Default: 8080 - * Note: requires at least version 2.0.0 - */ - ui?: UIOptions; - /** - * Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS - * & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob - * patterns. - * Default: false - */ - files?: string | string[]; - /** - * File watching options that get passed along to Chokidar. Check their docs for available options - * Default: undefined - * Note: requires at least version 2.6.0 - */ - watchOptions?: chokidar.WatchOptions; - /** - * Use the built-in static server for basic HTML/JS/CSS websites. - * Default: false - */ - server?: ServerOptions; - /** - * Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site. - * target - Default: undefined - * ws - Default: undefined - * middleware - Default: undefined - * reqHeaders - Default: undefined - * proxyRes - Default: undefined - */ - proxy?: string | boolean | ProxyOptions; - /** - * Use a specific port (instead of the one auto-detected by Browsersync) - * Default: 3000 - */ - port?: number; - /** - * Add additional directories from which static files should be served. - * Should only be used in proxy or snippet mode. - * Default: [] - * Note: requires at least version 2.8.0 - */ - serveStatic?: string[]; - /** - * Enable https for localhost development. - * Note - this is not needed for proxy option as it will be inferred from your target url. - * Note: requires at least version 1.3.0 - */ - https?: boolean; - /** - * Clicks, Scrolls & Form inputs on any device will be mirrored to all others. - * clicks - Default: true - * scroll - Default: true - * forms - Default: true - */ - ghostMode?: GhostOptions | boolean; - /** - * Can be either "info", "debug", "warn", or "silent" - * Default: info - */ - logLevel?: string; - /** - * Change the console logging prefix. Useful if you're creating your own project based on Browsersync - * Default: BS - * Note: requires at least version 1.5.1 - */ - logPrefix?: string; - /** - * Whether or not to log connections - * Default: false - */ - logConnections?: boolean; - /** - * Whether or not to log information about changed files - * Default: false - */ - logFileChanges?: boolean; - /** - * Log the snippet to the console when you're in snippet mode (no proxy/server) - * Default: true - * Note: requires at least version 1.5.2 - */ - logSnippet?: boolean; - /** - * You can control how the snippet is injected onto each page via a custom regex + function. - * You can also provide patterns for certain urls that should be ignored from the snippet injection. - * Note: requires at least version 2.0.0 - */ - snippetOptions?: SnippetOptions; - /** - * Add additional HTML rewriting rules. - * Default: false - * Note: requires at least version 2.4.0 - */ - rewriteRules?: boolean | RewriteRules[]; - /** - * Tunnel the Browsersync server through a random Public URL - * Default: null - */ - tunnel?: string | boolean; - /** - * Some features of Browsersync (such as xip & tunnel) require an internet connection, but if you're - * working offline, you can reduce start-up time by setting this option to false - */ - online?: boolean; - /** - * Default: true - * Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. - * Can be true, local, external, ui, ui-external, tunnel or false - */ - open?: string | boolean; - /** - * The browser(s) to open - * Default: default - */ - browser?: string | string[]; - /** - * Requires an internet connection - useful for services such as Typekit as it allows you to configure - * domains such as *.xip.io in your kit settings - * Default: false - */ - xip?: boolean; - /** - * Reload each browser when Browsersync is restarted. - * Default: false - */ - reloadOnRestart?: boolean; - /** - * The small pop-over notifications in the browser are not always needed/wanted. - * Default: true - */ - notify?: boolean; - /** - * scrollProportionally: false // Sync viewports to TOP position - * Default: true - */ - scrollProportionally?: boolean; - /** - * How often to send scroll events - * Default: 0 - */ - scrollThrottle?: number; - /** - * Decide which technique should be used to restore scroll position following a reload. - * Can be window.name or cookie - * Default: 'window.name' - */ - scrollRestoreTechnique?: string; - /** - * Sync the scroll position of any element on the page. Add any amount of CSS selectors - * Default: [] - * Note: requires at least version 2.9.0 - */ - scrollElements?: string[]; - /** - * Default: [] - * Note: requires at least version 2.9.0 - * Sync the scroll position of any element on the page - where any scrolled element will cause - * all others to match scroll position. This is helpful when a breakpoint alters which element - * is actually scrolling - */ - scrollElementMapping?: string[]; - /** - * Time, in milliseconds, to wait before instructing the browser to reload/inject following a file - * change event - * Default: 0 - */ - reloadDelay?: number; - /** - * Restrict the frequency in which browser:reload events can be emitted to connected clients - * Default: 0 - * Note: requires at least version 2.6.0 - */ - reloadDebounce?: number; - /** - * User provided plugins - * Default: [] - * Note: requires at least version 2.6.0 - */ - plugins?: any[]; - /** - * Whether to inject changes (rather than a page refresh) - * Default: true - */ - injectChanges?: boolean; - /** - * The initial path to load - */ - startPath?: string; - /** - * Whether to minify the client script - * Default: true - */ - minify?: boolean; - /** - * Override host detection if you know the correct IP to use - */ - host?: string; - /** - * Send file-change events to the browser - * Default: true - */ - codeSync?: boolean; - /** - * Append timestamps to injected files - * Default: true - */ - timestamps?: boolean; - /** - * Alter the script path for complete control over where the Browsersync Javascript is served - * from. Whatever you return from this function will be used as the script path. - * Note: requires at least version 1.5.0 - */ - scriptPath?: (path: string) => string; - /** - * Configure the Socket.IO path and namespace & domain to avoid collisions. - * path - Default: "/browser-sync/socket.io" - * clientPath - Default: "/browser-sync" - * namespace - Default: "/browser-sync" - * domain - Default: undefined - * port - Default: undefined - * clients.heartbeatTimeout - Default: 5000 - * Note: requires at least version 1.6.2 - */ - socket?: SocketOptions; - middleware?: MiddlewareHandler | MiddlewareHandler[]; - } - - interface Hash { - [path: string]: T; - } - - interface UIOptions { - /** set the default port */ - port?: number; - /** set the default weinre port */ - weinre?: { - port?: number; - }; - } - - interface ServerOptions { - /** set base directory */ - baseDir?: string | string[]; - /** enable directory listing */ - directory?: boolean; - /** set index filename */ - index?: string; - /** - * key-value object hash, where the key is the url to match, - * and the value is the folder to serve (relative to your working directory) - */ - routes?: Hash; - /** configure custom middleware */ - middleware?: MiddlewareHandler[]; - } - - interface ProxyOptions { - target?: string; - middleware?: MiddlewareHandler; - ws: boolean; - reqHeaders: (config: any) => Hash; - proxyRes: (res: http.ServerResponse, req: http.ServerRequest, next: Function) => any; - } - - interface MiddlewareHandler { - (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; - } - - interface GhostOptions { - clicks?: boolean; - scroll?: boolean; - forms?: boolean; - } - - interface SnippetOptions { - ignorePaths?: string; - rule?: { match?: RegExp; fn?: (snippet: string, match: string) => any }; - } - - interface SocketOptions { - path?: string; - clientPath?: string; - namespace?: string; - domain?: string; - port?: number; - clients?: { heartbeatTimeout?: number; }; - } - - interface RewriteRules { - match: RegExp; - fn: (match: string) => string; - } - - interface StreamOptions { - once?: boolean; - match?: mm.Pattern | mm.Pattern[]; - } - - interface BrowserSyncStatic extends BrowserSyncInstance { - /** - * Start the Browsersync service. This will launch a server, proxy or start the snippet mode - * depending on your use-case. - */ - (config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; - /** - * Create a Browsersync instance - * @param name an identifier that can used for retrieval later - */ - create(name?: string): BrowserSyncInstance; - /** - * Get a single instance by name. This is useful if you have your build scripts in separate files - * @param name the identifier used for retrieval - */ - get(name: string): BrowserSyncInstance; - /** - * Check if an instance has been created. - * @param name the name of the instance - */ - has(name: string): boolean; - } - - interface BrowserSyncInstance { - /** the name of this instance of browser-sync */ - name: string; - /** - * Start the Browsersync service. This will launch a server, proxy or start the snippet mode - * depending on your use-case. - */ - init(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; - /** - * Reload the browser - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(): void; - /** - * Reload a single file - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(file: string): void; - /** - * Reload multiple files - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(files: string[]): void; - /** - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(options: { stream: boolean }): NodeJS.ReadWriteStream; - /** - * The stream method returns a transform stream and can act once or on many files. - * @param opts Configuration for the stream method - */ - stream(opts?: StreamOptions): NodeJS.ReadWriteStream; - /** - * Helper method for browser notifications - * @param message Can be a simple message such as 'Connected' or HTML - * @param timeout How long the message will remain in the browser. @since 1.3.0 - */ - notify(message: string, timeout?: number): void; - /** - * This method will close any running server, stop file watching & exit the current process. - */ - exit(): void; - /** - * Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system - */ - watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any) - : NodeJS.EventEmitter; - /** - * Method to pause file change events - */ - pause(): void; - /** - * Method to resume paused watchers - */ - resume(): void; - /** - * The internal Event Emitter used by the running Browsersync instance (if there is one). You can use - * this to emit your own events, such as changed files, logging etc. - */ - emitter: NodeJS.EventEmitter; - /** - * A simple true/false flag that you can use to determine if there's a currently-running Browsersync instance. - */ - active: boolean; - /** - * A simple true/false flag to determine if the current instance is paused - */ - paused: boolean; - } - } - - const browserSync: browserSync.BrowserSyncStatic; - export = browserSync; -} diff --git a/browser-sync/index.d.ts b/browser-sync/index.d.ts new file mode 100644 index 0000000000..82563271d8 --- /dev/null +++ b/browser-sync/index.d.ts @@ -0,0 +1,419 @@ +// Type definitions for browser-sync +// Project: http://www.browsersync.io/ +// Definitions by: Asana , Joe Skeen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +import chokidar = require("chokidar"); +import fs = require("fs"); +import http = require("http"); +import mm = require("micromatch"); + +declare namespace browserSync { + interface Options { + /** + * Browsersync includes a user-interface that is accessed via a separate port. The UI allows to controls + * all devices, push sync updates and much more. + * + * port - Default: 3001 + * weinre.port - Default: 8080 + * Note: requires at least version 2.0.0 + */ + ui?: UIOptions; + /** + * Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS + * & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob + * patterns. + * Default: false + */ + files?: string | string[]; + /** + * File watching options that get passed along to Chokidar. Check their docs for available options + * Default: undefined + * Note: requires at least version 2.6.0 + */ + watchOptions?: chokidar.WatchOptions; + /** + * Use the built-in static server for basic HTML/JS/CSS websites. + * Default: false + */ + server?: ServerOptions; + /** + * Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site. + * target - Default: undefined + * ws - Default: undefined + * middleware - Default: undefined + * reqHeaders - Default: undefined + * proxyRes - Default: undefined + */ + proxy?: string | boolean | ProxyOptions; + /** + * Use a specific port (instead of the one auto-detected by Browsersync) + * Default: 3000 + */ + port?: number; + /** + * Add additional directories from which static files should be served. + * Should only be used in proxy or snippet mode. + * Default: [] + * Note: requires at least version 2.8.0 + */ + serveStatic?: string[]; + /** + * Enable https for localhost development. + * Note - this is not needed for proxy option as it will be inferred from your target url. + * Note: requires at least version 1.3.0 + */ + https?: boolean; + /** + * Clicks, Scrolls & Form inputs on any device will be mirrored to all others. + * clicks - Default: true + * scroll - Default: true + * forms - Default: true + */ + ghostMode?: GhostOptions | boolean; + /** + * Can be either "info", "debug", "warn", or "silent" + * Default: info + */ + logLevel?: string; + /** + * Change the console logging prefix. Useful if you're creating your own project based on Browsersync + * Default: BS + * Note: requires at least version 1.5.1 + */ + logPrefix?: string; + /** + * Whether or not to log connections + * Default: false + */ + logConnections?: boolean; + /** + * Whether or not to log information about changed files + * Default: false + */ + logFileChanges?: boolean; + /** + * Log the snippet to the console when you're in snippet mode (no proxy/server) + * Default: true + * Note: requires at least version 1.5.2 + */ + logSnippet?: boolean; + /** + * You can control how the snippet is injected onto each page via a custom regex + function. + * You can also provide patterns for certain urls that should be ignored from the snippet injection. + * Note: requires at least version 2.0.0 + */ + snippetOptions?: SnippetOptions; + /** + * Add additional HTML rewriting rules. + * Default: false + * Note: requires at least version 2.4.0 + */ + rewriteRules?: boolean | RewriteRules[]; + /** + * Tunnel the Browsersync server through a random Public URL + * Default: null + */ + tunnel?: string | boolean; + /** + * Some features of Browsersync (such as xip & tunnel) require an internet connection, but if you're + * working offline, you can reduce start-up time by setting this option to false + */ + online?: boolean; + /** + * Default: true + * Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. + * Can be true, local, external, ui, ui-external, tunnel or false + */ + open?: string | boolean; + /** + * The browser(s) to open + * Default: default + */ + browser?: string | string[]; + /** + * Requires an internet connection - useful for services such as Typekit as it allows you to configure + * domains such as *.xip.io in your kit settings + * Default: false + */ + xip?: boolean; + /** + * Reload each browser when Browsersync is restarted. + * Default: false + */ + reloadOnRestart?: boolean; + /** + * The small pop-over notifications in the browser are not always needed/wanted. + * Default: true + */ + notify?: boolean; + /** + * scrollProportionally: false // Sync viewports to TOP position + * Default: true + */ + scrollProportionally?: boolean; + /** + * How often to send scroll events + * Default: 0 + */ + scrollThrottle?: number; + /** + * Decide which technique should be used to restore scroll position following a reload. + * Can be window.name or cookie + * Default: 'window.name' + */ + scrollRestoreTechnique?: string; + /** + * Sync the scroll position of any element on the page. Add any amount of CSS selectors + * Default: [] + * Note: requires at least version 2.9.0 + */ + scrollElements?: string[]; + /** + * Default: [] + * Note: requires at least version 2.9.0 + * Sync the scroll position of any element on the page - where any scrolled element will cause + * all others to match scroll position. This is helpful when a breakpoint alters which element + * is actually scrolling + */ + scrollElementMapping?: string[]; + /** + * Time, in milliseconds, to wait before instructing the browser to reload/inject following a file + * change event + * Default: 0 + */ + reloadDelay?: number; + /** + * Restrict the frequency in which browser:reload events can be emitted to connected clients + * Default: 0 + * Note: requires at least version 2.6.0 + */ + reloadDebounce?: number; + /** + * User provided plugins + * Default: [] + * Note: requires at least version 2.6.0 + */ + plugins?: any[]; + /** + * Whether to inject changes (rather than a page refresh) + * Default: true + */ + injectChanges?: boolean; + /** + * The initial path to load + */ + startPath?: string; + /** + * Whether to minify the client script + * Default: true + */ + minify?: boolean; + /** + * Override host detection if you know the correct IP to use + */ + host?: string; + /** + * Send file-change events to the browser + * Default: true + */ + codeSync?: boolean; + /** + * Append timestamps to injected files + * Default: true + */ + timestamps?: boolean; + /** + * Alter the script path for complete control over where the Browsersync Javascript is served + * from. Whatever you return from this function will be used as the script path. + * Note: requires at least version 1.5.0 + */ + scriptPath?: (path: string) => string; + /** + * Configure the Socket.IO path and namespace & domain to avoid collisions. + * path - Default: "/browser-sync/socket.io" + * clientPath - Default: "/browser-sync" + * namespace - Default: "/browser-sync" + * domain - Default: undefined + * port - Default: undefined + * clients.heartbeatTimeout - Default: 5000 + * Note: requires at least version 1.6.2 + */ + socket?: SocketOptions; + middleware?: MiddlewareHandler | MiddlewareHandler[]; + } + + interface Hash { + [path: string]: T; + } + + interface UIOptions { + /** set the default port */ + port?: number; + /** set the default weinre port */ + weinre?: { + port?: number; + }; + } + + interface ServerOptions { + /** set base directory */ + baseDir?: string | string[]; + /** enable directory listing */ + directory?: boolean; + /** set index filename */ + index?: string; + /** + * key-value object hash, where the key is the url to match, + * and the value is the folder to serve (relative to your working directory) + */ + routes?: Hash; + /** configure custom middleware */ + middleware?: MiddlewareHandler[]; + } + + interface ProxyOptions { + target?: string; + middleware?: MiddlewareHandler; + ws: boolean; + reqHeaders: (config: any) => Hash; + proxyRes: (res: http.ServerResponse, req: http.ServerRequest, next: Function) => any; + } + + interface MiddlewareHandler { + (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; + } + + interface GhostOptions { + clicks?: boolean; + scroll?: boolean; + forms?: boolean; + } + + interface SnippetOptions { + ignorePaths?: string; + rule?: { match?: RegExp; fn?: (snippet: string, match: string) => any }; + } + + interface SocketOptions { + path?: string; + clientPath?: string; + namespace?: string; + domain?: string; + port?: number; + clients?: { heartbeatTimeout?: number; }; + } + + interface RewriteRules { + match: RegExp; + fn: (match: string) => string; + } + + interface StreamOptions { + once?: boolean; + match?: mm.Pattern | mm.Pattern[]; + } + + interface BrowserSyncStatic extends BrowserSyncInstance { + /** + * Start the Browsersync service. This will launch a server, proxy or start the snippet mode + * depending on your use-case. + */ + (config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; + /** + * Create a Browsersync instance + * @param name an identifier that can used for retrieval later + */ + create(name?: string): BrowserSyncInstance; + /** + * Get a single instance by name. This is useful if you have your build scripts in separate files + * @param name the identifier used for retrieval + */ + get(name: string): BrowserSyncInstance; + /** + * Check if an instance has been created. + * @param name the name of the instance + */ + has(name: string): boolean; + } + + interface BrowserSyncInstance { + /** the name of this instance of browser-sync */ + name: string; + /** + * Start the Browsersync service. This will launch a server, proxy or start the snippet mode + * depending on your use-case. + */ + init(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; + /** + * Reload the browser + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(): void; + /** + * Reload a single file + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(file: string): void; + /** + * Reload multiple files + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(files: string[]): void; + /** + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(options: { stream: boolean }): NodeJS.ReadWriteStream; + /** + * The stream method returns a transform stream and can act once or on many files. + * @param opts Configuration for the stream method + */ + stream(opts?: StreamOptions): NodeJS.ReadWriteStream; + /** + * Helper method for browser notifications + * @param message Can be a simple message such as 'Connected' or HTML + * @param timeout How long the message will remain in the browser. @since 1.3.0 + */ + notify(message: string, timeout?: number): void; + /** + * This method will close any running server, stop file watching & exit the current process. + */ + exit(): void; + /** + * Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system + */ + watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any) + : NodeJS.EventEmitter; + /** + * Method to pause file change events + */ + pause(): void; + /** + * Method to resume paused watchers + */ + resume(): void; + /** + * The internal Event Emitter used by the running Browsersync instance (if there is one). You can use + * this to emit your own events, such as changed files, logging etc. + */ + emitter: NodeJS.EventEmitter; + /** + * A simple true/false flag that you can use to determine if there's a currently-running Browsersync instance. + */ + active: boolean; + /** + * A simple true/false flag to determine if the current instance is paused + */ + paused: boolean; + } +} + +declare const browserSync: browserSync.BrowserSyncStatic; +export = browserSync; diff --git a/browser-sync/tsconfig.json b/browser-sync/tsconfig.json new file mode 100644 index 0000000000..8e33dc71e9 --- /dev/null +++ b/browser-sync/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "browser-sync-tests.ts" + ] +} \ No newline at end of file diff --git a/browserify/browserify-tests.ts b/browserify/browserify-tests.ts index b4096a7f98..68ebb59c7f 100644 --- a/browserify/browserify-tests.ts +++ b/browserify/browserify-tests.ts @@ -1,5 +1,3 @@ -/// - import browserify = require("browserify"); import fs = require("fs"); import stream = require('stream'); diff --git a/browserify/browserify.d.ts b/browserify/browserify.d.ts deleted file mode 100644 index a3a9c4efd1..0000000000 --- a/browserify/browserify.d.ts +++ /dev/null @@ -1,182 +0,0 @@ -// Type definitions for Browserify v12.0.1 -// Project: http://browserify.org/ -// Definitions by: Andrew Gaspar , John Vilk -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Browserify { - /** - * Options pertaining to an individual file. - */ - interface FileOptions { - // If true, this is considered an entry point to your app. - entry?: boolean; - // Expose this file under a custom dependency name. - // require('./vendor/angular/angular.js', {expose: 'angular'}) enables require('angular') - expose?: string; - // Basedir to use to resolve this file's path. - basedir?: string; - // The name/path to the file. - file?: string; - // Forward file to external() to be externalized. - external?: boolean; - // Disable transforms on file if set to false. - transform?: boolean; - // The ID to use for require() statements. - id?: string; - } - - - // Browserify accepts a filename, an input stream for file inputs, or a FileOptions configuration - // for each file in a bundle. - type InputFile = string | NodeJS.ReadableStream | FileOptions; - - /** - * Options pertaining to a Browserify instance. - */ - interface Options { - // Custom properties can be defined on Options. - // These options are forwarded along to module-deps and browser-pack directly. - [propName: string]: any; - // String, file object, or array of those types (they may be mixed) specifying entry file(s). - entries?: InputFile | InputFile[]; - // an array which will skip all require() and global parsing for each file in the array. - // Use this for giant libs like jquery or threejs that don't have any requires or node-style globals but take forever to parse. - noParse?: string[]; - // an array of optional extra extensions for the module lookup machinery to use when the extension has not been specified. - // By default Browserify considers only .js and .json files in such cases. - extensions?: string[]; - // the directory that Browserify starts bundling from for filenames that start with .. - basedir?: string; - // an array of directories that Browserify searches when looking for modules which are not referenced using relative path. - // Can be absolute or relative to basedir. Equivalent of setting NODE_PATH environmental variable when calling Browserify command. - paths?: string[]; - // sets the algorithm used to parse out the common paths. Use false to turn this off, otherwise it uses the commondir module. - commondir?: boolean; - // disables converting module ids into numerical indexes. This is useful for preserving the original paths that a bundle was generated with. - fullPaths?: boolean; - // sets the list of built-ins to use, which by default is set in lib/builtins.js in this distribution. - builtins?: string[] | {[builtinName: string]: string} | boolean; - // set if external modules should be bundled. Defaults to true. - bundleExternal?: boolean; - // When true, always insert process, global, __filename, and __dirname without analyzing the AST for faster builds but larger output bundles. Default false. - insertGlobals?: boolean; - // When true, scan all files for process, global, __filename, and __dirname, defining as necessary. - // With this option npm modules are more likely to work but bundling takes longer. Default true. - detectGlobals?: boolean; - // When true, add a source map inline to the end of the bundle. This makes debugging easier because you can see all the original files if you are in a modern enough browser. - debug?: boolean; - // When a non-empty string, a standalone module is created with that name and a umd wrapper. - // You can use namespaces in the standalone global export using a . in the string name as a separator, for example 'A.B.C'. - // The global export will be sanitized and camel cased. - standalone?: string; - // will be passed to insert-module-globals as the opts.vars parameter. - insertGlobalVars?: {[globalName: string]: (file: string, basedir: string) => any}; - // defaults to 'require' in expose mode but you can use another name. - externalRequireName?: string; - } - - interface BrowserifyConstructor { - (files: InputFile[], opts?: Options): BrowserifyObject; - (file: InputFile, opts?: Options): BrowserifyObject; - (opts: Options): BrowserifyObject; - (): BrowserifyObject - new(files: InputFile[], opts?: Options): BrowserifyObject; - new(file: InputFile, opts?: Options): BrowserifyObject; - new(opts: Options): BrowserifyObject; - new(): BrowserifyObject - } - - interface BrowserifyObject extends NodeJS.EventEmitter { - /** - * Add an entry file from file that will be executed when the bundle loads. - * If file is an array, each item in file will be added as an entry file. - */ - add(file: InputFile[], opts?: FileOptions): BrowserifyObject; - add(file: InputFile, opts?: FileOptions): BrowserifyObject; - /** - * Make file available from outside the bundle with require(file). - * The file param is anything that can be resolved by require.resolve(). - * file can also be a stream, but you should also use opts.basedir so that relative requires will be resolvable. - * If file is an array, each item in file will be required. In file array form, you can use a string or object for each item. Object items should have a file property and the rest of the parameters will be used for the opts. - * Use the expose property of opts to specify a custom dependency name. require('./vendor/angular/angular.js', {expose: 'angular'}) enables require('angular') - */ - require(file: InputFile, opts?: FileOptions): BrowserifyObject; - /** - * Bundle the files and their dependencies into a single javascript file. - * Return a readable stream with the javascript file contents or optionally specify a cb(err, buf) to get the buffered results. - */ - bundle(cb?: (err: any, src: Buffer) => any): NodeJS.ReadableStream; - /** - * Prevent file from being loaded into the current bundle, instead referencing from another bundle. - * If file is an array, each item in file will be externalized. - * If file is another bundle, that bundle's contents will be read and excluded from the current bundle as the bundle in file gets bundled. - */ - external(file: string[], opts?: { basedir?: string }): BrowserifyObject; - external(file: string, opts?: { basedir?: string }): BrowserifyObject; - external(file: BrowserifyObject): BrowserifyObject; - /** - * Prevent the module name or file at file from showing up in the output bundle. - * Instead you will get a file with module.exports = {}. - */ - ignore(file: string, opts?: { basedir?: string }): BrowserifyObject; - /** - * Prevent the module name or file at file from showing up in the output bundle. - * If your code tries to require() that file it will throw unless you've provided another mechanism for loading it. - */ - exclude(file: string, opts?: { basedir?: string }): BrowserifyObject; - /** - * Transform source code before parsing it for require() calls with the transform function or module name tr. - * If tr is a function, it will be called with tr(file) and it should return a through-stream that takes the raw file contents and produces the transformed source. - * If tr is a string, it should be a module name or file path of a transform module - */ - transform(tr: string, opts?: T): BrowserifyObject; - transform(tr: (file: string, opts: T) => NodeJS.ReadWriteStream, opts?: T): BrowserifyObject; - /** - * Register a plugin with opts. Plugins can be a string module name or a function the same as transforms. - * plugin(b, opts) is called with the Browserify instance b. - */ - plugin(plugin: string, opts?: T): BrowserifyObject; - plugin(plugin: (b: BrowserifyObject, opts: T) => any, opts?: T): BrowserifyObject; - /** - * Reset the pipeline back to a normal state. This function is called automatically when bundle() is called multiple times. - * This function triggers a 'reset' event. - */ - reset(opts?: Options): void; - - /** - * When a file is resolved for the bundle, the bundle emits a 'file' event with the full file path, the id string passed to require(), and the parent object used by browser-resolve. - * You could use the file event to implement a file watcher to regenerate bundles when files change. - */ - on(event: 'file', listener: (file: string, id: string, parent: any) => any): this; - /** - * When a package.json file is read, this event fires with the contents. - * The package directory is available at pkg.__dirname. - */ - on(event: 'package', listener: (pkg: any) => any): this; - /** - * When .bundle() is called, this event fires with the bundle output stream. - */ - on(event: 'bundle', listener: (bundle: NodeJS.ReadableStream) => any): this; - /** - * When the .reset() method is called or implicitly called by another call to .bundle(), this event fires. - */ - on(event: 'reset', listener: () => any): this; - /** - * When a transform is applied to a file, the 'transform' event fires on the bundle stream with the transform stream tr and the file that the transform is being applied to. - */ - on(event: 'transform', listener: (tr: NodeJS.ReadWriteStream, file: string) => any): this; - on(event: string, listener: Function): this; - - /** - * Set to any until substack/labeled-stream-splicer is defined - */ - pipeline: any; - } -} - -declare module "browserify" { - var browserify: Browserify.BrowserifyConstructor; - export = browserify; -} diff --git a/browserify/index.d.ts b/browserify/index.d.ts new file mode 100644 index 0000000000..506bc3dd86 --- /dev/null +++ b/browserify/index.d.ts @@ -0,0 +1,175 @@ +// Type definitions for Browserify v12.0.1 +// Project: http://browserify.org/ +// Definitions by: Andrew Gaspar , John Vilk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare var browserify: BrowserifyConstructor; +export = browserify; + +/** + * Options pertaining to an individual file. + */ +interface FileOptions { + // If true, this is considered an entry point to your app. + entry?: boolean; + // Expose this file under a custom dependency name. + // require('./vendor/angular/angular.js', {expose: 'angular'}) enables require('angular') + expose?: string; + // Basedir to use to resolve this file's path. + basedir?: string; + // The name/path to the file. + file?: string; + // Forward file to external() to be externalized. + external?: boolean; + // Disable transforms on file if set to false. + transform?: boolean; + // The ID to use for require() statements. + id?: string; +} + +// Browserify accepts a filename, an input stream for file inputs, or a FileOptions configuration +// for each file in a bundle. +type InputFile = string | NodeJS.ReadableStream | FileOptions; + +/** + * Options pertaining to a Browserify instance. + */ +interface Options { + // Custom properties can be defined on Options. + // These options are forwarded along to module-deps and browser-pack directly. + [propName: string]: any; + // String, file object, or array of those types (they may be mixed) specifying entry file(s). + entries?: InputFile | InputFile[]; + // an array which will skip all require() and global parsing for each file in the array. + // Use this for giant libs like jquery or threejs that don't have any requires or node-style globals but take forever to parse. + noParse?: string[]; + // an array of optional extra extensions for the module lookup machinery to use when the extension has not been specified. + // By default Browserify considers only .js and .json files in such cases. + extensions?: string[]; + // the directory that Browserify starts bundling from for filenames that start with .. + basedir?: string; + // an array of directories that Browserify searches when looking for modules which are not referenced using relative path. + // Can be absolute or relative to basedir. Equivalent of setting NODE_PATH environmental variable when calling Browserify command. + paths?: string[]; + // sets the algorithm used to parse out the common paths. Use false to turn this off, otherwise it uses the commondir module. + commondir?: boolean; + // disables converting module ids into numerical indexes. This is useful for preserving the original paths that a bundle was generated with. + fullPaths?: boolean; + // sets the list of built-ins to use, which by default is set in lib/builtins.js in this distribution. + builtins?: string[] | {[builtinName: string]: string} | boolean; + // set if external modules should be bundled. Defaults to true. + bundleExternal?: boolean; + // When true, always insert process, global, __filename, and __dirname without analyzing the AST for faster builds but larger output bundles. Default false. + insertGlobals?: boolean; + // When true, scan all files for process, global, __filename, and __dirname, defining as necessary. + // With this option npm modules are more likely to work but bundling takes longer. Default true. + detectGlobals?: boolean; + // When true, add a source map inline to the end of the bundle. This makes debugging easier because you can see all the original files if you are in a modern enough browser. + debug?: boolean; + // When a non-empty string, a standalone module is created with that name and a umd wrapper. + // You can use namespaces in the standalone global export using a . in the string name as a separator, for example 'A.B.C'. + // The global export will be sanitized and camel cased. + standalone?: string; + // will be passed to insert-module-globals as the opts.vars parameter. + insertGlobalVars?: {[globalName: string]: (file: string, basedir: string) => any}; + // defaults to 'require' in expose mode but you can use another name. + externalRequireName?: string; +} + +interface BrowserifyConstructor { + (files: InputFile[], opts?: Options): BrowserifyObject; + (file: InputFile, opts?: Options): BrowserifyObject; + (opts?: Options): BrowserifyObject; + new(files: InputFile[], opts?: Options): BrowserifyObject; + new(file: InputFile, opts?: Options): BrowserifyObject; + new(opts?: Options): BrowserifyObject; +} + +interface BrowserifyObject extends NodeJS.EventEmitter { + /** + * Add an entry file from file that will be executed when the bundle loads. + * If file is an array, each item in file will be added as an entry file. + */ + add(file: InputFile[], opts?: FileOptions): BrowserifyObject; + add(file: InputFile, opts?: FileOptions): BrowserifyObject; + /** + * Make file available from outside the bundle with require(file). + * The file param is anything that can be resolved by require.resolve(). + * file can also be a stream, but you should also use opts.basedir so that relative requires will be resolvable. + * If file is an array, each item in file will be required. In file array form, you can use a string or object for each item. Object items should have a file property and the rest of the parameters will be used for the opts. + * Use the expose property of opts to specify a custom dependency name. require('./vendor/angular/angular.js', {expose: 'angular'}) enables require('angular') + */ + require(file: InputFile, opts?: FileOptions): BrowserifyObject; + /** + * Bundle the files and their dependencies into a single javascript file. + * Return a readable stream with the javascript file contents or optionally specify a cb(err, buf) to get the buffered results. + */ + bundle(cb?: (err: any, src: Buffer) => any): NodeJS.ReadableStream; + /** + * Prevent file from being loaded into the current bundle, instead referencing from another bundle. + * If file is an array, each item in file will be externalized. + * If file is another bundle, that bundle's contents will be read and excluded from the current bundle as the bundle in file gets bundled. + */ + external(file: string[], opts?: { basedir?: string }): BrowserifyObject; + external(file: string, opts?: { basedir?: string }): BrowserifyObject; + external(file: BrowserifyObject): BrowserifyObject; + /** + * Prevent the module name or file at file from showing up in the output bundle. + * Instead you will get a file with module.exports = {}. + */ + ignore(file: string, opts?: { basedir?: string }): BrowserifyObject; + /** + * Prevent the module name or file at file from showing up in the output bundle. + * If your code tries to require() that file it will throw unless you've provided another mechanism for loading it. + */ + exclude(file: string, opts?: { basedir?: string }): BrowserifyObject; + /** + * Transform source code before parsing it for require() calls with the transform function or module name tr. + * If tr is a function, it will be called with tr(file) and it should return a through-stream that takes the raw file contents and produces the transformed source. + * If tr is a string, it should be a module name or file path of a transform module + */ + transform(tr: string, opts?: T): BrowserifyObject; + transform(tr: (file: string, opts: T) => NodeJS.ReadWriteStream, opts?: T): BrowserifyObject; + /** + * Register a plugin with opts. Plugins can be a string module name or a function the same as transforms. + * plugin(b, opts) is called with the Browserify instance b. + */ + plugin(plugin: string, opts?: T): BrowserifyObject; + plugin(plugin: (b: BrowserifyObject, opts: T) => any, opts?: T): BrowserifyObject; + /** + * Reset the pipeline back to a normal state. This function is called automatically when bundle() is called multiple times. + * This function triggers a 'reset' event. + */ + reset(opts?: Options): void; + + /** + * When a file is resolved for the bundle, the bundle emits a 'file' event with the full file path, the id string passed to require(), and the parent object used by browser-resolve. + * You could use the file event to implement a file watcher to regenerate bundles when files change. + */ + on(event: 'file', listener: (file: string, id: string, parent: any) => any): this; + /** + * When a package.json file is read, this event fires with the contents. + * The package directory is available at pkg.__dirname. + */ + on(event: 'package', listener: (pkg: any) => any): this; + /** + * When .bundle() is called, this event fires with the bundle output stream. + */ + on(event: 'bundle', listener: (bundle: NodeJS.ReadableStream) => any): this; + /** + * When the .reset() method is called or implicitly called by another call to .bundle(), this event fires. + */ + on(event: 'reset', listener: () => any): this; + /** + * When a transform is applied to a file, the 'transform' event fires on the bundle stream with the transform stream tr and the file that the transform is being applied to. + */ + on(event: 'transform', listener: (tr: NodeJS.ReadWriteStream, file: string) => any): this; + on(event: string, listener: Function): this; + + /** + * Set to any until substack/labeled-stream-splicer is defined + */ + pipeline: any; +} diff --git a/browserify/tsconfig.json b/browserify/tsconfig.json new file mode 100644 index 0000000000..e29ea03579 --- /dev/null +++ b/browserify/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "browserify-tests.ts" + ] +} \ No newline at end of file diff --git a/bs58/bs58-tests.ts b/bs58/bs58-tests.ts index 8016469269..5fe3b73675 100644 --- a/bs58/bs58-tests.ts +++ b/bs58/bs58-tests.ts @@ -1,4 +1,3 @@ -/// import * as bs58 from 'bs58'; diff --git a/bs58/bs58.d.ts b/bs58/bs58.d.ts deleted file mode 100644 index 00ebbbfec7..0000000000 --- a/bs58/bs58.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Type definitions for bs58 3.0.0 -// Project: https://github.com/cryptocoinjs/bs58 -// Definitions by: Ilya Mochalov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "bs58" { - namespace base58 {} - - let base58: BaseX.BaseConverter; - - export = base58; -} diff --git a/bs58/index.d.ts b/bs58/index.d.ts new file mode 100644 index 0000000000..dcc0735e08 --- /dev/null +++ b/bs58/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for bs58 3.0.0 +// Project: https://github.com/cryptocoinjs/bs58 +// Definitions by: Ilya Mochalov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +declare namespace base58 { } + +declare let base58: BaseX.BaseConverter; + +export = base58; diff --git a/bs58/tsconfig.json b/bs58/tsconfig.json new file mode 100644 index 0000000000..047bfbfd7a --- /dev/null +++ b/bs58/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bs58-tests.ts" + ] +} \ No newline at end of file diff --git a/bson/bson-tests.ts b/bson/bson-tests.ts index a454ed2366..e1e1c5d323 100644 --- a/bson/bson-tests.ts +++ b/bson/bson-tests.ts @@ -1,5 +1,3 @@ -/// - import * as bson from 'bson'; let BSON = new bson.BSONPure.BSON(); diff --git a/bson/bson.d.ts b/bson/bson.d.ts deleted file mode 100644 index c311103ff3..0000000000 --- a/bson/bson.d.ts +++ /dev/null @@ -1,133 +0,0 @@ -// Type definitions for bson 0.4.21 -// Project: https://github.com/mongodb/js-bson -// Definitions by: Hiroki Horiuchi -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - - -declare module 'bson' { - - namespace bson { - - export module BSONPure { - - export interface DeserializeOptions { - /** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. */ - evalFunctions?: boolean; - /** {Boolean, default:false}, cache evaluated functions for reuse. */ - cacheFunctions?: boolean; - /** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. */ - cacheFunctionsCrc32?: boolean; - /** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object. */ - promoteBuffers?: boolean; - } - export class BSON { - /** - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object (ignore). - * @param {Boolean} serializeFunctions serialize the javascript functions (default:false) - * @return {Buffer} returns a TypedArray or Array depending on what your browser supports - */ - serialize(object: any, checkKeys?: boolean, asBuffer?: boolean, serializeFunctions?: boolean): Buffer; - deserialize(buffer: Buffer, options?: DeserializeOptions, isArray?: boolean): any; - } - - - export interface Binary {} - export interface BinaryStatic { - SUBTYPE_DEFAULT: number; - SUBTYPE_FUNCTION: number; - SUBTYPE_BYTE_ARRAY: number; - SUBTYPE_UUID_OLD: number; - SUBTYPE_UUID: number; - SUBTYPE_MD5: number; - SUBTYPE_USER_DEFINED: number; - - new (buffer: Buffer, subType?: number): Binary; - } - export let Binary: BinaryStatic; - - export interface Code {} - export interface CodeStatic { - new (code: string | Function, scope?: any): Code; - } - export let Code: CodeStatic; - - export interface DBRef {} - export interface DBRefStatic { - new (namespace: string, oid: ObjectID, db?: string): DBRef; - } - export let DBRef: DBRefStatic; - - export interface Double {} - export interface DoubleStatic { - new (value: number): Double; - } - export let Double: DoubleStatic; - - export interface Long {} - export interface LongStatic { - new (low: number, high: number): Long; - fromInt(i: number): Long; - fromNumber(n: number): Long; - fromBits(lowBits: number, highBits: number): Long; - fromString(s: string, opt_radix?: number): Long; - } - export let Long: LongStatic; - - export interface MaxKey {} - export interface MaxKeyStatic { - new (): MaxKey; - } - export let MaxKey: MaxKeyStatic; - - export interface MinKey {} - export interface MinKeyStatic { - new (): MinKey; - } - export let MinKey: MinKeyStatic; - - export interface ObjectID {} - export interface ObjectIDStatic { - new (id?: number | string | ObjectID): ObjectID; - createPk(): ObjectID; - createFromTime(time: number): ObjectID; - createFromHexString(hexString: string): ObjectID; - isValid(id: number | string | ObjectID): boolean; - } - export let ObjectID: ObjectIDStatic; - export let ObjectId: ObjectIDStatic; - - export interface BSONRegExp {} - export interface BSONRegExpStatic { - new (pattern: string, options: string): BSONRegExp; - } - export let BSONRegExp: BSONRegExpStatic; - - export interface Symbol {} - export interface SymbolStatic { - new (value: string): Symbol; - } - export let Symbol: SymbolStatic; - - export interface Timestamp {} - export interface TimestampStatic { - new (low: number, high: number): Timestamp; - fromInt(i: number): Timestamp; - fromNumber(n: number): Timestamp; - fromBits(lowBits: number, highBits: number): Timestamp; - fromString(s: string, opt_radix?: number): Timestamp; - } - export let Timestamp: TimestampStatic; - - } - - export let BSONNative: typeof BSONPure; - - } - - export = bson; -} - diff --git a/bson/index.d.ts b/bson/index.d.ts new file mode 100644 index 0000000000..75726c4516 --- /dev/null +++ b/bson/index.d.ts @@ -0,0 +1,131 @@ +// Type definitions for bson 0.4.21 +// Project: https://github.com/mongodb/js-bson +// Definitions by: Hiroki Horiuchi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + + + +declare namespace bson { + + export module BSONPure { + + export interface DeserializeOptions { + /** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. */ + evalFunctions?: boolean; + /** {Boolean, default:false}, cache evaluated functions for reuse. */ + cacheFunctions?: boolean; + /** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. */ + cacheFunctionsCrc32?: boolean; + /** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object. */ + promoteBuffers?: boolean; + } + export class BSON { + /** + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object (ignore). + * @param {Boolean} serializeFunctions serialize the javascript functions (default:false) + * @return {Buffer} returns a TypedArray or Array depending on what your browser supports + */ + serialize(object: any, checkKeys?: boolean, asBuffer?: boolean, serializeFunctions?: boolean): Buffer; + deserialize(buffer: Buffer, options?: DeserializeOptions, isArray?: boolean): any; + } + + + export interface Binary { } + export interface BinaryStatic { + SUBTYPE_DEFAULT: number; + SUBTYPE_FUNCTION: number; + SUBTYPE_BYTE_ARRAY: number; + SUBTYPE_UUID_OLD: number; + SUBTYPE_UUID: number; + SUBTYPE_MD5: number; + SUBTYPE_USER_DEFINED: number; + + new (buffer: Buffer, subType?: number): Binary; + } + export let Binary: BinaryStatic; + + export interface Code { } + export interface CodeStatic { + new (code: string | Function, scope?: any): Code; + } + export let Code: CodeStatic; + + export interface DBRef { } + export interface DBRefStatic { + new (namespace: string, oid: ObjectID, db?: string): DBRef; + } + export let DBRef: DBRefStatic; + + export interface Double { } + export interface DoubleStatic { + new (value: number): Double; + } + export let Double: DoubleStatic; + + export interface Long { } + export interface LongStatic { + new (low: number, high: number): Long; + fromInt(i: number): Long; + fromNumber(n: number): Long; + fromBits(lowBits: number, highBits: number): Long; + fromString(s: string, opt_radix?: number): Long; + } + export let Long: LongStatic; + + export interface MaxKey { } + export interface MaxKeyStatic { + new (): MaxKey; + } + export let MaxKey: MaxKeyStatic; + + export interface MinKey { } + export interface MinKeyStatic { + new (): MinKey; + } + export let MinKey: MinKeyStatic; + + export interface ObjectID { } + export interface ObjectIDStatic { + new (id?: number | string | ObjectID): ObjectID; + createPk(): ObjectID; + createFromTime(time: number): ObjectID; + createFromHexString(hexString: string): ObjectID; + isValid(id: number | string | ObjectID): boolean; + } + export let ObjectID: ObjectIDStatic; + export let ObjectId: ObjectIDStatic; + + export interface BSONRegExp { } + export interface BSONRegExpStatic { + new (pattern: string, options: string): BSONRegExp; + } + export let BSONRegExp: BSONRegExpStatic; + + export interface Symbol { } + export interface SymbolStatic { + new (value: string): Symbol; + } + export let Symbol: SymbolStatic; + + export interface Timestamp { } + export interface TimestampStatic { + new (low: number, high: number): Timestamp; + fromInt(i: number): Timestamp; + fromNumber(n: number): Timestamp; + fromBits(lowBits: number, highBits: number): Timestamp; + fromString(s: string, opt_radix?: number): Timestamp; + } + export let Timestamp: TimestampStatic; + + } + + export let BSONNative: typeof BSONPure; + +} + +export = bson; diff --git a/bson/tsconfig.json b/bson/tsconfig.json new file mode 100644 index 0000000000..a44e9fa503 --- /dev/null +++ b/bson/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bson-tests.ts" + ] +} \ No newline at end of file diff --git a/bucks/bucks-tests.ts b/bucks/bucks-tests.ts index 5ebbd882cf..c996de4459 100644 --- a/bucks/bucks-tests.ts +++ b/bucks/bucks-tests.ts @@ -1,5 +1,3 @@ -/// - function add_and_end() { // // new Bucks object @@ -98,7 +96,6 @@ 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(); diff --git a/bucks/bucks.d.ts b/bucks/index.d.ts similarity index 100% rename from bucks/bucks.d.ts rename to bucks/index.d.ts diff --git a/bucks/tsconfig.json b/bucks/tsconfig.json new file mode 100644 index 0000000000..ba0598aff2 --- /dev/null +++ b/bucks/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bucks-tests.ts" + ] +} \ No newline at end of file diff --git a/buffer-compare/buffer-compare-tests.ts b/buffer-compare/buffer-compare-tests.ts index 88e6dddb94..0f43838bd4 100644 --- a/buffer-compare/buffer-compare-tests.ts +++ b/buffer-compare/buffer-compare-tests.ts @@ -1,5 +1,5 @@ -/// -/// + +/// import compare = require('buffer-compare'); diff --git a/buffer-compare/buffer-compare.d.ts b/buffer-compare/buffer-compare.d.ts deleted file mode 100644 index 47bd3fcbec..0000000000 --- a/buffer-compare/buffer-compare.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Type definitions for buffer-compare -// Project: https://github.com/soldair/node-buffer-compare -// Definitions by: Ilya Mochalov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "buffer-compare" { - interface List { - [index: number]: any; - length: number - } - - function compare(cmp: List, to: List): number; - function compare(cmp: T, to: T): number; - function compare(cmp: C, to: T): number; - - export = compare; -} diff --git a/buffer-compare/index.d.ts b/buffer-compare/index.d.ts new file mode 100644 index 0000000000..bd61febdb7 --- /dev/null +++ b/buffer-compare/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for buffer-compare +// Project: https://github.com/soldair/node-buffer-compare +// Definitions by: Ilya Mochalov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +interface List { + [index: number]: any; + length: number +} + +declare function compare(cmp: List, to: List): number; +declare function compare(cmp: T, to: T): number; +declare function compare(cmp: C, to: T): number; + +export = compare; diff --git a/buffer-compare/tsconfig.json b/buffer-compare/tsconfig.json new file mode 100644 index 0000000000..5ca9a18028 --- /dev/null +++ b/buffer-compare/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "buffer-compare-tests.ts" + ] +} \ No newline at end of file diff --git a/buffer-equal/buffer-equal-tests.ts b/buffer-equal/buffer-equal-tests.ts index 192051ab47..f025c2f4e6 100644 --- a/buffer-equal/buffer-equal-tests.ts +++ b/buffer-equal/buffer-equal-tests.ts @@ -1,4 +1,3 @@ -/// import bufferEqual = require('buffer-equal'); diff --git a/buffer-equal/buffer-equal.d.ts b/buffer-equal/buffer-equal.d.ts deleted file mode 100644 index b3ede1fc1d..0000000000 --- a/buffer-equal/buffer-equal.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Type definitions for buffer-equal 0.0.1 -// Project: https://github.com/substack/node-buffer-equal -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'buffer-equal' { - function bufferEqual(actual:Buffer, expected:Buffer): boolean; - export = bufferEqual; -} diff --git a/buffer-equal/index.d.ts b/buffer-equal/index.d.ts new file mode 100644 index 0000000000..b7862f6ee1 --- /dev/null +++ b/buffer-equal/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for buffer-equal 0.0.1 +// Project: https://github.com/substack/node-buffer-equal +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +declare function bufferEqual(actual: Buffer, expected: Buffer): boolean; +export = bufferEqual; diff --git a/buffer-equal/tsconfig.json b/buffer-equal/tsconfig.json new file mode 100644 index 0000000000..82cd53bcfe --- /dev/null +++ b/buffer-equal/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "buffer-equal-tests.ts" + ] +} \ No newline at end of file diff --git a/buffers/buffers-tests.ts b/buffers/buffers-tests.ts index 0a51f97ae4..73dbd57794 100644 --- a/buffers/buffers-tests.ts +++ b/buffers/buffers-tests.ts @@ -1,4 +1,4 @@ -/// + import Buffers = require('buffers'); var any: any; diff --git a/buffers/buffers.d.ts b/buffers/buffers.d.ts deleted file mode 100644 index e2ca5c2708..0000000000 --- a/buffers/buffers.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Type definitions for buffers 0.1.1 -// Project: https://github.com/substack/node-buffers -// Definitions by: Robert Hencke -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "buffers" { - - interface BuffersStatics { - new (bufs?: Buffer[]|Buffers): Buffers; - (bufs?: Buffer[]| Buffers): Buffers; - prototype: Buffers; - } - - interface Buffers { - buffers: Buffer[]; - length: number; - - push(...items: Buffer[]): number; - unshift(...items: Buffer[]): number; - slice(i?: number, j?: number): Buffer; - splice(i: number, howMany?: number, ...items: Buffer[]): Buffers; - copy(dst: Buffer, dstStart?: number, start?: number, end?: number): number; - get(i: number): any; - set(i: number, b: any): void; - indexOf(needle: string|Buffer, offset?: number): number; - toBuffer(): Buffer; - toString(encoding?: any, start?: number, end?: number): string; - } - - var Buffers: BuffersStatics; - - export = Buffers; - -} diff --git a/buffers/index.d.ts b/buffers/index.d.ts new file mode 100644 index 0000000000..ec8be5a493 --- /dev/null +++ b/buffers/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for buffers 0.1.1 +// Project: https://github.com/substack/node-buffers +// Definitions by: Robert Hencke +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + + +interface BuffersStatics { + new (bufs?: Buffer[] | Buffers): Buffers; + (bufs?: Buffer[] | Buffers): Buffers; + prototype: Buffers; +} + +interface Buffers { + buffers: Buffer[]; + length: number; + + push(...items: Buffer[]): number; + unshift(...items: Buffer[]): number; + slice(i?: number, j?: number): Buffer; + splice(i: number, howMany?: number, ...items: Buffer[]): Buffers; + copy(dst: Buffer, dstStart?: number, start?: number, end?: number): number; + get(i: number): any; + set(i: number, b: any): void; + indexOf(needle: string | Buffer, offset?: number): number; + toBuffer(): Buffer; + toString(encoding?: any, start?: number, end?: number): string; +} + +declare var Buffers: BuffersStatics; + +export = Buffers; diff --git a/buffers/tsconfig.json b/buffers/tsconfig.json new file mode 100644 index 0000000000..8ed06f90d3 --- /dev/null +++ b/buffers/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "buffers-tests.ts" + ] +} \ No newline at end of file diff --git a/bufferstream/bufferstream-tests.ts b/bufferstream/bufferstream-tests.ts index fe1ea70aa9..5d2bcbd4c7 100644 --- a/bufferstream/bufferstream-tests.ts +++ b/bufferstream/bufferstream-tests.ts @@ -1,4 +1,4 @@ -/// + import BufferStream = require('bufferstream') diff --git a/bufferstream/bufferstream.d.ts b/bufferstream/bufferstream.d.ts deleted file mode 100644 index ee115d0ab5..0000000000 --- a/bufferstream/bufferstream.d.ts +++ /dev/null @@ -1,119 +0,0 @@ -// Type definitions for bufferstream v0.6.2 -// Project: https://github.com/dodo/node-bufferstream -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'bufferstream' { - import stream = require('stream'); - - export = BufferStream; - - class BufferStream extends stream.Duplex { - constructor(options?: BufferStream.Opts); - - /* - different buffer behaviors can be triggered by size: - - none when output drains, bufferstream drains too - flexible buffers everthing that it gets and not piping out - TODO buffer has given size. buffers everthing until buffer is full. when buffer is full then the stream will drain - */ - setSize(size: string): void; // can be one of ['none', 'flexible', ] - setSize(size: number): void; // can be one of ['none', 'flexible', ] - /* - enables stream buffering default - */ - enable(): void; - /* - flushes buffer and disables stream buffering. BufferStream now pipes all data as long as the output accepting data. when the output is draining BufferStream will buffer all input temporary. - - token[s] buffer splitters (should be String or Buffer) - - disables given tokens. wont flush until no splitter tokens are left. - */ - disable(): void; - disable(token: string, ...tokens: string[]): void; - disable(tokens: string[]): void; // Array - disable(token: Buffer, ...tokens: Buffer[]): void; - disable(tokens: Buffer[]): void; // Array - /* - each time BufferStream finds a splitter token in the input data it will emit a split event. this also works for binary data. - - token[s] buffer splitters (should be String or Buffer) - */ - split(token: string, ...tokens: string[]): void; - split(tokens: string[]): void; // Array - split(token: Buffer, ...tokens: Buffer[]): void; - split(tokens: Buffer[]): void; // Array - /* - returns Buffer. - */ - getBuffer(): Buffer; - /* - returns Buffer. - */ - buffer: Buffer; - /* - shortcut for buffer.toString() - */ - toString(): string; - /* - shortcut for buffer.length - */ - length: number; - } - namespace BufferStream { - - export interface Opts { - /* - default encoding for writing strings - */ - encoding?: string; - /* - if true and the source is a child_process the stream will block the entire process (timeouts wont work anymore, but splitting and listening on data still works, because they work sync) - */ - blocking?: boolean; - /* - defines buffer level or sets buffer to given size (see ↓setSize for more) - */ - size?: any; - /* - immediately call disable - */ - disabled?: boolean; - /* - short form for: - split(token, function (chunk) {emit('data', chunk)}) - */ - // String or Buffer - split?: any; - } - export var fn: {warn: boolean}; - } -} - -declare module 'bufferstream/postbuffer' { - import http = require('http'); - import BufferStream = require('bufferstream'); - - class PostBuffer extends BufferStream { - /* - for if you want to get all the post data from a http server request and do some db reqeust before. - - http client buffer - */ - constructor(req: http.ServerRequest); - /* - set a callback to get all post data from a http server request - */ - onEnd(callback: (data: any) => void): void; - /* - pumps data into another stream to allow incoming streams given options will be passed to Stream.pipe - */ - pipe(stream: NodeJS.WritableStream, options?: BufferStream.Opts): NodeJS.ReadableStream; - } - - export = PostBuffer; -} diff --git a/bufferstream/index.d.ts b/bufferstream/index.d.ts new file mode 100644 index 0000000000..06ce5d96c4 --- /dev/null +++ b/bufferstream/index.d.ts @@ -0,0 +1,119 @@ +// Type definitions for bufferstream v0.6.2 +// Project: https://github.com/dodo/node-bufferstream +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'bufferstream' { + import stream = require('stream'); + + export = BufferStream; + + class BufferStream extends stream.Duplex { + constructor(options?: BufferStream.Opts); + + /* + different buffer behaviors can be triggered by size: + + none when output drains, bufferstream drains too + flexible buffers everthing that it gets and not piping out + TODO buffer has given size. buffers everthing until buffer is full. when buffer is full then the stream will drain + */ + setSize(size: string): void; // can be one of ['none', 'flexible', ] + setSize(size: number): void; // can be one of ['none', 'flexible', ] + /* + enables stream buffering default + */ + enable(): void; + /* + flushes buffer and disables stream buffering. BufferStream now pipes all data as long as the output accepting data. when the output is draining BufferStream will buffer all input temporary. + + token[s] buffer splitters (should be String or Buffer) + + disables given tokens. wont flush until no splitter tokens are left. + */ + disable(): void; + disable(token: string, ...tokens: string[]): void; + disable(tokens: string[]): void; // Array + disable(token: Buffer, ...tokens: Buffer[]): void; + disable(tokens: Buffer[]): void; // Array + /* + each time BufferStream finds a splitter token in the input data it will emit a split event. this also works for binary data. + + token[s] buffer splitters (should be String or Buffer) + */ + split(token: string, ...tokens: string[]): void; + split(tokens: string[]): void; // Array + split(token: Buffer, ...tokens: Buffer[]): void; + split(tokens: Buffer[]): void; // Array + /* + returns Buffer. + */ + getBuffer(): Buffer; + /* + returns Buffer. + */ + buffer: Buffer; + /* + shortcut for buffer.toString() + */ + toString(): string; + /* + shortcut for buffer.length + */ + length: number; + } + namespace BufferStream { + + export interface Opts { + /* + default encoding for writing strings + */ + encoding?: string; + /* + if true and the source is a child_process the stream will block the entire process (timeouts wont work anymore, but splitting and listening on data still works, because they work sync) + */ + blocking?: boolean; + /* + defines buffer level or sets buffer to given size (see ↓setSize for more) + */ + size?: any; + /* + immediately call disable + */ + disabled?: boolean; + /* + short form for: + split(token, function (chunk) {emit('data', chunk)}) + */ + // String or Buffer + split?: any; + } + export var fn: {warn: boolean}; + } +} + +declare module 'bufferstream/postbuffer' { + import http = require('http'); + import BufferStream = require('bufferstream'); + + class PostBuffer extends BufferStream { + /* + for if you want to get all the post data from a http server request and do some db reqeust before. + + http client buffer + */ + constructor(req: http.ServerRequest); + /* + set a callback to get all post data from a http server request + */ + onEnd(callback: (data: any) => void): void; + /* + pumps data into another stream to allow incoming streams given options will be passed to Stream.pipe + */ + pipe(stream: NodeJS.WritableStream, options?: BufferStream.Opts): NodeJS.ReadableStream; + } + + export = PostBuffer; +} diff --git a/bufferstream/tsconfig.json b/bufferstream/tsconfig.json new file mode 100644 index 0000000000..f9ba836771 --- /dev/null +++ b/bufferstream/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bufferstream-tests.ts" + ] +} \ No newline at end of file diff --git a/bugsnag/bugsnag-tests.ts b/bugsnag/bugsnag-tests.ts index 8e91e03c6b..033abe2a34 100644 --- a/bugsnag/bugsnag-tests.ts +++ b/bugsnag/bugsnag-tests.ts @@ -1,4 +1,4 @@ -/// + Bugsnag.apiKey = "API-KEY"; diff --git a/bugsnag/bugsnag.d.ts b/bugsnag/index.d.ts similarity index 100% rename from bugsnag/bugsnag.d.ts rename to bugsnag/index.d.ts diff --git a/bugsnag/tsconfig.json b/bugsnag/tsconfig.json new file mode 100644 index 0000000000..0b1b4625ca --- /dev/null +++ b/bugsnag/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bugsnag-tests.ts" + ] +} \ No newline at end of file diff --git a/bull/bull-tests.ts.tscparams b/bull/bull-tests.ts.tscparams deleted file mode 100644 index 6641df12d4..0000000000 --- a/bull/bull-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ ---target es5 --noImplicitAny --module commonjs diff --git a/bull/bull-tests.tsx b/bull/bull-tests.tsx index bd25efc0c9..1d307fd31e 100644 --- a/bull/bull-tests.tsx +++ b/bull/bull-tests.tsx @@ -2,9 +2,6 @@ * Created by Bruno Grieder */ -/// - - import * as Queue from "bull" var videoQueue = Queue( 'video transcoding', 6379, '127.0.0.1' ); @@ -87,16 +84,17 @@ interface VideoJob extends Queue.Job { videoQueue.process( ( job: VideoJob ) => { // don't forget to remove the done callback! // Simply return a promise - return fetchVideo( job.data.url ).then( transcodeVideo ); + fetchVideo( job.data.url ).then( transcodeVideo ); // Handles promise rejection - return Promise.reject( new Error( 'error transcoding' ) ); + Promise.reject( new Error( 'error transcoding' ) ); // Passes the value the promise is resolved with to the "completed" event - return Promise.resolve( { framerate: 29.5 /* etc... */ } ); + Promise.resolve( { framerate: 29.5 /* etc... */ } ); + + // same as + Promise.reject( new Error( 'some unexpected error' ) ); // If the job throws an unhandled exception it is also handled correctly throw new Error( 'some unexpected error' ); - // same as - return Promise.reject( new Error( 'some unexpected error' ) ); } ); diff --git a/bull/bull.d.ts b/bull/bull.d.ts deleted file mode 100644 index e04a9f21e8..0000000000 --- a/bull/bull.d.ts +++ /dev/null @@ -1,309 +0,0 @@ -// Type definitions for bull 0.7.0 -// Project: https://github.com/OptimalBits/bull -// Definitions by: Bruno Grieder -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "bull" { - - import * as Redis from "redis"; - - /** - * This is the Queue constructor. - * It creates a new Queue that is persisted in Redis. - * Everytime the same queue is instantiated it tries to process all the old jobs that may exist from a previous unfinished session. - */ - function Bull(queueName: string, redisPort: number, redisHost: string, redisOpt?: Redis.ClientOpts): Bull.Queue; - - namespace Bull { - - export interface DoneCallback { - (error?: Error, value?: any): void - } - - export interface Job { - - id: string - - /** - * The custom data passed when the job was created - */ - data: Object; - - /** - * Report progress on a job - */ - progress(value: any): Promise; - - /** - * Removes a Job from the queue from all the lists where it may be included. - * @returns {Promise} A promise that resolves when the job is removed. - */ - remove(): Promise; - - /** - * Rerun a Job that has failed. - * @returns {Promise} A promise that resolves when the job is scheduled for retry. - */ - retry(): Promise; - } - - export interface Backoff { - - /** - * Backoff type, which can be either `fixed` or `exponential` - */ - type: string - - /** - * Backoff delay, in milliseconds - */ - delay: number; - } - - export interface AddOptions { - /** - * An amount of miliseconds to wait until this job can be processed. - * Note that for accurate delays, both server and clients should have their clocks synchronized - */ - delay?: number; - - /** - * A number of attempts to retry if the job fails [optional] - */ - attempts?: number; - - /** - * Backoff setting for automatic retries if the job fails - */ - backoff?: number | Backoff - - /** - * A boolean which, if true, adds the job to the right - * of the queue instead of the left (default false) - */ - lifo?: boolean; - - /** - * The number of milliseconds after which the job should be fail with a timeout error - */ - timeout?: number; - } - - export interface Queue { - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. - * - * concurrency: Bull will then call you handler in parallel respecting this max number. - */ - process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. - */ - process(callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * A promise must be returned to signal job completion. - * If the promise is rejected, the error will be passed as a second argument to the "failed" event. - * If it is resolved, its value will be the "completed" event's second argument. - * - * concurrency: Bull will then call you handler in parallel respecting this max number. - */ - process(concurrency: number, callback: (job: Job) => void): Promise; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * A promise must be returned to signal job completion. - * If the promise is rejected, the error will be passed as a second argument to the "failed" event. - * If it is resolved, its value will be the "completed" event's second argument. - */ - process(callback: (job: Job) => void): Promise; - - // process(callback: (job: Job, done?: DoneCallback) => void): Promise; - - /** - * Creates a new job and adds it to the queue. - * If the queue is empty the job will be executed directly, - * otherwise it will be placed in the queue and executed as soon as possible. - */ - add(data: Object, opts?: AddOptions): Promise; - - /** - * Returns a promise that resolves when the queue is paused. - * The pause is global, meaning that all workers in all queue instances for a given queue will be paused. - * A paused queue will not process new jobs until resumed, - * but current jobs being processed will continue until they are finalized. - * - * Pausing a queue that is already paused does nothing. - */ - pause(): Promise; - - /** - * Returns a promise that resolves when the queue is resumed after being paused. - * The resume is global, meaning that all workers in all queue instances for a given queue will be resumed. - * - * Resuming a queue that is not paused does nothing. - */ - resume(): Promise; - - /** - * Returns a promise that returns the number of jobs in the queue, waiting or paused. - * Since there may be other processes adding or processing jobs, this value may be true only for a very small amount of time. - */ - count(): Promise; - - /** - * Empties a queue deleting all the input lists and associated jobs. - */ - empty(): Promise; - - /** - * Closes the underlying redis client. Use this to perform a graceful shutdown. - * - * `close` can be called from anywhere, with one caveat: - * if called from within a job handler the queue won't close until after the job has been processed - */ - close(): Promise; - - /** - * Returns a promise that will return the job instance associated with the jobId parameter. - * If the specified job cannot be located, the promise callback parameter will be set to null. - */ - getJob(jobId: string): Promise; - - /** - * Tells the queue remove all jobs created outside of a grace period in milliseconds. - * You can clean the jobs with the following states: completed, waiting, active, delayed, and failed. - */ - clean(gracePeriod: number, jobsState?: string): Promise; - - /** - * Listens to queue events - * 'ready', 'error', 'activ', 'progress', 'completed', 'failed', 'paused', 'resumed', 'cleaned' - */ - on(eventName: string, callback: EventCallback): void; - } - - interface EventCallback { - (...args: any[]): void - } - - interface ReadyEventCallback extends EventCallback { - (): void; - } - - interface ErrorEventCallback extends EventCallback { - (error: Error): void; - } - - interface JobPromise { - /** - * Abort this job - */ - cancel(): void - } - - interface ActiveEventCallback extends EventCallback { - (job: Job, jobPromise: JobPromise): void; - } - - interface ProgressEventCallback extends EventCallback { - (job: Job, progress: any): void; - } - - interface CompletedEventCallback extends EventCallback { - (job: Job, result: Object): void; - } - - interface FailedEventCallback extends EventCallback { - (job: Job, error: Error): void; - } - - interface PausedEventCallback extends EventCallback { - (): void; - } - - interface ResumedEventCallback extends EventCallback { - (job?: Job): void; - } - - /** - * @see clean() for details - */ - interface CleanedEventCallback extends EventCallback { - (jobs: Job[], type: string): void; - } - } - - export = Bull; -} - -declare module "bull/lib/priority-queue" { - - import * as Bull from "bull"; - import * as Redis from "redis"; - - /** - * This is the Queue constructor of priority queue. - * - * It works same a normal queue, with same function and parameters. - * The only difference is that the Queue#add() allow an options opts.priority - * that could take ["low", "normal", "medium", "hight", "critical"]. If no options provider, "normal" will be taken. - * - * The priority queue will process more often highter priority jobs than lower. - */ - function PQueue(queueName: string, redisPort: number, redisHost: string, redisOpt?: Redis.ClientOpts): PQueue.PriorityQueue; - - namespace PQueue { - - export interface AddOptions extends Bull.AddOptions { - - /** - * "low", "normal", "medium", "high", "critical" - */ - priority?: string; - } - - - export interface PriorityQueue extends Bull.Queue { - - /** - * Creates a new job and adds it to the queue. - * If the queue is empty the job will be executed directly, - * otherwise it will be placed in the queue and executed as soon as possible. - */ - add(data: Object, opts?: PQueue.AddOptions): Promise; - - } - } - - export = PQueue; -} diff --git a/bull/index.d.ts b/bull/index.d.ts new file mode 100644 index 0000000000..fc7e8ac015 --- /dev/null +++ b/bull/index.d.ts @@ -0,0 +1,308 @@ +// Type definitions for bull 0.7.0 +// Project: https://github.com/OptimalBits/bull +// Definitions by: Bruno Grieder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "bull" { + + import * as Redis from "redis"; + + /** + * This is the Queue constructor. + * It creates a new Queue that is persisted in Redis. + * Everytime the same queue is instantiated it tries to process all the old jobs that may exist from a previous unfinished session. + */ + function Bull(queueName: string, redisPort: number, redisHost: string, redisOpt?: Redis.ClientOpts): Bull.Queue; + + namespace Bull { + + export interface DoneCallback { + (error?: Error, value?: any): void + } + + export interface Job { + + id: string + + /** + * The custom data passed when the job was created + */ + data: Object; + + /** + * Report progress on a job + */ + progress(value: any): Promise; + + /** + * Removes a Job from the queue from all the lists where it may be included. + * @returns {Promise} A promise that resolves when the job is removed. + */ + remove(): Promise; + + /** + * Rerun a Job that has failed. + * @returns {Promise} A promise that resolves when the job is scheduled for retry. + */ + retry(): Promise; + } + + export interface Backoff { + + /** + * Backoff type, which can be either `fixed` or `exponential` + */ + type: string + + /** + * Backoff delay, in milliseconds + */ + delay: number; + } + + export interface AddOptions { + /** + * An amount of miliseconds to wait until this job can be processed. + * Note that for accurate delays, both server and clients should have their clocks synchronized + */ + delay?: number; + + /** + * A number of attempts to retry if the job fails [optional] + */ + attempts?: number; + + /** + * Backoff setting for automatic retries if the job fails + */ + backoff?: number | Backoff + + /** + * A boolean which, if true, adds the job to the right + * of the queue instead of the left (default false) + */ + lifo?: boolean; + + /** + * The number of milliseconds after which the job should be fail with a timeout error + */ + timeout?: number; + } + + export interface Queue { + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + * + * concurrency: Bull will then call you handler in parallel respecting this max number. + */ + process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + */ + process(callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + * + * concurrency: Bull will then call you handler in parallel respecting this max number. + */ + process(concurrency: number, callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + */ + process(callback: (job: Job) => void): Promise; + + // process(callback: (job: Job, done?: DoneCallback) => void): Promise; + + /** + * Creates a new job and adds it to the queue. + * If the queue is empty the job will be executed directly, + * otherwise it will be placed in the queue and executed as soon as possible. + */ + add(data: Object, opts?: AddOptions): Promise; + + /** + * Returns a promise that resolves when the queue is paused. + * The pause is global, meaning that all workers in all queue instances for a given queue will be paused. + * A paused queue will not process new jobs until resumed, + * but current jobs being processed will continue until they are finalized. + * + * Pausing a queue that is already paused does nothing. + */ + pause(): Promise; + + /** + * Returns a promise that resolves when the queue is resumed after being paused. + * The resume is global, meaning that all workers in all queue instances for a given queue will be resumed. + * + * Resuming a queue that is not paused does nothing. + */ + resume(): Promise; + + /** + * Returns a promise that returns the number of jobs in the queue, waiting or paused. + * Since there may be other processes adding or processing jobs, this value may be true only for a very small amount of time. + */ + count(): Promise; + + /** + * Empties a queue deleting all the input lists and associated jobs. + */ + empty(): Promise; + + /** + * Closes the underlying redis client. Use this to perform a graceful shutdown. + * + * `close` can be called from anywhere, with one caveat: + * if called from within a job handler the queue won't close until after the job has been processed + */ + close(): Promise; + + /** + * Returns a promise that will return the job instance associated with the jobId parameter. + * If the specified job cannot be located, the promise callback parameter will be set to null. + */ + getJob(jobId: string): Promise; + + /** + * Tells the queue remove all jobs created outside of a grace period in milliseconds. + * You can clean the jobs with the following states: completed, waiting, active, delayed, and failed. + */ + clean(gracePeriod: number, jobsState?: string): Promise; + + /** + * Listens to queue events + * 'ready', 'error', 'activ', 'progress', 'completed', 'failed', 'paused', 'resumed', 'cleaned' + */ + on(eventName: string, callback: EventCallback): void; + } + + interface EventCallback { + (...args: any[]): void + } + + interface ReadyEventCallback extends EventCallback { + (): void; + } + + interface ErrorEventCallback extends EventCallback { + (error: Error): void; + } + + interface JobPromise { + /** + * Abort this job + */ + cancel(): void + } + + interface ActiveEventCallback extends EventCallback { + (job: Job, jobPromise: JobPromise): void; + } + + interface ProgressEventCallback extends EventCallback { + (job: Job, progress: any): void; + } + + interface CompletedEventCallback extends EventCallback { + (job: Job, result: Object): void; + } + + interface FailedEventCallback extends EventCallback { + (job: Job, error: Error): void; + } + + interface PausedEventCallback extends EventCallback { + (): void; + } + + interface ResumedEventCallback extends EventCallback { + (job?: Job): void; + } + + /** + * @see clean() for details + */ + interface CleanedEventCallback extends EventCallback { + (jobs: Job[], type: string): void; + } + } + + export = Bull; +} + +declare module "bull/lib/priority-queue" { + + import * as Bull from "bull"; + import * as Redis from "redis"; + + /** + * This is the Queue constructor of priority queue. + * + * It works same a normal queue, with same function and parameters. + * The only difference is that the Queue#add() allow an options opts.priority + * that could take ["low", "normal", "medium", "hight", "critical"]. If no options provider, "normal" will be taken. + * + * The priority queue will process more often highter priority jobs than lower. + */ + function PQueue(queueName: string, redisPort: number, redisHost: string, redisOpt?: Redis.ClientOpts): PQueue.PriorityQueue; + + namespace PQueue { + + export interface AddOptions extends Bull.AddOptions { + + /** + * "low", "normal", "medium", "high", "critical" + */ + priority?: string; + } + + + export interface PriorityQueue extends Bull.Queue { + + /** + * Creates a new job and adds it to the queue. + * If the queue is empty the job will be executed directly, + * otherwise it will be placed in the queue and executed as soon as possible. + */ + add(data: Object, opts?: PQueue.AddOptions): Promise; + + } + } + + export = PQueue; +} diff --git a/bull/tsconfig.json b/bull/tsconfig.json new file mode 100644 index 0000000000..eb40d231fa --- /dev/null +++ b/bull/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bull-tests.tsx" + ] +} \ No newline at end of file diff --git a/bunyan-logentries/bunyan-logentries-tests.ts b/bunyan-logentries/bunyan-logentries-tests.ts index d0e4874898..a644d028e4 100644 --- a/bunyan-logentries/bunyan-logentries-tests.ts +++ b/bunyan-logentries/bunyan-logentries-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import bunyan = require("bunyan"); import bunyanLogentries = require("bunyan-logentries"); diff --git a/bunyan-logentries/bunyan-logentries.d.ts b/bunyan-logentries/bunyan-logentries.d.ts deleted file mode 100644 index bc91174dc1..0000000000 --- a/bunyan-logentries/bunyan-logentries.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Type definitions for node-bunyan-logentries v0.1.0 -// Project: https://github.com/nemtsov/node-bunyan-logentries -// Definitions by: Aymeric Beaumet -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare module "bunyan-logentries" { - import bunyan = require("bunyan"); - - interface StreamOptions { - token: string; - } - - export function createStream(options: StreamOptions): NodeJS.WritableStream; -} diff --git a/bunyan-logentries/index.d.ts b/bunyan-logentries/index.d.ts new file mode 100644 index 0000000000..9a2a5c3fb9 --- /dev/null +++ b/bunyan-logentries/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for node-bunyan-logentries v0.1.0 +// Project: https://github.com/nemtsov/node-bunyan-logentries +// Definitions by: Aymeric Beaumet +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import bunyan = require("bunyan"); + +interface StreamOptions { + token: string; +} + +export declare function createStream(options: StreamOptions): NodeJS.WritableStream; diff --git a/bunyan-logentries/tsconfig.json b/bunyan-logentries/tsconfig.json new file mode 100644 index 0000000000..b62ab6686d --- /dev/null +++ b/bunyan-logentries/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bunyan-logentries-tests.ts" + ] +} \ No newline at end of file diff --git a/bunyan-prettystream/bunyan-prettystream-tests.ts b/bunyan-prettystream/bunyan-prettystream-tests.ts index 3dd7b15a31..49a3d405dc 100644 --- a/bunyan-prettystream/bunyan-prettystream-tests.ts +++ b/bunyan-prettystream/bunyan-prettystream-tests.ts @@ -1,4 +1,3 @@ -/// import PrettyStream = require("bunyan-prettystream"); var stream = new PrettyStream(); diff --git a/bunyan-prettystream/bunyan-prettystream.d.ts b/bunyan-prettystream/bunyan-prettystream.d.ts deleted file mode 100644 index 297e63731c..0000000000 --- a/bunyan-prettystream/bunyan-prettystream.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Type definitions for bunyan-prettystream 0.1.3 -// Project: https://www.npmjs.com/package/bunyan-prettystream -// Definitions by: Jason Swearingen , Vadim Macagon -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "bunyan-prettystream" { - import stream = require("stream"); - class PrettyStream extends stream.Writable { - /** - * @param options.mode Output format, can be either `long`, `short`, or `dev`, - * defaults to `long`. - * @param options.useColor Indicates whether or not output should be colored, - * defaults to `true`. - */ - constructor(options?: { mode?: string; useColor?: boolean }); - - /** - * Pipes data from this stream to another. - * - * @param destination Stream to write data to. - * @param options.end Indicates whether `end()` should be called on the `destination` - * stream when this stream emits `end`, defaults to `true`. - * @return The `destination` stream. - */ - pipe(destination: T, options?: { end?: boolean; }): T; - } - export = PrettyStream; -} \ No newline at end of file diff --git a/bunyan-prettystream/index.d.ts b/bunyan-prettystream/index.d.ts new file mode 100644 index 0000000000..04c328b058 --- /dev/null +++ b/bunyan-prettystream/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for bunyan-prettystream 0.1.3 +// Project: https://www.npmjs.com/package/bunyan-prettystream +// Definitions by: Jason Swearingen , Vadim Macagon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import stream = require("stream"); +declare class PrettyStream extends stream.Writable { + /** + * @param options.mode Output format, can be either `long`, `short`, or `dev`, + * defaults to `long`. + * @param options.useColor Indicates whether or not output should be colored, + * defaults to `true`. + */ + constructor(options?: { mode?: string; useColor?: boolean }); + + /** + * Pipes data from this stream to another. + * + * @param destination Stream to write data to. + * @param options.end Indicates whether `end()` should be called on the `destination` + * stream when this stream emits `end`, defaults to `true`. + * @return The `destination` stream. + */ + pipe(destination: T, options?: { end?: boolean; }): T; +} +export = PrettyStream; diff --git a/bunyan-prettystream/tsconfig.json b/bunyan-prettystream/tsconfig.json new file mode 100644 index 0000000000..1f519f5495 --- /dev/null +++ b/bunyan-prettystream/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bunyan-prettystream-tests.ts" + ] +} \ No newline at end of file diff --git a/bunyan/bunyan-tests.ts b/bunyan/bunyan-tests.ts index 2575f043d8..86a24f6bef 100644 --- a/bunyan/bunyan-tests.ts +++ b/bunyan/bunyan-tests.ts @@ -1,4 +1,3 @@ -/// import * as bunyan from 'bunyan'; diff --git a/bunyan/bunyan.d.ts b/bunyan/bunyan.d.ts deleted file mode 100644 index 4ea2668a2b..0000000000 --- a/bunyan/bunyan.d.ts +++ /dev/null @@ -1,102 +0,0 @@ -// Type definitions for node-bunyan -// Project: https://github.com/trentm/node-bunyan -// Definitions by: Alex Mikhalev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "bunyan" { - import { EventEmitter } from 'events'; - - class Logger extends EventEmitter { - constructor(options:LoggerOptions); - addStream(stream:Stream):void; - addSerializers(serializers:Serializers):void; - child(options:LoggerOptions, simple?:boolean):Logger; - child(obj:Object, simple?:boolean):Logger; - reopenFileStreams():void; - - level():string|number; - level(value: number | string):void; - levels(name: number | string, value: number | string):void; - - trace(error:Error, format?:any, ...params:any[]):void; - trace(buffer:Buffer, format?:any, ...params:any[]):void; - trace(obj:Object, format?:any, ...params:any[]):void; - trace(format:string, ...params:any[]):void; - debug(error:Error, format?:any, ...params:any[]):void; - debug(buffer:Buffer, format?:any, ...params:any[]):void; - debug(obj:Object, format?:any, ...params:any[]):void; - debug(format:string, ...params:any[]):void; - info(error:Error, format?:any, ...params:any[]):void; - info(buffer:Buffer, format?:any, ...params:any[]):void; - info(obj:Object, format?:any, ...params:any[]):void; - info(format:string, ...params:any[]):void; - warn(error:Error, format?:any, ...params:any[]):void; - warn(buffer:Buffer, format?:any, ...params:any[]):void; - warn(obj:Object, format?:any, ...params:any[]):void; - warn(format:string, ...params:any[]):void; - error(error:Error, format?:any, ...params:any[]):void; - error(buffer:Buffer, format?:any, ...params:any[]):void; - error(obj:Object, format?:any, ...params:any[]):void; - error(format:string, ...params:any[]):void; - fatal(error:Error, format?:any, ...params:any[]):void; - fatal(buffer:Buffer, format?:any, ...params:any[]):void; - fatal(obj:Object, format?:any, ...params:any[]):void; - fatal(format:string, ...params:any[]):void; - } - - interface LoggerOptions { - name: string; - streams?: Stream[]; - level?: string | number; - stream?: NodeJS.WritableStream; - serializers?: Serializers; - src?: boolean; - } - - interface Serializers { - [key:string]: (input:any) => string; - } - - interface Stream { - type?: string; - level?: number | string; - path?: string; - stream?: NodeJS.WritableStream | Stream; - closeOnExit?: boolean; - period?: string; - count?: number; - } - - export var stdSerializers:Serializers; - - export var TRACE:number; - export var DEBUG:number; - export var INFO:number; - export var WARN:number; - export var ERROR:number; - export var FATAL:number; - - export function resolveLevel(value: number | string):number; - - export function createLogger(options:LoggerOptions):Logger; - - class RingBuffer extends EventEmitter { - constructor(options:RingBufferOptions); - - writable:boolean; - records:any[]; - - write(record:any):void; - end(record?:any):void; - destroy():void; - destroySoon():void; - } - - interface RingBufferOptions { - limit?: number; - } - - export function safeCycles():(key:string, value:any) => any; -} diff --git a/bunyan/index.d.ts b/bunyan/index.d.ts new file mode 100644 index 0000000000..ade8577847 --- /dev/null +++ b/bunyan/index.d.ts @@ -0,0 +1,104 @@ +// Type definitions for node-bunyan +// Project: https://github.com/trentm/node-bunyan +// Definitions by: Alex Mikhalev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import { EventEmitter } from 'events'; + +declare class Logger extends EventEmitter { + constructor(options: LoggerOptions); + addStream(stream: Stream): void; + addSerializers(serializers: Serializers): void; + child(options: LoggerOptions, simple?: boolean): Logger; + child(obj: Object, simple?: boolean): Logger; + reopenFileStreams(): void; + + level(): string | number; + level(value: number | string): void; + levels(name: number | string, value: number | string): void; + + fields: any; + src: boolean; + + trace(error: Error, format?: any, ...params: any[]): void; + trace(buffer: Buffer, format?: any, ...params: any[]): void; + trace(obj: Object, format?: any, ...params: any[]): void; + trace(format: string, ...params: any[]): void; + debug(error: Error, format?: any, ...params: any[]): void; + debug(buffer: Buffer, format?: any, ...params: any[]): void; + debug(obj: Object, format?: any, ...params: any[]): void; + debug(format: string, ...params: any[]): void; + info(error: Error, format?: any, ...params: any[]): void; + info(buffer: Buffer, format?: any, ...params: any[]): void; + info(obj: Object, format?: any, ...params: any[]): void; + info(format: string, ...params: any[]): void; + warn(error: Error, format?: any, ...params: any[]): void; + warn(buffer: Buffer, format?: any, ...params: any[]): void; + warn(obj: Object, format?: any, ...params: any[]): void; + warn(format: string, ...params: any[]): void; + error(error: Error, format?: any, ...params: any[]): void; + error(buffer: Buffer, format?: any, ...params: any[]): void; + error(obj: Object, format?: any, ...params: any[]): void; + error(format: string, ...params: any[]): void; + fatal(error: Error, format?: any, ...params: any[]): void; + fatal(buffer: Buffer, format?: any, ...params: any[]): void; + fatal(obj: Object, format?: any, ...params: any[]): void; + fatal(format: string, ...params: any[]): void; +} + +interface LoggerOptions { + name: string; + streams?: Stream[]; + level?: string | number; + stream?: NodeJS.WritableStream; + serializers?: Serializers; + src?: boolean; +} + +interface Serializers { + [key: string]: (input: any) => string; +} + +interface Stream { + type?: string; + level?: number | string; + path?: string; + stream?: NodeJS.WritableStream | Stream; + closeOnExit?: boolean; + period?: string; + count?: number; +} + +export declare var stdSerializers: Serializers; + +export declare var TRACE: number; +export declare var DEBUG: number; +export declare var INFO: number; +export declare var WARN: number; +export declare var ERROR: number; +export declare var FATAL: number; + +export declare function resolveLevel(value: number | string): number; + +export declare function createLogger(options: LoggerOptions): Logger; + +declare class RingBuffer extends EventEmitter { + constructor(options: RingBufferOptions); + + writable: boolean; + records: any[]; + + write(record: any): void; + end(record?: any): void; + destroy(): void; + destroySoon(): void; +} + +interface RingBufferOptions { + limit?: number; +} + +export declare function safeCycles(): (key: string, value: any) => any; diff --git a/bunyan/tsconfig.json b/bunyan/tsconfig.json new file mode 100644 index 0000000000..2beee66906 --- /dev/null +++ b/bunyan/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bunyan-tests.ts" + ] +} \ No newline at end of file diff --git a/business-rules-engine/BasicValidators.d.ts b/business-rules-engine/BasicValidators.d.ts deleted file mode 100644 index aa176d94a2..0000000000 --- a/business-rules-engine/BasicValidators.d.ts +++ /dev/null @@ -1,112 +0,0 @@ -// Type definitions for business-rules-engine - v1.0.20 -// Project: https://github.com/rsamec/form -// Definitions by: Roman Samec -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// -/// -/// -/// -declare namespace Validators { - class LettersOnlyValidator implements Validation.IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class ZipCodeValidator implements Validation.IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class EmailValidator implements Validation.IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class UrlValidator implements Validation.IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class RequiredValidator implements Validation.IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class DateValidator implements Validation.IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class DateISOValidator implements Validation.IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class NumberValidator implements Validation.IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class DigitValidator implements Validation.IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class SignedDigitValidator implements Validation.IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class MinLengthValidator implements Validation.IStringValidator { - public MinLength: number; - constructor(MinLength?: number); - public isAcceptable(s: string): boolean; - public tagName: string; - } - class MaxLengthValidator implements Validation.IStringValidator { - public MaxLength: number; - constructor(MaxLength?: number); - public isAcceptable(s: string): boolean; - public tagName: string; - } - class RangeLengthValidator implements Validation.IStringValidator { - public RangeLength: number[]; - constructor(RangeLength?: number[]); - public isAcceptable(s: string): boolean; - public MinLength : number; - public MaxLength : number; - public tagName: string; - } - class MinValidator implements Validation.IPropertyValidator { - public Min: number; - constructor(Min?: number); - public isAcceptable(s: any): boolean; - public tagName: string; - } - class MaxValidator implements Validation.IPropertyValidator { - public Max: number; - constructor(Max?: number); - public isAcceptable(s: any): boolean; - public tagName: string; - } - class RangeValidator implements Validation.IPropertyValidator { - public Range: number[]; - constructor(Range?: number[]); - public isAcceptable(s: any): boolean; - public Min : number; - public Max : number; - public tagName: string; - } - class StepValidator implements Validation.IPropertyValidator { - public Step: string; - constructor(Step?: string); - public isAcceptable(s: any): boolean; - public tagName: string; - } - class PatternValidator implements Validation.IStringValidator { - public Pattern: string; - constructor(Pattern?: string); - public isAcceptable(s: string): boolean; - public tagName: string; - } - class ContainsValidator implements Validation.IAsyncPropertyValidator { - public Options: Q.Promise; - constructor(Options: Q.Promise); - public isAcceptable(s: string): Q.Promise; - public isAsync: boolean; - public tagName: string; - } -} -declare module "node-validators" {export = Validators;} diff --git a/business-rules-engine/Utils.d.ts b/business-rules-engine/Utils.d.ts index e9ca88a547..0efa349a73 100644 --- a/business-rules-engine/Utils.d.ts +++ b/business-rules-engine/Utils.d.ts @@ -3,7 +3,7 @@ // Definitions by: Roman Samec // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Utils { class StringFce { static format(s: string, args: any): string; diff --git a/business-rules-engine/Validation.d.ts b/business-rules-engine/Validation.d.ts index bcfd0d6d9a..91efba146a 100644 --- a/business-rules-engine/Validation.d.ts +++ b/business-rules-engine/Validation.d.ts @@ -3,8 +3,8 @@ // Definitions by: Roman Samec // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// + declare namespace Validation { interface IErrorCustomMessage { (config: any, args: any): string; diff --git a/business-rules-engine/business-rules-engine-tests.ts b/business-rules-engine/business-rules-engine-tests.ts index 5695c3b7fb..2a8180ce6b 100644 --- a/business-rules-engine/business-rules-engine-tests.ts +++ b/business-rules-engine/business-rules-engine-tests.ts @@ -1,8 +1,6 @@ -/// -/// -/// -/// -/// +/// +import * as Validators from './node-validators'; +import Validation = require("business-rules-engine"); export interface IPerson{ Checked:boolean; diff --git a/business-rules-engine/business-rules-engine.d.ts b/business-rules-engine/business-rules-engine.d.ts deleted file mode 100644 index a26e49492d..0000000000 --- a/business-rules-engine/business-rules-engine.d.ts +++ /dev/null @@ -1,242 +0,0 @@ -// Type definitions for business-rules-engine v1.0.20 -// Project: https://github.com/rsamec/form -// Definitions by: Roman Samec -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// Source: typings/business-rules-engine/Validation.d.ts -/// -/// -declare namespace Validation { - interface IErrorCustomMessage { - (config: any, args: any): string; - } - interface IPropertyValidator { - isAcceptable(s: any): boolean; - customMessage?: IErrorCustomMessage; - tagName?: string; - } - interface IStringValidator extends IPropertyValidator { - isAcceptable(s: string): boolean; - } - interface IAsyncPropertyValidator { - isAcceptable(s: any): Q.Promise; - customMessage?: IErrorCustomMessage; - isAsync: boolean; - tagName?: string; - } - interface IAsyncStringPropertyValidator extends IAsyncPropertyValidator { - isAcceptable(s: string): Q.Promise; - } - enum CompareOperator { - LessThan = 0, - LessThanEqual = 1, - Equal = 2, - NotEqual = 3, - GreaterThanEqual = 4, - GreaterThan = 5, - } - interface IError { - HasError: boolean; - ErrorMessage: string; - TranslateArgs?: IErrorTranslateArgs; - } - interface IErrorTranslateArgs { - TranslateId: string; - MessageArgs: any; - CustomMessage?: IErrorCustomMessage; - } - interface IOptional { - (): boolean; - } - interface IValidationFailure extends IError { - IsAsync: boolean; - Error: IError; - } - interface IValidationResult { - Name: string; - Add(validationResult: IValidationResult): void; - Remove(index: number): void; - Children: IValidationResult[]; - HasErrors: boolean; - HasErrorsDirty: boolean; - ErrorMessage: string; - ErrorCount: number; - Optional?: IOptional; - TranslateArgs?: IErrorTranslateArgs[]; - } - interface IValidate { - (args: IError): void; - } - interface IAsyncValidate { - (args: IError): Q.Promise; - } - interface IValidatorFce { - Name: string; - ValidationFce?: IValidate; - AsyncValidationFce?: IAsyncValidate; - } - interface IValidator { - Validate(context: any): IValidationFailure; - ValidateAsync(context: any): Q.Promise; - Error: IError; - } - interface IAbstractValidator { - RuleFor(prop: string, validator: IPropertyValidator): any; - ValidationFor(prop: string, validatorFce: IValidatorFce): any; - Validation(validatorFce: IValidatorFce): any; - ValidatorFor(prop: string, validator: IAbstractValidator): any; - CreateRule(name: string): IAbstractValidationRule; - CreateAbstractRule(name: string): IAbstractValidationRule; - CreateAbstractListRule(name: string): IAbstractValidationRule; - ForList: boolean; - } - interface IAbstractValidationRule { - Validate(context: T): IValidationResult; - ValidateAsync(context: T): Q.Promise; - ValidateAll(context: T): Q.Promise; - ValidateProperty(context: T, propName: string): void; - ValidationResult: IValidationResult; - Rules: { - [name: string]: IPropertyValidationRule; - }; - Validators: { - [name: string]: IValidator; - }; - Children: { - [name: string]: IAbstractValidationRule; - }; - } - interface IPropertyValidationRule { - Validators: { - [name: string]: any; - }; - Validate(context: IValidationContext): IValidationFailure[]; - ValidateAsync(context: IValidationContext): Q.Promise; - } - interface IValidationContext { - Value: string; - Key: string; - Data: T; - } - class Error implements IError { - public HasError: boolean; - public ErrorMessage: string; - constructor(); - } - class ValidationFailure implements IError { - public Error: IError; - public IsAsync: boolean; - constructor(Error: IError, IsAsync: boolean); - public HasError : boolean; - public ErrorMessage : string; - public TranslateArgs : IErrorTranslateArgs; - } - class ValidationResult implements IValidationResult { - public Name: string; - constructor(Name: string); - public IsDirty: boolean; - public Children : IValidationResult[]; - public Add(error: IValidationResult): void; - public Remove(index: number): void; - public Optional: IOptional; - public TranslateArgs: IErrorTranslateArgs[]; - public HasErrorsDirty : boolean; - public HasErrors : boolean; - public ErrorCount : number; - public ErrorMessage : string; - } - class CompositeValidationResult implements IValidationResult { - public Name: string; - public Children: IValidationResult[]; - constructor(Name: string); - public Optional: IOptional; - public AddFirst(error: IValidationResult): void; - public Add(error: IValidationResult): void; - public Remove(index: number): void; - public HasErrorsDirty : boolean; - public HasErrors : boolean; - public ErrorCount : number; - public ErrorMessage : string; - public TranslateArgs : IErrorTranslateArgs[]; - public LogErrors(headerMessage?: string): void; - public Errors : { - [name: string]: IValidationResult; - }; - private FlattenErros; - public SetDirty(): void; - public SetPristine(): void; - private SetDirtyEx(node, dirty); - private flattenErrors(node, errorCollection); - private traverse(node, indent); - } - class AbstractValidator implements IAbstractValidator { - public Validators: { - [name: string]: IPropertyValidator[]; - }; - public AbstractValidators: { - [name: string]: IAbstractValidator; - }; - public ValidationFunctions: { - [name: string]: IValidatorFce[]; - }; - public RuleFor(prop: string, validator: IPropertyValidator): void; - public ValidationFor(prop: string, fce: IValidatorFce): void; - public Validation(fce: IValidatorFce): void; - public ValidatorFor(prop: string, validator: IAbstractValidator, forList?: boolean): void; - public CreateAbstractRule(name: string): IAbstractValidationRule; - public CreateAbstractListRule(name: string): IAbstractValidationRule; - public CreateRule(name: string): IAbstractValidationRule; - public ForList: boolean; - } - class MessageLocalization { - static customMsg: string; - static defaultMessages: { - "required": string; - "remote": string; - "email": string; - "url": string; - "date": string; - "dateISO": string; - "number": string; - "digits": string; - "signedDigits": string; - "creditcard": string; - "equalTo": string; - "maxlength": string; - "minlength": string; - "rangelength": string; - "range": string; - "max": string; - "min": string; - "step": string; - "contains": string; - "mask": string; - "custom": string; - }; - static ValidationMessages: { - "required": string; - "remote": string; - "email": string; - "url": string; - "date": string; - "dateISO": string; - "number": string; - "digits": string; - "signedDigits": string; - "creditcard": string; - "equalTo": string; - "maxlength": string; - "minlength": string; - "rangelength": string; - "range": string; - "max": string; - "min": string; - "step": string; - "contains": string; - "mask": string; - "custom": string; - }; - static GetValidationMessage(validator: any): string; - } -} -declare module "business-rule-engine" {export = Validation;} diff --git a/business-rules-engine/index.d.ts b/business-rules-engine/index.d.ts new file mode 100644 index 0000000000..197c4fd23f --- /dev/null +++ b/business-rules-engine/index.d.ts @@ -0,0 +1,243 @@ +// Type definitions for business-rules-engine v1.0.20 +// Project: https://github.com/rsamec/form +// Definitions by: Roman Samec +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Source: typings/business-rules-engine/Validation.d.ts +/// + +declare namespace Validation { + interface IErrorCustomMessage { + (config: any, args: any): string; + } + interface IPropertyValidator { + isAcceptable(s: any): boolean; + customMessage?: IErrorCustomMessage; + tagName?: string; + } + interface IStringValidator extends IPropertyValidator { + isAcceptable(s: string): boolean; + } + interface IAsyncPropertyValidator { + isAcceptable(s: any): Q.Promise; + customMessage?: IErrorCustomMessage; + isAsync: boolean; + tagName?: string; + } + interface IAsyncStringPropertyValidator extends IAsyncPropertyValidator { + isAcceptable(s: string): Q.Promise; + } + enum CompareOperator { + LessThan = 0, + LessThanEqual = 1, + Equal = 2, + NotEqual = 3, + GreaterThanEqual = 4, + GreaterThan = 5, + } + interface IError { + HasError: boolean; + ErrorMessage: string; + TranslateArgs?: IErrorTranslateArgs; + } + interface IErrorTranslateArgs { + TranslateId: string; + MessageArgs: any; + CustomMessage?: IErrorCustomMessage; + } + interface IOptional { + (): boolean; + } + interface IValidationFailure extends IError { + IsAsync: boolean; + Error: IError; + } + interface IValidationResult { + Name: string; + Add(validationResult: IValidationResult): void; + Remove(index: number): void; + Children: IValidationResult[]; + HasErrors: boolean; + HasErrorsDirty: boolean; + ErrorMessage: string; + ErrorCount: number; + Optional?: IOptional; + TranslateArgs?: IErrorTranslateArgs[]; + } + interface IValidate { + (args: IError): void; + } + interface IAsyncValidate { + (args: IError): Q.Promise; + } + interface IValidatorFce { + Name: string; + ValidationFce?: IValidate; + AsyncValidationFce?: IAsyncValidate; + } + interface IValidator { + Validate(context: any): IValidationFailure; + ValidateAsync(context: any): Q.Promise; + Error: IError; + } + interface IAbstractValidator { + RuleFor(prop: string, validator: IPropertyValidator): any; + ValidationFor(prop: string, validatorFce: IValidatorFce): any; + Validation(validatorFce: IValidatorFce): any; + ValidatorFor(prop: string, validator: IAbstractValidator): any; + CreateRule(name: string): IAbstractValidationRule; + CreateAbstractRule(name: string): IAbstractValidationRule; + CreateAbstractListRule(name: string): IAbstractValidationRule; + ForList: boolean; + } + interface IAbstractValidationRule { + Validate(context: T): IValidationResult; + ValidateAsync(context: T): Q.Promise; + ValidateAll(context: T): Q.Promise; + ValidateProperty(context: T, propName: string): void; + ValidationResult: IValidationResult; + Rules: { + [name: string]: IPropertyValidationRule; + }; + Validators: { + [name: string]: IValidator; + }; + Children: { + [name: string]: IAbstractValidationRule; + }; + } + interface IPropertyValidationRule { + Validators: { + [name: string]: any; + }; + Validate(context: IValidationContext): IValidationFailure[]; + ValidateAsync(context: IValidationContext): Q.Promise; + } + interface IValidationContext { + Value: string; + Key: string; + Data: T; + } + class Error implements IError { + public HasError: boolean; + public ErrorMessage: string; + constructor(); + } + class ValidationFailure implements IError { + public Error: IError; + public IsAsync: boolean; + constructor(Error: IError, IsAsync: boolean); + public HasError : boolean; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs; + } + class ValidationResult implements IValidationResult { + public Name: string; + constructor(Name: string); + public IsDirty: boolean; + public Children : IValidationResult[]; + public Add(error: IValidationResult): void; + public Remove(index: number): void; + public Optional: IOptional; + public TranslateArgs: IErrorTranslateArgs[]; + public HasErrorsDirty : boolean; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + } + class CompositeValidationResult implements IValidationResult { + public Name: string; + public Children: IValidationResult[]; + constructor(Name: string); + public Optional: IOptional; + public AddFirst(error: IValidationResult): void; + public Add(error: IValidationResult): void; + public Remove(index: number): void; + public HasErrorsDirty : boolean; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs[]; + public LogErrors(headerMessage?: string): void; + public Errors : { + [name: string]: IValidationResult; + }; + private FlattenErros; + public SetDirty(): void; + public SetPristine(): void; + private SetDirtyEx(node, dirty); + private flattenErrors(node, errorCollection); + private traverse(node, indent); + } + class AbstractValidator implements IAbstractValidator { + public Validators: { + [name: string]: IPropertyValidator[]; + }; + public AbstractValidators: { + [name: string]: IAbstractValidator; + }; + public ValidationFunctions: { + [name: string]: IValidatorFce[]; + }; + public RuleFor(prop: string, validator: IPropertyValidator): void; + public ValidationFor(prop: string, fce: IValidatorFce): void; + public Validation(fce: IValidatorFce): void; + public ValidatorFor(prop: string, validator: IAbstractValidator, forList?: boolean): void; + public CreateAbstractRule(name: string): IAbstractValidationRule; + public CreateAbstractListRule(name: string): IAbstractValidationRule; + public CreateRule(name: string): IAbstractValidationRule; + public ForList: boolean; + } + class MessageLocalization { + static customMsg: string; + static defaultMessages: { + "required": string; + "remote": string; + "email": string; + "url": string; + "date": string; + "dateISO": string; + "number": string; + "digits": string; + "signedDigits": string; + "creditcard": string; + "equalTo": string; + "maxlength": string; + "minlength": string; + "rangelength": string; + "range": string; + "max": string; + "min": string; + "step": string; + "contains": string; + "mask": string; + "custom": string; + }; + static ValidationMessages: { + "required": string; + "remote": string; + "email": string; + "url": string; + "date": string; + "dateISO": string; + "number": string; + "digits": string; + "signedDigits": string; + "creditcard": string; + "equalTo": string; + "maxlength": string; + "minlength": string; + "rangelength": string; + "range": string; + "max": string; + "min": string; + "step": string; + "contains": string; + "mask": string; + "custom": string; + }; + static GetValidationMessage(validator: any): string; + } +} +export = Validation; +export as namespace Validation; diff --git a/business-rules-engine/node-validators.d.ts b/business-rules-engine/node-validators.d.ts new file mode 100644 index 0000000000..715acbb243 --- /dev/null +++ b/business-rules-engine/node-validators.d.ts @@ -0,0 +1,112 @@ +// Type definitions for business-rules-engine - v1.0.20 +// Project: https://github.com/rsamec/form +// Definitions by: Roman Samec +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +import Validation = require("business-rules-engine"); +export as namespace Validators; + +import * as moment from 'moment'; + +export class LettersOnlyValidator implements Validation.IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class ZipCodeValidator implements Validation.IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class EmailValidator implements Validation.IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class UrlValidator implements Validation.IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class RequiredValidator implements Validation.IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class DateValidator implements Validation.IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class DateISOValidator implements Validation.IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class NumberValidator implements Validation.IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class DigitValidator implements Validation.IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class SignedDigitValidator implements Validation.IStringValidator { + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class MinLengthValidator implements Validation.IStringValidator { + public MinLength: number; + constructor(MinLength?: number); + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class MaxLengthValidator implements Validation.IStringValidator { + public MaxLength: number; + constructor(MaxLength?: number); + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class RangeLengthValidator implements Validation.IStringValidator { + public RangeLength: number[]; + constructor(RangeLength?: number[]); + public isAcceptable(s: string): boolean; + public MinLength : number; + public MaxLength : number; + public tagName: string; +} +export class MinValidator implements Validation.IPropertyValidator { + public Min: number; + constructor(Min?: number); + public isAcceptable(s: any): boolean; + public tagName: string; +} +export class MaxValidator implements Validation.IPropertyValidator { + public Max: number; + constructor(Max?: number); + public isAcceptable(s: any): boolean; + public tagName: string; +} +export class RangeValidator implements Validation.IPropertyValidator { + public Range: number[]; + constructor(Range?: number[]); + public isAcceptable(s: any): boolean; + public Min : number; + public Max : number; + public tagName: string; +} +export class StepValidator implements Validation.IPropertyValidator { + public Step: string; + constructor(Step?: string); + public isAcceptable(s: any): boolean; + public tagName: string; +} +export class PatternValidator implements Validation.IStringValidator { + public Pattern: string; + constructor(Pattern?: string); + public isAcceptable(s: string): boolean; + public tagName: string; +} +export class ContainsValidator implements Validation.IAsyncPropertyValidator { + public Options: Q.Promise; + constructor(Options: Q.Promise); + public isAcceptable(s: string): Q.Promise; + public isAsync: boolean; + public tagName: string; +} diff --git a/business-rules-engine/tsconfig.json b/business-rules-engine/tsconfig.json new file mode 100644 index 0000000000..8ebc501b41 --- /dev/null +++ b/business-rules-engine/tsconfig.json @@ -0,0 +1,17 @@ +{ + "files": [ + "index.d.ts", + "business-rules-engine-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/byline/byline-tests.ts b/byline/byline-tests.ts index 42de3d5d9c..d21b8a196c 100644 --- a/byline/byline-tests.ts +++ b/byline/byline-tests.ts @@ -2,7 +2,6 @@ * Created by stefansteinhart on 31.01.15. */ -/// import fs = require( 'fs' ); import byline = require( 'byline' ); diff --git a/byline/byline.d.ts b/byline/byline.d.ts deleted file mode 100644 index 48ddd2d57a..0000000000 --- a/byline/byline.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Type definitions for byline 4.2.1 -// Project: https://github.com/jahewson/node-byline -// Definitions by: Stefan Steinhart -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "byline" { - import stream = require("stream"); - - export interface LineStreamOptions extends stream.TransformOptions { - keepEmptyLines?: boolean; - } - - export interface LineStream extends stream.Transform { - } - - export interface LineStreamCreatable extends LineStream { - new (options?:LineStreamOptions):LineStream - } - - //TODO is it possible to declare static factory functions without name (directly on the module) - // - // JS: - // // convinience API - // module.exports = function(readStream, options) { - // return module.exports.createStream(readStream, options); - // }; - // - // TS: - // ():LineStream; // same as createStream():LineStream - // (stream:stream.Stream, options?:LineStreamOptions):LineStream; // same as createStream(stream, options?):LineStream - - export function createStream():LineStream; - export function createStream(stream:NodeJS.ReadableStream, options?:LineStreamOptions):LineStream; - - export var LineStream:LineStreamCreatable; -} diff --git a/byline/index.d.ts b/byline/index.d.ts new file mode 100644 index 0000000000..243db166cd --- /dev/null +++ b/byline/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for byline 4.2.1 +// Project: https://github.com/jahewson/node-byline +// Definitions by: Stefan Steinhart +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import stream = require("stream"); + +export interface LineStreamOptions extends stream.TransformOptions { + keepEmptyLines?: boolean; +} + +export interface LineStream extends stream.Transform { +} + +export interface LineStreamCreatable extends LineStream { + new (options?: LineStreamOptions): LineStream +} + +//TODO is it possible to declare static factory functions without name (directly on the module) +// +// JS: +// // convinience API +// module.exports = function(readStream, options) { +// return module.exports.createStream(readStream, options); +// }; +// +// TS: +// ():LineStream; // same as createStream():LineStream +// (stream:stream.Stream, options?:LineStreamOptions):LineStream; // same as createStream(stream, options?):LineStream + +export declare function createStream(): LineStream; +export declare function createStream(stream: NodeJS.ReadableStream, options?: LineStreamOptions): LineStream; + +export declare var LineStream: LineStreamCreatable; diff --git a/byline/tsconfig.json b/byline/tsconfig.json new file mode 100644 index 0000000000..5754ae25a7 --- /dev/null +++ b/byline/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "byline-tests.ts" + ] +} \ No newline at end of file diff --git a/bytebuffer/bytebuffer-tests.ts b/bytebuffer/bytebuffer-tests.ts index 34db7368d5..eec2f3e583 100644 --- a/bytebuffer/bytebuffer-tests.ts +++ b/bytebuffer/bytebuffer-tests.ts @@ -1,4 +1,4 @@ -/// + import ByteBuffer = require("bytebuffer"); diff --git a/bytebuffer/bytebuffer.d.ts b/bytebuffer/bytebuffer.d.ts deleted file mode 100644 index e5d267787f..0000000000 --- a/bytebuffer/bytebuffer.d.ts +++ /dev/null @@ -1,616 +0,0 @@ -// Type definitions for bytebuffer.js 5.0.0 -// Project: https://github.com/dcodeIO/bytebuffer.js -// Definitions by: Denis Cappellin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Definitions by: SINTEF-9012 - -/// - -declare class ByteBuffer -{ - /** - * Constructs a new ByteBuffer. - */ - constructor( capacity?: number, littleEndian?: boolean, noAssert?: boolean ); - - /** - * Big endian constant that can be used instead of its boolean value. Evaluates to false. - */ - static BIG_ENDIAN: boolean; - - /** - * Default initial capacity of 16. - */ - static DEFAULT_CAPACITY: number; - - /** - * Default no assertions flag of false. - */ - static DEFAULT_NOASSERT: boolean; - - /** - * Little endian constant that can be used instead of its boolean value. Evaluates to true. - */ - static LITTLE_ENDIAN: boolean; - - /** - * Maximum number of bytes required to store a 32bit base 128 variable-length integer. - */ - static MAX_VARINT32_BYTES: number; - - /** - * Maximum number of bytes required to store a 64bit base 128 variable-length integer. - */ - static MAX_VARINT64_BYTES: number; - - /** - * Metrics representing number of bytes.Evaluates to 2. - */ - static METRICS_BYTES: number; - - /** - * Metrics representing number of UTF8 characters.Evaluates to 1. - */ - static METRICS_CHARS: number; - - /** - * ByteBuffer version. - */ - static VERSION: string; - - /** - * Backing buffer. - */ - buffer: ArrayBuffer; - - /** - * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation. - */ - limit: number; - - /** - * Whether to use little endian byte order, defaults to false for big endian. - */ - littleEndian: boolean; - - /** - * Marked offset. - */ - markedOffset: number; - - /** - * Whether to skip assertions of offsets and values, defaults to false. - */ - noAssert: boolean; - - /** - * Absolute read/write offset. - */ - offset: number; - - /** - * Data view to manipulate the backing buffer. Becomes null if the backing buffer has a capacity of 0. - */ - view: DataView; - - /** - * Allocates a new ByteBuffer backed by a buffer of the specified capacity. - */ - static allocate( capacity?: number, littleEndian?: number, noAssert?: boolean ): ByteBuffer; - - /** - * Decodes a base64 encoded string to binary like window.atob does. - */ - static atob( b64: string ): string; - - /** - * Encodes a binary string to base64 like window.btoa does. - */ - static btoa( str: string ): string; - - /** - * Calculates the number of UTF8 bytes of a string. - */ - static calculateUTF8Byte( str: string ): number; - - /** - * Calculates the number of UTF8 characters of a string.JavaScript itself uses UTF- 16, so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF. - */ - static calculateUTF8Char( str: string ): number; - - /** - * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer. - */ - static calculateVariant32( value: number ): number; - - /** - * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer. - */ - static calculateVariant64( value: number | Long ): number; - - /** - * Concatenates multiple ByteBuffers into one. - */ - static concat( buffers: Array, encoding?: string | boolean, litteEndian?: boolean, noAssert?: boolean ): ByteBuffer; - - /** - * Decodes a base64 encoded string to a ByteBuffer. - */ - static fromBase64( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; - - /** - * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer. - */ - static fromBinary( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; - - /** - * Decodes a hex encoded string with marked offsets to a ByteBuffer. - */ - static fromDebug( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; - - /** - * Decodes a hex encoded string to a ByteBuffer. - */ - static fromHex( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; - - /** - * Decodes an UTF8 encoded string to a ByteBuffer. - */ - static fromUTF8( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; - - /** - * Gets the backing buffer type. - */ - static isByteBuffer( bb: any ): boolean; - - /** - * Wraps a buffer or a string. Sets the allocated ByteBuffer's ByteBuffer#offset to 0 and its ByteBuffer#limit to the length of the wrapped data. - * @param buffer Anything that can be wrapped - * @param encoding String encoding if buffer is a string ("base64", "hex", "binary", defaults to "utf8") - * @param littleEndian Whether to use little or big endian byte order. Defaults to ByteBuffer.DEFAULT_ENDIAN. - * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteBuffer.DEFAULT_NOASSERT. - */ - static wrap( buffer: ByteBuffer | ArrayBuffer | Uint8Array | string, enc?: string | boolean, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; - - /** - * Decodes a zigzag encoded signed 32bit integer. - */ - static zigZagDecode32( n: number ): number; - - /** - * Decodes a zigzag encoded signed 64bit integer. - */ - static zigZagDecode64( n: number | Long ): Long; - - /** - * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding. - */ - static zigZagEncode32( n: number ): number; - - /** - * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding. - */ - static zigZagEncode64( n: number | Long ): Long; - - /** - * Switches (to) big endian byte order. - */ - BE( bigEndian?: boolean ): ByteBuffer; - - /** - * Switches (to) little endian byte order. - */ - LE( bigEndian?: boolean ): ByteBuffer; - - /** - * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended data's length. - */ - append( source: ByteBuffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer; - - /** - * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents behind the specified offset up to the length of this ByteBuffer's data. - */ - appendTo( target: ByteBuffer, offset?: number ): ByteBuffer; - - /** - * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to disable them if your code already makes sure that everything is valid. - */ - assert( assert: boolean ): ByteBuffer; - - /** - * Gets the capacity of this ByteBuffer's backing buffer. - */ - capacity(): number; - - /** - * Clears this ByteBuffer's offsets by setting ByteBuffer#offset to 0 and - * ByteBuffer#limit to the backing buffer's capacity. Discards ByteBuffer#markedOffset. - */ - clear(): ByteBuffer; - - /** - * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for ByteBuffer#offset, ByteBuffer#markedOffset and ByteBuffer#limit. - */ - clone( copy?: boolean ): ByteBuffer; - - /** - * Compacts this ByteBuffer to be backed by a ByteBuffer#buffer of its contents' length. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will set offset = 0 and limit = capacity and adapt ByteBuffer#markedOffset to the same relative position if set. - */ - compact( begin?: number, end?: number ): ByteBuffer; - - /** - * Creates a copy of this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. - */ - copy( begin?: number, end?: number ): ByteBuffer; - - /** - * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. - */ - copyTo( target: ByteBuffer, targetOffset?: number, sourceOffset?: number, sourceLimit?: number ): ByteBuffer; - - /** - * Makes sure that this ByteBuffer is backed by a ByteBuffer#buffer of at least the specified capacity. If the current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity, the required capacity will be used instead. - */ - ensureCapacity( capacity: number ): ByteBuffer; - - /** - * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. - */ - fill( value: number | string, begin?: number, end?: number ): ByteBuffer; - - /** - * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets limit = offset and offset = 0. Make sure always to flip a ByteBuffer when all relative read or write operations are complete. - */ - flip(): ByteBuffer; - - /** - * Marks an offset on this ByteBuffer to be used later. - */ - mark( offset?: number ): ByteBuffer; - - /** - * Sets the byte order. - */ - order( littleEndian: boolean ): ByteBuffer; - - /** - * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly. - */ - prepend( source: ByteBuffer | string | ArrayBuffer, encoding?: string | number, offset?: number ): ByteBuffer; - - /** - * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly. - */ - prependTo( target: ByteBuffer, offset?: number ): ByteBuffer; - - /** - * Prints debug information about this ByteBuffer's contents. - */ - printDebug( out?: ( text: string ) => void ): void; - - /** - * Reads an 8bit signed integer. This is an alias of ByteBuffer#readInt8. - */ - readByte( offset?: number ): number; - - /** - * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters itself. - */ - readCString( offset?: number ): string; - - /** - * Reads a 64bit float. This is an alias of ByteBuffer#readFloat64. - */ - readDouble( offset?: number ): number; - - /** - * Reads a 32bit float. This is an alias of ByteBuffer#readFloat32. - */ - readFloat( offset?: number ): number; - - /** - * Reads a 32bit float. - */ - readFloat32( offset?: number ): number; - - /** - * Reads a 64bit float. - */ - readFloat64( offset?: number ): number; - - /** - * Reads a length as uint32 prefixed UTF8 encoded string. - */ - readIString( offset?: number ): string; - - /** - * Reads a 32bit signed integer.This is an alias of ByteBuffer#readInt32. - */ - readInt( offset?: number ): number; - - /** - * Reads a 16bit signed integer. - */ - readInt16( offset?: number ): number; - - /** - * Reads a 32bit signed integer. - */ - readInt32( offset?: number ): number; - - /** - * Reads a 64bit signed integer. - */ - readInt64( offset?: number ): Long; - - /** - * Reads an 8bit signed integer. - */ - readInt8( offset?: number ): number; - - /** - * Reads a 64bit signed integer. This is an alias of ByteBuffer#readInt64. - */ - readLong( offset?: number ): Long; - - /** - * Reads a 16bit signed integer. This is an alias of ByteBuffer#readInt16. - */ - readShort( offset?: number ): number; - - /** - * Reads an UTF8 encoded string. This is an alias of ByteBuffer#readUTF8String. - */ - readString( length: number, metrics?: number, offset?: number ): string; - - /** - * Reads an UTF8 encoded string. - */ - readUTF8String( chars: number, offset?: number ): string; - - /** - * Reads a 16bit unsigned integer. - */ - readUint16( offset?: number ): number; - - /** - * Reads a 32bit unsigned integer. - */ - readUint32( offset?: number ): number; - - /** - * Reads a 64bit unsigned integer. - */ - readUint64( offset?: number ): Long; - /** - * Reads an 8bit unsigned integer. - */ - readUint8( offset?: number ): number; - - /** - * Reads a length as varint32 prefixed UTF8 encoded string. - */ - readVString( offset?: number ): string; - - /** - * Reads a 32bit base 128 variable-length integer. - */ - readVarint32( offset?: number ): number; - - /** - * Reads a zig-zag encoded 32bit base 128 variable-length integer. - */ - readVarint32ZiZag( offset?: number ): number; - - /** - * Reads a 64bit base 128 variable-length integer. Requires Long.js. - */ - readVarint64( offset?: number ): Long; - - /** - * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js. - */ - readVarint64ZigZag( offset?: number ): Long; - - /** - * Gets the number of remaining readable bytes. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit, so this returns limit - offset. - */ - remaining(): number; - - /** - * Resets this ByteBuffer's ByteBuffer#offset. If an offset has been marked through ByteBuffer#mark before, offset will be set to ByteBuffer#markedOffset, which will then be discarded. If no offset has been marked, sets offset = 0. - */ - reset(): ByteBuffer; - - /** - * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that large or larger. - */ - resize( capacity: number ): ByteBuffer; - - /** - * Reverses this ByteBuffer's contents - */ - reverse( begin?: number, end?: number ): ByteBuffer; - - /** - * Skips the next length bytes. This will just advance - */ - skip( length: number ): ByteBuffer; - - /** - * Slices this ByteBuffer by creating a cloned instance with offset = begin and limit = end. - */ - slice( begin?: number, end?: number ): ByteBuffer; - - /** - * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will transparently ByteBuffer#flip this ByteBuffer if offset > limit but the actual offsets remain untouched. This is an alias of ByteBuffer#toBuffer. - */ - toArrayBuffer( forceCopy?: boolean ): ArrayBuffer; - - /** - * Encodes this ByteBuffer's contents to a base64 encoded string. - */ - toBase64( begin?: number, end?: number ): string; - - /** - * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes. - */ - toBinary( begin?: number, end?: number ): string; - - /** - * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will transparently ByteBuffer#flip this ByteBuffer if offset > limit but the actual offsets remain untouched. - */ - toBuffer( forceCopy?: boolean ): ArrayBuffer; - - /** - *Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are: - * < : offset, - * ' : markedOffset, - * > : limit, - * | : offset and limit, - * [ : offset and markedOffset, - * ] : markedOffset and limit, - * ! : offset, markedOffset and limit - */ - toDebug( columns?: boolean ): string | Array - - /** - * Encodes this ByteBuffer's contents to a hex encoded string. - */ - toHex( begin?: number, end?: number ): string; - - /** - * Converts the ByteBuffer's contents to a string. - */ - toString( encoding?: string ): string; - - /** - * Encodes this ByteBuffer's contents between ByteBuffer#offset and ByteBuffer#limit to an UTF8 encoded string. - */ - toUTF8(): string; - - /** - * Writes an 8bit signed integer. This is an alias of ByteBuffer#writeInt8. - */ - writeByte( value: number, offset?: number ): ByteBuffer; - - /** - * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL characters itself. - */ - writeCString( str: string, offset?: number ): ByteBuffer; - - /** - * Writes a 64bit float. This is an alias of ByteBuffer#writeFloat64. - */ - writeDouble( value: number, offset?: number ): ByteBuffer; - - /** - * Writes a 32bit float. This is an alias of ByteBuffer#writeFloat32. - */ - writeFloat( value: number, offset?: number ): ByteBuffer; - - /** - * Writes a 32bit float. - */ - writeFloat32( value: number, offset?: number ): ByteBuffer; - - /** - * Writes a 64bit float. - */ - writeFloat64( value: number, offset?: number ): ByteBuffer; - - /** - * Writes a length as uint32 prefixed UTF8 encoded string. - */ - writeIString( str: string, offset?: number ): ByteBuffer; - - /** - * Writes a 32bit signed integer. This is an alias of ByteBuffer#writeInt32. - */ - writeInt( value: number, offset?: number ): ByteBuffer; - - /** - * Writes a 16bit signed integer. - */ - writeInt16( value: number, offset?: number ): ByteBuffer; - - /** - * Writes a 32bit signed integer. - */ - writeInt32( value: number, offset?: number ): ByteBuffer; - - /** - * Writes a 64bit signed integer. - */ - writeInt64( value: number | Long, offset?: number ): ByteBuffer; - - /** - * Writes an 8bit signed integer. - */ - writeInt8( value: number, offset?: number ): ByteBuffer; - - /** - * Writes a 16bit signed integer. This is an alias of ByteBuffer#writeInt16. - */ - writeShort( value: number, offset?: number ): ByteBuffer; - - /** - * Writes an UTF8 encoded string.This is an alias of ByteBuffer#writeUTF8String. - */ - WriteString( str: string, offset?: number ): ByteBuffer | number; - - /** - * Writes an UTF8 encoded string. - */ - writeUTF8String( str: string, offset?: number ): ByteBuffer | number; - - /** - * Writes a 16bit unsigned integer. - */ - writeUint16( value: number, offset?: number ): ByteBuffer; - - /** - * Writes a 32bit unsigned integer. - */ - writeUint32( value: number, offset?: number ): ByteBuffer; - - /** - * Writes a 64bit unsigned integer. - */ - writeUint64( value: number | Long, offset?: number ): ByteBuffer; - - /** - * Writes an 8bit unsigned integer. - */ - writeUint8( value: number, offset?: number ): ByteBuffer; - - /** - * Writes a length as varint32 prefixed UTF8 encoded string. - */ - writeVString( str: string, offset?: number ): ByteBuffer | number; - - /** - * Writes a 32bit base 128 variable-length integer. - */ - writeVarint32( value: number, offset?: number ): ByteBuffer | number; - - /** - * Writes a zig-zag encoded 32bit base 128 variable-length integer. - */ - writeVarint32ZigZag( value: number, offset?: number ): ByteBuffer | number; - - /** - * Writes a 64bit base 128 variable-length integer. - */ - writeVarint64( value: number | Long, offset?: number ): ByteBuffer; - - /** - * Writes a zig-zag encoded 64bit base 128 variable-length integer. - */ - writeVarint64ZigZag( value: number | Long, offset?: number ): ByteBuffer | number; -} - -declare module 'bytebuffer' { - namespace ByteBuffer {} - export = ByteBuffer; -} diff --git a/bytebuffer/index.d.ts b/bytebuffer/index.d.ts new file mode 100644 index 0000000000..ed5677dd05 --- /dev/null +++ b/bytebuffer/index.d.ts @@ -0,0 +1,615 @@ +// Type definitions for bytebuffer.js 5.0.0 +// Project: https://github.com/dcodeIO/bytebuffer.js +// Definitions by: Denis Cappellin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions by: SINTEF-9012 + +/// + +declare class ByteBuffer +{ + /** + * Constructs a new ByteBuffer. + */ + constructor( capacity?: number, littleEndian?: boolean, noAssert?: boolean ); + + /** + * Big endian constant that can be used instead of its boolean value. Evaluates to false. + */ + static BIG_ENDIAN: boolean; + + /** + * Default initial capacity of 16. + */ + static DEFAULT_CAPACITY: number; + + /** + * Default no assertions flag of false. + */ + static DEFAULT_NOASSERT: boolean; + + /** + * Little endian constant that can be used instead of its boolean value. Evaluates to true. + */ + static LITTLE_ENDIAN: boolean; + + /** + * Maximum number of bytes required to store a 32bit base 128 variable-length integer. + */ + static MAX_VARINT32_BYTES: number; + + /** + * Maximum number of bytes required to store a 64bit base 128 variable-length integer. + */ + static MAX_VARINT64_BYTES: number; + + /** + * Metrics representing number of bytes.Evaluates to 2. + */ + static METRICS_BYTES: number; + + /** + * Metrics representing number of UTF8 characters.Evaluates to 1. + */ + static METRICS_CHARS: number; + + /** + * ByteBuffer version. + */ + static VERSION: string; + + /** + * Backing buffer. + */ + buffer: ArrayBuffer; + + /** + * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation. + */ + limit: number; + + /** + * Whether to use little endian byte order, defaults to false for big endian. + */ + littleEndian: boolean; + + /** + * Marked offset. + */ + markedOffset: number; + + /** + * Whether to skip assertions of offsets and values, defaults to false. + */ + noAssert: boolean; + + /** + * Absolute read/write offset. + */ + offset: number; + + /** + * Data view to manipulate the backing buffer. Becomes null if the backing buffer has a capacity of 0. + */ + view: DataView; + + /** + * Allocates a new ByteBuffer backed by a buffer of the specified capacity. + */ + static allocate( capacity?: number, littleEndian?: number, noAssert?: boolean ): ByteBuffer; + + /** + * Decodes a base64 encoded string to binary like window.atob does. + */ + static atob( b64: string ): string; + + /** + * Encodes a binary string to base64 like window.btoa does. + */ + static btoa( str: string ): string; + + /** + * Calculates the number of UTF8 bytes of a string. + */ + static calculateUTF8Byte( str: string ): number; + + /** + * Calculates the number of UTF8 characters of a string.JavaScript itself uses UTF- 16, so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF. + */ + static calculateUTF8Char( str: string ): number; + + /** + * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer. + */ + static calculateVariant32( value: number ): number; + + /** + * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer. + */ + static calculateVariant64( value: number | Long ): number; + + /** + * Concatenates multiple ByteBuffers into one. + */ + static concat( buffers: Array, encoding?: string | boolean, litteEndian?: boolean, noAssert?: boolean ): ByteBuffer; + + /** + * Decodes a base64 encoded string to a ByteBuffer. + */ + static fromBase64( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; + + /** + * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer. + */ + static fromBinary( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; + + /** + * Decodes a hex encoded string with marked offsets to a ByteBuffer. + */ + static fromDebug( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; + + /** + * Decodes a hex encoded string to a ByteBuffer. + */ + static fromHex( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; + + /** + * Decodes an UTF8 encoded string to a ByteBuffer. + */ + static fromUTF8( str: string, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; + + /** + * Gets the backing buffer type. + */ + static isByteBuffer( bb: any ): boolean; + + /** + * Wraps a buffer or a string. Sets the allocated ByteBuffer's ByteBuffer#offset to 0 and its ByteBuffer#limit to the length of the wrapped data. + * @param buffer Anything that can be wrapped + * @param encoding String encoding if buffer is a string ("base64", "hex", "binary", defaults to "utf8") + * @param littleEndian Whether to use little or big endian byte order. Defaults to ByteBuffer.DEFAULT_ENDIAN. + * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteBuffer.DEFAULT_NOASSERT. + */ + static wrap( buffer: ByteBuffer | ArrayBuffer | Uint8Array | string, enc?: string | boolean, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer; + + /** + * Decodes a zigzag encoded signed 32bit integer. + */ + static zigZagDecode32( n: number ): number; + + /** + * Decodes a zigzag encoded signed 64bit integer. + */ + static zigZagDecode64( n: number | Long ): Long; + + /** + * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding. + */ + static zigZagEncode32( n: number ): number; + + /** + * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding. + */ + static zigZagEncode64( n: number | Long ): Long; + + /** + * Switches (to) big endian byte order. + */ + BE( bigEndian?: boolean ): ByteBuffer; + + /** + * Switches (to) little endian byte order. + */ + LE( bigEndian?: boolean ): ByteBuffer; + + /** + * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended data's length. + */ + append( source: ByteBuffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer; + + /** + * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents behind the specified offset up to the length of this ByteBuffer's data. + */ + appendTo( target: ByteBuffer, offset?: number ): ByteBuffer; + + /** + * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to disable them if your code already makes sure that everything is valid. + */ + assert( assert: boolean ): ByteBuffer; + + /** + * Gets the capacity of this ByteBuffer's backing buffer. + */ + capacity(): number; + + /** + * Clears this ByteBuffer's offsets by setting ByteBuffer#offset to 0 and + * ByteBuffer#limit to the backing buffer's capacity. Discards ByteBuffer#markedOffset. + */ + clear(): ByteBuffer; + + /** + * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for ByteBuffer#offset, ByteBuffer#markedOffset and ByteBuffer#limit. + */ + clone( copy?: boolean ): ByteBuffer; + + /** + * Compacts this ByteBuffer to be backed by a ByteBuffer#buffer of its contents' length. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will set offset = 0 and limit = capacity and adapt ByteBuffer#markedOffset to the same relative position if set. + */ + compact( begin?: number, end?: number ): ByteBuffer; + + /** + * Creates a copy of this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. + */ + copy( begin?: number, end?: number ): ByteBuffer; + + /** + * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. + */ + copyTo( target: ByteBuffer, targetOffset?: number, sourceOffset?: number, sourceLimit?: number ): ByteBuffer; + + /** + * Makes sure that this ByteBuffer is backed by a ByteBuffer#buffer of at least the specified capacity. If the current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity, the required capacity will be used instead. + */ + ensureCapacity( capacity: number ): ByteBuffer; + + /** + * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. + */ + fill( value: number | string, begin?: number, end?: number ): ByteBuffer; + + /** + * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets limit = offset and offset = 0. Make sure always to flip a ByteBuffer when all relative read or write operations are complete. + */ + flip(): ByteBuffer; + + /** + * Marks an offset on this ByteBuffer to be used later. + */ + mark( offset?: number ): ByteBuffer; + + /** + * Sets the byte order. + */ + order( littleEndian: boolean ): ByteBuffer; + + /** + * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly. + */ + prepend( source: ByteBuffer | string | ArrayBuffer, encoding?: string | number, offset?: number ): ByteBuffer; + + /** + * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly. + */ + prependTo( target: ByteBuffer, offset?: number ): ByteBuffer; + + /** + * Prints debug information about this ByteBuffer's contents. + */ + printDebug( out?: ( text: string ) => void ): void; + + /** + * Reads an 8bit signed integer. This is an alias of ByteBuffer#readInt8. + */ + readByte( offset?: number ): number; + + /** + * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters itself. + */ + readCString( offset?: number ): string; + + /** + * Reads a 64bit float. This is an alias of ByteBuffer#readFloat64. + */ + readDouble( offset?: number ): number; + + /** + * Reads a 32bit float. This is an alias of ByteBuffer#readFloat32. + */ + readFloat( offset?: number ): number; + + /** + * Reads a 32bit float. + */ + readFloat32( offset?: number ): number; + + /** + * Reads a 64bit float. + */ + readFloat64( offset?: number ): number; + + /** + * Reads a length as uint32 prefixed UTF8 encoded string. + */ + readIString( offset?: number ): string; + + /** + * Reads a 32bit signed integer.This is an alias of ByteBuffer#readInt32. + */ + readInt( offset?: number ): number; + + /** + * Reads a 16bit signed integer. + */ + readInt16( offset?: number ): number; + + /** + * Reads a 32bit signed integer. + */ + readInt32( offset?: number ): number; + + /** + * Reads a 64bit signed integer. + */ + readInt64( offset?: number ): Long; + + /** + * Reads an 8bit signed integer. + */ + readInt8( offset?: number ): number; + + /** + * Reads a 64bit signed integer. This is an alias of ByteBuffer#readInt64. + */ + readLong( offset?: number ): Long; + + /** + * Reads a 16bit signed integer. This is an alias of ByteBuffer#readInt16. + */ + readShort( offset?: number ): number; + + /** + * Reads an UTF8 encoded string. This is an alias of ByteBuffer#readUTF8String. + */ + readString( length: number, metrics?: number, offset?: number ): string; + + /** + * Reads an UTF8 encoded string. + */ + readUTF8String( chars: number, offset?: number ): string; + + /** + * Reads a 16bit unsigned integer. + */ + readUint16( offset?: number ): number; + + /** + * Reads a 32bit unsigned integer. + */ + readUint32( offset?: number ): number; + + /** + * Reads a 64bit unsigned integer. + */ + readUint64( offset?: number ): Long; + /** + * Reads an 8bit unsigned integer. + */ + readUint8( offset?: number ): number; + + /** + * Reads a length as varint32 prefixed UTF8 encoded string. + */ + readVString( offset?: number ): string; + + /** + * Reads a 32bit base 128 variable-length integer. + */ + readVarint32( offset?: number ): number; + + /** + * Reads a zig-zag encoded 32bit base 128 variable-length integer. + */ + readVarint32ZiZag( offset?: number ): number; + + /** + * Reads a 64bit base 128 variable-length integer. Requires Long.js. + */ + readVarint64( offset?: number ): Long; + + /** + * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js. + */ + readVarint64ZigZag( offset?: number ): Long; + + /** + * Gets the number of remaining readable bytes. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit, so this returns limit - offset. + */ + remaining(): number; + + /** + * Resets this ByteBuffer's ByteBuffer#offset. If an offset has been marked through ByteBuffer#mark before, offset will be set to ByteBuffer#markedOffset, which will then be discarded. If no offset has been marked, sets offset = 0. + */ + reset(): ByteBuffer; + + /** + * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that large or larger. + */ + resize( capacity: number ): ByteBuffer; + + /** + * Reverses this ByteBuffer's contents + */ + reverse( begin?: number, end?: number ): ByteBuffer; + + /** + * Skips the next length bytes. This will just advance + */ + skip( length: number ): ByteBuffer; + + /** + * Slices this ByteBuffer by creating a cloned instance with offset = begin and limit = end. + */ + slice( begin?: number, end?: number ): ByteBuffer; + + /** + * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will transparently ByteBuffer#flip this ByteBuffer if offset > limit but the actual offsets remain untouched. This is an alias of ByteBuffer#toBuffer. + */ + toArrayBuffer( forceCopy?: boolean ): ArrayBuffer; + + /** + * Encodes this ByteBuffer's contents to a base64 encoded string. + */ + toBase64( begin?: number, end?: number ): string; + + /** + * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes. + */ + toBinary( begin?: number, end?: number ): string; + + /** + * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will transparently ByteBuffer#flip this ByteBuffer if offset > limit but the actual offsets remain untouched. + */ + toBuffer( forceCopy?: boolean ): ArrayBuffer; + + /** + *Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are: + * < : offset, + * ' : markedOffset, + * > : limit, + * | : offset and limit, + * [ : offset and markedOffset, + * ] : markedOffset and limit, + * ! : offset, markedOffset and limit + */ + toDebug( columns?: boolean ): string | Array + + /** + * Encodes this ByteBuffer's contents to a hex encoded string. + */ + toHex( begin?: number, end?: number ): string; + + /** + * Converts the ByteBuffer's contents to a string. + */ + toString( encoding?: string ): string; + + /** + * Encodes this ByteBuffer's contents between ByteBuffer#offset and ByteBuffer#limit to an UTF8 encoded string. + */ + toUTF8(): string; + + /** + * Writes an 8bit signed integer. This is an alias of ByteBuffer#writeInt8. + */ + writeByte( value: number, offset?: number ): ByteBuffer; + + /** + * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL characters itself. + */ + writeCString( str: string, offset?: number ): ByteBuffer; + + /** + * Writes a 64bit float. This is an alias of ByteBuffer#writeFloat64. + */ + writeDouble( value: number, offset?: number ): ByteBuffer; + + /** + * Writes a 32bit float. This is an alias of ByteBuffer#writeFloat32. + */ + writeFloat( value: number, offset?: number ): ByteBuffer; + + /** + * Writes a 32bit float. + */ + writeFloat32( value: number, offset?: number ): ByteBuffer; + + /** + * Writes a 64bit float. + */ + writeFloat64( value: number, offset?: number ): ByteBuffer; + + /** + * Writes a length as uint32 prefixed UTF8 encoded string. + */ + writeIString( str: string, offset?: number ): ByteBuffer; + + /** + * Writes a 32bit signed integer. This is an alias of ByteBuffer#writeInt32. + */ + writeInt( value: number, offset?: number ): ByteBuffer; + + /** + * Writes a 16bit signed integer. + */ + writeInt16( value: number, offset?: number ): ByteBuffer; + + /** + * Writes a 32bit signed integer. + */ + writeInt32( value: number, offset?: number ): ByteBuffer; + + /** + * Writes a 64bit signed integer. + */ + writeInt64( value: number | Long, offset?: number ): ByteBuffer; + + /** + * Writes an 8bit signed integer. + */ + writeInt8( value: number, offset?: number ): ByteBuffer; + + /** + * Writes a 16bit signed integer. This is an alias of ByteBuffer#writeInt16. + */ + writeShort( value: number, offset?: number ): ByteBuffer; + + /** + * Writes an UTF8 encoded string.This is an alias of ByteBuffer#writeUTF8String. + */ + WriteString( str: string, offset?: number ): ByteBuffer | number; + + /** + * Writes an UTF8 encoded string. + */ + writeUTF8String( str: string, offset?: number ): ByteBuffer | number; + + /** + * Writes a 16bit unsigned integer. + */ + writeUint16( value: number, offset?: number ): ByteBuffer; + + /** + * Writes a 32bit unsigned integer. + */ + writeUint32( value: number, offset?: number ): ByteBuffer; + + /** + * Writes a 64bit unsigned integer. + */ + writeUint64( value: number | Long, offset?: number ): ByteBuffer; + + /** + * Writes an 8bit unsigned integer. + */ + writeUint8( value: number, offset?: number ): ByteBuffer; + + /** + * Writes a length as varint32 prefixed UTF8 encoded string. + */ + writeVString( str: string, offset?: number ): ByteBuffer | number; + + /** + * Writes a 32bit base 128 variable-length integer. + */ + writeVarint32( value: number, offset?: number ): ByteBuffer | number; + + /** + * Writes a zig-zag encoded 32bit base 128 variable-length integer. + */ + writeVarint32ZigZag( value: number, offset?: number ): ByteBuffer | number; + + /** + * Writes a 64bit base 128 variable-length integer. + */ + writeVarint64( value: number | Long, offset?: number ): ByteBuffer; + + /** + * Writes a zig-zag encoded 64bit base 128 variable-length integer. + */ + writeVarint64ZigZag( value: number | Long, offset?: number ): ByteBuffer | number; +} + +declare namespace ByteBuffer {} +export = ByteBuffer; +export as namespace ByteBuffer; diff --git a/bytebuffer/tsconfig.json b/bytebuffer/tsconfig.json new file mode 100644 index 0000000000..c82b8b1261 --- /dev/null +++ b/bytebuffer/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bytebuffer-tests.ts" + ] +} \ No newline at end of file diff --git a/bytes/bytes-tests.ts b/bytes/bytes-tests.ts index 4a981aee47..8df0bcbf18 100644 --- a/bytes/bytes-tests.ts +++ b/bytes/bytes-tests.ts @@ -1,6 +1,4 @@ -/// - -import bytes = require('bytes'); +import bytes = require('bytes'); // 1024*1024 = 1048576 console.log(bytes(104857)); diff --git a/bytes/bytes.d.ts b/bytes/bytes.d.ts deleted file mode 100644 index b99ebee7c6..0000000000 --- a/bytes/bytes.d.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Type definitions for bytes v2.1.0 -// Project: https://github.com/visionmedia/bytes.js -// Definitions by: Zhiyuan Wang -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module 'bytes' { - - /** - *Convert the given value in bytes into a string. - * - * @param {number} value - * @param {{ - * thousandsSeparator: [string] - * }} [options] bytes options. - * - * @returns {string} - */ - function bytes(value: number, options?: { thousandsSeparator: string }): string; - - /** - *Parse string to an integer in bytes. - * - * @param {string} value - * @returns {number} - */ - function bytes(value: string): number; - - namespace bytes { - - /** - * Format the given value in bytes into a string. - * - * If the value is negative, take Math.abs(). If it is a float, - * it is rounded. - * - * @param {number} value - * @param {BytesFormatOptions} [options] - */ - - function format(value: number, options?: { thousandsSeparator: string }): string; - - /** - * Just return the input number value. - * - * @param {number} value - * @return {number} - */ - function parse(value: number): number; - - /** - * Parse the string value into an integer in bytes. - * - * If no unit is given, it is assumed the value is in bytes. - * - * @param {string} value - * @return {number} - */ - function parse(value: string): number; - } - - export = bytes; -} diff --git a/bytes/index.d.ts b/bytes/index.d.ts new file mode 100644 index 0000000000..37a25897a0 --- /dev/null +++ b/bytes/index.d.ts @@ -0,0 +1,61 @@ +// Type definitions for bytes v2.1.0 +// Project: https://github.com/visionmedia/bytes.js +// Definitions by: Zhiyuan Wang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + +/** + *Convert the given value in bytes into a string. + * + * @param {number} value + * @param {{ + * thousandsSeparator: [string] + * }} [options] bytes options. + * + * @returns {string} + */ +declare function bytes(value: number, options?: { thousandsSeparator: string }): string; + +/** + *Parse string to an integer in bytes. + * + * @param {string} value + * @returns {number} + */ +declare function bytes(value: string): number; + +declare namespace bytes { + + /** + * Format the given value in bytes into a string. + * + * If the value is negative, take Math.abs(). If it is a float, + * it is rounded. + * + * @param {number} value + * @param {BytesFormatOptions} [options] + */ + + function format(value: number, options?: { thousandsSeparator: string }): string; + + /** + * Just return the input number value. + * + * @param {number} value + * @return {number} + */ + function parse(value: number): number; + + /** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {string} value + * @return {number} + */ + function parse(value: string): number; +} + +export = bytes; diff --git a/bytes/tsconfig.json b/bytes/tsconfig.json new file mode 100644 index 0000000000..8b7e4e50e4 --- /dev/null +++ b/bytes/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "bytes-tests.ts" + ] +} \ No newline at end of file diff --git a/c3/c3-tests.ts b/c3/c3-tests.ts index 5413db82d7..3bbab6f4af 100644 --- a/c3/c3-tests.ts +++ b/c3/c3-tests.ts @@ -1,4 +1,4 @@ -/// + ////////////////// // Doc Examples diff --git a/c3/c3.d.ts b/c3/c3.d.ts deleted file mode 100644 index 32dee37dce..0000000000 --- a/c3/c3.d.ts +++ /dev/null @@ -1,1073 +0,0 @@ -// Type definitions for C3js -// Project: http://c3js.org/ -// Definitions by: Marc Climent -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace c3 { - - type PrimitiveArray = Array; - type FormatFunction = (v: any, id: string, i: number, j: number) => void; - - interface TargetIds { - ids: ArrayOrString; - } - - type ArrayOrString = Array | string; - - interface ChartConfiguration { - /** - * The CSS selector or the element which the chart will be set to. D3 selection object can be specified. If other chart is set already, it will be replaced with the new one (only one chart can be set in one element). - * If this option is not specified, the chart will be generated but not be set. Instead, we can access the element by chart.element and set it by ourselves. - * Note: When chart is not binded, c3 starts observing if chart.element is binded by MutationObserver. In this case, polyfill is required in IE9 and IE10 becuase they do not support MutationObserver. On the other hand, if chart always will be binded, polyfill will not be required because MutationObserver will never be called. - */ - bindto?: string | HTMLElement | d3.Selection; - size?: { - /** - * The desired width of the chart element. - * If this option is not specified, the width of the chart will be calculated by the size of the parent element it's appended to. - * Note: This option should be specified if possible because it can improve its performance because some size calculations will be skipped by an explicit value. - */ - width?: number; - /** - * The desired height of the chart element. - * If this option is not specified, the height of the chart will be calculated by the size of the parent element it's appended to. - */ - height?: number; - }; - - padding?: { - /** - * The padding on the top of the chart. - */ - top?: number; - /** - * The padding on the right of the chart. - */ - right?: number; - /** - * The padding on the bottom of the chart. - */ - bottom?: number; - /** - * The padding on the left of the chart. - */ - left?: number; - }; - - color?: { - /** - * Set custom color pattern. - */ - pattern?: Array; - threshold?: any; // Undocumented - }; - - interaction?: { - /** - * Indicate if the chart should have interactions. - * If false is set, all of interactions (showing/hiding tooltip, selection, mouse events, etc) will be disabled. - */ - enabled?: boolean; - }; - - transition?: { - /** - * Set duration of transition (in milliseconds) for chart animation. - * Note: If 0 or null set, transition will be skipped. So, this makes initial rendering faster especially in case you have a lot of data. - */ - duration?: number; - }; - - /** - * Set a callback to execute when the chart is initialized. - */ - oninit?: () => void; - - /** - * Set a callback which is executed when the chart is rendered. Basically, this callback will be called in each time when the chart is redrawed. - */ - onrendered?: () => void; - - /** - * Set a callback to execute when mouse enters the chart. - */ - onmouseover?: () => void; - - /** - * Set a callback to execute when mouse leaves the chart. - */ - onmouseout?: () => void; - - /** - * Set a callback to execute when user resizes the screen. - */ - onresize?: () => void; - - /** - * Set a callback to execute when screen resize finished. - */ - onresized?: () => void; - - data: Data; - - axis?: Axis; - - grid?: Grid; - - /** - * Show rectangles inside the chart. - * This option accepts array including object that has axis, start, end and class. The keys start, end and class are optional. - * axis must be x, y or y2. start and end should be the value where regions start and end. If not specified, the edge values will be used. If timeseries x axis, date string, Date object and unixtime integer can be used. If class is set, the region element will have it as class. - */ - regions?: Array; - - legend?: LegendOptions; - - tooltip?: TooltipOptions; - - subchart?: SubchartOptions; - - zoom?: ZoomOptions; - - point?: PointOptions; - - line?: { - /** - * Set if null data point will be connected or not. - * If true set, the region of null data will be connected without any data point. If false set, the region of null data will not be connected and get empty. - */ - connectNull?: boolean; - /** - * Change step type for step chart. 'step', 'step-before' and 'step-after' can be used. - */ - step_type?: string; - }; - - area?: { - /** - * Set if min or max value will be 0 on area chart. - */ - zerobased?: boolean; - }; - - bar?: { - /** - * Change the width of bar chart. If ratio is specified, change the width of bar chart by ratio. - */ - width?: number | { ratio: number }; - /** - * Set if min or max value will be 0 on bar chart. - */ - zerobased?: boolean; - }; - - pie?: { - label?: { - /** - * Show or hide label on each pie piece. - */ - show?: boolean; - /** - * Set formatter for the label on each pie piece. - */ - format?: (value: number, ratio: number, id: string) => string; - /** - * Set threshold to show/hide labels. - */ - threshold?: number - }; - /** - * Enable or disable expanding pie pieces. - */ - expand?: boolean; - }; - - donut?: { - label?: { - /** - * Show or hide label on each donut piece. - */ - show?: boolean; - /** - * Set formatter for the label on each donut piece. - */ - format?: (value: number, ratio: number, id: string) => string; - /** - * Set threshold to show/hide labels. - */ - threshold?: number - }; - /** - * Enable or disable expanding pie pieces. - */ - expand?: boolean; - /** - * Set width of donut chart. - */ - width?: number; - /** - * Set title of donut chart. - */ - title?: string; - }; - - gauge?: { - label?: { - /** - * Show or hide label on gauge. - */ - show?: boolean; - /** - * Set formatter for the label on gauge. - */ - format?: (value: any, ratio: number) => string; - }; - /** - * Enable or disable expanding gauge. - */ - expand?: boolean; - /** - * Set min value of the gauge. - */ - min?: number; - /** - * Set max value of the gauge. - */ - max?: number; - /** - * Set units of the gauge. - */ - units?: string; - /** - * Set width of gauge chart. - */ - width?: number; - }; - } - - interface Data { - /** - * Load a CSV or JSON file from a URL. Note that this will not work if loading via the "file://" protocol as most browsers with block XMLHTTPRequests. - */ - url?: string; - /** - * Parse a JSON object for data. - */ - json?: Object; - /** - * Load data from a multidimensional array, with the first element containing the data names, the following containing related data in that order. - */ - rows?: Array; - /* - * Load data from a multidimensional array, with each element containing an array consisting of a datum name and associated data values. - */ - columns?: Array; - /** - * Used if loading JSON via data.url - */ - mimeType?: string; - /** - * Choose which JSON object keys correspond to desired data. - */ - keys?: { x?: string; value: Array; }; - /** - * Specify the key of x values in the data. - * We can show the data with non-index x values by this option. This option is required when the type of x axis is timeseries. If this option is set on category axis, the values of the data on the key will be used for category names. - */ - x?: string; - /** - * Specify the keys of the x values for each data. - * This option can be used if we want to show the data that has different x values. - */ - xs?: { [key: string]: string }; - /** - * Set a format to parse string specifed as x. - * Default is %Y-%m-%d - */ - xFormat?: string; - //xLocaltime?: any; - //xSort?: any; - /** - * Set custom data name. - */ - names?: { [key: string]: string }; - /** - * Set custom data class. - * If this option is specified, the element g for the data has an additional class that has the prefix c3-target- (e.g. c3-target-additional-data1-class). - */ - classes?: { [key: string]: string }; - /** - * Set groups for the data for stacking. - */ - groups?: Array>; - /** - * Set y axis the data related to. y and y2 can be used. - */ - axes?: { [key: string]: string }; - /** - * Set chart type at once. - * If this option is specified, the type will be applied to every data. This setting can be overwritten by data.types. - * Available Values: line, spline, step, area, area-spline, area-step, bar, scatter, pie, donut, gauge - */ - type?: string; - /** - * Set chart type for each data. - * This setting overwrites data.type setting. - */ - types?: { [key: string]: string }; - /** - * Show labels on each data points or set formatter function for data labels. - * The formatter function receives 4 arguments such as v, id, i, j and it must return a string that will be shown as the label. The arguments are: - * - v is the value of the data point where the label is shown. - * - id is the id of the data where the label is shown. - * - i is the index of the data point where the label is shown. - * - j is the sub index of the data point where the label is shown. - * Formatter function can be defined for each data by specifying as an object and D3 formatter function can be set (e.g. d3.format('$')) - */ - labels?: boolean | - { format: FormatFunction } | - { format: { [key: string]: FormatFunction } }; - /** - * Define the order of the data. - * This option changes the order of stacking the data and pieces of pie/donut. If null specified, it will be the order the data loaded. If function specified, it will be used to sort the data and it will recieve the data as argument. - * Available Values: desc, asc, function (data1, data2) { ... }, null - */ - order?: string | ((...data: string[]) => void); - /** - * Define regions for each data. - * The values must be an array for each data and it should include an object that has start, end, style. If start is not set, the start will be the first data point. If end is not set, the end will be the last data point. - * Currently this option supports only line chart and dashed style. If this option specified, the line will be dashed only in the regions. - */ - regions?: { [key: string]: any }; - /** - * Set color converter function. - * This option should a function and the specified function receives color (e.g. '#ff0000') and d that has data parameters like id, value, index, etc. And it must return a string that represents color (e.g. '#00ff00'). - */ - color?: (color: string, d: any) => string | d3.Rgb; - /** - * Set color for each data. - */ - colors?: { [key: string]: string | d3.Rgb }; - /** - * Hide each data when the chart appears. - * If true specified, all of data will be hidden. If multiple ids specified as an array, those will be hidden. - */ - hide?: boolean | Array; - /** - * Set text displayed when empty data. - */ - empty?: { label: { text: string } }; - - selection?: { - enabled?: boolean; - grouped?: boolean; - multiple?: boolean; - draggable?: boolean; - isselectable?: (d?: any) => boolean; - }; - /** - * Set a callback for click event on each data point. - * This callback will be called when each data point clicked and will receive d and element as the arguments. - * - d is the data clicked and element is the element clicked. In this callback, this will be the Chart object. - */ - onclick?: (d: any, element: any) => void; - /** - * Set a callback for mouseover event on each data point. - * This callback will be called when mouse cursor moves onto each data point and will receive d as the argument. - * - d is the data where mouse cursor moves onto. In this callback, this will be the Chart object. - */ - onmouseover?: (d: any, element?: any) => void; - /** - * Set a callback for mouseout event on each data point. - * This callback will be called when mouse cursor moves out each data point and will receive d as the argument. - * - d is the data where mouse cursor moves out. In this callback, this will be the Chart object. - */ - onmouseout?: (d: any, element?: any) => void; - // onselected?: any; - // onunselected?: any; - // ondragstart?: any; - // ondragend?: any; - } - - interface Axis { - /** - * Switch x and y axis position. - */ - rotated?: boolean; - x?: XAxisConfiguration; - y?: YAxisConfiguration; - y2?: YAxisConfiguration; - } - - interface XAxisConfiguration { - /** - * Show or hide x axis. - */ - show?: boolean; - /** - * Set type of x axis (timeseries, category, indexed) - */ - type?: string; - /** - * Set how to treat the timezone of x values. - * If true, treat x value as localtime. If false, convert to UTC internally. - */ - localtime?: boolean; - /** - * Set category names on category axis. - * This must be an array that includes category names in string. If category names are included in the date by data.x option, this is not required. - */ - categories?: Array; - - tick?: XTickConfiguration; - /** - * Set max value of x axis range. - */ - max?: number; - /** - * Set min value of x axis range. - */ - min?: number; - /** - * Set padding for x axis. - * If this option is set, the range of x axis will increase/decrease according to the values. If no padding is needed in the ragen of x axis, 0 should be set. On category axis, this option will be ignored. - */ - padding?: { - left?: number; - right?: number; - }; - /** - * Set height of x axis. - * The height of x axis can be set manually by this option. If you need more space for x axis, please use this option for that. The unit is pixel. - */ - height?: number; - /** - * Set default extent for subchart and zoom. This can be an array or function that returns an array. - */ - extent?: Array | (() => Array); - /** - * Set label on x axis. - * You can set x axis label and change its position by this option. string and object can be passed and we can change the poisiton by passing object that has position key. Available position differs according to the axis direction (vertical or horizontal). If string set, the position will be the default. - * Valid horizontal positions: inner-right (Default), inner-center, inner-left, outer-right, outer-center, outer-left - * Valid vertical positions: inner-top, inner-middle, inner-bottom, outer-top, outer-middle, outer-bottom - */ - label?: string | { text: string; position: string }; - } - - interface YAxisConfiguration { - /** - * Show or hide y axis. - */ - show?: boolean; - /** - * Show y axis inside of the chart. - */ - inner?: boolean; - /** - * Set max value of y axis. - */ - max?: number; - /** - * Set min value of y axis. - */ - min?: number; - /** - * Change the direction of y axis. - * If true set, the direction will be from the top to the bottom. - */ - inverted?: boolean; - /** - * Set center value of y axis. - */ - center?: number; - /** - * Set label on y axis. This option works in the same way as axis.x.label. - * Valid horizontal positions: inner-right (Default), inner-center, inner-left, outer-right, outer-center, outer-left - * Valid vertical positions: inner-top, inner-middle, inner-bottom, outer-top, outer-middle, outer-bottom - */ - label?: string | { text: string; position: string }; - tick?: YTickConfiguration; - /** - * Set padding for y axis. - * You can set padding for y axis to create more space on the edge of the axis. This option accepts object and it can include top and bottom. top, bottom will be treated as pixels. - */ - padding?: { - top?: number; - bottom?: number; - }; - /** - * Set default range of y axis. This option set the default value for y axis when there is no data on init. - */ - default?: Array; - - } - - interface XTickConfiguration { - /** - * Centerise ticks on category axis - */ - centered?: boolean; - /** - * A function to format tick value. Format string is also available for timeseries data. - */ - format?: string | ((x: number | Date) => string | number); - /** - * Setting for culling ticks. - * If true is set, the ticks will be culled, then only limitted tick text will be shown. This option does not hide the tick lines. If false is set, all of ticks will be shown. - */ - culling?: boolean | CullingConfiguration; - /** - * The number of x axis ticks to show. - * This option hides tick lines together with tick text. If this option is used on timeseries axis, the ticks position will be determined precisely and not nicely positioned (e.g. it will have rough second value). - */ - count?: number; - /** - * Fit x axis ticks. - * If true set, the ticks will be positioned nicely. If false set, the ticks will be positioned according to x value of the data points. - */ - fit?: boolean; - /** - * Set the x values of ticks manually. - * If this option is provided, the position of the ticks will be determined based on those values. This option works with timeseries data and the x values will be parsed accoding to the type of the value and data.xFormat option. - */ - values?: Array | Array; - /** - * Rotate x axis tick text. If you set negative value, it will rotate to opposite direction. - */ - rotate?: number; - /** - * Show x axis outer tick. - */ - outer?: boolean; - multiline?: boolean; // Undocumented - } - - interface YTickConfiguration { - /** - * Set formatter for y axis tick text. - * This option accepts d3.format object as well as a function you define. - */ - format?: (x: number) => string; - /** - * Show or hide outer tick. - */ - outer?: boolean; - /** - * Set the y values of ticks manually. - */ - values?: Array; - /** - * The number of y axis ticks to show. - * The position of the ticks will be calculated precisely, so the values on the ticks will not be rounded nicely. In the case, axis.y.tick.format or axis.y.tick.values will be helpful. - */ - count?: number; - } - - interface CullingConfiguration { - /** - * The number of tick texts will be adjusted to less than this value. - */ - max: number; - } - - interface Grid { - x?: { - /** - * Show grids along x axis. - */ - show?: boolean; - /** - * Show additional grid lines along x axis. - * This option accepts array including object that has value, text, position and class. text, position and class are optional. For position, start, middle and end (default) are available. - * If x axis is category axis, value can be category name. If x axis is timeseries axis, value can be date string, Date object and unixtime integer. - */ - lines?: Array; - }; - y?: { - /** - * Show grids along y axis. - */ - show?: boolean; - /** - * Show additional grid lines along y axis. - * This option accepts array including object that has value, text, position and class. - */ - lines?: Array; - }; - } - - interface LineOptions { - value: number; - text?: string; - axis?: string; - position?: string; - class?: string; - } - - interface RegionOptions { - axis?: string; - start?: string | number | Date; - end?: string | number | Date; - class?: string; - } - - interface LegendOptions { - /** - * Show or hide legend. - */ - show?: boolean; - /** - * Hide legend - * If true given, all legend will be hidden. If string or array given, only the legend that has the id will be hidden. - */ - hide?: boolean | ArrayOrString; - /** - * Change the position of legend. - * Currently bottom, right and inset are supported. - */ - position?: string; - /** - * Change inset legend attributes. - * This option accepts object that has the keys anchor, x, y and step. - * anchor decides the position of the legend. These anchors are available: top-left, top-right, bottom-left, bottom-right - * x and y set the position of the legend based on the anchor. - * step defines the max step the lagend has (e.g. If 2 set and legend has 3 legend item, the legend 2 columns). - */ - inset?: { - anchor?: string; - x?: number; - y?: number; - step?: number; - }; - - item?: { - /** - * Set click event handler to the legend item. - */ - onclick?: (id: any) => void; - /** - * Set mouseover event handler to the legend item. - */ - onmoouseover?: (id: any) => void; - /** - * Set mouseout event handler to the legend item. - */ - onmouseout?: (id: any) => void; - }; - } - - interface TooltipOptions { - /** - * Show or hide tooltip. - */ - show?: boolean; - /** - * Set if tooltip is grouped or not for the data points. - */ - grouped?: boolean; - format?: { - /** - * Set format for the title of tooltip. Specified function receives x of the data point to show. - */ - title?: (x: any) => string; - /** - * Set format for the name of each data in tooltip. Specified function receives name, ratio, id and index of the data point to show. ratio will be undefined if the chart is not donut/pie/gauge. - */ - name?: (name: string, ratio: number, id: string, index: number) => string; - /** - * Set format for the value of each data in tooltip. - * Specified function receives name, ratio, id and index of the data point to show. ratio will be undefined if the chart is not donut/pie/gauge. - * If undefined returned, the row of that value will be skipped. - */ - value?: (name: string, ratio: number, id: string, index: number) => string; - }; - /** - * Set custom position for the tooltip. This option can be used to modify the tooltip position by returning object that has top and left. - */ - position?: (data: any, width: number, height: number, element: any) => { top: number; left: number }; - /** - * Set custom HTML for the tooltip. - * Specified function receives data, defaultTitleFormat, defaultValueFormat and color of the data point to show. If tooltip.grouped is true, data includes multiple data points. - */ - contents?: (data: any, defaultTitleFormat: string, defaultValueFormat: string, color: any) => string; - } - - interface SubchartOptions { - /** - * Show sub chart on the bottom of the chart. - */ - show?: boolean; - size?: { - /** - * Change the height of the subchart. - */ - height: number; - }; - /** - * Set callback for brush event. - * Specified function receives the current zoomed x domain. - */ - onbrush?: (domain: any) => void; - } - - interface ZoomOptions { - /** - * Enable zooming. - */ - enabled?: boolean; - /** - * Enable to rescale after zooming. If true set, y domain will be updated according to the zoomed region. - */ - rescale?: boolean; - /** - * Change zoom extent. - */ - extent?: [number, number]; - /** - * Set callback that is called when the chart is zooming. Specified function receives the zoomed domain. - */ - onzoom?: (domain: any) => void; - /** - * Set callback that is called when zooming starts. Specified function receives the zoom event. - */ - onzoomstart?: (event: Event) => void; - /** - * Set callback that is called when zooming ends. Specified function receives the zoomed domain. - */ - onzoomend?: (domain: any) => void; - } - - interface PointOptions { - /** - * Whether to show each point in line. - */ - show?: boolean; - /** - * The radius size of each point. - */ - r?: number; - - focus?: { - expand: { - /** - * Whether to expand each point on focus. - */ - enabled?: boolean; - /** - * The radius size of each point on focus. - */ - r?: number - }; - }; - - select?: { - /** - * The radius size of each point on selected. - */ - r?: number; - }; - } - - interface ChartAPI { - /** - * This API highlights specified targets and fade out the others. - * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be highlighted. - */ - focus(targetIds?: ArrayOrString): void; - /** - * This API fades out specified targets and reverts the others. - * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be faded out. - */ - defocus(targetIds?: ArrayOrString): void; - /** - * This API reverts specified targets. - * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be reverted. - */ - revert(targetIds?: ArrayOrString): void; - - /** - * This API shows specified targets. - * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be shown. - * If withLegend is set true, legend will be shown together with the specified data. - */ - show(targetIds?: ArrayOrString, options?: { withLegend: boolean }): void; - /** - * This API hides specified targets. - * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be hidden. - * If withLegend is set true, legend will be hidden together with the specified data. - */ - hide(targetIds?: ArrayOrString, options?: { withLegend: boolean }): void; - /** - * This API toggles (shows or hides) specified targets. - * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be toggles. - * If withLegend is set true, legend will be toggled together with the specified data. - */ - toggle(targetIds?: ArrayOrString, options?: { withLegend: boolean }): void; - /** - * Load data to the chart. - * If url, json, rows and columns given, the data will be loaded. If data that has the same target id is given, the chart will be updated. Otherwise, new target will be added. - * If classes given, the classes specifed by data.classes will be updated. classes must be Object that has target id as keys. - * If categories given, the categories specifed by axis.x.categories or data.x will be updated. categories must be Array. - * If axes given, the axes specifed by data.axes will be updated. axes must be Object that has target id as keys. - * If colors given, the colors specifed by data.colors will be updated. colors must be Object that has target id as keys. - * If type or types given, the type of targets will be updated. type must be String and types must be Object. - * If unload given, data will be unloaded before loading new data. If true given, all of data will be unloaded. If target ids given as String or Array, specified targets will be unloaded. - * If done given, the specified function will be called after data loded. - * NOTE: unload should be used if some data needs to be unloaded simultaneously. If you call unload API soon after/before load instead of unload param, chart will not be rendered properly because of cancel of animation. - * NOTE: done will be called after data loaded, but it's not after rendering. It's because rendering will finish after some transition and there is some time lag between loading and rendering. - */ - load(args: { - url?: string; - json?: Object; - keys?: { x?: string; value: Array; } - rows?: Array; - columns?: Array; - classes?: { [key: string]: string }; - categories?: Array; - axes?: { [key: string]: string }; - colors?: { [key: string]: string | d3.Rgb }; - type?: string; - types?: { [key: string]: string }; - unload?: boolean | ArrayOrString; - done?: () => any; - }): void; - /** - * Unload data to the chart. - * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be toggles. - * If ids given, the data that has specified target id will be unloaded. ids should be String or Array. If ids is not specified, all data will be unloaded. - * If done given, the specified function will be called after data loded. - * NOTE: If you call load API soon after/before unload, unload param of load should be used. Otherwise chart will not be rendered properly because of cancel of animation. - * NOTE: done will be called after data loaded, but it's not after rendering. It's because rendering will finish after some transition and there is some time lag between loading and rendering. - */ - unload(targetIds?: TargetIds, done?: () => any): any; - /** - * Flow data to the chart. By this API, you can append new data points to the chart. - * If json, rows and columns given, the data will be loaded. If data that has the same target id is given, the chart will be appended. Otherwise, new target will be added. One of these is required when calling. If json specified, keys is required as well as data.json - * If to is given, the lower x edge will move to that point. If not given, the lower x edge will move by the number of given data points. - * If length is given, the lower x edge will move by the number of this argument. - * If duration is given, the duration of the transition will be specified value. If not given, transition.duration will be used as default. - * If done is given, the specified function will be called when flow ends. - */ - flow(args: { - json?: Object; - keys?: { x?: string; value: Array; } - rows?: Array; - columns?: Array; - to?: any; - length?: number; - duration?: number; - done?: () => any; - }): void; - /** - * Change data point state to selected. By this API, you can select data points. To use this API, data.selection.enabled needs to be set true. - * @param ids Specify target ids to be selected. If this argument is not given, all targets will be the candidate. - * @param indices Specify indices to be selected. If this argument is not given, all data points will be the candidate. - * @param resetOthers If this argument is set true, the data points that are not specified by ids, indices will be unselected. - */ - select(ids?: Array, indices?: Array, resetOthers?: boolean): void; - /** - * Change data point state to unselected. By this API, you can unselect data points. To use this API, data.selection.enabled needs to be set true. - * @param ids Specify target ids to be unselected. If this argument is not given, all targets will be the candidate. - * @param indices Specify indices to be unselected. If this argument is not given, all data points will be the candidate. - */ - unselect(ids?: Array, indices?: Array): void; - /** - * Get selected data points. By this API, you can get selected data points information. To use this API, data.selection.enabled needs to be set true. - * @param targetId You can filter the result by giving target id that you want to get. If not given, all of data points will be returned. - */ - selected(targetId?: string): Data; - /** - * Change the type of the chart. - * @param type Specify the type to be transformed. The types listed in data.type can be used. - * @param targetIds Specify targets to be transformed. If not given, all targets will be the candidate. - */ - transform(type: string, targetIds?: ArrayOrString): void; - /** - * Update groups for the targets. - * @param groups This argument needs to be an Array that includes one or more Array that includes target ids to be grouped. - */ - groups(groups: Array>): void; - - xgrids: GridOperations; - - ygrids: GridOperations; - - regions: { - /** - * Update regions. - * @param regions Regions will be replaced with this argument. The format of this argument is the same as regions. - */ - (regions: Array): void; - /** - * Add new region. This API adds new region instead of replacing like regions. - * @param grids New region will be added. The format of this argument is the same as regions and it's possible to give an Object if only one region will be added. - */ - add(regions: Array | Object): void; - /** - * Remove regions. This API removes regions. - * @param args This argument should include classes. If classes is given, the regions that have one of the specified classes will be removed. If args is not given, all of regions will be removed. - */ - remove(args?: { value?: number | string; class?: string }): void; - }; - - data: { - /** - * Get data loaded in the chart. - * @param targetIds If this argument is given, this API returns the specified target data. If this argument is not given, all of data will be returned. - */ - (targetIds?: ArrayOrString): Data; - /** - * Get data shown in the chart. - * @param targetIds If this argument is given, this API filters the data with specified target ids. If this argument is not given, all shown data will be returned. - */ - shown(targetIds?: ArrayOrString): Data; - /** - * Get values of the data loaded in the chart. - * @param targetIds This API returns the values of specified target. If this argument is not given, null will be retruned. - */ - values(targetIds?: ArrayOrString): Array; - /** - * Get and set names of the data loaded in the chart. - * @param names If this argument is given, the names of data will be updated. If not given, the current names will be returned. The format of this argument is the same as data.names. - */ - names(names?: { [key: string]: string }): { [key: string]: string }; - /** - * Get and set colors of the data loaded in the chart. - * @param colors If this argument is given, the colors of data will be updated. If not given, the current colors will be returned. The format of this argument is the same as data.colors. - */ - colors(colors?: { [key: string]: string | d3.Rgb }): { [key: string]: string }; - /** - * Get and set axes of the data loaded in the chart. - * @param axes If this argument is given, the axes of data will be updated. If not given, the current axes will be returned. The format of this argument is the same as data.axes. - */ - axes(axes?: { [key: string]: string }): { [key: string]: string }; - }; - - /** - * Gets and sets the value a category - * @param index Index of the category to get or set - * @param category: Value of the category to update - */ - category(index: number, category?: string): string; - - /** - * Get and set the categories - * @param categories: Value of the categories to update - */ - categories(categories?: Array): Array; - - /** - * Get the color for the specified targetId - */ - color(targetId: string): string; - - /** - * Get and set x values for the chart. - * @param x If x is given, x values of every target will be updated. If no argument is given, current x values will be returned as an Object whose keys are the target ids. - */ - x(x?: PrimitiveArray): PrimitiveArray; - - /** - * Get and set x values for the chart. - * @param x If x is given, x values of every target will be updated. If no argument is given, current x values will be returned as an Object whose keys are the target ids. - */ - xs(xs?: { [key: string]: PrimitiveArray }): { [key: string]: PrimitiveArray }; - - axis: { - /** - * Get and set axis labels. - * @param labels If labels is given, specified axis' label will be updated. - */ - labels(labels?: { [key: string]: string }): { [key: string]: string } - /** - * Get and set axis min value. - * @param min If min is given, specified axis' min value will be updated. If no argument is given, the current min values for each axis will be returned. - */ - min(min?: number | { [key: string]: number }): number | { [key: string]: number } - /** - * Get and set axis max value. - * @param max If max is given, specified axis' max value will be updated. If no argument is given, the current max values for each axis will be returned. - */ - max(max?: number | { [key: string]: number }): number | { [key: string]: number } - /** - * Get and set axis min and max value. - * @param range If range is given, specified axis' min and max value will be updated. If no argument is given, the current min and max values for each axis will be returned. - */ - range(range?: { min?: number | { [key: string]: number }; max?: number | { [key: string]: number } }): { min: number | { [key: string]: number }; max: number | { [key: string]: number } } - }; - - legend: { - /** - * Show legend for each target. - * @param targetIds If targetIds is given, specified target's legend will be shown. If only one target is the candidate, String can be passed. If no argument is given, all of target's legend will be shown. - */ - show(targetIds?: ArrayOrString): void; - /** - * Hide legend for each target. - * @param targetIds If targetIds is given, specified target's legend will be hidden. If only one target is the candidate, String can be passed. If no argument is given, all of target's legend will be hidden. - */ - hide(targetIds?: ArrayOrString): void; - }; - - zoom: { - /** - * Zoom by giving x domain. - * @param domain If domain is given, the chart will be zoomed to the given domain. If no argument is given, the current zoomed domain will be returned. - */ - (domain?: Array): Array; - - /** - * Enable and disable zooming. - * @param enabled If enabled is true, the feature of zooming will be enabled. If false is given, it will be disabled. - */ - enable(enabled: boolean): void; - }; - - /** - * Unzoom to the original domain. - */ - unzoom(): void; - - /** - * Resize the chart. If no size is specified it will resize to fit. - * @param size This argument should include width and height in pixels. - */ - resize(size?: { width?: number; height?: number }): void; - - /** - * Force to redraw. - */ - flush(): void; - - /** - * Reset the chart object and remove element and events completely. - */ - destroy(): void; - } - - interface GridOperations { - /** - * Update the x/y grid lines. - * @param grids X/Y grid lines will be replaced with this argument. The format of this argument is the same as grid.x.lines or grid.y.lines. - */ - (grids: Array): void; - /** - * Add x/y grid lines. This API adds new x/y grid lines instead of replacing like xgrids. - * @param grids New x/y grid lines will be added. The format of this argument is the same as grid.x.lines or grid.y.lines and it's possible to give an Object if only one line will be added. - */ - add(grids: Array | Object): void; - /** - * Remove x/y grid lines. This API removes x/y grid lines. - * @param args This argument should include value or class. If value is given, the x/y grid lines that have specified x/y value will be removed. If class is given, the x/y grid lines that have specified class will be removed. If args is not given, all of x/y grid lines will be removed. - */ - remove(args?: { class?: string; value?: number | string }): void; - } - - export function generate(config: ChartConfiguration): ChartAPI; -} - -declare module "c3" { - export = c3; -} diff --git a/c3/index.d.ts b/c3/index.d.ts new file mode 100644 index 0000000000..e4616627f1 --- /dev/null +++ b/c3/index.d.ts @@ -0,0 +1,1069 @@ +// Type definitions for C3js +// Project: http://c3js.org/ +// Definitions by: Marc Climent +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace c3 { + + type PrimitiveArray = Array; + type FormatFunction = (v: any, id: string, i: number, j: number) => void; + + interface TargetIds { + ids: ArrayOrString; + } + + type ArrayOrString = Array | string; + + interface ChartConfiguration { + /** + * The CSS selector or the element which the chart will be set to. D3 selection object can be specified. If other chart is set already, it will be replaced with the new one (only one chart can be set in one element). + * If this option is not specified, the chart will be generated but not be set. Instead, we can access the element by chart.element and set it by ourselves. + * Note: When chart is not binded, c3 starts observing if chart.element is binded by MutationObserver. In this case, polyfill is required in IE9 and IE10 becuase they do not support MutationObserver. On the other hand, if chart always will be binded, polyfill will not be required because MutationObserver will never be called. + */ + bindto?: string | HTMLElement | d3.Selection; + size?: { + /** + * The desired width of the chart element. + * If this option is not specified, the width of the chart will be calculated by the size of the parent element it's appended to. + * Note: This option should be specified if possible because it can improve its performance because some size calculations will be skipped by an explicit value. + */ + width?: number; + /** + * The desired height of the chart element. + * If this option is not specified, the height of the chart will be calculated by the size of the parent element it's appended to. + */ + height?: number; + }; + + padding?: { + /** + * The padding on the top of the chart. + */ + top?: number; + /** + * The padding on the right of the chart. + */ + right?: number; + /** + * The padding on the bottom of the chart. + */ + bottom?: number; + /** + * The padding on the left of the chart. + */ + left?: number; + }; + + color?: { + /** + * Set custom color pattern. + */ + pattern?: Array; + threshold?: any; // Undocumented + }; + + interaction?: { + /** + * Indicate if the chart should have interactions. + * If false is set, all of interactions (showing/hiding tooltip, selection, mouse events, etc) will be disabled. + */ + enabled?: boolean; + }; + + transition?: { + /** + * Set duration of transition (in milliseconds) for chart animation. + * Note: If 0 or null set, transition will be skipped. So, this makes initial rendering faster especially in case you have a lot of data. + */ + duration?: number; + }; + + /** + * Set a callback to execute when the chart is initialized. + */ + oninit?: () => void; + + /** + * Set a callback which is executed when the chart is rendered. Basically, this callback will be called in each time when the chart is redrawed. + */ + onrendered?: () => void; + + /** + * Set a callback to execute when mouse enters the chart. + */ + onmouseover?: () => void; + + /** + * Set a callback to execute when mouse leaves the chart. + */ + onmouseout?: () => void; + + /** + * Set a callback to execute when user resizes the screen. + */ + onresize?: () => void; + + /** + * Set a callback to execute when screen resize finished. + */ + onresized?: () => void; + + data: Data; + + axis?: Axis; + + grid?: Grid; + + /** + * Show rectangles inside the chart. + * This option accepts array including object that has axis, start, end and class. The keys start, end and class are optional. + * axis must be x, y or y2. start and end should be the value where regions start and end. If not specified, the edge values will be used. If timeseries x axis, date string, Date object and unixtime integer can be used. If class is set, the region element will have it as class. + */ + regions?: Array; + + legend?: LegendOptions; + + tooltip?: TooltipOptions; + + subchart?: SubchartOptions; + + zoom?: ZoomOptions; + + point?: PointOptions; + + line?: { + /** + * Set if null data point will be connected or not. + * If true set, the region of null data will be connected without any data point. If false set, the region of null data will not be connected and get empty. + */ + connectNull?: boolean; + /** + * Change step type for step chart. 'step', 'step-before' and 'step-after' can be used. + */ + step_type?: string; + }; + + area?: { + /** + * Set if min or max value will be 0 on area chart. + */ + zerobased?: boolean; + }; + + bar?: { + /** + * Change the width of bar chart. If ratio is specified, change the width of bar chart by ratio. + */ + width?: number | { ratio: number }; + /** + * Set if min or max value will be 0 on bar chart. + */ + zerobased?: boolean; + }; + + pie?: { + label?: { + /** + * Show or hide label on each pie piece. + */ + show?: boolean; + /** + * Set formatter for the label on each pie piece. + */ + format?: (value: number, ratio: number, id: string) => string; + /** + * Set threshold to show/hide labels. + */ + threshold?: number + }; + /** + * Enable or disable expanding pie pieces. + */ + expand?: boolean; + }; + + donut?: { + label?: { + /** + * Show or hide label on each donut piece. + */ + show?: boolean; + /** + * Set formatter for the label on each donut piece. + */ + format?: (value: number, ratio: number, id: string) => string; + /** + * Set threshold to show/hide labels. + */ + threshold?: number + }; + /** + * Enable or disable expanding pie pieces. + */ + expand?: boolean; + /** + * Set width of donut chart. + */ + width?: number; + /** + * Set title of donut chart. + */ + title?: string; + }; + + gauge?: { + label?: { + /** + * Show or hide label on gauge. + */ + show?: boolean; + /** + * Set formatter for the label on gauge. + */ + format?: (value: any, ratio: number) => string; + }; + /** + * Enable or disable expanding gauge. + */ + expand?: boolean; + /** + * Set min value of the gauge. + */ + min?: number; + /** + * Set max value of the gauge. + */ + max?: number; + /** + * Set units of the gauge. + */ + units?: string; + /** + * Set width of gauge chart. + */ + width?: number; + }; + } + + interface Data { + /** + * Load a CSV or JSON file from a URL. Note that this will not work if loading via the "file://" protocol as most browsers with block XMLHTTPRequests. + */ + url?: string; + /** + * Parse a JSON object for data. + */ + json?: Object; + /** + * Load data from a multidimensional array, with the first element containing the data names, the following containing related data in that order. + */ + rows?: Array; + /* + * Load data from a multidimensional array, with each element containing an array consisting of a datum name and associated data values. + */ + columns?: Array; + /** + * Used if loading JSON via data.url + */ + mimeType?: string; + /** + * Choose which JSON object keys correspond to desired data. + */ + keys?: { x?: string; value: Array; }; + /** + * Specify the key of x values in the data. + * We can show the data with non-index x values by this option. This option is required when the type of x axis is timeseries. If this option is set on category axis, the values of the data on the key will be used for category names. + */ + x?: string; + /** + * Specify the keys of the x values for each data. + * This option can be used if we want to show the data that has different x values. + */ + xs?: { [key: string]: string }; + /** + * Set a format to parse string specifed as x. + * Default is %Y-%m-%d + */ + xFormat?: string; + //xLocaltime?: any; + //xSort?: any; + /** + * Set custom data name. + */ + names?: { [key: string]: string }; + /** + * Set custom data class. + * If this option is specified, the element g for the data has an additional class that has the prefix c3-target- (e.g. c3-target-additional-data1-class). + */ + classes?: { [key: string]: string }; + /** + * Set groups for the data for stacking. + */ + groups?: Array>; + /** + * Set y axis the data related to. y and y2 can be used. + */ + axes?: { [key: string]: string }; + /** + * Set chart type at once. + * If this option is specified, the type will be applied to every data. This setting can be overwritten by data.types. + * Available Values: line, spline, step, area, area-spline, area-step, bar, scatter, pie, donut, gauge + */ + type?: string; + /** + * Set chart type for each data. + * This setting overwrites data.type setting. + */ + types?: { [key: string]: string }; + /** + * Show labels on each data points or set formatter function for data labels. + * The formatter function receives 4 arguments such as v, id, i, j and it must return a string that will be shown as the label. The arguments are: + * - v is the value of the data point where the label is shown. + * - id is the id of the data where the label is shown. + * - i is the index of the data point where the label is shown. + * - j is the sub index of the data point where the label is shown. + * Formatter function can be defined for each data by specifying as an object and D3 formatter function can be set (e.g. d3.format('$')) + */ + labels?: boolean | + { format: FormatFunction } | + { format: { [key: string]: FormatFunction } }; + /** + * Define the order of the data. + * This option changes the order of stacking the data and pieces of pie/donut. If null specified, it will be the order the data loaded. If function specified, it will be used to sort the data and it will recieve the data as argument. + * Available Values: desc, asc, function (data1, data2) { ... }, null + */ + order?: string | ((...data: string[]) => void); + /** + * Define regions for each data. + * The values must be an array for each data and it should include an object that has start, end, style. If start is not set, the start will be the first data point. If end is not set, the end will be the last data point. + * Currently this option supports only line chart and dashed style. If this option specified, the line will be dashed only in the regions. + */ + regions?: { [key: string]: any }; + /** + * Set color converter function. + * This option should a function and the specified function receives color (e.g. '#ff0000') and d that has data parameters like id, value, index, etc. And it must return a string that represents color (e.g. '#00ff00'). + */ + color?: (color: string, d: any) => string | d3.Rgb; + /** + * Set color for each data. + */ + colors?: { [key: string]: string | d3.Rgb }; + /** + * Hide each data when the chart appears. + * If true specified, all of data will be hidden. If multiple ids specified as an array, those will be hidden. + */ + hide?: boolean | Array; + /** + * Set text displayed when empty data. + */ + empty?: { label: { text: string } }; + + selection?: { + enabled?: boolean; + grouped?: boolean; + multiple?: boolean; + draggable?: boolean; + isselectable?: (d?: any) => boolean; + }; + /** + * Set a callback for click event on each data point. + * This callback will be called when each data point clicked and will receive d and element as the arguments. + * - d is the data clicked and element is the element clicked. In this callback, this will be the Chart object. + */ + onclick?: (d: any, element: any) => void; + /** + * Set a callback for mouseover event on each data point. + * This callback will be called when mouse cursor moves onto each data point and will receive d as the argument. + * - d is the data where mouse cursor moves onto. In this callback, this will be the Chart object. + */ + onmouseover?: (d: any, element?: any) => void; + /** + * Set a callback for mouseout event on each data point. + * This callback will be called when mouse cursor moves out each data point and will receive d as the argument. + * - d is the data where mouse cursor moves out. In this callback, this will be the Chart object. + */ + onmouseout?: (d: any, element?: any) => void; + // onselected?: any; + // onunselected?: any; + // ondragstart?: any; + // ondragend?: any; + } + + interface Axis { + /** + * Switch x and y axis position. + */ + rotated?: boolean; + x?: XAxisConfiguration; + y?: YAxisConfiguration; + y2?: YAxisConfiguration; + } + + interface XAxisConfiguration { + /** + * Show or hide x axis. + */ + show?: boolean; + /** + * Set type of x axis (timeseries, category, indexed) + */ + type?: string; + /** + * Set how to treat the timezone of x values. + * If true, treat x value as localtime. If false, convert to UTC internally. + */ + localtime?: boolean; + /** + * Set category names on category axis. + * This must be an array that includes category names in string. If category names are included in the date by data.x option, this is not required. + */ + categories?: Array; + + tick?: XTickConfiguration; + /** + * Set max value of x axis range. + */ + max?: number; + /** + * Set min value of x axis range. + */ + min?: number; + /** + * Set padding for x axis. + * If this option is set, the range of x axis will increase/decrease according to the values. If no padding is needed in the ragen of x axis, 0 should be set. On category axis, this option will be ignored. + */ + padding?: { + left?: number; + right?: number; + }; + /** + * Set height of x axis. + * The height of x axis can be set manually by this option. If you need more space for x axis, please use this option for that. The unit is pixel. + */ + height?: number; + /** + * Set default extent for subchart and zoom. This can be an array or function that returns an array. + */ + extent?: Array | (() => Array); + /** + * Set label on x axis. + * You can set x axis label and change its position by this option. string and object can be passed and we can change the poisiton by passing object that has position key. Available position differs according to the axis direction (vertical or horizontal). If string set, the position will be the default. + * Valid horizontal positions: inner-right (Default), inner-center, inner-left, outer-right, outer-center, outer-left + * Valid vertical positions: inner-top, inner-middle, inner-bottom, outer-top, outer-middle, outer-bottom + */ + label?: string | { text: string; position: string }; + } + + interface YAxisConfiguration { + /** + * Show or hide y axis. + */ + show?: boolean; + /** + * Show y axis inside of the chart. + */ + inner?: boolean; + /** + * Set max value of y axis. + */ + max?: number; + /** + * Set min value of y axis. + */ + min?: number; + /** + * Change the direction of y axis. + * If true set, the direction will be from the top to the bottom. + */ + inverted?: boolean; + /** + * Set center value of y axis. + */ + center?: number; + /** + * Set label on y axis. This option works in the same way as axis.x.label. + * Valid horizontal positions: inner-right (Default), inner-center, inner-left, outer-right, outer-center, outer-left + * Valid vertical positions: inner-top, inner-middle, inner-bottom, outer-top, outer-middle, outer-bottom + */ + label?: string | { text: string; position: string }; + tick?: YTickConfiguration; + /** + * Set padding for y axis. + * You can set padding for y axis to create more space on the edge of the axis. This option accepts object and it can include top and bottom. top, bottom will be treated as pixels. + */ + padding?: { + top?: number; + bottom?: number; + }; + /** + * Set default range of y axis. This option set the default value for y axis when there is no data on init. + */ + default?: Array; + + } + + interface XTickConfiguration { + /** + * Centerise ticks on category axis + */ + centered?: boolean; + /** + * A function to format tick value. Format string is also available for timeseries data. + */ + format?: string | ((x: number | Date) => string | number); + /** + * Setting for culling ticks. + * If true is set, the ticks will be culled, then only limitted tick text will be shown. This option does not hide the tick lines. If false is set, all of ticks will be shown. + */ + culling?: boolean | CullingConfiguration; + /** + * The number of x axis ticks to show. + * This option hides tick lines together with tick text. If this option is used on timeseries axis, the ticks position will be determined precisely and not nicely positioned (e.g. it will have rough second value). + */ + count?: number; + /** + * Fit x axis ticks. + * If true set, the ticks will be positioned nicely. If false set, the ticks will be positioned according to x value of the data points. + */ + fit?: boolean; + /** + * Set the x values of ticks manually. + * If this option is provided, the position of the ticks will be determined based on those values. This option works with timeseries data and the x values will be parsed accoding to the type of the value and data.xFormat option. + */ + values?: Array | Array; + /** + * Rotate x axis tick text. If you set negative value, it will rotate to opposite direction. + */ + rotate?: number; + /** + * Show x axis outer tick. + */ + outer?: boolean; + multiline?: boolean; // Undocumented + } + + interface YTickConfiguration { + /** + * Set formatter for y axis tick text. + * This option accepts d3.format object as well as a function you define. + */ + format?: (x: number) => string; + /** + * Show or hide outer tick. + */ + outer?: boolean; + /** + * Set the y values of ticks manually. + */ + values?: Array; + /** + * The number of y axis ticks to show. + * The position of the ticks will be calculated precisely, so the values on the ticks will not be rounded nicely. In the case, axis.y.tick.format or axis.y.tick.values will be helpful. + */ + count?: number; + } + + interface CullingConfiguration { + /** + * The number of tick texts will be adjusted to less than this value. + */ + max: number; + } + + interface Grid { + x?: { + /** + * Show grids along x axis. + */ + show?: boolean; + /** + * Show additional grid lines along x axis. + * This option accepts array including object that has value, text, position and class. text, position and class are optional. For position, start, middle and end (default) are available. + * If x axis is category axis, value can be category name. If x axis is timeseries axis, value can be date string, Date object and unixtime integer. + */ + lines?: Array; + }; + y?: { + /** + * Show grids along y axis. + */ + show?: boolean; + /** + * Show additional grid lines along y axis. + * This option accepts array including object that has value, text, position and class. + */ + lines?: Array; + }; + } + + interface LineOptions { + value: number; + text?: string; + axis?: string; + position?: string; + class?: string; + } + + interface RegionOptions { + axis?: string; + start?: string | number | Date; + end?: string | number | Date; + class?: string; + } + + interface LegendOptions { + /** + * Show or hide legend. + */ + show?: boolean; + /** + * Hide legend + * If true given, all legend will be hidden. If string or array given, only the legend that has the id will be hidden. + */ + hide?: boolean | ArrayOrString; + /** + * Change the position of legend. + * Currently bottom, right and inset are supported. + */ + position?: string; + /** + * Change inset legend attributes. + * This option accepts object that has the keys anchor, x, y and step. + * anchor decides the position of the legend. These anchors are available: top-left, top-right, bottom-left, bottom-right + * x and y set the position of the legend based on the anchor. + * step defines the max step the lagend has (e.g. If 2 set and legend has 3 legend item, the legend 2 columns). + */ + inset?: { + anchor?: string; + x?: number; + y?: number; + step?: number; + }; + + item?: { + /** + * Set click event handler to the legend item. + */ + onclick?: (id: any) => void; + /** + * Set mouseover event handler to the legend item. + */ + onmoouseover?: (id: any) => void; + /** + * Set mouseout event handler to the legend item. + */ + onmouseout?: (id: any) => void; + }; + } + + interface TooltipOptions { + /** + * Show or hide tooltip. + */ + show?: boolean; + /** + * Set if tooltip is grouped or not for the data points. + */ + grouped?: boolean; + format?: { + /** + * Set format for the title of tooltip. Specified function receives x of the data point to show. + */ + title?: (x: any) => string; + /** + * Set format for the name of each data in tooltip. Specified function receives name, ratio, id and index of the data point to show. ratio will be undefined if the chart is not donut/pie/gauge. + */ + name?: (name: string, ratio: number, id: string, index: number) => string; + /** + * Set format for the value of each data in tooltip. + * Specified function receives name, ratio, id and index of the data point to show. ratio will be undefined if the chart is not donut/pie/gauge. + * If undefined returned, the row of that value will be skipped. + */ + value?: (name: string, ratio: number, id: string, index: number) => string; + }; + /** + * Set custom position for the tooltip. This option can be used to modify the tooltip position by returning object that has top and left. + */ + position?: (data: any, width: number, height: number, element: any) => { top: number; left: number }; + /** + * Set custom HTML for the tooltip. + * Specified function receives data, defaultTitleFormat, defaultValueFormat and color of the data point to show. If tooltip.grouped is true, data includes multiple data points. + */ + contents?: (data: any, defaultTitleFormat: string, defaultValueFormat: string, color: any) => string; + } + + interface SubchartOptions { + /** + * Show sub chart on the bottom of the chart. + */ + show?: boolean; + size?: { + /** + * Change the height of the subchart. + */ + height: number; + }; + /** + * Set callback for brush event. + * Specified function receives the current zoomed x domain. + */ + onbrush?: (domain: any) => void; + } + + interface ZoomOptions { + /** + * Enable zooming. + */ + enabled?: boolean; + /** + * Enable to rescale after zooming. If true set, y domain will be updated according to the zoomed region. + */ + rescale?: boolean; + /** + * Change zoom extent. + */ + extent?: [number, number]; + /** + * Set callback that is called when the chart is zooming. Specified function receives the zoomed domain. + */ + onzoom?: (domain: any) => void; + /** + * Set callback that is called when zooming starts. Specified function receives the zoom event. + */ + onzoomstart?: (event: Event) => void; + /** + * Set callback that is called when zooming ends. Specified function receives the zoomed domain. + */ + onzoomend?: (domain: any) => void; + } + + interface PointOptions { + /** + * Whether to show each point in line. + */ + show?: boolean; + /** + * The radius size of each point. + */ + r?: number; + + focus?: { + expand: { + /** + * Whether to expand each point on focus. + */ + enabled?: boolean; + /** + * The radius size of each point on focus. + */ + r?: number + }; + }; + + select?: { + /** + * The radius size of each point on selected. + */ + r?: number; + }; + } + + interface ChartAPI { + /** + * This API highlights specified targets and fade out the others. + * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be highlighted. + */ + focus(targetIds?: ArrayOrString): void; + /** + * This API fades out specified targets and reverts the others. + * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be faded out. + */ + defocus(targetIds?: ArrayOrString): void; + /** + * This API reverts specified targets. + * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be reverted. + */ + revert(targetIds?: ArrayOrString): void; + + /** + * This API shows specified targets. + * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be shown. + * If withLegend is set true, legend will be shown together with the specified data. + */ + show(targetIds?: ArrayOrString, options?: { withLegend: boolean }): void; + /** + * This API hides specified targets. + * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be hidden. + * If withLegend is set true, legend will be hidden together with the specified data. + */ + hide(targetIds?: ArrayOrString, options?: { withLegend: boolean }): void; + /** + * This API toggles (shows or hides) specified targets. + * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be toggles. + * If withLegend is set true, legend will be toggled together with the specified data. + */ + toggle(targetIds?: ArrayOrString, options?: { withLegend: boolean }): void; + /** + * Load data to the chart. + * If url, json, rows and columns given, the data will be loaded. If data that has the same target id is given, the chart will be updated. Otherwise, new target will be added. + * If classes given, the classes specifed by data.classes will be updated. classes must be Object that has target id as keys. + * If categories given, the categories specifed by axis.x.categories or data.x will be updated. categories must be Array. + * If axes given, the axes specifed by data.axes will be updated. axes must be Object that has target id as keys. + * If colors given, the colors specifed by data.colors will be updated. colors must be Object that has target id as keys. + * If type or types given, the type of targets will be updated. type must be String and types must be Object. + * If unload given, data will be unloaded before loading new data. If true given, all of data will be unloaded. If target ids given as String or Array, specified targets will be unloaded. + * If done given, the specified function will be called after data loded. + * NOTE: unload should be used if some data needs to be unloaded simultaneously. If you call unload API soon after/before load instead of unload param, chart will not be rendered properly because of cancel of animation. + * NOTE: done will be called after data loaded, but it's not after rendering. It's because rendering will finish after some transition and there is some time lag between loading and rendering. + */ + load(args: { + url?: string; + json?: Object; + keys?: { x?: string; value: Array; } + rows?: Array; + columns?: Array; + classes?: { [key: string]: string }; + categories?: Array; + axes?: { [key: string]: string }; + colors?: { [key: string]: string | d3.Rgb }; + type?: string; + types?: { [key: string]: string }; + unload?: boolean | ArrayOrString; + done?: () => any; + }): void; + /** + * Unload data to the chart. + * You can specify multiple targets by giving an array that includes id as String. If no argument is given, all of targets will be toggles. + * If ids given, the data that has specified target id will be unloaded. ids should be String or Array. If ids is not specified, all data will be unloaded. + * If done given, the specified function will be called after data loded. + * NOTE: If you call load API soon after/before unload, unload param of load should be used. Otherwise chart will not be rendered properly because of cancel of animation. + * NOTE: done will be called after data loaded, but it's not after rendering. It's because rendering will finish after some transition and there is some time lag between loading and rendering. + */ + unload(targetIds?: TargetIds, done?: () => any): any; + /** + * Flow data to the chart. By this API, you can append new data points to the chart. + * If json, rows and columns given, the data will be loaded. If data that has the same target id is given, the chart will be appended. Otherwise, new target will be added. One of these is required when calling. If json specified, keys is required as well as data.json + * If to is given, the lower x edge will move to that point. If not given, the lower x edge will move by the number of given data points. + * If length is given, the lower x edge will move by the number of this argument. + * If duration is given, the duration of the transition will be specified value. If not given, transition.duration will be used as default. + * If done is given, the specified function will be called when flow ends. + */ + flow(args: { + json?: Object; + keys?: { x?: string; value: Array; } + rows?: Array; + columns?: Array; + to?: any; + length?: number; + duration?: number; + done?: () => any; + }): void; + /** + * Change data point state to selected. By this API, you can select data points. To use this API, data.selection.enabled needs to be set true. + * @param ids Specify target ids to be selected. If this argument is not given, all targets will be the candidate. + * @param indices Specify indices to be selected. If this argument is not given, all data points will be the candidate. + * @param resetOthers If this argument is set true, the data points that are not specified by ids, indices will be unselected. + */ + select(ids?: Array, indices?: Array, resetOthers?: boolean): void; + /** + * Change data point state to unselected. By this API, you can unselect data points. To use this API, data.selection.enabled needs to be set true. + * @param ids Specify target ids to be unselected. If this argument is not given, all targets will be the candidate. + * @param indices Specify indices to be unselected. If this argument is not given, all data points will be the candidate. + */ + unselect(ids?: Array, indices?: Array): void; + /** + * Get selected data points. By this API, you can get selected data points information. To use this API, data.selection.enabled needs to be set true. + * @param targetId You can filter the result by giving target id that you want to get. If not given, all of data points will be returned. + */ + selected(targetId?: string): Data; + /** + * Change the type of the chart. + * @param type Specify the type to be transformed. The types listed in data.type can be used. + * @param targetIds Specify targets to be transformed. If not given, all targets will be the candidate. + */ + transform(type: string, targetIds?: ArrayOrString): void; + /** + * Update groups for the targets. + * @param groups This argument needs to be an Array that includes one or more Array that includes target ids to be grouped. + */ + groups(groups: Array>): void; + + xgrids: GridOperations; + + ygrids: GridOperations; + + regions: { + /** + * Update regions. + * @param regions Regions will be replaced with this argument. The format of this argument is the same as regions. + */ + (regions: Array): void; + /** + * Add new region. This API adds new region instead of replacing like regions. + * @param grids New region will be added. The format of this argument is the same as regions and it's possible to give an Object if only one region will be added. + */ + add(regions: Array | Object): void; + /** + * Remove regions. This API removes regions. + * @param args This argument should include classes. If classes is given, the regions that have one of the specified classes will be removed. If args is not given, all of regions will be removed. + */ + remove(args?: { value?: number | string; class?: string }): void; + }; + + data: { + /** + * Get data loaded in the chart. + * @param targetIds If this argument is given, this API returns the specified target data. If this argument is not given, all of data will be returned. + */ + (targetIds?: ArrayOrString): Data; + /** + * Get data shown in the chart. + * @param targetIds If this argument is given, this API filters the data with specified target ids. If this argument is not given, all shown data will be returned. + */ + shown(targetIds?: ArrayOrString): Data; + /** + * Get values of the data loaded in the chart. + * @param targetIds This API returns the values of specified target. If this argument is not given, null will be retruned. + */ + values(targetIds?: ArrayOrString): Array; + /** + * Get and set names of the data loaded in the chart. + * @param names If this argument is given, the names of data will be updated. If not given, the current names will be returned. The format of this argument is the same as data.names. + */ + names(names?: { [key: string]: string }): { [key: string]: string }; + /** + * Get and set colors of the data loaded in the chart. + * @param colors If this argument is given, the colors of data will be updated. If not given, the current colors will be returned. The format of this argument is the same as data.colors. + */ + colors(colors?: { [key: string]: string | d3.Rgb }): { [key: string]: string }; + /** + * Get and set axes of the data loaded in the chart. + * @param axes If this argument is given, the axes of data will be updated. If not given, the current axes will be returned. The format of this argument is the same as data.axes. + */ + axes(axes?: { [key: string]: string }): { [key: string]: string }; + }; + + /** + * Gets and sets the value a category + * @param index Index of the category to get or set + * @param category: Value of the category to update + */ + category(index: number, category?: string): string; + + /** + * Get and set the categories + * @param categories: Value of the categories to update + */ + categories(categories?: Array): Array; + + /** + * Get the color for the specified targetId + */ + color(targetId: string): string; + + /** + * Get and set x values for the chart. + * @param x If x is given, x values of every target will be updated. If no argument is given, current x values will be returned as an Object whose keys are the target ids. + */ + x(x?: PrimitiveArray): PrimitiveArray; + + /** + * Get and set x values for the chart. + * @param x If x is given, x values of every target will be updated. If no argument is given, current x values will be returned as an Object whose keys are the target ids. + */ + xs(xs?: { [key: string]: PrimitiveArray }): { [key: string]: PrimitiveArray }; + + axis: { + /** + * Get and set axis labels. + * @param labels If labels is given, specified axis' label will be updated. + */ + labels(labels?: { [key: string]: string }): { [key: string]: string } + /** + * Get and set axis min value. + * @param min If min is given, specified axis' min value will be updated. If no argument is given, the current min values for each axis will be returned. + */ + min(min?: number | { [key: string]: number }): number | { [key: string]: number } + /** + * Get and set axis max value. + * @param max If max is given, specified axis' max value will be updated. If no argument is given, the current max values for each axis will be returned. + */ + max(max?: number | { [key: string]: number }): number | { [key: string]: number } + /** + * Get and set axis min and max value. + * @param range If range is given, specified axis' min and max value will be updated. If no argument is given, the current min and max values for each axis will be returned. + */ + range(range?: { min?: number | { [key: string]: number }; max?: number | { [key: string]: number } }): { min: number | { [key: string]: number }; max: number | { [key: string]: number } } + }; + + legend: { + /** + * Show legend for each target. + * @param targetIds If targetIds is given, specified target's legend will be shown. If only one target is the candidate, String can be passed. If no argument is given, all of target's legend will be shown. + */ + show(targetIds?: ArrayOrString): void; + /** + * Hide legend for each target. + * @param targetIds If targetIds is given, specified target's legend will be hidden. If only one target is the candidate, String can be passed. If no argument is given, all of target's legend will be hidden. + */ + hide(targetIds?: ArrayOrString): void; + }; + + zoom: { + /** + * Zoom by giving x domain. + * @param domain If domain is given, the chart will be zoomed to the given domain. If no argument is given, the current zoomed domain will be returned. + */ + (domain?: Array): Array; + + /** + * Enable and disable zooming. + * @param enabled If enabled is true, the feature of zooming will be enabled. If false is given, it will be disabled. + */ + enable(enabled: boolean): void; + }; + + /** + * Unzoom to the original domain. + */ + unzoom(): void; + + /** + * Resize the chart. If no size is specified it will resize to fit. + * @param size This argument should include width and height in pixels. + */ + resize(size?: { width?: number; height?: number }): void; + + /** + * Force to redraw. + */ + flush(): void; + + /** + * Reset the chart object and remove element and events completely. + */ + destroy(): void; + } + + interface GridOperations { + /** + * Update the x/y grid lines. + * @param grids X/Y grid lines will be replaced with this argument. The format of this argument is the same as grid.x.lines or grid.y.lines. + */ + (grids: Array): void; + /** + * Add x/y grid lines. This API adds new x/y grid lines instead of replacing like xgrids. + * @param grids New x/y grid lines will be added. The format of this argument is the same as grid.x.lines or grid.y.lines and it's possible to give an Object if only one line will be added. + */ + add(grids: Array | Object): void; + /** + * Remove x/y grid lines. This API removes x/y grid lines. + * @param args This argument should include value or class. If value is given, the x/y grid lines that have specified x/y value will be removed. If class is given, the x/y grid lines that have specified class will be removed. If args is not given, all of x/y grid lines will be removed. + */ + remove(args?: { class?: string; value?: number | string }): void; + } + + export function generate(config: ChartConfiguration): ChartAPI; +} diff --git a/c3/tsconfig.json b/c3/tsconfig.json new file mode 100644 index 0000000000..0db9fbc685 --- /dev/null +++ b/c3/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "c3-tests.ts" + ] +} \ No newline at end of file diff --git a/cal-heatmap/cal-heatmap-tests.ts b/cal-heatmap/cal-heatmap-tests.ts index 4a7b0cb949..f19a88c3c1 100644 --- a/cal-heatmap/cal-heatmap-tests.ts +++ b/cal-heatmap/cal-heatmap-tests.ts @@ -1,6 +1,6 @@ -/// -/// -/// + +/// +/// var cal = new CalHeatMap(); cal.init(); diff --git a/cal-heatmap/cal-heatmap.d.ts b/cal-heatmap/cal-heatmap.d.ts deleted file mode 100644 index 85a20d6d9d..0000000000 --- a/cal-heatmap/cal-heatmap.d.ts +++ /dev/null @@ -1,514 +0,0 @@ -// Type definitions for cal-heatmap v3.5.4 -// Project: https://github.com/wa0x6e/cal-heatmap -// Definitions by: Chris Baker -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace CalHeatMap -{ - interface CalHeatMapStatic - { - new (): CalHeatMap; - } - - interface CalHeatMap - { - /** - * Initialise the CalHeatMap with the specified options - * @param {InitOptions} options The CalHeatMap options - */ - init(options?: InitOptions): void; - - options: RuntimeOptions; - - // Various update mode when using the update() API - /** Reset the whole calendar data before inserting the new data. */ - RESET_ALL_ON_UPDATE: number; - /** - * Update only the dates (subDomain) you pass in the data argument, replace their value by the new ones. - * All other dates are leaved untouched. - */ - RESET_SINGLE_ON_UPDATE: number; - /** - * Instead of replacing a date's value by a new one, increment it by the new value. All other dates are leaved untouched. - * That's the one you want to use of you're populating the calendar in realtime! - */ - APPEND_ON_UPDATE: number; - - /** - * Shift the calendar n domains back - * @param {number} n The number of domains to shift back. The default is 1. - */ - previous(n?: number): void; - /** - * Shift the calendar n domains forward - * @param {number} n The number of domains to shift forward. The default is 1. - */ - next(n?: number): void; - /** - * Jump the calendar to the specified date - * This method will shift the calendar backward or forward, until the domain containing the specified date is visible. - * @param {Date} date The date to jump to. - * @param {boolean} reset Whether to set the domain with the specified as the calendar's first domain. - */ - jumpTo(date: Date, reset?: boolean): void; - /** Reset the calendar back to the start date */ - rewind(): void; - /** - * Update the calendar with new data - * Use update() when you want to refresh the calendar with a new set of data. - * Particularly useful if you're filling the calendar in realtime, or if you want to display a subset of the current data. - * @param {string|Object} data Accept the same format as the data option. - * @param {} afterLoad Whether to execute the afterLoad() callback to convert your data into the json object, expected by cal-heatmap. - * It can also directly takes a function, in case your data can not be converted with the afterLoad() function you defined. - * @param {} updateMode Define how to insert the new data into the calendar. - * Accepted values are: - * Instance.RESET_ALL_ON_UPDATE (default) Reset the whole calendar data before inserting the new data. - * Instance.RESET_SINGLE_ON_UPDATE Update only the dates (subDomain) you pass in the data argument, - * replace their value by the new ones. All other dates are leaved untouched. - * Instance.APPEND_ON_UPDATE Instead of replacing a date's value by a new one, increment it by the new value. - * All other dates are leaved untouched. That's the one you want to use of you're - * populating the calendar in realtime! - */ - update(data: string | Object, afterLoad?: boolean | Function, updateMode?: number): void; - /** - * Change the highlighted dates. - * Takes an array of Date object. Can also accepts the now string, equivalent to Date.now(). - * @param {string|Date|Date[]} dates The date or dates to highlight. - */ - highlight(dates: string | Date | Date[]): void; - /** - * Return the SVG source code with the appropriate CSS - * The returned string code is valid and ready to be placed in a .svg file. - * @returns SVG source code with the appropriate CSS. - */ - getSVG(): string; - /** - * Change the legend settings and/or threshold - * When called without arguments, setLegend() will just redraw the legend. - * @param {} legend Same as legend : an array of thresholds - * @param {} legendColor Same as legendColors : an object with the heatmap's colors, or an array of 2 colors - */ - setLegend(legend?: number[], legendColors?: LegendColor | string[]): void; - /** - * Remove the legend from the calendar - * Settings are kept and you can re-add the legend with the same settings using showLegend(). - */ - removeLegend(): void; - /** Display the legend, if not already shown. */ - showLegend(): void; - /** - * Remove the calendar from the DOM - * Remember to self-assign the result of destroy() to your calendar instance, or it'll lead to a memory leak. - * @param {Function} callback function that will be executed when the calendar is removed from the DOM, at the end of the animation. - * @returns always returns null. - */ - destroy(callback?: Function): CalHeatMap; - } - - interface LegendColor - { - /** Color of the smallest value on the legend */ - min: string; - /** Color of the highest value on the legend */ - max: string; - /** Color for the dates with value == 0 */ - empty?: string; - /** Base color of the date cells */ - base?: string; - /** Color for the special value */ - overflow?: string; - } - - interface InitOptions - { - // ================================================ - // Presentation - // ================================================ - - /** DOM node to insert the calendar in. Default: "#cal-heatmap" */ - itemSelector?: string | HTMLElement | Element | EventTarget; - - /** - * Type of domain. Default: "hour" - * Valid domains: {"hour", "day", "week", "month", "year"} - */ - domain?: string; - - /** - * Type of subDomain. Default: "min" - * Valid subDomains: {"min", "x_min", "hour", "x_hour", "day", "x_day", "week", "x_week", "month", "x_month"} - */ - subDomain?: string; - - /** Number of domain to display. Default: 12 */ - range?: number; - - /** Size of each subDomain cell, in pixels. Default: 10 */ - cellSize?: number; - - /** Space between each subDomain cell, in pixel. Default: 2 */ - cellPadding?: number; - - /** subDomain cell's border radius, for rounder corner, in pixel. Default: 0 */ - cellRadius?: number; - - /** Space between each domain, in pixel. Default: 2 */ - domainGutter?: number; - - /** - * Margin around each domain, in pixel. Default: [0,0,0,0] - * Ordered like in CSS (top, right, bottom, left), it also accepts CSS like values - */ - domainMargin?: number | number[]; - - /** - * Whether to enable domain dynamic width and height. Default: true - * Some domain>subdomain couple, like month>days, doesn't always have the same number of - * subDomain cells. Some months have 6 weeks, some only 4. - * With dynamic dimension enabled, the domain width and height will be adjusted to fit the - * domain content, whereas when it's disabled, all domains will have the same dimension : the biggest. - */ - domainDynamicDimension?: boolean; - - /** To display the calendar vertically, with each domain one under the other. Default: false */ - verticalOrientation?: boolean; - - /** Position and alignment of the domain label. */ - label?: Label; - - /** - * Control the number of columns to split the domain dates into. Default: null - * Each domain is split into an arbitrary number of columns (or rows depending on the - * reading direction). You can overwrite that number with colLimit, and force all dates on the - * same line, or split them into more columns. - * That setting limit the maximum number of columns, and doesn't necessary means that each rows will - * contains that number of columns. - */ - colLimit?: number; - - /** Control the number of rows to split the domain dates into. Default: null - * If rowLimit and colLimit are both used, rowLimit will be ignored. */ - rowLimit?: number; - - /** Whether to display a tooltip when hovering over a date. Default: false */ - tooltip?: boolean; - - // ================================================ - // Data - // ================================================ - - /** - * Starting date of the calendar. Default: new Date() - * It doesn't have to be precise, the calendar will not start at that date, but at the first domain containing that date. - */ - start?: Date; - /** - * Data used to fill the calendar. Default: "" - * String is interpreted as a URL to an API, which should be returning the data used to fill the calendar. - */ - - data?: string | Object; - - /** - * Engine used to parse the data. Default: json - * Valid values: - * "json" - Interpret the data as json. - * "csv" - Interpret the data as csv. - * "tsv" - Interpret the data exactly like csv, but are delimited with a tab character, instead of comma. - * "txt" - Just return the data as a string. - */ - dataType?: string; - - /** - * Highlight selected subDomain cells. Default: false - * Takes an array of Date object. Can also accepts the now string, equivalent to Date.now(). - */ - highlight?: string | string[] | Date[] | any[]; - - /** Whether to start the week on Monday, instead of Sunday. Default: true */ - weekStartOnMonday?: boolean; - - /** - * Lower limit of the domain navigation, preventing navigating beyond a certain date. Default: null - * When set, calling previous() will only work only until the leftmost domain containing minDate. - * Like with start, minDate does not have to be precise, and just have to be a date inside the domain. - * previous() will always return true, unless the domain containing minDate is reached, in which case, it'll return false. - */ - minDate?: Date; - - /** Upper limit of the domain navigation, preventing navigating beyond a certain date. Default: null */ - maxDate?: Date; - - /** - * Whether to consider missing date:value couple in the data source as equal to 0. Default: false - * By default, when the a date is not associated to a value, it's considered as null, and rendered as a no value cell. - * You should ask yourself, if the API is not returning result for a date, is it because there is really no value - * associated to this date, or because it's supposed to be equal to 0, and it's skipped in order to save bandwidth ? - */ - considerMissingDataAsZero?: boolean; - - // ================================================ - // Legend - // ================================================ - - /** Assign each range of values to a color. Default: [10, 20, 30, 40] */ - legend?: number[]; - - /** Whether to display the legend. Default: true */ - displayLegend?: boolean; - - /** Size of the legend cells, in pixels. Default: 10 */ - legendCellSize?: number; - - /** Padding between each legend cell, in pixels. Default: 2 */ - legendCellPadding?: number; - - /** Margin around the legend, in pixels. Default: [10, 0, 0, 0] */ - legendMargin?: number | number[]; - - /** - * Vertical position of the legend. Default: "bottom" - * Valid values: - * "top" - Place the legend above the calendar - * "center" - Place the legend on the calendar's side - * Use with legendHorizontalPosition, to position the legend on the left (default) or on the right. - * "bottom" - Place the legend on below the calendar - */ - legendVerticalPosition?: string; - - /** - * Horizontal position of the legend. Default: "left" - * Valid values: - * "left" - Align the legend to the left - * "center" - Center the legend - * "right" - Align the legend to the right - */ - legendHorizontalPosition?: string; - - /** - * Orientation of the legend. Default: "horizontal" - * legendOrientation is best used together with legendHorizontalPosition when the legend is positioned on the side. - * Valid values: - * "horizontal" - Legend is displayed horizontally, from left to right - * "vertical" - Legend is displayed vertically, from top to bottom - */ - legendOrientation?: string; - - /** - * Set of colors to automagically compute the heatmap colors. - * Instead of relying on the CSS for your heatmap's colors, you can also set the heatmap's colors directly with - * cal-heatmap on initialization, or even dynamically change them after. - * All legend settings can be changed dynamically after calendar initialisation, with setLegend(). - */ - legendColors?: LegendColor | string[]; - - // ================================================ - // i18n - // ================================================ - - /** - * Name of the entity you're representing on the calendar. - * Takes an array of string, with the first index as the singular form, and the second index the plural form. - * For the lazy, you can also pass a simple string, ar a single element array, and it'll automatically guess - * the plural form, as long as it's the singular form plus the "s" suffix. - */ - itemName?: string | string[]; - /** - * Format of the title displayed when hovering a subDomain. - * Some template strings are available, and enclosed in braces. - * {name} Name of the entity represented in the calendar (see itemName) - * {count} The value associated to the date. - * {date} The date of the cell. It's automatically formatted according to the type of subDomain. - * See subDomainDateFormat to further customize that date formatting. - * {connector} An English preposition placed before a datetime (on Monday, at 15:00, etc.). Each subDomain - * have their own default connector, corresponding to the default date format. - */ - subDomainTitleFormat?: SubDomainFormatTemplates; - /** - * Format of the {date} template string inside subDomainTitleFormat. - * {date} is by default formatted according to the subDomain type. - * subDomainFormat can accept any string with directive accepted by d3.time.format(), like "%Y-%m-%d". - * As d3.time.format() will only output English dates, subDomainDateFormat can also accept a function, - * with the subDomain date as the argument. - */ - subDomainDateFormat?: string | Function; - /** - * Format of the text inside a subDomain cell. - * Disabled by default, you can display a text inside each subDomain cell. - * Works exactly like subDomainDateFormat, except that the function takes the cell value as second argument. - */ - subDomainTextFormat?: string | Function; - /** - * Format of the domain label. - * Works exactly like subDomainDateFormat, and will format the domain label with any string accepted by d3.time.format(), or a function. - * To not display the domain label, set domainLabelFormat to "" (empty string). - */ - domainLabelFormat?: string | Function; - /** - * Formatting of the legend title, displayed when hovering a legend cell. - * Some template strings are available, and enclosed in braces. - * {name} Name of the entity represented in the calendar (see itemName) - * {min} The first value of the legend array. - * {max} The last value of the legend array. - * {down} The lower bound of a color - * {up} The upper bound of a color - */ - legendTitleFormat?: LegendTitleTemplates; - - // ================================================ - // Other - // ================================================ - - /** Animation duration, in milliseconds. Default value: 500 */ - animationDuration?: number; - /** - * Will attach the previous() event to the specified element, on a mouse click, shifting the calendar one domain back. Default value: false - * If you want to shift by more than one domain, see the previous() method. - */ - previousSelector?: string | HTMLElement; - /** - * Will attach the next() event to the specified element, on a mouse click, shifting the calendar one domain forward. Default value: false - * If you want to shift by more than one domain, see the next() method. - */ - nextSelector?: string | HTMLElement; - /** - * The calendar instance namespace. - * If you have more than one instance of Cal-Heatmap, you should assign each instance its own namespace, in order to isolate each instance event handler. - */ - itemNamespace?: string; - - // ================================================ - // Events - // ================================================ - - /** Called after a mouse click event on a subDomain cell. */ - onClick?: (date: Date, value: number) => void; - /** Called after drawing the empty calendar, and before filling it with data. */ - afterLoad?: () => void; - /** - * Called after shifting the calendar one domain back. - * The date argument is the start date of the domain that was added. - */ - afterLoadPreviousDomain?: (date: Date) => void; - /** - * Called after shifting the calendar one domain forward. - * The date argument is the start date of the domain that was added. - */ - afterLoadNextDomain?: (date: Date) => void; - /** - * Called after drawing and filling the calendar. - * Useful in case you're loading data via ajax, as it's loading data asynchronously. This event will wait for the ajax - * request to complete before triggering. - * This event will only trigger once, on the initial setup. See afterLoadPreviousDomain and afterLoadNextDomain for - * callback events after a domain navigation. - */ - onComplete?: () => void; - /** - * Called after getting the data from source, but before filling the calendar. - * This callback must return a json object formatted in the expected data format. - * afterLoadData() is used to do some works on the data, especially when the data source is not returning data in the expected format. - */ - afterLoadData?: (data: any) => DataFormat; - /** - * Triggered after previous(), when the incoming domain is containing minDate. - * When the leftmost domain set by minDate is loaded into the calendar, onMinDomainReached() will be triggered with true as argument. - * This event is useful if you want to disable your previous button, since there is no more previous domains to load. - * In order to reverse the action, onMinDomainReached() will be called with false as argument afer next(), only once, and only if the - * leftmost domain is not the lower limit domain anymore. - */ - onMinDomainReached?: (reached: boolean) => void; - /** - * Triggered after next(), when the incoming domain is containing maxDate. - * See onMinDomainReached(). - */ - onMaxDomainReached?: (reached: boolean) => void; - } - - interface RuntimeOptions extends InitOptions - { - /** Margin around each domain, in pixels. Ordered like in CSS (top, right, bottom, left) */ - domainMargin: number[]; - /** Margin around the legend, in pixels. Ordered like in CSS (top, right, bottom, left) */ - legendMargin: number[]; - /** List of dates to highlight */ - highlight: Date[]; - /** - * Name of the items to represent in the calendar. - * First index is singular form, and the second index, the plural form. - */ - itemName: string[]; - } - - interface LegendTitleTemplates - { - /** Formatting of the smallest (leftmost) value of the legend. Default value: "less than {min} {name}" */ - lower?: string; - /** Formatting of all the value but the first and the last. Default value: "between {down} and {up} {name}" */ - inner?: string; - /** Formatting of the biggest (rightmost) value of the legend. Default value: "more than {max} {name}" */ - upper?: string; - } - - interface SubDomainFormatTemplates - { - /** Format of the title when there is no value associated to the date. Default value: "{date}" */ - empty?: string; - /** Format of the title when it's associated to a value. Default value: "{count} {name} {connector} {date}" */ - filled?: string; - } - - interface DataFormat - { - /** timestamp are in seconds, value can be any number (integer or float) */ - [timestamp: string]: number; - } - - interface LabelOffset - { - x: number; - y: number; - } - - /** Position and alignment of the domain label. */ - interface Label - { - /** - * Position of the label, relative to the domain. Default: "bottom" - * Valid values: {"top", "right", "bottom", "left"} - */ - position?: string; - - /** - * Horizontal align of the domain. Default: "center" - * Valid values: {"left", "center", "right"} - */ - align?: string; - /** - * Rotation for a vertical label. Default: null - * Valid values: {null, "left", "right"} - */ - rotate?: string; - /** - * Only used when label is rotated, defines the width of the label. Default: 100 - * Valid values: any intger - */ - width?: number; - /** - * More control about label positioning, if the default value does not fit your need, - * especially when label is rotated, or when using a big font-size. Default: {x:0, y:0} - */ - offset?: LabelOffset; - /** - * Height of the domain label in pixels. - * By leaving it to null, the label will be set to 2 times the height of the subDomain cell. - * If you want to remove the label, set domainLabelFormat to "" (empty string), instead - * of setting the label height to 0. Default: null - * Valid values: any integer - */ - height?: number; - } -} - -declare var CalHeatMap: CalHeatMap.CalHeatMapStatic; diff --git a/cal-heatmap/index.d.ts b/cal-heatmap/index.d.ts new file mode 100644 index 0000000000..356487c3e9 --- /dev/null +++ b/cal-heatmap/index.d.ts @@ -0,0 +1,514 @@ +// Type definitions for cal-heatmap v3.5.4 +// Project: https://github.com/wa0x6e/cal-heatmap +// Definitions by: Chris Baker +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace CalHeatMap +{ + interface CalHeatMapStatic + { + new (): CalHeatMap; + } + + interface CalHeatMap + { + /** + * Initialise the CalHeatMap with the specified options + * @param {InitOptions} options The CalHeatMap options + */ + init(options?: InitOptions): void; + + options: RuntimeOptions; + + // Various update mode when using the update() API + /** Reset the whole calendar data before inserting the new data. */ + RESET_ALL_ON_UPDATE: number; + /** + * Update only the dates (subDomain) you pass in the data argument, replace their value by the new ones. + * All other dates are leaved untouched. + */ + RESET_SINGLE_ON_UPDATE: number; + /** + * Instead of replacing a date's value by a new one, increment it by the new value. All other dates are leaved untouched. + * That's the one you want to use of you're populating the calendar in realtime! + */ + APPEND_ON_UPDATE: number; + + /** + * Shift the calendar n domains back + * @param {number} n The number of domains to shift back. The default is 1. + */ + previous(n?: number): void; + /** + * Shift the calendar n domains forward + * @param {number} n The number of domains to shift forward. The default is 1. + */ + next(n?: number): void; + /** + * Jump the calendar to the specified date + * This method will shift the calendar backward or forward, until the domain containing the specified date is visible. + * @param {Date} date The date to jump to. + * @param {boolean} reset Whether to set the domain with the specified as the calendar's first domain. + */ + jumpTo(date: Date, reset?: boolean): void; + /** Reset the calendar back to the start date */ + rewind(): void; + /** + * Update the calendar with new data + * Use update() when you want to refresh the calendar with a new set of data. + * Particularly useful if you're filling the calendar in realtime, or if you want to display a subset of the current data. + * @param {string|Object} data Accept the same format as the data option. + * @param {} afterLoad Whether to execute the afterLoad() callback to convert your data into the json object, expected by cal-heatmap. + * It can also directly takes a function, in case your data can not be converted with the afterLoad() function you defined. + * @param {} updateMode Define how to insert the new data into the calendar. + * Accepted values are: + * Instance.RESET_ALL_ON_UPDATE (default) Reset the whole calendar data before inserting the new data. + * Instance.RESET_SINGLE_ON_UPDATE Update only the dates (subDomain) you pass in the data argument, + * replace their value by the new ones. All other dates are leaved untouched. + * Instance.APPEND_ON_UPDATE Instead of replacing a date's value by a new one, increment it by the new value. + * All other dates are leaved untouched. That's the one you want to use of you're + * populating the calendar in realtime! + */ + update(data: string | Object, afterLoad?: boolean | Function, updateMode?: number): void; + /** + * Change the highlighted dates. + * Takes an array of Date object. Can also accepts the now string, equivalent to Date.now(). + * @param {string|Date|Date[]} dates The date or dates to highlight. + */ + highlight(dates: string | Date | Date[]): void; + /** + * Return the SVG source code with the appropriate CSS + * The returned string code is valid and ready to be placed in a .svg file. + * @returns SVG source code with the appropriate CSS. + */ + getSVG(): string; + /** + * Change the legend settings and/or threshold + * When called without arguments, setLegend() will just redraw the legend. + * @param {} legend Same as legend : an array of thresholds + * @param {} legendColor Same as legendColors : an object with the heatmap's colors, or an array of 2 colors + */ + setLegend(legend?: number[], legendColors?: LegendColor | string[]): void; + /** + * Remove the legend from the calendar + * Settings are kept and you can re-add the legend with the same settings using showLegend(). + */ + removeLegend(): void; + /** Display the legend, if not already shown. */ + showLegend(): void; + /** + * Remove the calendar from the DOM + * Remember to self-assign the result of destroy() to your calendar instance, or it'll lead to a memory leak. + * @param {Function} callback function that will be executed when the calendar is removed from the DOM, at the end of the animation. + * @returns always returns null. + */ + destroy(callback?: Function): CalHeatMap; + } + + interface LegendColor + { + /** Color of the smallest value on the legend */ + min: string; + /** Color of the highest value on the legend */ + max: string; + /** Color for the dates with value == 0 */ + empty?: string; + /** Base color of the date cells */ + base?: string; + /** Color for the special value */ + overflow?: string; + } + + interface InitOptions + { + // ================================================ + // Presentation + // ================================================ + + /** DOM node to insert the calendar in. Default: "#cal-heatmap" */ + itemSelector?: string | HTMLElement | Element | EventTarget; + + /** + * Type of domain. Default: "hour" + * Valid domains: {"hour", "day", "week", "month", "year"} + */ + domain?: string; + + /** + * Type of subDomain. Default: "min" + * Valid subDomains: {"min", "x_min", "hour", "x_hour", "day", "x_day", "week", "x_week", "month", "x_month"} + */ + subDomain?: string; + + /** Number of domain to display. Default: 12 */ + range?: number; + + /** Size of each subDomain cell, in pixels. Default: 10 */ + cellSize?: number; + + /** Space between each subDomain cell, in pixel. Default: 2 */ + cellPadding?: number; + + /** subDomain cell's border radius, for rounder corner, in pixel. Default: 0 */ + cellRadius?: number; + + /** Space between each domain, in pixel. Default: 2 */ + domainGutter?: number; + + /** + * Margin around each domain, in pixel. Default: [0,0,0,0] + * Ordered like in CSS (top, right, bottom, left), it also accepts CSS like values + */ + domainMargin?: number | number[]; + + /** + * Whether to enable domain dynamic width and height. Default: true + * Some domain>subdomain couple, like month>days, doesn't always have the same number of + * subDomain cells. Some months have 6 weeks, some only 4. + * With dynamic dimension enabled, the domain width and height will be adjusted to fit the + * domain content, whereas when it's disabled, all domains will have the same dimension : the biggest. + */ + domainDynamicDimension?: boolean; + + /** To display the calendar vertically, with each domain one under the other. Default: false */ + verticalOrientation?: boolean; + + /** Position and alignment of the domain label. */ + label?: Label; + + /** + * Control the number of columns to split the domain dates into. Default: null + * Each domain is split into an arbitrary number of columns (or rows depending on the + * reading direction). You can overwrite that number with colLimit, and force all dates on the + * same line, or split them into more columns. + * That setting limit the maximum number of columns, and doesn't necessary means that each rows will + * contains that number of columns. + */ + colLimit?: number; + + /** Control the number of rows to split the domain dates into. Default: null + * If rowLimit and colLimit are both used, rowLimit will be ignored. */ + rowLimit?: number; + + /** Whether to display a tooltip when hovering over a date. Default: false */ + tooltip?: boolean; + + // ================================================ + // Data + // ================================================ + + /** + * Starting date of the calendar. Default: new Date() + * It doesn't have to be precise, the calendar will not start at that date, but at the first domain containing that date. + */ + start?: Date; + /** + * Data used to fill the calendar. Default: "" + * String is interpreted as a URL to an API, which should be returning the data used to fill the calendar. + */ + + data?: string | Object; + + /** + * Engine used to parse the data. Default: json + * Valid values: + * "json" - Interpret the data as json. + * "csv" - Interpret the data as csv. + * "tsv" - Interpret the data exactly like csv, but are delimited with a tab character, instead of comma. + * "txt" - Just return the data as a string. + */ + dataType?: string; + + /** + * Highlight selected subDomain cells. Default: false + * Takes an array of Date object. Can also accepts the now string, equivalent to Date.now(). + */ + highlight?: string | string[] | Date[] | any[]; + + /** Whether to start the week on Monday, instead of Sunday. Default: true */ + weekStartOnMonday?: boolean; + + /** + * Lower limit of the domain navigation, preventing navigating beyond a certain date. Default: null + * When set, calling previous() will only work only until the leftmost domain containing minDate. + * Like with start, minDate does not have to be precise, and just have to be a date inside the domain. + * previous() will always return true, unless the domain containing minDate is reached, in which case, it'll return false. + */ + minDate?: Date; + + /** Upper limit of the domain navigation, preventing navigating beyond a certain date. Default: null */ + maxDate?: Date; + + /** + * Whether to consider missing date:value couple in the data source as equal to 0. Default: false + * By default, when the a date is not associated to a value, it's considered as null, and rendered as a no value cell. + * You should ask yourself, if the API is not returning result for a date, is it because there is really no value + * associated to this date, or because it's supposed to be equal to 0, and it's skipped in order to save bandwidth ? + */ + considerMissingDataAsZero?: boolean; + + // ================================================ + // Legend + // ================================================ + + /** Assign each range of values to a color. Default: [10, 20, 30, 40] */ + legend?: number[]; + + /** Whether to display the legend. Default: true */ + displayLegend?: boolean; + + /** Size of the legend cells, in pixels. Default: 10 */ + legendCellSize?: number; + + /** Padding between each legend cell, in pixels. Default: 2 */ + legendCellPadding?: number; + + /** Margin around the legend, in pixels. Default: [10, 0, 0, 0] */ + legendMargin?: number | number[]; + + /** + * Vertical position of the legend. Default: "bottom" + * Valid values: + * "top" - Place the legend above the calendar + * "center" - Place the legend on the calendar's side + * Use with legendHorizontalPosition, to position the legend on the left (default) or on the right. + * "bottom" - Place the legend on below the calendar + */ + legendVerticalPosition?: string; + + /** + * Horizontal position of the legend. Default: "left" + * Valid values: + * "left" - Align the legend to the left + * "center" - Center the legend + * "right" - Align the legend to the right + */ + legendHorizontalPosition?: string; + + /** + * Orientation of the legend. Default: "horizontal" + * legendOrientation is best used together with legendHorizontalPosition when the legend is positioned on the side. + * Valid values: + * "horizontal" - Legend is displayed horizontally, from left to right + * "vertical" - Legend is displayed vertically, from top to bottom + */ + legendOrientation?: string; + + /** + * Set of colors to automagically compute the heatmap colors. + * Instead of relying on the CSS for your heatmap's colors, you can also set the heatmap's colors directly with + * cal-heatmap on initialization, or even dynamically change them after. + * All legend settings can be changed dynamically after calendar initialisation, with setLegend(). + */ + legendColors?: LegendColor | string[]; + + // ================================================ + // i18n + // ================================================ + + /** + * Name of the entity you're representing on the calendar. + * Takes an array of string, with the first index as the singular form, and the second index the plural form. + * For the lazy, you can also pass a simple string, ar a single element array, and it'll automatically guess + * the plural form, as long as it's the singular form plus the "s" suffix. + */ + itemName?: string | string[]; + /** + * Format of the title displayed when hovering a subDomain. + * Some template strings are available, and enclosed in braces. + * {name} Name of the entity represented in the calendar (see itemName) + * {count} The value associated to the date. + * {date} The date of the cell. It's automatically formatted according to the type of subDomain. + * See subDomainDateFormat to further customize that date formatting. + * {connector} An English preposition placed before a datetime (on Monday, at 15:00, etc.). Each subDomain + * have their own default connector, corresponding to the default date format. + */ + subDomainTitleFormat?: SubDomainFormatTemplates; + /** + * Format of the {date} template string inside subDomainTitleFormat. + * {date} is by default formatted according to the subDomain type. + * subDomainFormat can accept any string with directive accepted by d3.time.format(), like "%Y-%m-%d". + * As d3.time.format() will only output English dates, subDomainDateFormat can also accept a function, + * with the subDomain date as the argument. + */ + subDomainDateFormat?: string | Function; + /** + * Format of the text inside a subDomain cell. + * Disabled by default, you can display a text inside each subDomain cell. + * Works exactly like subDomainDateFormat, except that the function takes the cell value as second argument. + */ + subDomainTextFormat?: string | Function; + /** + * Format of the domain label. + * Works exactly like subDomainDateFormat, and will format the domain label with any string accepted by d3.time.format(), or a function. + * To not display the domain label, set domainLabelFormat to "" (empty string). + */ + domainLabelFormat?: string | Function; + /** + * Formatting of the legend title, displayed when hovering a legend cell. + * Some template strings are available, and enclosed in braces. + * {name} Name of the entity represented in the calendar (see itemName) + * {min} The first value of the legend array. + * {max} The last value of the legend array. + * {down} The lower bound of a color + * {up} The upper bound of a color + */ + legendTitleFormat?: LegendTitleTemplates; + + // ================================================ + // Other + // ================================================ + + /** Animation duration, in milliseconds. Default value: 500 */ + animationDuration?: number; + /** + * Will attach the previous() event to the specified element, on a mouse click, shifting the calendar one domain back. Default value: false + * If you want to shift by more than one domain, see the previous() method. + */ + previousSelector?: string | HTMLElement; + /** + * Will attach the next() event to the specified element, on a mouse click, shifting the calendar one domain forward. Default value: false + * If you want to shift by more than one domain, see the next() method. + */ + nextSelector?: string | HTMLElement; + /** + * The calendar instance namespace. + * If you have more than one instance of Cal-Heatmap, you should assign each instance its own namespace, in order to isolate each instance event handler. + */ + itemNamespace?: string; + + // ================================================ + // Events + // ================================================ + + /** Called after a mouse click event on a subDomain cell. */ + onClick?: (date: Date, value: number) => void; + /** Called after drawing the empty calendar, and before filling it with data. */ + afterLoad?: () => void; + /** + * Called after shifting the calendar one domain back. + * The date argument is the start date of the domain that was added. + */ + afterLoadPreviousDomain?: (date: Date) => void; + /** + * Called after shifting the calendar one domain forward. + * The date argument is the start date of the domain that was added. + */ + afterLoadNextDomain?: (date: Date) => void; + /** + * Called after drawing and filling the calendar. + * Useful in case you're loading data via ajax, as it's loading data asynchronously. This event will wait for the ajax + * request to complete before triggering. + * This event will only trigger once, on the initial setup. See afterLoadPreviousDomain and afterLoadNextDomain for + * callback events after a domain navigation. + */ + onComplete?: () => void; + /** + * Called after getting the data from source, but before filling the calendar. + * This callback must return a json object formatted in the expected data format. + * afterLoadData() is used to do some works on the data, especially when the data source is not returning data in the expected format. + */ + afterLoadData?: (data: any) => DataFormat; + /** + * Triggered after previous(), when the incoming domain is containing minDate. + * When the leftmost domain set by minDate is loaded into the calendar, onMinDomainReached() will be triggered with true as argument. + * This event is useful if you want to disable your previous button, since there is no more previous domains to load. + * In order to reverse the action, onMinDomainReached() will be called with false as argument afer next(), only once, and only if the + * leftmost domain is not the lower limit domain anymore. + */ + onMinDomainReached?: (reached: boolean) => void; + /** + * Triggered after next(), when the incoming domain is containing maxDate. + * See onMinDomainReached(). + */ + onMaxDomainReached?: (reached: boolean) => void; + } + + interface RuntimeOptions extends InitOptions + { + /** Margin around each domain, in pixels. Ordered like in CSS (top, right, bottom, left) */ + domainMargin: number[]; + /** Margin around the legend, in pixels. Ordered like in CSS (top, right, bottom, left) */ + legendMargin: number[]; + /** List of dates to highlight */ + highlight: Date[]; + /** + * Name of the items to represent in the calendar. + * First index is singular form, and the second index, the plural form. + */ + itemName: string[]; + } + + interface LegendTitleTemplates + { + /** Formatting of the smallest (leftmost) value of the legend. Default value: "less than {min} {name}" */ + lower?: string; + /** Formatting of all the value but the first and the last. Default value: "between {down} and {up} {name}" */ + inner?: string; + /** Formatting of the biggest (rightmost) value of the legend. Default value: "more than {max} {name}" */ + upper?: string; + } + + interface SubDomainFormatTemplates + { + /** Format of the title when there is no value associated to the date. Default value: "{date}" */ + empty?: string; + /** Format of the title when it's associated to a value. Default value: "{count} {name} {connector} {date}" */ + filled?: string; + } + + interface DataFormat + { + /** timestamp are in seconds, value can be any number (integer or float) */ + [timestamp: string]: number; + } + + interface LabelOffset + { + x: number; + y: number; + } + + /** Position and alignment of the domain label. */ + interface Label + { + /** + * Position of the label, relative to the domain. Default: "bottom" + * Valid values: {"top", "right", "bottom", "left"} + */ + position?: string; + + /** + * Horizontal align of the domain. Default: "center" + * Valid values: {"left", "center", "right"} + */ + align?: string; + /** + * Rotation for a vertical label. Default: null + * Valid values: {null, "left", "right"} + */ + rotate?: string; + /** + * Only used when label is rotated, defines the width of the label. Default: 100 + * Valid values: any intger + */ + width?: number; + /** + * More control about label positioning, if the default value does not fit your need, + * especially when label is rotated, or when using a big font-size. Default: {x:0, y:0} + */ + offset?: LabelOffset; + /** + * Height of the domain label in pixels. + * By leaving it to null, the label will be set to 2 times the height of the subDomain cell. + * If you want to remove the label, set domainLabelFormat to "" (empty string), instead + * of setting the label height to 0. Default: null + * Valid values: any integer + */ + height?: number; + } +} + +declare var CalHeatMap: CalHeatMap.CalHeatMapStatic; diff --git a/cal-heatmap/tsconfig.json b/cal-heatmap/tsconfig.json new file mode 100644 index 0000000000..8f0487a2e2 --- /dev/null +++ b/cal-heatmap/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "cal-heatmap-tests.ts" + ] +} \ No newline at end of file diff --git a/callsite/callsite-tests.ts b/callsite/callsite-tests.ts index fcabcd8b50..079e7522e1 100644 --- a/callsite/callsite-tests.ts +++ b/callsite/callsite-tests.ts @@ -1,5 +1,4 @@ -/// import callsite = require("callsite"); diff --git a/callsite/callsite.d.ts b/callsite/callsite.d.ts deleted file mode 100644 index ffaa5d7e6f..0000000000 --- a/callsite/callsite.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Type definitions for callsite 1.0.0 -// Project: https://github.com/tj/callsite -// Definitions by: newclear -// Definitions: https://github.com/newclear/DefinitelyTyped - -declare module "callsite" { - - namespace Callsite{ - - interface CallSite { - getThis(): any; - getTypeName(): string; - getFunctionName(): string; - getMethodName(): string; - getFileName(): string; - getLineNumber(): number; - getColumnNumber(): number; - getFunction(): Function; - getEvalOrigin(): string; - isNative(): boolean; - isToplevel(): boolean; - isEval(): boolean; - isConstructor(): boolean; - } - } - - function Callsite(): Callsite.CallSite[]; - - export = Callsite; -} diff --git a/callsite/index.d.ts b/callsite/index.d.ts new file mode 100644 index 0000000000..780ca8b0ab --- /dev/null +++ b/callsite/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for callsite 1.0.0 +// Project: https://github.com/tj/callsite +// Definitions by: newclear +// Definitions: https://github.com/newclear/DefinitelyTyped + + + +declare namespace Callsite { + + interface CallSite { + getThis(): any; + getTypeName(): string; + getFunctionName(): string; + getMethodName(): string; + getFileName(): string; + getLineNumber(): number; + getColumnNumber(): number; + getFunction(): Function; + getEvalOrigin(): string; + isNative(): boolean; + isToplevel(): boolean; + isEval(): boolean; + isConstructor(): boolean; + } +} + +declare function Callsite(): Callsite.CallSite[]; + +export = Callsite; diff --git a/callsite/tsconfig.json b/callsite/tsconfig.json new file mode 100644 index 0000000000..ce34e53195 --- /dev/null +++ b/callsite/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "callsite-tests.ts" + ] +} \ No newline at end of file diff --git a/calq/calq-tests.ts b/calq/calq-tests.ts index 6f8019261d..45d6d69e41 100644 --- a/calq/calq-tests.ts +++ b/calq/calq-tests.ts @@ -1,4 +1,4 @@ -/// + function calq_base() { calq.init("bfff14a4e0225789be3d9d22c4bb42a1"); diff --git a/calq/calq.d.ts b/calq/index.d.ts similarity index 100% rename from calq/calq.d.ts rename to calq/index.d.ts diff --git a/calq/tsconfig.json b/calq/tsconfig.json new file mode 100644 index 0000000000..95bf5b8356 --- /dev/null +++ b/calq/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "calq-tests.ts" + ] +} \ No newline at end of file diff --git a/camel-case/camel-case-tests.ts b/camel-case/camel-case-tests.ts index 4f40e11fb2..f26f7cdb85 100644 --- a/camel-case/camel-case-tests.ts +++ b/camel-case/camel-case-tests.ts @@ -1,4 +1,3 @@ -/// import camelCase = require('camel-case'); diff --git a/camel-case/camel-case.d.ts b/camel-case/camel-case.d.ts deleted file mode 100644 index e2a4777f21..0000000000 --- a/camel-case/camel-case.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Type definitions for camel-case -// Project: https://github.com/blakeembrey/camel-case -// Definitions by: Sam Saint-Pettersen -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "camel-case" { - function camelCase(string: string, locale?: string): string; - export = camelCase; -} diff --git a/camel-case/index.d.ts b/camel-case/index.d.ts new file mode 100644 index 0000000000..1345063e82 --- /dev/null +++ b/camel-case/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for camel-case +// Project: https://github.com/blakeembrey/camel-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare function camelCase(string: string, locale?: string): string; +export = camelCase; diff --git a/camel-case/tsconfig.json b/camel-case/tsconfig.json new file mode 100644 index 0000000000..6d379a9d5a --- /dev/null +++ b/camel-case/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "camel-case-tests.ts" + ] +} \ No newline at end of file diff --git a/camelcase/camelcase-tests.ts b/camelcase/camelcase-tests.ts index 945f79abb4..aacb29481a 100644 --- a/camelcase/camelcase-tests.ts +++ b/camelcase/camelcase-tests.ts @@ -1,4 +1,3 @@ -/// import camelCase = require('camelcase'); diff --git a/camelcase/camelcase.d.ts b/camelcase/camelcase.d.ts deleted file mode 100644 index 2edd71948a..0000000000 --- a/camelcase/camelcase.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Type definitions for camelcase -// Project: https://github.com/sindresorhus/camelcase -// Definitions by: Sam Verschueren -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "camelcase" { - function camelcase(...args: string[]): string; - namespace camelcase {} - export = camelcase; -} diff --git a/camelcase/index.d.ts b/camelcase/index.d.ts new file mode 100644 index 0000000000..79705dd423 --- /dev/null +++ b/camelcase/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for camelcase +// Project: https://github.com/sindresorhus/camelcase +// Definitions by: Sam Verschueren +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare function camelcase(...args: string[]): string; +declare namespace camelcase { } +export = camelcase; diff --git a/camelcase/tsconfig.json b/camelcase/tsconfig.json new file mode 100644 index 0000000000..d2e2e7bbe8 --- /dev/null +++ b/camelcase/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "camelcase-tests.ts" + ] +} \ No newline at end of file diff --git a/camljs/camljs-tests.ts b/camljs/camljs-tests.ts index ddececcc52..12afd10fbb 100644 --- a/camljs/camljs-tests.ts +++ b/camljs/camljs-tests.ts @@ -1,4 +1,4 @@ -/// + var caml = new CamlBuilder().Where() .Any( diff --git a/camljs/camljs.d.ts b/camljs/index.d.ts similarity index 100% rename from camljs/camljs.d.ts rename to camljs/index.d.ts diff --git a/camljs/tsconfig.json b/camljs/tsconfig.json new file mode 100644 index 0000000000..b689c6af86 --- /dev/null +++ b/camljs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "camljs-tests.ts" + ] +} \ No newline at end of file diff --git a/camo/camo-tests.ts b/camo/camo-tests.ts index 68b515a61c..31354dc945 100644 --- a/camo/camo-tests.ts +++ b/camo/camo-tests.ts @@ -1,4 +1,3 @@ -/// import { connect, diff --git a/camo/camo.d.ts b/camo/camo.d.ts deleted file mode 100644 index 70f9817ffb..0000000000 --- a/camo/camo.d.ts +++ /dev/null @@ -1,139 +0,0 @@ -// Type definitions for camo v0.11.4 -// Project: https://github.com/scottwrobinson/camo -// Definitions by: Lucas Matías Ciruzzi -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "camo" { - - type TypeOrArray = Type | Type[]; - - /** - * Supported type constructors for document properties - */ - export type SchemaTypeConstructor = - TypeOrArray | - TypeOrArray | - TypeOrArray | - TypeOrArray | - TypeOrArray | - TypeOrArray; - - /** - * Supported types for document properties - */ - export type SchemaType = TypeOrArray; - - /** - * Document property with options - */ - export interface SchemaTypeOptions { - /** - * Type of data - */ - type: SchemaTypeConstructor; - /** - * Default value - */ - default?: Type; - /** - * Min value (only with Number) - */ - min?: number; - /** - * Max value (only with Number) - */ - max?: number; - /** - * Posible options - */ - choices?: Type[]; - /** - * RegEx to match value - */ - match?: RegExp; - /** - * Validation function - * - * @param value Value taken - * @returns true (validation ok) or false (validation wrong) - */ - validate?(value: Type): boolean; - /** - * Unique value (like ids) - */ - unique?: boolean; - /** - * Required field - */ - required?: boolean; - } - - /** - * Document property type or options - */ - export type SchemaTypeExtended = SchemaTypeConstructor | SchemaTypeOptions; - - /** - * Schema passed to Document.create() - */ - interface DocumentSchema { - /** - * Index signature - */ - [property: string]: SchemaType; - /** - * Document id - */ - _id?: string; - } - - /** - * Camo document instance - */ - class DocumentInstance { - public save(): Promise; - public loadOne(): Promise; - public loadMany(): Promise; - public delete(): Promise; - public deleteOne(): Promise; - public deleteMany(): Promise; - public loadOneAndDelete(): Promise; - public count(): Promise; - public preValidate(): Promise; - public postValidate(): Promise; - public preSave(): Promise; - public postSave(): Promise; - public preDelete(): Promise; - public postDelete(): Promise; - } - - /** - * Camo document - */ - export class Document { - /** - * Index signature - */ - [property: string]: SchemaTypeExtended | string | DocumentInstance; - /** - * Static method to define the collection name - * - * @returns The collection name - */ - static collectionName(): string; - /** - * Creates a camo document instance - * - * @returns A camo document instance - */ - static create(schema: Schema): DocumentInstance; - } - - /** - * Connect function - * - * @param uri Connection URI - */ - export function connect (uri: string): Promise; - -} diff --git a/camo/index.d.ts b/camo/index.d.ts new file mode 100644 index 0000000000..168765f136 --- /dev/null +++ b/camo/index.d.ts @@ -0,0 +1,137 @@ +// Type definitions for camo v0.11.4 +// Project: https://github.com/scottwrobinson/camo +// Definitions by: Lucas Matías Ciruzzi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + +type TypeOrArray = Type | Type[]; + +/** + * Supported type constructors for document properties + */ +export type SchemaTypeConstructor = + TypeOrArray | + TypeOrArray | + TypeOrArray | + TypeOrArray | + TypeOrArray | + TypeOrArray; + +/** + * Supported types for document properties + */ +export type SchemaType = TypeOrArray; + +/** + * Document property with options + */ +export interface SchemaTypeOptions { + /** + * Type of data + */ + type: SchemaTypeConstructor; + /** + * Default value + */ + default?: Type; + /** + * Min value (only with Number) + */ + min?: number; + /** + * Max value (only with Number) + */ + max?: number; + /** + * Posible options + */ + choices?: Type[]; + /** + * RegEx to match value + */ + match?: RegExp; + /** + * Validation function + * + * @param value Value taken + * @returns true (validation ok) or false (validation wrong) + */ + validate?(value: Type): boolean; + /** + * Unique value (like ids) + */ + unique?: boolean; + /** + * Required field + */ + required?: boolean; +} + +/** + * Document property type or options + */ +export type SchemaTypeExtended = SchemaTypeConstructor | SchemaTypeOptions; + +/** + * Schema passed to Document.create() + */ +interface DocumentSchema { + /** + * Index signature + */ + [property: string]: SchemaType; + /** + * Document id + */ + _id?: string; +} + +/** + * Camo document instance + */ +declare class DocumentInstance { + public save(): Promise; + public loadOne(): Promise; + public loadMany(): Promise; + public delete(): Promise; + public deleteOne(): Promise; + public deleteMany(): Promise; + public loadOneAndDelete(): Promise; + public count(): Promise; + public preValidate(): Promise; + public postValidate(): Promise; + public preSave(): Promise; + public postSave(): Promise; + public preDelete(): Promise; + public postDelete(): Promise; +} + +/** + * Camo document + */ +export declare class Document { + /** + * Index signature + */ + [property: string]: SchemaTypeExtended | string | DocumentInstance; + /** + * Static method to define the collection name + * + * @returns The collection name + */ + static collectionName(): string; + /** + * Creates a camo document instance + * + * @returns A camo document instance + */ + static create(schema: Schema): DocumentInstance; +} + +/** + * Connect function + * + * @param uri Connection URI + */ +export declare function connect(uri: string): Promise; diff --git a/camo/tsconfig.json b/camo/tsconfig.json new file mode 100644 index 0000000000..55ad8d4d21 --- /dev/null +++ b/camo/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "camo-tests.ts" + ] +} \ No newline at end of file diff --git a/canvasjs/canvasjs-tests.ts b/canvasjs/canvasjs-tests.ts index c9fe45e927..cfc67ab128 100644 --- a/canvasjs/canvasjs-tests.ts +++ b/canvasjs/canvasjs-tests.ts @@ -1,4 +1,4 @@ -/// + namespace CanvasJS.Tests { // Column Chart diff --git a/canvasjs/canvasjs.d.ts b/canvasjs/index.d.ts similarity index 100% rename from canvasjs/canvasjs.d.ts rename to canvasjs/index.d.ts diff --git a/canvasjs/tsconfig.json b/canvasjs/tsconfig.json new file mode 100644 index 0000000000..964a6e8955 --- /dev/null +++ b/canvasjs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "canvasjs-tests.ts" + ] +} \ No newline at end of file diff --git a/casperjs/casperjs.d.ts b/casperjs/casperjs.d.ts deleted file mode 100644 index cfe345c72f..0000000000 --- a/casperjs/casperjs.d.ts +++ /dev/null @@ -1,312 +0,0 @@ -// Type definitions for CasperJS v1.0.0 -// Project: http://casperjs.org/ -// Definitions by: Jed Mao -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface CasperModule { - create(options: CasperOptions): Casper; - selectXPath(expression: string): Object -} - -interface EventEmitter { - removeAllFilters(filter: string): Casper; - setFilter(filter: string, cb: Function): boolean; -} - -interface Casper extends EventEmitter { - test: Tester; - - constructor (options: CasperOptions): Casper; - - options: CasperOptions; - // Properties - __utils__: ClientUtils; - - // Methods - back(): Casper; - base64encode(url: string, method?: string, data?: any): string; - bypass(nb: number): any; - click(selector: string): boolean; - clickLabel(label: string, tag?: string): boolean; - capture(targetFilePath: string, clipRect: ClipRect): Casper; - captureBase64(format: string): string; - captureBase64(format: string, area: string): string; - captureBase64(format: string, area: ClipRect): string; - captureBase64(format: string, area: any): string; - captureSelector(targetFile: string, selector: string): Casper; - clear(): Casper; - debugHTML(selector?: string, outer?: boolean): Casper; - debugPage(): Casper; - die(message: string, status?: number): Casper; - download(url: string, target?: string, method?: string, data?: any): Casper; - each(array: T[], fn: (self: Casper, item: T, index: number) => void): Casper; - echo(message: string, style?: string): Casper; - evaluate(fn: () => T, ...args: any[]): T - evaluateOrDie(fn: () => any, message?: string, status?: number): Casper; - exit(status?: number): Casper; - exists(selector: string): boolean; - fetchText(selector: string): string; - forward(): Casper; - log(message: string, level?: string, space?: string): Casper; - fill(selector: string, values: any, submit?: boolean): void; - fillSelectors(selector: string, values: any, submit?: boolean): void; - fillXPath(selector: string, values: any, submit?: boolean): void; - getCurrentUrl(): string; - getElementAttribute(selector: string, attribute: string): string; - getElementsAttribute(selector: string, attribute: string): string; - getElementBounds(selector: string): ElementBounds; - getElementsBounds(selector: string): ElementBounds[]; - getElementInfo(selector: string): ElementInfo; - getElementsInfo(selector: string): ElementInfo; - getFormValues(selector: string): any; - getGlobal(name: string): any; - getHTML(selector?: string, outer?: boolean): string; - getPageContent(): string; - getTitle(): string; - mouseEvent(type: string, selector: string): boolean; - open(location: string, settings: OpenSettings): Casper; - reload(then?: (response: HttpResponse) => void): Casper; - repeat(times: number, then: Function): Casper; - resourceExists(test: Function): boolean; - resourceExists(test: string): boolean; - run(onComplete: Function, time?: number): Casper; - scrollTo(x: number, y: number): Casper; - scrollToBottom(): Casper; - sendKeys(selector: string, keys: string, options?: any): Casper; - setHttpAuth(username: string, password: string): Casper; - start(url?: string, then?: (response: HttpResponse) => void): Casper; - status(asString: boolean): any; - then(fn: (self?: Casper) => void): Casper; - thenBypass(nb: number): Casper; - thenBypassIf(condition: any, nb: number): Casper; - thenBypassUnless(condition: any, nb: number): Casper; - thenClick(selector: string): Casper; - thenEvaluate(fn: () => any, ...args: any[]): Casper; - thenOpen(location: string, then?: (response: HttpResponse) => void): Casper; - thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void): Casper; - thenOpenAndEvaluate(location: string, then?: Function, ...args: any[]): Casper; - toString(): string; - unwait(): Casper; - userAgent(agent: string): string; - viewport(width: number, height: number): Casper; - visible(selector: string): boolean; - wait(timeout: number, then?: Function): Casper; - waitFor(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForAlert(then: Function, onTimeout?: Function, timeout?: number): Casper; - waitForPopup(urlPattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForPopup(urlPattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForUrl(url: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForUrl(url: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitWhileSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForResource(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForText(pattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitForText(pattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitUntilVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - waitWhileVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; - warn(message: string): Casper; - withFrame(frameInfo: string, then: Function): Casper; - withFrame(frameInfo: number, then: Function): Casper; - withPopup(popupInfo: string, step: Function): Casper; - withPopup(popupInfo: RegExp, step: Function): Casper; - zoom(factor: number): Casper; -} - -interface HttpResponse { - contentType: string; - headers: any[]; - id: number; - redirectURL: string; - stage: string; - status: number; - statusText: string; - time: string; - url: string; -} - -interface OpenSettings { - method: string; - data: any; - headers: any; -} - -interface ElementBounds { - top: number; - left: number; - width: number; - height: number; -} - -interface ElementInfo { - nodeName: string; - attributes: any; - tag: string; - html: string; - text: string; - x: number; - y: number; - width: number; - height: number; - visible: boolean; -} - -interface CasperOptions { - clientScripts?: any[]; - exitOnError?: boolean; - httpStatusHandlers?: any; - logLevel?: string; - onAlert?: Function; - onDie?: Function; - onError?: Function; - onLoadError?: Function; - onPageInitialized?: Function; - onResourceReceived?: Function; - onResourceRequested?: Function; - onStepComplete?: Function; - onStepTimeout?: Function; - onTimeout?: Function; - onWaitTimeout?: Function; - page?: WebPage; - pageSettings?: any; - remoteScripts?: any[]; - safeLogs?: boolean; - silentErrors?: boolean; - stepTimeout?: number; - timeout?: number; - verbose?: boolean; - viewportSize?: any; - retryTimeout?: number; - waitTimeout?: number; -} - -interface ClientUtils { - echo(message: string): void; - encode(contents: string): void; - exists(selector: string): void; - findAll(selector: string): void; - findOne(selector: string): void; - getBase64(url: string, method?: string, data?: any): void; - getBinary(url: string, method?: string, data?: any): void; - getDocumentHeight(): void; - getElementBounds(selector: string): void; - getElementsBounds(selector: string): void; - getElementByXPath(expression: string, scope?: HTMLElement): void; - getElementsByXPath(expression: string, scope?: HTMLElement): void; - getFieldValue(inputName: string): void; - getFormValues(selector: string): void; - mouseEvent(type: string, selector: string): void; - removeElementsByXPath(expression: string): void; - sendAJAX(url: string, method?: string, data?: any, async?: boolean): void; - visible(selector: string): void; -} - -interface Colorizer { - colorize(text: string, styleName: string): void; - format(text: string, style: any): void; -} - -interface Tester { - assert(condition: boolean, message?: string): any; - assertDoesntExist(selector: string, message?: string): any; - assertElementCount(selctor: string, expected: number, message?: string): any; - assertEquals(testValue: any, expected: any, message?: string): any; - assertEval(fn: Function, message: string, arguments: any): any; - assertEvalEquals(fn: Function, expected: any, message?: string, arguments?: any): any; - assertExists(selector: string, message?: string): any; - assertFalsy(subject: any, message?: string): any; - assertField(inputName: string, expected: string, message?: string): any; - assertFieldName(inputName: string, expected: string, message?: string, options?: any): any; - assertFieldCSS(cssSelector: string, expected: string, message?: string): any; - assertFieldXPath(xpathSelector: string, expected: string, message?: string): any; - assertHttpStatus(status: number, message?: string): any; - assertMatch(subject: any, pattern: RegExp, message?: string): any; - assertNot(subject: any, message?: string): any; - assertNotEquals(testValue: any, expected: any, message?: string): any; - assertNotVisible(selector: string, message?: string): any; - assertRaises(fn: Function, args: any[], message?: string): any; - assertSelectorDoesntHaveText(selector: string, text: string, message?: string): any; - assertSelectorExists(selector: string, message?: string): any; - assertSelectorHasText(selector: string, text: string, message?: string): any; - assertResourceExists(testFx: Function, message?: string): any; - assertTextExists(expected: string, message?: string): any; - assertTextDoesntExist(unexpected: string, message: string): any; - assertTitle(expected: string, message?: string): any; - assertTitleMatch(pattern: RegExp, message?: string): any; - assertTruthy(subject: any, message?: string): any; - assertType(input: any, type: string, message?: string): any; - assertInstanceOf(input: any, ctor: Function, message?: string): any; - assertUrlMatch(pattern: string, message?: string): any; - assertUrlMatch(pattern: RegExp, message?: string): any; - assertVisible(selector: string, message?: string): any; - - /* since 1.1 */ - begin(description: string, planned: number, suite: Function): any; - begin(description: string, suite: Function): any; - begin(description: string, planned: number, config: Object): any; - begin(description: string, config: Object): any; - - colorize(message: string, style: string): any; - comment(message: string): any; - done(expected?: number): any; - error(message: string): any; - fail(message: string): any; - formatMessage(message: string, style: string): any; - getFailures(): Cases; - getPasses(): Cases; - info(message: string): any; - pass(message: string): any; - renderResults(exit: boolean, status: number, save: string): any; - - setup(fn: Function): any; - skip(nb: number, message: string): any; - tearDown(fn: Function): any; -} - -interface Cases { - length: number; - cases: Case[]; -} - -interface Case { - success: boolean; - type: string; - standard: string; - file: string; - values: CaseValues; -} - -interface CaseValues { - subject: boolean; - expected: boolean; -} - -interface Utils { - betterTypeOf(input: any): any; - dump(value: any): any; - fileExt(file: string): any; - fillBlanks(text: string, pad: number): any; - format(f: string, ...args: any[]): any; - getPropertyPath(obj: any, path: string): any; - inherits(ctor: any, superCtor: any): any; - isArray(value: any): any; - isCasperObject(value: any): any; - isClipRect(value: any): any; - isFalsy(subject: any): any; - isFunction(value: any): any; - isJsFile(file: string): any; - isNull(value: any): any; - isNumber(value: any): any; - isObject(value: any): any; - isRegExp(value: any): any; - isString(value: any): any; - isTruthy(subject: any): any; - isType(what: any, type: string): any; - isUndefined(value: any): any; - isWebPage(what: any): any; - mergeObjects(origin: any, add: any): any; - node(name: string, attributes: any): any; - serialize(value: any): any; - unique(array: any[]): any; -} diff --git a/casperjs/index.d.ts b/casperjs/index.d.ts new file mode 100644 index 0000000000..a3f456f238 --- /dev/null +++ b/casperjs/index.d.ts @@ -0,0 +1,312 @@ +// Type definitions for CasperJS v1.0.0 +// Project: http://casperjs.org/ +// Definitions by: Jed Mao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface CasperModule { + create(options: CasperOptions): Casper; + selectXPath(expression: string): Object +} + +interface EventEmitter { + removeAllFilters(filter: string): Casper; + setFilter(filter: string, cb: Function): boolean; +} + +interface Casper extends EventEmitter { + test: Tester; + + constructor (options: CasperOptions): Casper; + + options: CasperOptions; + // Properties + __utils__: ClientUtils; + + // Methods + back(): Casper; + base64encode(url: string, method?: string, data?: any): string; + bypass(nb: number): any; + click(selector: string): boolean; + clickLabel(label: string, tag?: string): boolean; + capture(targetFilePath: string, clipRect: ClipRect): Casper; + captureBase64(format: string): string; + captureBase64(format: string, area: string): string; + captureBase64(format: string, area: ClipRect): string; + captureBase64(format: string, area: any): string; + captureSelector(targetFile: string, selector: string): Casper; + clear(): Casper; + debugHTML(selector?: string, outer?: boolean): Casper; + debugPage(): Casper; + die(message: string, status?: number): Casper; + download(url: string, target?: string, method?: string, data?: any): Casper; + each(array: T[], fn: (self: Casper, item: T, index: number) => void): Casper; + echo(message: string, style?: string): Casper; + evaluate(fn: () => T, ...args: any[]): T + evaluateOrDie(fn: () => any, message?: string, status?: number): Casper; + exit(status?: number): Casper; + exists(selector: string): boolean; + fetchText(selector: string): string; + forward(): Casper; + log(message: string, level?: string, space?: string): Casper; + fill(selector: string, values: any, submit?: boolean): void; + fillSelectors(selector: string, values: any, submit?: boolean): void; + fillXPath(selector: string, values: any, submit?: boolean): void; + getCurrentUrl(): string; + getElementAttribute(selector: string, attribute: string): string; + getElementsAttribute(selector: string, attribute: string): string; + getElementBounds(selector: string): ElementBounds; + getElementsBounds(selector: string): ElementBounds[]; + getElementInfo(selector: string): ElementInfo; + getElementsInfo(selector: string): ElementInfo; + getFormValues(selector: string): any; + getGlobal(name: string): any; + getHTML(selector?: string, outer?: boolean): string; + getPageContent(): string; + getTitle(): string; + mouseEvent(type: string, selector: string): boolean; + open(location: string, settings: OpenSettings): Casper; + reload(then?: (response: HttpResponse) => void): Casper; + repeat(times: number, then: Function): Casper; + resourceExists(test: Function): boolean; + resourceExists(test: string): boolean; + run(onComplete: Function, time?: number): Casper; + scrollTo(x: number, y: number): Casper; + scrollToBottom(): Casper; + sendKeys(selector: string, keys: string, options?: any): Casper; + setHttpAuth(username: string, password: string): Casper; + start(url?: string, then?: (response: HttpResponse) => void): Casper; + status(asString: boolean): any; + then(fn: (self?: Casper) => void): Casper; + thenBypass(nb: number): Casper; + thenBypassIf(condition: any, nb: number): Casper; + thenBypassUnless(condition: any, nb: number): Casper; + thenClick(selector: string): Casper; + thenEvaluate(fn: () => any, ...args: any[]): Casper; + thenOpen(location: string, then?: (response: HttpResponse) => void): Casper; + thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void): Casper; + thenOpenAndEvaluate(location: string, then?: Function, ...args: any[]): Casper; + toString(): string; + unwait(): Casper; + userAgent(agent: string): string; + viewport(width: number, height: number): Casper; + visible(selector: string): boolean; + wait(timeout: number, then?: Function): Casper; + waitFor(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForAlert(then: Function, onTimeout?: Function, timeout?: number): Casper; + waitForPopup(urlPattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForPopup(urlPattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForUrl(url: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForUrl(url: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitWhileSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForResource(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForText(pattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitForText(pattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitUntilVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + waitWhileVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper; + warn(message: string): Casper; + withFrame(frameInfo: string, then: Function): Casper; + withFrame(frameInfo: number, then: Function): Casper; + withPopup(popupInfo: string, step: Function): Casper; + withPopup(popupInfo: RegExp, step: Function): Casper; + zoom(factor: number): Casper; +} + +interface HttpResponse { + contentType: string; + headers: any[]; + id: number; + redirectURL: string; + stage: string; + status: number; + statusText: string; + time: string; + url: string; +} + +interface OpenSettings { + method: string; + data: any; + headers: any; +} + +interface ElementBounds { + top: number; + left: number; + width: number; + height: number; +} + +interface ElementInfo { + nodeName: string; + attributes: any; + tag: string; + html: string; + text: string; + x: number; + y: number; + width: number; + height: number; + visible: boolean; +} + +interface CasperOptions { + clientScripts?: any[]; + exitOnError?: boolean; + httpStatusHandlers?: any; + logLevel?: string; + onAlert?: Function; + onDie?: Function; + onError?: Function; + onLoadError?: Function; + onPageInitialized?: Function; + onResourceReceived?: Function; + onResourceRequested?: Function; + onStepComplete?: Function; + onStepTimeout?: Function; + onTimeout?: Function; + onWaitTimeout?: Function; + page?: WebPage; + pageSettings?: any; + remoteScripts?: any[]; + safeLogs?: boolean; + silentErrors?: boolean; + stepTimeout?: number; + timeout?: number; + verbose?: boolean; + viewportSize?: any; + retryTimeout?: number; + waitTimeout?: number; +} + +interface ClientUtils { + echo(message: string): void; + encode(contents: string): void; + exists(selector: string): void; + findAll(selector: string): void; + findOne(selector: string): void; + getBase64(url: string, method?: string, data?: any): void; + getBinary(url: string, method?: string, data?: any): void; + getDocumentHeight(): void; + getElementBounds(selector: string): void; + getElementsBounds(selector: string): void; + getElementByXPath(expression: string, scope?: HTMLElement): void; + getElementsByXPath(expression: string, scope?: HTMLElement): void; + getFieldValue(inputName: string): void; + getFormValues(selector: string): void; + mouseEvent(type: string, selector: string): void; + removeElementsByXPath(expression: string): void; + sendAJAX(url: string, method?: string, data?: any, async?: boolean): void; + visible(selector: string): void; +} + +interface Colorizer { + colorize(text: string, styleName: string): void; + format(text: string, style: any): void; +} + +interface Tester { + assert(condition: boolean, message?: string): any; + assertDoesntExist(selector: string, message?: string): any; + assertElementCount(selctor: string, expected: number, message?: string): any; + assertEquals(testValue: any, expected: any, message?: string): any; + assertEval(fn: Function, message: string, arguments: any): any; + assertEvalEquals(fn: Function, expected: any, message?: string, arguments?: any): any; + assertExists(selector: string, message?: string): any; + assertFalsy(subject: any, message?: string): any; + assertField(inputName: string, expected: string, message?: string): any; + assertFieldName(inputName: string, expected: string, message?: string, options?: any): any; + assertFieldCSS(cssSelector: string, expected: string, message?: string): any; + assertFieldXPath(xpathSelector: string, expected: string, message?: string): any; + assertHttpStatus(status: number, message?: string): any; + assertMatch(subject: any, pattern: RegExp, message?: string): any; + assertNot(subject: any, message?: string): any; + assertNotEquals(testValue: any, expected: any, message?: string): any; + assertNotVisible(selector: string, message?: string): any; + assertRaises(fn: Function, args: any[], message?: string): any; + assertSelectorDoesntHaveText(selector: string, text: string, message?: string): any; + assertSelectorExists(selector: string, message?: string): any; + assertSelectorHasText(selector: string, text: string, message?: string): any; + assertResourceExists(testFx: Function, message?: string): any; + assertTextExists(expected: string, message?: string): any; + assertTextDoesntExist(unexpected: string, message: string): any; + assertTitle(expected: string, message?: string): any; + assertTitleMatch(pattern: RegExp, message?: string): any; + assertTruthy(subject: any, message?: string): any; + assertType(input: any, type: string, message?: string): any; + assertInstanceOf(input: any, ctor: Function, message?: string): any; + assertUrlMatch(pattern: string, message?: string): any; + assertUrlMatch(pattern: RegExp, message?: string): any; + assertVisible(selector: string, message?: string): any; + + /* since 1.1 */ + begin(description: string, planned: number, suite: Function): any; + begin(description: string, suite: Function): any; + begin(description: string, planned: number, config: Object): any; + begin(description: string, config: Object): any; + + colorize(message: string, style: string): any; + comment(message: string): any; + done(expected?: number): any; + error(message: string): any; + fail(message: string): any; + formatMessage(message: string, style: string): any; + getFailures(): Cases; + getPasses(): Cases; + info(message: string): any; + pass(message: string): any; + renderResults(exit: boolean, status: number, save: string): any; + + setup(fn: Function): any; + skip(nb: number, message: string): any; + tearDown(fn: Function): any; +} + +interface Cases { + length: number; + cases: Case[]; +} + +interface Case { + success: boolean; + type: string; + standard: string; + file: string; + values: CaseValues; +} + +interface CaseValues { + subject: boolean; + expected: boolean; +} + +interface Utils { + betterTypeOf(input: any): any; + dump(value: any): any; + fileExt(file: string): any; + fillBlanks(text: string, pad: number): any; + format(f: string, ...args: any[]): any; + getPropertyPath(obj: any, path: string): any; + inherits(ctor: any, superCtor: any): any; + isArray(value: any): any; + isCasperObject(value: any): any; + isClipRect(value: any): any; + isFalsy(subject: any): any; + isFunction(value: any): any; + isJsFile(file: string): any; + isNull(value: any): any; + isNumber(value: any): any; + isObject(value: any): any; + isRegExp(value: any): any; + isString(value: any): any; + isTruthy(subject: any): any; + isType(what: any, type: string): any; + isUndefined(value: any): any; + isWebPage(what: any): any; + mergeObjects(origin: any, add: any): any; + node(name: string, attributes: any): any; + serialize(value: any): any; + unique(array: any[]): any; +} diff --git a/casperjs/tsconfig.json b/casperjs/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/casperjs/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/chai-as-promised/chai-as-promised-tests.ts b/chai-as-promised/chai-as-promised-tests.ts index 8685f953f2..b860a78dc8 100644 --- a/chai-as-promised/chai-as-promised-tests.ts +++ b/chai-as-promised/chai-as-promised-tests.ts @@ -1,6 +1,6 @@ -/// -/// -/// + +/// +/// import chai = require('chai'); import chaiAsPromised = require('chai-as-promised'); diff --git a/chai-as-promised/chai-as-promised.d.ts b/chai-as-promised/chai-as-promised.d.ts deleted file mode 100644 index 91a46f9033..0000000000 --- a/chai-as-promised/chai-as-promised.d.ts +++ /dev/null @@ -1,285 +0,0 @@ -// Type definitions for chai-as-promised -// Project: https://github.com/domenic/chai-as-promised/ -// Definitions by: jt000 , Yuki Kokubun -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare module 'chai-as-promised' { - function chaiAsPromised(chai: any, utils: any): void; - namespace chaiAsPromised {} - export = chaiAsPromised; -} - -declare namespace Chai { - - // For BDD API - interface Assertion extends LanguageChains, NumericComparison, TypeComparison { - eventually: PromisedAssertion; - become(expected: any): PromisedAssertion; - fulfilled: PromisedAssertion; - rejected: PromisedAssertion; - rejectedWith(expected: any, message?: string | RegExp): PromisedAssertion; - notify(fn: Function): PromisedAssertion; - } - - // Eventually does not have .then(), but PromisedAssertion have. - interface Eventually extends PromisedLanguageChains, PromisedNumericComparison, PromisedTypeComparison { - // From chai-as-promised - become(expected: PromisesAPlus.Thenable): PromisedAssertion; - fulfilled: PromisedAssertion; - rejected: PromisedAssertion; - rejectedWith(expected: any, message?: string | RegExp): PromisedAssertion; - notify(fn: Function): PromisedAssertion; - - // From chai - not: PromisedAssertion; - deep: PromisedDeep; - a: PromisedTypeComparison; - an: PromisedTypeComparison; - include: PromisedInclude; - contain: PromisedInclude; - ok: PromisedAssertion; - true: PromisedAssertion; - false: PromisedAssertion; - null: PromisedAssertion; - undefined: PromisedAssertion; - exist: PromisedAssertion; - empty: PromisedAssertion; - arguments: PromisedAssertion; - Arguments: PromisedAssertion; - equal: PromisedEqual; - equals: PromisedEqual; - eq: PromisedEqual; - eql: PromisedEqual; - eqls: PromisedEqual; - property: PromisedProperty; - ownProperty: PromisedOwnProperty; - haveOwnProperty: PromisedOwnProperty; - length: PromisedLength; - lengthOf: PromisedLength; - match(regexp: RegExp|string, message?: string): PromisedAssertion; - string(string: string, message?: string): PromisedAssertion; - keys: PromisedKeys; - key(string: string): PromisedAssertion; - throw: PromisedThrow; - throws: PromisedThrow; - Throw: PromisedThrow; - respondTo(method: string, message?: string): PromisedAssertion; - itself: PromisedAssertion; - satisfy(matcher: Function, message?: string): PromisedAssertion; - closeTo(expected: number, delta: number, message?: string): PromisedAssertion; - members: PromisedMembers; - } - - interface PromisedAssertion extends Eventually, PromisesAPlus.Thenable { - } - - interface PromisedLanguageChains { - eventually: Eventually; - - // From chai - to: PromisedAssertion; - be: PromisedAssertion; - been: PromisedAssertion; - is: PromisedAssertion; - that: PromisedAssertion; - which: PromisedAssertion; - and: PromisedAssertion; - has: PromisedAssertion; - have: PromisedAssertion; - with: PromisedAssertion; - at: PromisedAssertion; - of: PromisedAssertion; - same: PromisedAssertion; - } - - interface PromisedNumericComparison { - above: PromisedNumberComparer; - gt: PromisedNumberComparer; - greaterThan: PromisedNumberComparer; - least: PromisedNumberComparer; - gte: PromisedNumberComparer; - below: PromisedNumberComparer; - lt: PromisedNumberComparer; - lessThan: PromisedNumberComparer; - most: PromisedNumberComparer; - lte: PromisedNumberComparer; - within(start: number, finish: number, message?: string): PromisedAssertion; - } - - interface PromisedNumberComparer { - (value: number, message?: string): PromisedAssertion; - } - - interface PromisedTypeComparison { - (type: string, message?: string): PromisedAssertion; - instanceof: PromisedInstanceOf; - instanceOf: PromisedInstanceOf; - } - - interface PromisedInstanceOf { - (constructor: Object, message?: string): PromisedAssertion; - } - - interface PromisedDeep { - equal: PromisedEqual; - include: PromisedInclude; - property: PromisedProperty; - } - - interface PromisedEqual { - (value: any, message?: string): PromisedAssertion; - } - - interface PromisedProperty { - (name: string, value?: any, message?: string): PromisedAssertion; - } - - interface PromisedOwnProperty { - (name: string, message?: string): PromisedAssertion; - } - - interface PromisedLength extends PromisedLanguageChains, PromisedNumericComparison { - (length: number, message?: string): PromisedAssertion; - } - - interface PromisedInclude { - (value: Object, message?: string): PromisedAssertion; - (value: string, message?: string): PromisedAssertion; - (value: number, message?: string): PromisedAssertion; - keys: PromisedKeys; - members: PromisedMembers; - } - - interface PromisedKeys { - (...keys: string[]): PromisedAssertion; - (keys: any[]): PromisedAssertion; - } - - interface PromisedThrow { - (): PromisedAssertion; - (expected: string, message?: string): PromisedAssertion; - (expected: RegExp, message?: string): PromisedAssertion; - (constructor: Error, expected?: string, message?: string): PromisedAssertion; - (constructor: Error, expected?: RegExp, message?: string): PromisedAssertion; - (constructor: Function, expected?: string, message?: string): PromisedAssertion; - (constructor: Function, expected?: RegExp, message?: string): PromisedAssertion; - } - - interface PromisedMembers { - (set: any[], message?: string): PromisedAssertion; - } - - // For Assert API - interface Assert { - eventually: PromisedAssert; - isFulfilled(promise: PromisesAPlus.Thenable, message?: string): PromisesAPlus.Thenable; - becomes(promise: PromisesAPlus.Thenable, expected: any, message?: string): PromisesAPlus.Thenable; - doesNotBecome(promise: PromisesAPlus.Thenable, expected: any, message?: string): PromisesAPlus.Thenable; - isRejected(promise: PromisesAPlus.Thenable, message?: string): PromisesAPlus.Thenable; - isRejected(promise: PromisesAPlus.Thenable, expected: any, message?: string): PromisesAPlus.Thenable; - isRejected(promise: PromisesAPlus.Thenable, match: RegExp, message?: string): PromisesAPlus.Thenable; - notify(fn: Function): PromisesAPlus.Thenable; - } - - export interface PromisedAssert { - fail(actual?: any, expected?: any, msg?: string, operator?: string): PromisesAPlus.Thenable; - - ok(val: any, msg?: string): PromisesAPlus.Thenable; - notOk(val: any, msg?: string): PromisesAPlus.Thenable; - - equal(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; - notEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; - - strictEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; - notStrictEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; - - deepEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; - notDeepEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; - - isTrue(val: any, msg?: string): PromisesAPlus.Thenable; - isFalse(val: any, msg?: string): PromisesAPlus.Thenable; - - isNull(val: any, msg?: string): PromisesAPlus.Thenable; - isNotNull(val: any, msg?: string): PromisesAPlus.Thenable; - - isUndefined(val: any, msg?: string): PromisesAPlus.Thenable; - isDefined(val: any, msg?: string): PromisesAPlus.Thenable; - - isFunction(val: any, msg?: string): PromisesAPlus.Thenable; - isNotFunction(val: any, msg?: string): PromisesAPlus.Thenable; - - isObject(val: any, msg?: string): PromisesAPlus.Thenable; - isNotObject(val: any, msg?: string): PromisesAPlus.Thenable; - - isArray(val: any, msg?: string): PromisesAPlus.Thenable; - isNotArray(val: any, msg?: string): PromisesAPlus.Thenable; - - isString(val: any, msg?: string): PromisesAPlus.Thenable; - isNotString(val: any, msg?: string): PromisesAPlus.Thenable; - - isNumber(val: any, msg?: string): PromisesAPlus.Thenable; - isNotNumber(val: any, msg?: string): PromisesAPlus.Thenable; - - isBoolean(val: any, msg?: string): PromisesAPlus.Thenable; - isNotBoolean(val: any, msg?: string): PromisesAPlus.Thenable; - - typeOf(val: any, type: string, msg?: string): PromisesAPlus.Thenable; - notTypeOf(val: any, type: string, msg?: string): PromisesAPlus.Thenable; - - instanceOf(val: any, type: Function, msg?: string): PromisesAPlus.Thenable; - notInstanceOf(val: any, type: Function, msg?: string): PromisesAPlus.Thenable; - - include(exp: string, inc: any, msg?: string): PromisesAPlus.Thenable; - include(exp: any[], inc: any, msg?: string): PromisesAPlus.Thenable; - - notInclude(exp: string, inc: any, msg?: string): PromisesAPlus.Thenable; - notInclude(exp: any[], inc: any, msg?: string): PromisesAPlus.Thenable; - - match(exp: any, re: RegExp, msg?: string): PromisesAPlus.Thenable; - notMatch(exp: any, re: RegExp, msg?: string): PromisesAPlus.Thenable; - - property(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable; - notProperty(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable; - deepProperty(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable; - notDeepProperty(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable; - - propertyVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable; - - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable; - - lengthOf(exp: any, len: number, msg?: string): PromisesAPlus.Thenable; - //alias frenzy - throw(fn: Function, msg?: string): PromisesAPlus.Thenable; - throw(fn: Function, regExp: RegExp): PromisesAPlus.Thenable; - throw(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable; - throw(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable; - - throws(fn: Function, msg?: string): PromisesAPlus.Thenable; - throws(fn: Function, regExp: RegExp): PromisesAPlus.Thenable; - throws(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable; - throws(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable; - - Throw(fn: Function, msg?: string): PromisesAPlus.Thenable; - Throw(fn: Function, regExp: RegExp): PromisesAPlus.Thenable; - Throw(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable; - Throw(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable; - - doesNotThrow(fn: Function, msg?: string): PromisesAPlus.Thenable; - doesNotThrow(fn: Function, regExp: RegExp): PromisesAPlus.Thenable; - doesNotThrow(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable; - - operator(val: any, operator: string, val2: any, msg?: string): PromisesAPlus.Thenable; - closeTo(act: number, exp: number, delta: number, msg?: string): PromisesAPlus.Thenable; - - sameMembers(set1: any[], set2: any[], msg?: string): PromisesAPlus.Thenable; - includeMembers(set1: any[], set2: any[], msg?: string): PromisesAPlus.Thenable; - - ifError(val: any, msg?: string): PromisesAPlus.Thenable; - } -} diff --git a/chai-as-promised/index.d.ts b/chai-as-promised/index.d.ts new file mode 100644 index 0000000000..b4f3ca405d --- /dev/null +++ b/chai-as-promised/index.d.ts @@ -0,0 +1,291 @@ +// Type definitions for chai-as-promised +// Project: https://github.com/domenic/chai-as-promised/ +// Definitions by: jt000 , Yuki Kokubun +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module 'chai-as-promised' { + function chaiAsPromised(chai: any, utils: any): void; + namespace chaiAsPromised {} + export = chaiAsPromised; +} + +declare namespace Chai { + + // For BDD API + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + eventually: PromisedAssertion; + become(expected: any): PromisedAssertion; + fulfilled: PromisedAssertion; + rejected: PromisedAssertion; + rejectedWith(expected: any, message?: string | RegExp): PromisedAssertion; + notify(fn: Function): PromisedAssertion; + } + + // Eventually does not have .then(), but PromisedAssertion have. + interface Eventually extends PromisedLanguageChains, PromisedNumericComparison, PromisedTypeComparison { + // From chai-as-promised + become(expected: PromisesAPlus.Thenable): PromisedAssertion; + fulfilled: PromisedAssertion; + rejected: PromisedAssertion; + rejectedWith(expected: any, message?: string | RegExp): PromisedAssertion; + notify(fn: Function): PromisedAssertion; + + // From chai + not: PromisedAssertion; + deep: PromisedDeep; + all: PromisedKeyFilter; + a: PromisedTypeComparison; + an: PromisedTypeComparison; + include: PromisedInclude; + contain: PromisedInclude; + ok: PromisedAssertion; + true: PromisedAssertion; + false: PromisedAssertion; + null: PromisedAssertion; + undefined: PromisedAssertion; + exist: PromisedAssertion; + empty: PromisedAssertion; + arguments: PromisedAssertion; + Arguments: PromisedAssertion; + equal: PromisedEqual; + equals: PromisedEqual; + eq: PromisedEqual; + eql: PromisedEqual; + eqls: PromisedEqual; + property: PromisedProperty; + ownProperty: PromisedOwnProperty; + haveOwnProperty: PromisedOwnProperty; + length: PromisedLength; + lengthOf: PromisedLength; + match(regexp: RegExp|string, message?: string): PromisedAssertion; + string(string: string, message?: string): PromisedAssertion; + keys: PromisedKeys; + key(string: string): PromisedAssertion; + throw: PromisedThrow; + throws: PromisedThrow; + Throw: PromisedThrow; + respondTo(method: string, message?: string): PromisedAssertion; + itself: PromisedAssertion; + satisfy(matcher: Function, message?: string): PromisedAssertion; + closeTo(expected: number, delta: number, message?: string): PromisedAssertion; + members: PromisedMembers; + } + + interface PromisedAssertion extends Eventually, PromisesAPlus.Thenable { + } + + interface PromisedLanguageChains { + eventually: Eventually; + + // From chai + to: PromisedAssertion; + be: PromisedAssertion; + been: PromisedAssertion; + is: PromisedAssertion; + that: PromisedAssertion; + which: PromisedAssertion; + and: PromisedAssertion; + has: PromisedAssertion; + have: PromisedAssertion; + with: PromisedAssertion; + at: PromisedAssertion; + of: PromisedAssertion; + same: PromisedAssertion; + } + + interface PromisedNumericComparison { + above: PromisedNumberComparer; + gt: PromisedNumberComparer; + greaterThan: PromisedNumberComparer; + least: PromisedNumberComparer; + gte: PromisedNumberComparer; + below: PromisedNumberComparer; + lt: PromisedNumberComparer; + lessThan: PromisedNumberComparer; + most: PromisedNumberComparer; + lte: PromisedNumberComparer; + within(start: number, finish: number, message?: string): PromisedAssertion; + } + + interface PromisedNumberComparer { + (value: number, message?: string): PromisedAssertion; + } + + interface PromisedTypeComparison { + (type: string, message?: string): PromisedAssertion; + instanceof: PromisedInstanceOf; + instanceOf: PromisedInstanceOf; + } + + interface PromisedInstanceOf { + (constructor: Object, message?: string): PromisedAssertion; + } + + interface PromisedDeep { + equal: PromisedEqual; + include: PromisedInclude; + property: PromisedProperty; + } + + interface PromisedKeyFilter { + keys: PromisedKeys; + } + + interface PromisedEqual { + (value: any, message?: string): PromisedAssertion; + } + + interface PromisedProperty { + (name: string, value?: any, message?: string): PromisedAssertion; + } + + interface PromisedOwnProperty { + (name: string, message?: string): PromisedAssertion; + } + + interface PromisedLength extends PromisedLanguageChains, PromisedNumericComparison { + (length: number, message?: string): PromisedAssertion; + } + + interface PromisedInclude { + (value: Object, message?: string): PromisedAssertion; + (value: string, message?: string): PromisedAssertion; + (value: number, message?: string): PromisedAssertion; + keys: PromisedKeys; + members: PromisedMembers; + all: PromisedKeyFilter; + } + + interface PromisedKeys { + (...keys: string[]): PromisedAssertion; + (keys: any[]): PromisedAssertion; + } + + interface PromisedThrow { + (): PromisedAssertion; + (expected: string, message?: string): PromisedAssertion; + (expected: RegExp, message?: string): PromisedAssertion; + (constructor: Error, expected?: string, message?: string): PromisedAssertion; + (constructor: Error, expected?: RegExp, message?: string): PromisedAssertion; + (constructor: Function, expected?: string, message?: string): PromisedAssertion; + (constructor: Function, expected?: RegExp, message?: string): PromisedAssertion; + } + + interface PromisedMembers { + (set: any[], message?: string): PromisedAssertion; + } + + // For Assert API + interface Assert { + eventually: PromisedAssert; + isFulfilled(promise: PromisesAPlus.Thenable, message?: string): PromisesAPlus.Thenable; + becomes(promise: PromisesAPlus.Thenable, expected: any, message?: string): PromisesAPlus.Thenable; + doesNotBecome(promise: PromisesAPlus.Thenable, expected: any, message?: string): PromisesAPlus.Thenable; + isRejected(promise: PromisesAPlus.Thenable, message?: string): PromisesAPlus.Thenable; + isRejected(promise: PromisesAPlus.Thenable, expected: any, message?: string): PromisesAPlus.Thenable; + isRejected(promise: PromisesAPlus.Thenable, match: RegExp, message?: string): PromisesAPlus.Thenable; + notify(fn: Function): PromisesAPlus.Thenable; + } + + export interface PromisedAssert { + fail(actual?: any, expected?: any, msg?: string, operator?: string): PromisesAPlus.Thenable; + + ok(val: any, msg?: string): PromisesAPlus.Thenable; + notOk(val: any, msg?: string): PromisesAPlus.Thenable; + + equal(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; + notEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; + + strictEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; + notStrictEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; + + deepEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; + notDeepEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable; + + isTrue(val: any, msg?: string): PromisesAPlus.Thenable; + isFalse(val: any, msg?: string): PromisesAPlus.Thenable; + + isNull(val: any, msg?: string): PromisesAPlus.Thenable; + isNotNull(val: any, msg?: string): PromisesAPlus.Thenable; + + isUndefined(val: any, msg?: string): PromisesAPlus.Thenable; + isDefined(val: any, msg?: string): PromisesAPlus.Thenable; + + isFunction(val: any, msg?: string): PromisesAPlus.Thenable; + isNotFunction(val: any, msg?: string): PromisesAPlus.Thenable; + + isObject(val: any, msg?: string): PromisesAPlus.Thenable; + isNotObject(val: any, msg?: string): PromisesAPlus.Thenable; + + isArray(val: any, msg?: string): PromisesAPlus.Thenable; + isNotArray(val: any, msg?: string): PromisesAPlus.Thenable; + + isString(val: any, msg?: string): PromisesAPlus.Thenable; + isNotString(val: any, msg?: string): PromisesAPlus.Thenable; + + isNumber(val: any, msg?: string): PromisesAPlus.Thenable; + isNotNumber(val: any, msg?: string): PromisesAPlus.Thenable; + + isBoolean(val: any, msg?: string): PromisesAPlus.Thenable; + isNotBoolean(val: any, msg?: string): PromisesAPlus.Thenable; + + typeOf(val: any, type: string, msg?: string): PromisesAPlus.Thenable; + notTypeOf(val: any, type: string, msg?: string): PromisesAPlus.Thenable; + + instanceOf(val: any, type: Function, msg?: string): PromisesAPlus.Thenable; + notInstanceOf(val: any, type: Function, msg?: string): PromisesAPlus.Thenable; + + include(exp: string, inc: any, msg?: string): PromisesAPlus.Thenable; + include(exp: any[], inc: any, msg?: string): PromisesAPlus.Thenable; + + notInclude(exp: string, inc: any, msg?: string): PromisesAPlus.Thenable; + notInclude(exp: any[], inc: any, msg?: string): PromisesAPlus.Thenable; + + match(exp: any, re: RegExp, msg?: string): PromisesAPlus.Thenable; + notMatch(exp: any, re: RegExp, msg?: string): PromisesAPlus.Thenable; + + property(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable; + notProperty(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable; + deepProperty(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable; + notDeepProperty(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable; + + propertyVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable; + + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable; + + lengthOf(exp: any, len: number, msg?: string): PromisesAPlus.Thenable; + //alias frenzy + throw(fn: Function, msg?: string): PromisesAPlus.Thenable; + throw(fn: Function, regExp: RegExp): PromisesAPlus.Thenable; + throw(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable; + throw(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable; + + throws(fn: Function, msg?: string): PromisesAPlus.Thenable; + throws(fn: Function, regExp: RegExp): PromisesAPlus.Thenable; + throws(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable; + throws(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable; + + Throw(fn: Function, msg?: string): PromisesAPlus.Thenable; + Throw(fn: Function, regExp: RegExp): PromisesAPlus.Thenable; + Throw(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable; + Throw(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable; + + doesNotThrow(fn: Function, msg?: string): PromisesAPlus.Thenable; + doesNotThrow(fn: Function, regExp: RegExp): PromisesAPlus.Thenable; + doesNotThrow(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable; + + operator(val: any, operator: string, val2: any, msg?: string): PromisesAPlus.Thenable; + closeTo(act: number, exp: number, delta: number, msg?: string): PromisesAPlus.Thenable; + + sameMembers(set1: any[], set2: any[], msg?: string): PromisesAPlus.Thenable; + includeMembers(set1: any[], set2: any[], msg?: string): PromisesAPlus.Thenable; + + ifError(val: any, msg?: string): PromisesAPlus.Thenable; + } +} diff --git a/chai-as-promised/tsconfig.json b/chai-as-promised/tsconfig.json new file mode 100644 index 0000000000..faa3ff15be --- /dev/null +++ b/chai-as-promised/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chai-as-promised-tests.ts" + ] +} \ No newline at end of file diff --git a/chai-datetime/chai-datetime-tests.ts b/chai-datetime/chai-datetime-tests.ts index 5c15326f48..255d816b5a 100644 --- a/chai-datetime/chai-datetime-tests.ts +++ b/chai-datetime/chai-datetime-tests.ts @@ -1,4 +1,3 @@ -/// import chai = require('chai'); import chaiDateTime = require('chai-datetime'); diff --git a/chai-datetime/chai-datetime.d.ts b/chai-datetime/chai-datetime.d.ts deleted file mode 100644 index 16dd6b8856..0000000000 --- a/chai-datetime/chai-datetime.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -// Type definitions for chai-datetime -// Project: https://github.com/gaslight/chai-datetime.git -// Definitions by: Cliff Burger -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Chai { - - interface Assertion { - afterDate(date: Date): Assertion; - beforeDate(date: Date): Assertion; - equalDate(date: Date): Assertion; - afterTime(date: Date): Assertion; - beforeTime(date: Date): Assertion; - equalTime(date: Date): Assertion; - } - - interface Assert { - equalTime(val: Date, exp: Date, msg?: string): void; - notEqualTime(val: Date, exp: Date, msg?: string): void; - beforeTime(val: Date, exp: Date, msg?: string): void; - notBeforeTime(val: Date, exp: Date, msg?: string): void; - afterTime(val: Date, exp: Date, msg?: string): void; - notAfterTime(val: Date, exp: Date, msg?: string): void; - equalDate(val: Date, exp: Date, msg?: string): void; - notEqualDate(val: Date, exp: Date, msg?: string): void; - beforeDate(val: Date, exp: Date, msg?: string): void; - notBeforeDate(val: Date, exp: Date, msg?: string): void; - afterDate(val: Date, exp: Date, msg?: string): void; - notAfterDate(val: Date, exp: Date, msg?: string): void; - } -} - -interface Date { - should: Chai.Assertion; -} - -declare module "chai-datetime" { - function chaiDateTime(chai: any, utils: any): void; - export = chaiDateTime; -} diff --git a/chai-datetime/index.d.ts b/chai-datetime/index.d.ts new file mode 100644 index 0000000000..c008586cfe --- /dev/null +++ b/chai-datetime/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for chai-datetime +// Project: https://github.com/gaslight/chai-datetime.git +// Definitions by: Cliff Burger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare function chaiDateTime(chai: any, utils: any): void; +export = chaiDateTime; + +declare global { + namespace Chai { + interface Assertion { + afterDate(date: Date): Assertion; + beforeDate(date: Date): Assertion; + equalDate(date: Date): Assertion; + afterTime(date: Date): Assertion; + beforeTime(date: Date): Assertion; + equalTime(date: Date): Assertion; + } + + interface Assert { + equalTime(val: Date, exp: Date, msg?: string): void; + notEqualTime(val: Date, exp: Date, msg?: string): void; + beforeTime(val: Date, exp: Date, msg?: string): void; + notBeforeTime(val: Date, exp: Date, msg?: string): void; + afterTime(val: Date, exp: Date, msg?: string): void; + notAfterTime(val: Date, exp: Date, msg?: string): void; + equalDate(val: Date, exp: Date, msg?: string): void; + notEqualDate(val: Date, exp: Date, msg?: string): void; + beforeDate(val: Date, exp: Date, msg?: string): void; + notBeforeDate(val: Date, exp: Date, msg?: string): void; + afterDate(val: Date, exp: Date, msg?: string): void; + notAfterDate(val: Date, exp: Date, msg?: string): void; + } + } + + interface Date { + should: Chai.Assertion; + } +} diff --git a/chai-datetime/tsconfig.json b/chai-datetime/tsconfig.json new file mode 100644 index 0000000000..4ecf86a4fb --- /dev/null +++ b/chai-datetime/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chai-datetime-tests.ts" + ] +} \ No newline at end of file diff --git a/chai-fuzzy/chai-fuzzy-tests.ts b/chai-fuzzy/chai-fuzzy-tests.ts index 292b25002d..42805a1869 100644 --- a/chai-fuzzy/chai-fuzzy-tests.ts +++ b/chai-fuzzy/chai-fuzzy-tests.ts @@ -1,4 +1,3 @@ -/// // tests taken from http://chaijs.com/plugins/chai-fuzzy diff --git a/chai-fuzzy/chai-fuzzy.d.ts b/chai-fuzzy/chai-fuzzy.d.ts deleted file mode 100644 index 163ce7dda7..0000000000 --- a/chai-fuzzy/chai-fuzzy.d.ts +++ /dev/null @@ -1,76 +0,0 @@ -// Type definitions for chai-fuzzy 1.3.0 -// Project: http://chaijs.com/plugins/chai-fuzzy -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Chai { - - interface Assertion { - /** - * Compare object attributes and values rather than checking to see if - * they're the same reference. - */ - like(expected: any, message?: string): Assertion; - /** - * Compare object attributes and values rather than checking to see if - * they're the same reference. - */ - notLike(expected: any, message?: string): Assertion; - /** - * Check the first level of the container for a value like the one provided. - */ - containOneLike(expected: any, message?: string): Assertion; - /** - * Check the first level of the container for a value like the one provided. - */ - notContainOneLike(expected: any, message?: string): Assertion; - /** - * Check that the given javascript object is like the JSON-ified expected - * value. Useful for checking stringification and parsing of an object. - */ - jsonOf(expected: any, message?: string): Assertion; - /** - * Check that the given javascript object is like the JSON-ified expected - * value. Useful for checking stringification and parsing of an object. - */ - notJsonOf(expected: any, message?: string): Assertion; - } - - export interface Assert { - /** - * Compare object attributes and values rather than checking to see if - * they're the same reference. - */ - like(actual: any, expected: any, message?: string): void; - /** - * Compare object attributes and values rather than checking to see if - * they're the same reference. - */ - notLike(actual: any, expected: any, message?: string): void; - /** - * Check the first level of the container for a value like the one provided. - */ - containOneLike(actual: any, expected: any, message?: string): void; - /** - * Check the first level of the container for a value like the one provided. - */ - notContainOneLike(actual: any, expected: any, message?: string): void; - /** - * Check that the given javascript object is like the JSON-ified expected - * value. Useful for checking stringification and parsing of an object. - */ - jsonOf(actual: any, expected: any, message?: string): void; - /** - * Check that the given javascript object is like the JSON-ified expected - * value. Useful for checking stringification and parsing of an object. - */ - notJsonOf(actual: any, expected: any, message?: string): void; - } -} - -declare module "chai-fuzzy" { - function chaiFuzzy(chai: any, utils: any): void; - export = chaiFuzzy; -} diff --git a/chai-fuzzy/index.d.ts b/chai-fuzzy/index.d.ts new file mode 100644 index 0000000000..b4f8c1191c --- /dev/null +++ b/chai-fuzzy/index.d.ts @@ -0,0 +1,76 @@ +// Type definitions for chai-fuzzy 1.3.0 +// Project: http://chaijs.com/plugins/chai-fuzzy +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare global { + namespace Chai { + interface Assertion { + /** + * Compare object attributes and values rather than checking to see if + * they're the same reference. + */ + like(expected: any, message?: string): Assertion; + /** + * Compare object attributes and values rather than checking to see if + * they're the same reference. + */ + notLike(expected: any, message?: string): Assertion; + /** + * Check the first level of the container for a value like the one provided. + */ + containOneLike(expected: any, message?: string): Assertion; + /** + * Check the first level of the container for a value like the one provided. + */ + notContainOneLike(expected: any, message?: string): Assertion; + /** + * Check that the given javascript object is like the JSON-ified expected + * value. Useful for checking stringification and parsing of an object. + */ + jsonOf(expected: any, message?: string): Assertion; + /** + * Check that the given javascript object is like the JSON-ified expected + * value. Useful for checking stringification and parsing of an object. + */ + notJsonOf(expected: any, message?: string): Assertion; + } + + interface Assert { + /** + * Compare object attributes and values rather than checking to see if + * they're the same reference. + */ + like(actual: any, expected: any, message?: string): void; + /** + * Compare object attributes and values rather than checking to see if + * they're the same reference. + */ + notLike(actual: any, expected: any, message?: string): void; + /** + * Check the first level of the container for a value like the one provided. + */ + containOneLike(actual: any, expected: any, message?: string): void; + /** + * Check the first level of the container for a value like the one provided. + */ + notContainOneLike(actual: any, expected: any, message?: string): void; + /** + * Check that the given javascript object is like the JSON-ified expected + * value. Useful for checking stringification and parsing of an object. + */ + jsonOf(actual: any, expected: any, message?: string): void; + /** + * Check that the given javascript object is like the JSON-ified expected + * value. Useful for checking stringification and parsing of an object. + */ + notJsonOf(actual: any, expected: any, message?: string): void; + } + } +} + +declare function chaiFuzzy(chai: any, utils: any): void; +export = chaiFuzzy; + diff --git a/chai-fuzzy/tsconfig.json b/chai-fuzzy/tsconfig.json new file mode 100644 index 0000000000..d0ab502b12 --- /dev/null +++ b/chai-fuzzy/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chai-fuzzy-tests.ts" + ] +} \ No newline at end of file diff --git a/chai-http/chai-http-tests.ts b/chai-http/chai-http-tests.ts index 078a7799c6..369e5b8ee3 100644 --- a/chai-http/chai-http-tests.ts +++ b/chai-http/chai-http-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + import fs = require('fs'); import http = require('http'); diff --git a/chai-http/chai-http.d.ts b/chai-http/chai-http.d.ts deleted file mode 100644 index a542081635..0000000000 --- a/chai-http/chai-http.d.ts +++ /dev/null @@ -1,84 +0,0 @@ -// Type definitions for chai-http -// Project: https://github.com/chaijs/chai-http -// Definitions by: Wim Looman -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare namespace Chai { - - interface ChaiStatic { - request: ChaiHttpRequest; - } - - interface ChaiHttpRequest { - (server: any): ChaiHttp.Agent; - agent(server: any): ChaiHttp.Agent; - addPromises(promiseConstructor: any): void; - } - - interface Assertion { - status(code: number): Assertion; - header(key: string, value?: string): Assertion; - header(key: string, value?: RegExp): Assertion; - headers: Assertion; - json: Assertion; - text: Assertion; - html: Assertion; - redirect: Assertion; - redirectTo(location: string): Assertion; - param(key: string, value?: string): Assertion; - cookie(key: string, value?: string): Assertion; - } - - interface TypeComparison { - ip: Assertion; - } -} - -declare namespace ChaiHttp { - interface Promise { - then(onFulfilled: (value: T) => U, onRejected?: (reason: any) => U): Promise; - } - - interface Response { - body: any; - type: string; - status: number; - } - - interface Request extends FinishedRequest { - attach(field: string, file: string|Buffer, filename: string): Request; - set(field: string, val: string): Request; - query(params: Object): Request; - send(data: Object): Request; - auth(user: string, name: string): Request; - field(name: string, val: string): Request; - end(callback?: (err: any, res: Response) => void): FinishedRequest; - } - - interface FinishedRequest { - then(success?: (res: Response) => void, failure?: (err: any) => void): FinishedRequest; - catch(failure?: (err: any) => void): FinishedRequest; - } - - interface Agent { - get(url: string, callback?: (err: any, res: Response) => void): Request; - post(url: string, callback?: (err: any, res: Response) => void): Request; - put(url: string, callback?: (err: any, res: Response) => void): Request; - head(url: string, callback?: (err: any, res: Response) => void): Request; - del(url: string, callback?: (err: any, res: Response) => void): Request; - options(url: string, callback?: (err: any, res: Response) => void): Request; - patch(url: string, callback?: (err: any, res: Response) => void): Request; - } - - interface TypeComparison { - ip: any; - } -} - -declare module "chai-http" { - function chaiHttp(chai: any, utils: any): void; - export = chaiHttp; -} diff --git a/chai-http/index.d.ts b/chai-http/index.d.ts new file mode 100644 index 0000000000..567f13e4e7 --- /dev/null +++ b/chai-http/index.d.ts @@ -0,0 +1,84 @@ +// Type definitions for chai-http +// Project: https://github.com/chaijs/chai-http +// Definitions by: Wim Looman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace Chai { + + interface ChaiStatic { + request: ChaiHttpRequest; + } + + interface ChaiHttpRequest { + (server: any): ChaiHttp.Agent; + agent(server: any): ChaiHttp.Agent; + addPromises(promiseConstructor: any): void; + } + + interface Assertion { + status(code: number): Assertion; + header(key: string, value?: string): Assertion; + header(key: string, value?: RegExp): Assertion; + headers: Assertion; + json: Assertion; + text: Assertion; + html: Assertion; + redirect: Assertion; + redirectTo(location: string): Assertion; + param(key: string, value?: string): Assertion; + cookie(key: string, value?: string): Assertion; + } + + interface TypeComparison { + ip: Assertion; + } +} + +declare namespace ChaiHttp { + interface Promise { + then(onFulfilled: (value: T) => U, onRejected?: (reason: any) => U): Promise; + } + + interface Response { + body: any; + type: string; + status: number; + } + + interface Request extends FinishedRequest { + attach(field: string, file: string|Buffer, filename: string): Request; + set(field: string, val: string): Request; + query(params: Object): Request; + send(data: Object): Request; + auth(user: string, name: string): Request; + field(name: string, val: string): Request; + end(callback?: (err: any, res: Response) => void): FinishedRequest; + } + + interface FinishedRequest { + then(success?: (res: Response) => void, failure?: (err: any) => void): FinishedRequest; + catch(failure?: (err: any) => void): FinishedRequest; + } + + interface Agent { + get(url: string, callback?: (err: any, res: Response) => void): Request; + post(url: string, callback?: (err: any, res: Response) => void): Request; + put(url: string, callback?: (err: any, res: Response) => void): Request; + head(url: string, callback?: (err: any, res: Response) => void): Request; + del(url: string, callback?: (err: any, res: Response) => void): Request; + options(url: string, callback?: (err: any, res: Response) => void): Request; + patch(url: string, callback?: (err: any, res: Response) => void): Request; + } + + interface TypeComparison { + ip: any; + } +} + +declare module "chai-http" { + function chaiHttp(chai: any, utils: any): void; + export = chaiHttp; +} diff --git a/chai-http/tsconfig.json b/chai-http/tsconfig.json new file mode 100644 index 0000000000..4453285f95 --- /dev/null +++ b/chai-http/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chai-http-tests.ts" + ] +} \ No newline at end of file diff --git a/chai-jquery/chai-jquery-tests.ts b/chai-jquery/chai-jquery-tests.ts index 64f6b040b9..52c54ab7ee 100644 --- a/chai-jquery/chai-jquery-tests.ts +++ b/chai-jquery/chai-jquery-tests.ts @@ -1,4 +1,4 @@ -/// + // tests taken from https://github.com/chaijs/chai-jquery diff --git a/chai-jquery/chai-jquery.d.ts b/chai-jquery/chai-jquery.d.ts deleted file mode 100644 index 3d287f30fc..0000000000 --- a/chai-jquery/chai-jquery.d.ts +++ /dev/null @@ -1,2580 +0,0 @@ -// Type definitions for chai-jquery 1.1.1 -// Project: https://github.com/chaijs/chai-jquery -// Definitions by: Kazi Manzur Rashid -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare namespace Chai { - - interface Assertion { - attr: (name: string, value?: string) => Assertion; - css: (name: string, value?: string) => Assertion; - data: (name: string, value?: string) => Assertion; - class(className: string): Assertion; - id(id: string): Assertion; - html(html: string): Assertion; - text(text: string): Assertion; - value(text: string): Assertion; - (selector: string): Assertion; - visible: Assertion; - hidden: Assertion; - selected: Assertion; - checked: Assertion; - disabled: Assertion; - (selector: string): Assertion; - } -} - -/** - * Static members of chai-jquery (those on $ and jQuery themselves) - */ -interface ChaiJQueryStatic { - - /** - * Perform an asynchronous HTTP (Ajax) request. - * - * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). - */ - ajax(settings: JQueryAjaxSettings): JQueryXHR; - /** - * Perform an asynchronous HTTP (Ajax) request. - * - * @param url A string containing the URL to which the request is sent. - * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). - */ - ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; - - /** - * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). - * - * @param dataTypes An optional string containing one or more space-separated dataTypes - * @param handler A handler to set default values for future Ajax requests. - */ - ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; - /** - * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). - * - * @param handler A handler to set default values for future Ajax requests. - */ - ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; - - ajaxSettings: JQueryAjaxSettings; - - /** - * Set default values for future Ajax requests. Its use is not recommended. - * - * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. - */ - ajaxSetup(options: JQueryAjaxSettings): void; - - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). - */ - get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). - */ - get(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - */ - getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. - */ - getJSON(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; - /** - * Load a JavaScript file from the server using a GET HTTP request, then execute it. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - */ - getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; - - /** - * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - */ - param: JQueryParam; - - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - */ - post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - */ - post(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; - - /** - * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. - * - * @param flags An optional list of space-separated flags that change how the callback list behaves. - */ - Callbacks(flags?: string): JQueryCallback; - - /** - * Holds or releases the execution of jQuery's ready event. - * - * @param hold Indicates whether the ready hold is being requested or released - */ - holdReady(hold: boolean): void; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param selector A string containing a selector expression - * @param context A DOM Element, Document, or jQuery to use as context - */ - (selector: string, context?: Element|JQuery): ChaiJQuery; - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param element A DOM element to wrap in a jQuery object. - */ - (element: Element): ChaiJQuery; - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. - */ - (elementArray: Element[]): ChaiJQuery; - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param object A plain object to wrap in a jQuery object. - */ - (object: {}): ChaiJQuery; - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param object An existing jQuery object to clone. - */ - (object: JQuery): ChaiJQuery; - /** - * Specify a function to execute when the DOM is fully loaded. - */ - (): ChaiJQuery; - - /** - * Creates DOM elements on the fly from the provided string of raw HTML. - * - * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. - * @param ownerDocument A document in which the new elements will be created. - */ - (html: string, ownerDocument?: Document): ChaiJQuery; - /** - * Creates DOM elements on the fly from the provided string of raw HTML. - * - * @param html A string defining a single, standalone, HTML element (e.g.
or
). - * @param attributes An object of attributes, events, and methods to call on the newly-created element. - */ - (html: string, attributes: Object): ChaiJQuery; - - /** - * Binds a function to be executed when the DOM has finished loading. - * - * @param callback A function to execute after the DOM is ready. - */ - (callback: Function): ChaiJQuery; - - /** - * Relinquish jQuery's control of the $ variable. - * - * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). - */ - noConflict(removeAll?: boolean): Object; - - /** - * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. - * - * @param deferreds One or more Deferred objects, or plain JavaScript objects. - */ - when(...deferreds: Array/* as JQueryDeferred */>): JQueryPromise; - - /** - * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties. - */ - cssHooks: { [key: string]: any; }; - cssNumber: any; - - /** - * Store arbitrary data associated with the specified element. Returns the value that was set. - * - * @param element The DOM element to associate with the data. - * @param key A string naming the piece of data to set. - * @param value The new data value. - */ - data(element: Element, key: string, value: T): T; - /** - * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. - * - * @param element The DOM element to associate with the data. - * @param key A string naming the piece of data to set. - */ - data(element: Element, key: string): any; - /** - * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. - * - * @param element The DOM element to associate with the data. - */ - data(element: Element): any; - - /** - * Execute the next function on the queue for the matched element. - * - * @param element A DOM element from which to remove and execute a queued function. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - dequeue(element: Element, queueName?: string): void; - - /** - * Determine whether an element has any jQuery data associated with it. - * - * @param element A DOM element to be checked for data. - */ - hasData(element: Element): boolean; - - /** - * Show the queue of functions to be executed on the matched element. - * - * @param element A DOM element to inspect for an attached queue. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - queue(element: Element, queueName?: string): any[]; - /** - * Manipulate the queue of functions to be executed on the matched element. - * - * @param element A DOM element where the array of queued functions is attached. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param newQueue An array of functions to replace the current queue contents. - */ - queue(element: Element, queueName: string, newQueue: Function[]): ChaiJQuery; - /** - * Manipulate the queue of functions to be executed on the matched element. - * - * @param element A DOM element on which to add a queued function. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param callback The new function to add to the queue. - */ - queue(element: Element, queueName: string, callback: Function): ChaiJQuery; - - /** - * Remove a previously-stored piece of data. - * - * @param element A DOM element from which to remove data. - * @param name A string naming the piece of data to remove. - */ - removeData(element: Element, name?: string): ChaiJQuery; - - /** - * A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. - * - * @param beforeStart A function that is called just before the constructor returns. - */ - Deferred(beforeStart?: (deferred: JQueryDeferred) => any): JQueryDeferred; - - /** - * Effects - */ - fx: { - tick: () => void; - /** - * The rate (in milliseconds) at which animations fire. - */ - interval: number; - stop: () => void; - speeds: { slow: number; fast: number; }; - /** - * Globally disable all animations. - */ - off: boolean; - step: any; - }; - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fnction The function whose context will be changed. - * @param context The object to which the context (this) of the function should be set. - * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. - */ - proxy(fnction: (...args: any[]) => any, context: Object, ...additionalArguments: any[]): any; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param context The object to which the context (this) of the function should be set. - * @param name The name of the function whose context will be changed (should be a property of the context object). - * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. - */ - proxy(context: Object, name: string, ...additionalArguments: any[]): any; - - Event: JQueryEventConstructor; - - /** - * Takes a string and throws an exception containing it. - * - * @param message The message to send out. - */ - error(message: any): ChaiJQuery; - - expr: any; - fn: any; //TODO: Decide how we want to type this - - isReady: boolean; - - // Properties - support: JQuerySupport; - - /** - * Check to see if a DOM element is a descendant of another DOM element. - * - * @param container The DOM element that may contain the other element. - * @param contained The DOM element that may be contained by (a descendant of) the other element. - */ - contains(container: Element, contained: Element): boolean; - - /** - * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * - * @param collection The object or array to iterate over. - * @param callback The function that will be executed on every object. - */ - each( - collection: T[], - callback: (indexInArray: number, valueOfElement: T) => any - ): any; - - /** - * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * - * @param collection The object or array to iterate over. - * @param callback The function that will be executed on every object. - */ - each( - collection: any, - callback: (indexInArray: any, valueOfElement: any) => any - ): any; - - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. - * @param object1 An object containing additional properties to merge in. - * @param objectN Additional objects containing properties to merge in. - */ - extend(target: any, object1?: any, ...objectN: any[]): any; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). - * @param target The object to extend. It will receive the new properties. - * @param object1 An object containing additional properties to merge in. - * @param objectN Additional objects containing properties to merge in. - */ - extend(deep: boolean, target: any, object1?: any, ...objectN: any[]): any; - - /** - * Execute some JavaScript code globally. - * - * @param code The JavaScript code to execute. - */ - globalEval(code: string): any; - - /** - * Finds the elements of an array which satisfy a filter function. The original array is not affected. - * - * @param array The array to search through. - * @param func The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. - * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false. - */ - grep(array: T[], func: (elementOfArray: T, indexInArray: number) => boolean, invert?: boolean): T[]; - - /** - * Search for a specified value within an array and return its index (or -1 if not found). - * - * @param value The value to search for. - * @param array An array through which to search. - * @param fromIndex he index of the array at which to begin the search. The default is 0, which will search the whole array. - */ - inArray(value: T, array: T[], fromIndex?: number): number; - - /** - * Determine whether the argument is an array. - * - * @param obj Object to test whether or not it is an array. - */ - isArray(obj: any): boolean; - /** - * Check to see if an object is empty (contains no enumerable properties). - * - * @param obj The object that will be checked to see if it's empty. - */ - isEmptyObject(obj: any): boolean; - /** - * Determine if the argument passed is a Javascript function object. - * - * @param obj Object to test whether or not it is a function. - */ - isFunction(obj: any): boolean; - /** - * Determines whether its argument is a number. - * - * @param obj The value to be tested. - */ - isNumeric(value: any): boolean; - /** - * Check to see if an object is a plain object (created using "{}" or "new Object"). - * - * @param obj The object that will be checked to see if it's a plain object. - */ - isPlainObject(obj: any): boolean; - /** - * Determine whether the argument is a window. - * - * @param obj Object to test whether or not it is a window. - */ - isWindow(obj: any): boolean; - /** - * Check to see if a DOM node is within an XML document (or is an XML document). - * - * @param node he DOM node that will be checked to see if it's in an XML document. - */ - isXMLDoc(node: Node): boolean; - - /** - * Convert an array-like object into a true JavaScript array. - * - * @param obj Any object to turn into a native Array. - */ - makeArray(obj: any): any[]; - - /** - * Translate all items in an array or object to new array of items. - * - * @param array The Array to translate. - * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. - */ - map(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[]; - /** - * Translate all items in an array or object to new array of items. - * - * @param arrayOrObject The Array or Object to translate. - * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. - */ - map(arrayOrObject: any, callback: (value: any, indexOrKey: any) => any): any; - - /** - * Merge the contents of two arrays together into the first array. - * - * @param first The first array to merge, the elements of second added. - * @param second The second array to merge into the first, unaltered. - */ - merge(first: T[], second: T[]): T[]; - - /** - * An empty function. - */ - noop(): any; - - /** - * Return a number representing the current time. - */ - now(): number; - - /** - * Takes a well-formed JSON string and returns the resulting JavaScript object. - * - * @param json The JSON string to parse. - */ - parseJSON(json: string): any; - - /** - * Parses a string into an XML document. - * - * @param data a well-formed XML string to be parsed - */ - parseXML(data: string): XMLDocument; - - /** - * Remove the whitespace from the beginning and end of a string. - * - * @param str Remove the whitespace from the beginning and end of a string. - */ - trim(str: string): string; - - /** - * Determine the internal JavaScript [[Class]] of an object. - * - * @param obj Object to get the internal JavaScript [[Class]] of. - */ - type(obj: any): string; - - /** - * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. - * - * @param array The Array of DOM elements. - */ - unique(array: Element[]): Element[]; - - /** - * Parses a string into an array of DOM nodes. - * - * @param data HTML string to be parsed - * @param context DOM element to serve as the context in which the HTML fragment will be created - * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string - */ - parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; - - /** - * Parses a string into an array of DOM nodes. - * - * @param data HTML string to be parsed - * @param context DOM element to serve as the context in which the HTML fragment will be created - * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string - */ - parseHTML(data: string, context?: Document, keepScripts?: boolean): any[]; -} - -/** - * The chai-jquery instance members - */ -interface ChaiJQuery { - /** - * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. - * - * @param handler The function to be invoked. - */ - ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): ChaiJQuery; - /** - * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: any) => any): ChaiJQuery; - /** - * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) => any): ChaiJQuery; - /** - * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxStart(handler: () => any): ChaiJQuery; - /** - * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxStop(handler: () => any): ChaiJQuery; - /** - * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. - * - * @param handler The function to be invoked. - */ - ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) => any): ChaiJQuery; - - /** - * Load data from the server and place the returned HTML into the matched element. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param complete A callback function that is executed when the request completes. - */ - load(url: string, data?: string|Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): ChaiJQuery; - - /** - * Encode a set of form elements as a string for submission. - */ - serialize(): string; - /** - * Encode a set of form elements as an array of names and values. - */ - serializeArray(): JQuerySerializeArrayElement[]; - - /** - * Adds the specified class(es) to each of the set of matched elements. - * - * @param className One or more space-separated classes to be added to the class attribute of each matched element. - */ - addClass(className: string): ChaiJQuery; - /** - * Adds the specified class(es) to each of the set of matched elements. - * - * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set. - */ - addClass(func: (index: number, className: string) => string): ChaiJQuery; - - /** - * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. - */ - addBack(selector?: string): ChaiJQuery; - - /** - * Get the value of an attribute for the first element in the set of matched elements. - * - * @param attributeName The name of the attribute to get. - */ - attr(attributeName: string): string; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributeName The name of the attribute to set. - * @param value A value to set for the attribute. - */ - attr(attributeName: string, value: string|number): ChaiJQuery; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributeName The name of the attribute to set. - * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. - */ - attr(attributeName: string, func: (index: number, attr: string) => string|number): ChaiJQuery; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributes An object of attribute-value pairs to set. - */ - attr(attributes: Object): ChaiJQuery; - - /** - * Determine whether any of the matched elements are assigned the given class. - * - * @param className The class name to search for. - */ - hasClass(className: string): boolean; - - /** - * Get the HTML contents of the first element in the set of matched elements. - */ - html(): string; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param htmlString A string of HTML to set as the content of each matched element. - */ - html(htmlString: string): ChaiJQuery; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. - */ - html(func: (index: number, oldhtml: string) => string): ChaiJQuery; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. - */ - - /** - * Get the value of a property for the first element in the set of matched elements. - * - * @param propertyName The name of the property to get. - */ - prop(propertyName: string): any; - /** - * Set one or more properties for the set of matched elements. - * - * @param propertyName The name of the property to set. - * @param value A value to set for the property. - */ - prop(propertyName: string, value: string|number|boolean): ChaiJQuery; - /** - * Set one or more properties for the set of matched elements. - * - * @param properties An object of property-value pairs to set. - */ - prop(properties: Object): ChaiJQuery; - /** - * Set one or more properties for the set of matched elements. - * - * @param propertyName The name of the property to set. - * @param func A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element. - */ - prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): ChaiJQuery; - - /** - * Remove an attribute from each element in the set of matched elements. - * - * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. - */ - removeAttr(attributeName: string): ChaiJQuery; - - /** - * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. - * - * @param className One or more space-separated classes to be removed from the class attribute of each matched element. - */ - removeClass(className?: string): ChaiJQuery; - /** - * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. - * - * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. - */ - removeClass(func: (index: number, className: string) => string): ChaiJQuery; - - /** - * Remove a property for the set of matched elements. - * - * @param propertyName The name of the property to remove. - */ - removeProp(propertyName: string): ChaiJQuery; - - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - * - * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. - * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. - */ - toggleClass(className: string, swtch?: boolean): ChaiJQuery; - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - * - * @param swtch A boolean value to determine whether the class should be added or removed. - */ - toggleClass(swtch?: boolean): ChaiJQuery; - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. - * - * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. - * @param swtch A boolean value to determine whether the class should be added or removed. - */ - toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): ChaiJQuery; - - /** - * Get the current value of the first element in the set of matched elements. - */ - val(): any; - /** - * Set the value of each element in the set of matched elements. - * - * @param value A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked. - */ - val(value: string|string[]): ChaiJQuery; - /** - * Set the value of each element in the set of matched elements. - * - * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. - */ - val(func: (index: number, value: string) => string): ChaiJQuery; - - - /** - * Get the value of style properties for the first element in the set of matched elements. - * - * @param propertyName A CSS property. - */ - css(propertyName: string): string; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param propertyName A CSS property name. - * @param value A value to set for the property. - */ - css(propertyName: string, value: string|number): ChaiJQuery; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param propertyName A CSS property name. - * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. - */ - css(propertyName: string, value: (index: number, value: string) => string|number): ChaiJQuery; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param properties An object of property-value pairs to set. - */ - css(properties: Object): ChaiJQuery; - - /** - * Get the current computed height for the first element in the set of matched elements. - */ - height(): number; - /** - * Set the CSS height of every matched element. - * - * @param value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string). - */ - height(value: number|string): ChaiJQuery; - /** - * Set the CSS height of every matched element. - * - * @param func A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set. - */ - height(func: (index: number, height: number) => number|string): ChaiJQuery; - - /** - * Get the current computed height for the first element in the set of matched elements, including padding but not border. - */ - innerHeight(): number; - - /** - * Sets the inner height on elements in the set of matched elements, including padding but not border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - innerHeight(height: number|string): ChaiJQuery; - - /** - * Get the current computed width for the first element in the set of matched elements, including padding but not border. - */ - innerWidth(): number; - - /** - * Sets the inner width on elements in the set of matched elements, including padding but not border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - innerWidth(width: number|string): ChaiJQuery; - - /** - * Get the current coordinates of the first element in the set of matched elements, relative to the document. - */ - offset(): JQueryCoordinates; - /** - * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - * - * @param coordinates An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - */ - offset(coordinates: JQueryCoordinates): ChaiJQuery; - /** - * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. - * - * @param func A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties. - */ - offset(func: (index: number, coords: JQueryCoordinates) => JQueryCoordinates): ChaiJQuery; - - /** - * Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements. - * - * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. - */ - outerHeight(includeMargin?: boolean): number; - - /** - * Sets the outer height on elements in the set of matched elements, including padding and border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - outerHeight(height: number|string): ChaiJQuery; - - /** - * Get the current computed width for the first element in the set of matched elements, including padding and border. - * - * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. - */ - outerWidth(includeMargin?: boolean): number; - - /** - * Sets the outer width on elements in the set of matched elements, including padding and border. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - outerWidth(width: number|string): ChaiJQuery; - - /** - * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. - */ - position(): JQueryCoordinates; - - /** - * Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element. - */ - scrollLeft(): number; - /** - * Set the current horizontal position of the scroll bar for each of the set of matched elements. - * - * @param value An integer indicating the new position to set the scroll bar to. - */ - scrollLeft(value: number): ChaiJQuery; - - /** - * Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. - */ - scrollTop(): number; - /** - * Set the current vertical position of the scroll bar for each of the set of matched elements. - * - * @param value An integer indicating the new position to set the scroll bar to. - */ - scrollTop(value: number): ChaiJQuery; - - /** - * Get the current computed width for the first element in the set of matched elements. - */ - width(): number; - /** - * Set the CSS width of each element in the set of matched elements. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). - */ - width(value: number|string): ChaiJQuery; - /** - * Set the CSS width of each element in the set of matched elements. - * - * @param func A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set. - */ - width(func: (index: number, width: number) => number|string): ChaiJQuery; - - /** - * Remove from the queue all items that have not yet been run. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - clearQueue(queueName?: string): ChaiJQuery; - - /** - * Store arbitrary data associated with the matched elements. - * - * @param key A string naming the piece of data to set. - * @param value The new data value; it can be any Javascript type including Array or Object. - */ - data(key: string, value: any): ChaiJQuery; - /** - * Store arbitrary data associated with the matched elements. - * - * @param obj An object of key-value pairs of data to update. - */ - data(obj: { [key: string]: any; }): ChaiJQuery; - /** - * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. - * - * @param key Name of the data stored. - */ - data(key: string): any; - /** - * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. - */ - data(): any; - - /** - * Execute the next function on the queue for the matched elements. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - dequeue(queueName?: string): ChaiJQuery; - - /** - * Remove a previously-stored piece of data. - * - * @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete. - */ - removeData(name: string): ChaiJQuery; - /** - * Remove a previously-stored piece of data. - * - * @param list An array of strings naming the pieces of data to delete. - */ - removeData(list: string[]): ChaiJQuery; - - /** - * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. - * - * @param type The type of queue that needs to be observed. (default: fx) - * @param target Object onto which the promise methods have to be attached - */ - promise(type?: string, target?: Object): JQueryPromise; - - /** - * Perform a custom animation of a set of CSS properties. - * - * @param properties An object of CSS properties and values that the animation will move toward. - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - animate(properties: Object, duration?: string|number, complete?: Function): ChaiJQuery; - /** - * Perform a custom animation of a set of CSS properties. - * - * @param properties An object of CSS properties and values that the animation will move toward. - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. (default: swing) - * @param complete A function to call once the animation is complete. - */ - animate(properties: Object, duration?: string|number, easing?: string, complete?: Function): ChaiJQuery; - /** - * Perform a custom animation of a set of CSS properties. - * - * @param properties An object of CSS properties and values that the animation will move toward. - * @param options A map of additional options to pass to the method. - */ - animate(properties: Object, options: JQueryAnimationOptions): ChaiJQuery; - - /** - * Set a timer to delay execution of subsequent items in the queue. - * - * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - delay(duration: number, queueName?: string): ChaiJQuery; - - /** - * Display the matched elements by fading them to opaque. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - fadeIn(duration?: number|string, complete?: Function): ChaiJQuery; - /** - * Display the matched elements by fading them to opaque. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeIn(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; - /** - * Display the matched elements by fading them to opaque. - * - * @param options A map of additional options to pass to the method. - */ - fadeIn(options: JQueryAnimationOptions): ChaiJQuery; - - /** - * Hide the matched elements by fading them to transparent. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - fadeOut(duration?: number|string, complete?: Function): ChaiJQuery; - /** - * Hide the matched elements by fading them to transparent. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeOut(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; - /** - * Hide the matched elements by fading them to transparent. - * - * @param options A map of additional options to pass to the method. - */ - fadeOut(options: JQueryAnimationOptions): ChaiJQuery; - - /** - * Adjust the opacity of the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param opacity A number between 0 and 1 denoting the target opacity. - * @param complete A function to call once the animation is complete. - */ - fadeTo(duration: string|number, opacity: number, complete?: Function): ChaiJQuery; - /** - * Adjust the opacity of the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param opacity A number between 0 and 1 denoting the target opacity. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeTo(duration: string|number, opacity: number, easing?: string, complete?: Function): ChaiJQuery; - - /** - * Display or hide the matched elements by animating their opacity. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - fadeToggle(duration?: number|string, complete?: Function): ChaiJQuery; - /** - * Display or hide the matched elements by animating their opacity. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - fadeToggle(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; - /** - * Display or hide the matched elements by animating their opacity. - * - * @param options A map of additional options to pass to the method. - */ - fadeToggle(options: JQueryAnimationOptions): ChaiJQuery; - - /** - * Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. - * - * @param queue The name of the queue in which to stop animations. - */ - finish(queue?: string): ChaiJQuery; - - /** - * Hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - hide(duration?: number|string, complete?: Function): ChaiJQuery; - /** - * Hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - hide(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; - /** - * Hide the matched elements. - * - * @param options A map of additional options to pass to the method. - */ - hide(options: JQueryAnimationOptions): ChaiJQuery; - - /** - * Display the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - show(duration?: number|string, complete?: Function): ChaiJQuery; - /** - * Display the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - show(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; - /** - * Display the matched elements. - * - * @param options A map of additional options to pass to the method. - */ - show(options: JQueryAnimationOptions): ChaiJQuery; - - /** - * Display the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - slideDown(duration?: number|string, complete?: Function): ChaiJQuery; - /** - * Display the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - slideDown(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; - /** - * Display the matched elements with a sliding motion. - * - * @param options A map of additional options to pass to the method. - */ - slideDown(options: JQueryAnimationOptions): ChaiJQuery; - - /** - * Display or hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - slideToggle(duration?: number|string, complete?: Function): ChaiJQuery; - /** - * Display or hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - slideToggle(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; - /** - * Display or hide the matched elements with a sliding motion. - * - * @param options A map of additional options to pass to the method. - */ - slideToggle(options: JQueryAnimationOptions): ChaiJQuery; - - /** - * Hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - slideUp(duration?: number|string, complete?: Function): ChaiJQuery; - /** - * Hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - slideUp(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; - /** - * Hide the matched elements with a sliding motion. - * - * @param options A map of additional options to pass to the method. - */ - slideUp(options: JQueryAnimationOptions): ChaiJQuery; - - /** - * Stop the currently-running animation on the matched elements. - * - * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. - * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. - */ - stop(clearQueue?: boolean, jumpToEnd?: boolean): ChaiJQuery; - /** - * Stop the currently-running animation on the matched elements. - * - * @param queue The name of the queue in which to stop animations. - * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. - * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. - */ - stop(queue?: string, clearQueue?: boolean, jumpToEnd?: boolean): ChaiJQuery; - - /** - * Display or hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete. - */ - toggle(duration?: number|string, complete?: Function): ChaiJQuery; - /** - * Display or hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete. - */ - toggle(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; - /** - * Display or hide the matched elements. - * - * @param options A map of additional options to pass to the method. - */ - toggle(options: JQueryAnimationOptions): ChaiJQuery; - /** - * Display or hide the matched elements. - * - * @param showOrHide A Boolean indicating whether to show or hide the elements. - */ - toggle(showOrHide: boolean): ChaiJQuery; - - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute each time the event is triggered. - */ - bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param eventData An object containing data that will be passed to the event handler. - * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. - */ - bind(eventType: string, eventData: any, preventBubble: boolean): ChaiJQuery; - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. - */ - bind(eventType: string, preventBubble: boolean): ChaiJQuery; - /** - * Attach a handler to an event for the elements. - * - * @param events An object containing one or more DOM event types and functions to execute for them. - */ - bind(events: any): ChaiJQuery; - - /** - * Trigger the "blur" event on an element - */ - blur(): ChaiJQuery; - /** - * Bind an event handler to the "blur" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - blur(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "blur" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Trigger the "change" event on an element. - */ - change(): ChaiJQuery; - /** - * Bind an event handler to the "change" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - change(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "change" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Trigger the "click" event on an element. - */ - click(): ChaiJQuery; - /** - * Bind an event handler to the "click" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - */ - click(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "click" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Trigger the "dblclick" event on an element. - */ - dblclick(): ChaiJQuery; - /** - * Bind an event handler to the "dblclick" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - dblclick(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "dblclick" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - delegate(selector: any, eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Trigger the "focus" event on an element. - */ - focus(): ChaiJQuery; - /** - * Bind an event handler to the "focus" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - focus(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "focus" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Bind an event handler to the "focusin" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - focusin(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "focusin" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Bind an event handler to the "focusout" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - focusout(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "focusout" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. - * - * @param handlerIn A function to execute when the mouse pointer enters the element. - * @param handlerOut A function to execute when the mouse pointer leaves the element. - */ - hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. - * - * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. - */ - hover(handlerInOut: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Trigger the "keydown" event on an element. - */ - keydown(): ChaiJQuery; - /** - * Bind an event handler to the "keydown" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - keydown(handler: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "keydown" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; - - /** - * Trigger the "keypress" event on an element. - */ - keypress(): ChaiJQuery; - /** - * Bind an event handler to the "keypress" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - keypress(handler: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "keypress" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; - - /** - * Trigger the "keyup" event on an element. - */ - keyup(): ChaiJQuery; - /** - * Bind an event handler to the "keyup" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - keyup(handler: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "keyup" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; - - /** - * Bind an event handler to the "load" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - load(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "load" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Trigger the "mousedown" event on an element. - */ - mousedown(): ChaiJQuery; - /** - * Bind an event handler to the "mousedown" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mousedown(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "mousedown" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - - /** - * Trigger the "mouseenter" event on an element. - */ - mouseenter(): ChaiJQuery; - /** - * Bind an event handler to be fired when the mouse enters an element. - * - * @param handler A function to execute when the event is triggered. - */ - mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to be fired when the mouse enters an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - - /** - * Trigger the "mouseleave" event on an element. - */ - mouseleave(): ChaiJQuery; - /** - * Bind an event handler to be fired when the mouse leaves an element. - * - * @param handler A function to execute when the event is triggered. - */ - mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to be fired when the mouse leaves an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - - /** - * Trigger the "mousemove" event on an element. - */ - mousemove(): ChaiJQuery; - /** - * Bind an event handler to the "mousemove" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mousemove(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "mousemove" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - - /** - * Trigger the "mouseout" event on an element. - */ - mouseout(): ChaiJQuery; - /** - * Bind an event handler to the "mouseout" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mouseout(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "mouseout" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - - /** - * Trigger the "mouseover" event on an element. - */ - mouseover(): ChaiJQuery; - /** - * Bind an event handler to the "mouseover" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mouseover(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "mouseover" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - - /** - * Trigger the "mouseup" event on an element. - */ - mouseup(): ChaiJQuery; - /** - * Bind an event handler to the "mouseup" JavaScript event. - * - * @param handler A function to execute when the event is triggered. - */ - mouseup(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "mouseup" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; - - /** - * Remove an event handler. - */ - off(): ChaiJQuery; - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". - * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Remove an event handler. - * - * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). - * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - */ - off(events: { [key: string]: any; }, selector?: string): ChaiJQuery; - - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): ChaiJQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string, data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): ChaiJQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): ChaiJQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): ChaiJQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - on(events: { [key: string]: any; }, selector?: string, data?: any): ChaiJQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - on(events: { [key: string]: any; }, data?: any): ChaiJQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute at the time the event is triggered. - */ - one(events: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. - * @param data An object containing data that will be passed to the event handler. - * @param handler A function to execute at the time the event is triggered. - */ - one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - one(events: { [key: string]: any; }, selector?: string, data?: any): ChaiJQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). - * @param data Data to be passed to the handler in event.data when an event occurs. - */ - one(events: { [key: string]: any; }, data?: any): ChaiJQuery; - - - /** - * Specify a function to execute when the DOM is fully loaded. - * - * @param handler A function to execute after the DOM is ready. - */ - ready(handler: Function): ChaiJQuery; - - /** - * Trigger the "resize" event on an element. - */ - resize(): ChaiJQuery; - /** - * Bind an event handler to the "resize" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - */ - resize(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "resize" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Trigger the "scroll" event on an element. - */ - scroll(): ChaiJQuery; - /** - * Bind an event handler to the "scroll" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - */ - scroll(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "scroll" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Trigger the "select" event on an element. - */ - select(): ChaiJQuery; - /** - * Bind an event handler to the "select" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - */ - select(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "select" JavaScript event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Trigger the "submit" event on an element. - */ - submit(): ChaiJQuery; - /** - * Bind an event handler to the "submit" JavaScript event - * - * @param handler A function to execute each time the event is triggered. - */ - submit(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "submit" JavaScript event - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Execute all handlers and behaviors attached to the matched elements for the given event type. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param extraParameters Additional parameters to pass along to the event handler. - */ - trigger(eventType: string, extraParameters?: any[]|Object): ChaiJQuery; - /** - * Execute all handlers and behaviors attached to the matched elements for the given event type. - * - * @param event A jQuery.Event object. - * @param extraParameters Additional parameters to pass along to the event handler. - */ - trigger(event: JQueryEventObject, extraParameters?: any[]|Object): ChaiJQuery; - - /** - * Execute all handlers attached to an element for an event. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param extraParameters An array of additional parameters to pass along to the event handler. - */ - triggerHandler(eventType: string, ...extraParameters: any[]): Object; - - /** - * Remove a previously-attached event handler from the elements. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param handler The function that is to be no longer executed. - */ - unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Remove a previously-attached event handler from the elements. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). - */ - unbind(eventType: string, fls: boolean): ChaiJQuery; - /** - * Remove a previously-attached event handler from the elements. - * - * @param evt A JavaScript event object as passed to an event handler. - */ - unbind(evt: any): ChaiJQuery; - - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - */ - undelegate(): ChaiJQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param selector A selector which will be used to filter the event results. - * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" - * @param handler A function to execute at the time the event is triggered. - */ - undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param selector A selector which will be used to filter the event results. - * @param events An object of one or more event types and previously bound functions to unbind from them. - */ - undelegate(selector: string, events: Object): ChaiJQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param namespace A string containing a namespace to unbind all events from. - */ - undelegate(namespace: string): ChaiJQuery; - - /** - * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) - * - * @param handler A function to execute when the event is triggered. - */ - unload(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) - * - * @param eventData A plain object of data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. (DEPRECATED from v1.10) - */ - context: Element; - - jquery: string; - - /** - * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) - * - * @param handler A function to execute when the event is triggered. - */ - error(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - /** - * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) - * - * @param eventData A plain object of data that will be passed to the event handler. - * @param handler A function to execute when the event is triggered. - */ - error(eventData: any, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; - - /** - * Add a collection of DOM elements onto the jQuery stack. - * - * @param elements An array of elements to push onto the stack and make into a new jQuery object. - */ - pushStack(elements: any[]): ChaiJQuery; - /** - * Add a collection of DOM elements onto the jQuery stack. - * - * @param elements An array of elements to push onto the stack and make into a new jQuery object. - * @param name The name of a jQuery method that generated the array of elements. - * @param arguments The arguments that were passed in to the jQuery method (for serialization). - */ - pushStack(elements: any[], name: string, arguments: any[]): ChaiJQuery; - - /** - * Insert content, specified by the parameter, after each element in the set of matched elements. - * - * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. - */ - after(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): ChaiJQuery; - /** - * Insert content, specified by the parameter, after each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - after(func: (index: number, html: string) => string|Element|JQuery): ChaiJQuery; - - /** - * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * - * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. - */ - append(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): ChaiJQuery; - /** - * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. - */ - append(func: (index: number, html: string) => string|Element|JQuery): ChaiJQuery; - - /** - * Insert every element in the set of matched elements to the end of the target. - * - * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. - */ - appendTo(target: JQuery|any[]|Element|string): ChaiJQuery; - - /** - * Insert content, specified by the parameter, before each element in the set of matched elements. - * - * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. - */ - before(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): ChaiJQuery; - /** - * Insert content, specified by the parameter, before each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - before(func: (index: number, html: string) => string|Element|JQuery): ChaiJQuery; - - /** - * Create a deep copy of the set of matched elements. - * - * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. - * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). - */ - clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): ChaiJQuery; - - /** - * Remove the set of matched elements from the DOM. - * - * param selector A selector expression that filters the set of matched elements to be removed. - */ - detach(selector?: string): ChaiJQuery; - - /** - * Remove all child nodes of the set of matched elements from the DOM. - */ - empty(): ChaiJQuery; - - /** - * Insert every element in the set of matched elements after the target. - * - * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. - */ - insertAfter(target: JQuery|any[]|Element|Text|string): ChaiJQuery; - - /** - * Insert every element in the set of matched elements before the target. - * - * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. - */ - insertBefore(target: JQuery|any[]|Element|Text|string): ChaiJQuery; - - /** - * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * - * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. - * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. - */ - prepend(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): ChaiJQuery; - /** - * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * - * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. - */ - prepend(func: (index: number, html: string) => string|Element|JQuery): ChaiJQuery; - - /** - * Insert every element in the set of matched elements to the beginning of the target. - * - * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. - */ - prependTo(target: JQuery|any[]|Element|string): ChaiJQuery; - - /** - * Remove the set of matched elements from the DOM. - * - * @param selector A selector expression that filters the set of matched elements to be removed. - */ - remove(selector?: string): ChaiJQuery; - - /** - * Replace each target element with the set of matched elements. - * - * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. - */ - replaceAll(target: JQuery|any[]|Element|string): ChaiJQuery; - - /** - * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * - * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. - */ - replaceWith(newContent: JQuery|any[]|Element|Text|string): ChaiJQuery; - /** - * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * - * param func A function that returns content with which to replace the set of matched elements. - */ - replaceWith(func: () => Element|JQuery): ChaiJQuery; - - /** - * Get the combined text contents of each element in the set of matched elements, including their descendants. - */ - text(): string; - /** - * Set the content of each element in the set of matched elements to the specified text. - * - * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. - */ - text(text: string|number|boolean): ChaiJQuery; - /** - * Set the content of each element in the set of matched elements to the specified text. - * - * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. - */ - text(func: (index: number, text: string) => string): ChaiJQuery; - - /** - * Retrieve all the elements contained in the jQuery set, as an array. - */ - toArray(): any[]; - - /** - * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. - */ - unwrap(): ChaiJQuery; - - /** - * Wrap an HTML structure around each element in the set of matched elements. - * - * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. - */ - wrap(wrappingElement: JQuery|Element|string): ChaiJQuery; - /** - * Wrap an HTML structure around each element in the set of matched elements. - * - * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - wrap(func: (index: number) => string|JQuery): ChaiJQuery; - - /** - * Wrap an HTML structure around all elements in the set of matched elements. - * - * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. - */ - wrapAll(wrappingElement: JQuery|Element|string): ChaiJQuery; - wrapAll(func: (index: number) => string): ChaiJQuery; - - /** - * Wrap an HTML structure around the content of each element in the set of matched elements. - * - * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. - */ - wrapInner(wrappingElement: JQuery|Element|string): ChaiJQuery; - /** - * Wrap an HTML structure around the content of each element in the set of matched elements. - * - * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. - */ - wrapInner(func: (index: number) => string): ChaiJQuery; - - /** - * Iterate over a jQuery object, executing a function for each matched element. - * - * @param func A function to execute for each matched element. - */ - each(func: (index: number, elem: Element) => any): ChaiJQuery; - - /** - * Retrieve one of the elements matched by the jQuery object. - * - * @param index A zero-based integer indicating which element to retrieve. - */ - get(index: number): HTMLElement; - /** - * Retrieve the elements matched by the jQuery object. - */ - get(): any[]; - - /** - * Search for a given element from among the matched elements. - */ - index(): number; - /** - * Search for a given element from among the matched elements. - * - * @param selector A selector representing a jQuery collection in which to look for an element. - */ - index(selector: string|JQuery|Element): number; - - /** - * The number of elements in the jQuery object. - */ - length: number; - /** - * A selector representing selector passed to jQuery(), if any, when creating the original set. - * version deprecated: 1.7, removed: 1.9 - */ - selector: string; - [index: string]: any; - [index: number]: HTMLElement; - - /** - * Add elements to the set of matched elements. - * - * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. - * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. - */ - add(selector: string, context?: Element): ChaiJQuery; - /** - * Add elements to the set of matched elements. - * - * @param elements One or more elements to add to the set of matched elements. - */ - add(...elements: Element[]): ChaiJQuery; - /** - * Add elements to the set of matched elements. - * - * @param html An HTML fragment to add to the set of matched elements. - */ - add(html: string): ChaiJQuery; - /** - * Add elements to the set of matched elements. - * - * @param obj An existing jQuery object to add to the set of matched elements. - */ - add(obj: JQuery): ChaiJQuery; - - /** - * Get the children of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - children(selector?: string): ChaiJQuery; - - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param selector A string containing a selector expression to match elements against. - */ - closest(selector: string): ChaiJQuery; - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param selector A string containing a selector expression to match elements against. - * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. - */ - closest(selector: string, context?: Element): ChaiJQuery; - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param obj A jQuery object to match elements against. - */ - closest(obj: JQuery): ChaiJQuery; - /** - * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * - * @param element An element to match elements against. - */ - closest(element: Element): ChaiJQuery; - - /** - * Get an array of all the elements and selectors matched against the current element up through the DOM tree. - * - * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). - * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. - */ - closest(selectors: any, context?: Element): any[]; - - /** - * Get the children of each element in the set of matched elements, including text and comment nodes. - */ - contents(): ChaiJQuery; - - /** - * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. - */ - end(): ChaiJQuery; - - /** - * Reduce the set of matched elements to the one at the specified index. - * - * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. - * - */ - eq(index: number): ChaiJQuery; - - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param selector A string containing a selector expression to match the current set of elements against. - */ - filter(selector: string): ChaiJQuery; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param func A function used as a test for each element in the set. this is the current DOM element. - */ - filter(func: (index: number, element: Element) => any): ChaiJQuery; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param element An element to match the current set of elements against. - */ - filter(element: Element): ChaiJQuery; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param obj An existing jQuery object to match the current set of elements against. - */ - filter(obj: JQuery): ChaiJQuery; - - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * - * @param selector A string containing a selector expression to match elements against. - */ - find(selector: string): ChaiJQuery; - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * - * @param element An element to match elements against. - */ - find(element: Element): ChaiJQuery; - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * - * @param obj A jQuery object to match elements against. - */ - find(obj: JQuery): ChaiJQuery; - - /** - * Reduce the set of matched elements to the first in the set. - */ - first(): ChaiJQuery; - - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param selector A string containing a selector expression to match elements against. - */ - has(selector: string): ChaiJQuery; - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param contained A DOM element to match elements against. - */ - has(contained: Element): ChaiJQuery; - - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param selector A string containing a selector expression to match elements against. - */ - is(selector: string): boolean; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. - */ - is(func: (index: number, element: Element) => boolean): boolean; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param obj An existing jQuery object to match the current set of elements against. - */ - is(obj: JQuery): boolean; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * - * @param elements One or more elements to match the current set of elements against. - */ - is(elements: any): boolean; - - /** - * Reduce the set of matched elements to the final one in the set. - */ - last(): ChaiJQuery; - - /** - * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. - * - * @param callback A function object that will be invoked for each element in the current set. - */ - map(callback: (index: number, domElement: Element) => any): ChaiJQuery; - - /** - * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - next(selector?: string): ChaiJQuery; - - /** - * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - nextAll(selector?: string): ChaiJQuery; - - /** - * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * - * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - nextUntil(selector?: string, filter?: string): ChaiJQuery; - /** - * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * - * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - nextUntil(element?: Element, filter?: string): ChaiJQuery; - /** - * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * - * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - nextUntil(obj?: JQuery, filter?: string): ChaiJQuery; - - /** - * Remove elements from the set of matched elements. - * - * @param selector A string containing a selector expression to match elements against. - */ - not(selector: string): ChaiJQuery; - /** - * Remove elements from the set of matched elements. - * - * @param func A function used as a test for each element in the set. this is the current DOM element. - */ - not(func: (index: number, element: Element) => boolean): ChaiJQuery; - /** - * Remove elements from the set of matched elements. - * - * @param elements One or more DOM elements to remove from the matched set. - */ - not(...elements: Element[]): ChaiJQuery; - /** - * Remove elements from the set of matched elements. - * - * @param obj An existing jQuery object to match the current set of elements against. - */ - not(obj: JQuery): ChaiJQuery; - - /** - * Get the closest ancestor element that is positioned. - */ - offsetParent(): ChaiJQuery; - - /** - * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - parent(selector?: string): ChaiJQuery; - - /** - * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - parents(selector?: string): ChaiJQuery; - - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - */ - parentsUntil(selector?: string, filter?: string): ChaiJQuery; - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - */ - parentsUntil(element?: Element, filter?: string): ChaiJQuery; - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - */ - parentsUntil(obj?: JQuery, filter?: string): ChaiJQuery; - - /** - * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - prev(selector?: string): ChaiJQuery; - - /** - * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - prevAll(selector?: string): ChaiJQuery; - - /** - * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - prevUntil(selector?: string, filter?: string): ChaiJQuery; - /** - * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - prevUntil(element?: Element, filter?: string): ChaiJQuery; - /** - * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * - * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - */ - prevUntil(obj?: JQuery, filter?: string): ChaiJQuery; - - /** - * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - */ - siblings(selector?: string): ChaiJQuery; - - /** - * Reduce the set of matched elements to a subset specified by a range of indices. - * - * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. - * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. - */ - slice(start: number, end?: number): ChaiJQuery; - - /** - * Show the queue of functions to be executed on the matched elements. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - */ - queue(queueName?: string): any[]; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param newQueue An array of functions to replace the current queue contents. - */ - queue(newQueue: Function[]): ChaiJQuery; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. - */ - queue(callback: Function): ChaiJQuery; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param newQueue An array of functions to replace the current queue contents. - */ - queue(queueName: string, newQueue: Function[]): ChaiJQuery; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. - */ - queue(queueName: string, callback: Function): ChaiJQuery; - should: Chai.Assertion; -} diff --git a/chai-jquery/index.d.ts b/chai-jquery/index.d.ts new file mode 100644 index 0000000000..79774640f6 --- /dev/null +++ b/chai-jquery/index.d.ts @@ -0,0 +1,2580 @@ +// Type definitions for chai-jquery 1.1.1 +// Project: https://github.com/chaijs/chai-jquery +// Definitions by: Kazi Manzur Rashid +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace Chai { + + interface Assertion { + attr: (name: string, value?: string) => Assertion; + css: (name: string, value?: string) => Assertion; + data: (name: string, value?: string) => Assertion; + class(className: string): Assertion; + id(id: string): Assertion; + html(html: string): Assertion; + text(text: string): Assertion; + value(text: string): Assertion; + (selector: string): Assertion; + visible: Assertion; + hidden: Assertion; + selected: Assertion; + checked: Assertion; + disabled: Assertion; + (selector: string): Assertion; + } +} + +/** + * Static members of chai-jquery (those on $ and jQuery themselves) + */ +interface ChaiJQueryStatic { + + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + */ + ajax(settings: JQueryAjaxSettings): JQueryXHR; + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param url A string containing the URL to which the request is sent. + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + */ + ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; + + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * + * @param dataTypes An optional string containing one or more space-separated dataTypes + * @param handler A handler to set default values for future Ajax requests. + */ + ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * + * @param handler A handler to set default values for future Ajax requests. + */ + ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + + ajaxSettings: JQueryAjaxSettings; + + /** + * Set default values for future Ajax requests. Its use is not recommended. + * + * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. + */ + ajaxSetup(options: JQueryAjaxSettings): void; + + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + */ + get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + */ + get(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + */ + getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + */ + getJSON(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + /** + * Load a JavaScript file from the server using a GET HTTP request, then execute it. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + */ + getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + */ + param: JQueryParam; + + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + */ + post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + */ + post(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + + /** + * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. + * + * @param flags An optional list of space-separated flags that change how the callback list behaves. + */ + Callbacks(flags?: string): JQueryCallback; + + /** + * Holds or releases the execution of jQuery's ready event. + * + * @param hold Indicates whether the ready hold is being requested or released + */ + holdReady(hold: boolean): void; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param selector A string containing a selector expression + * @param context A DOM Element, Document, or jQuery to use as context + */ + (selector: string, context?: Element|JQuery): ChaiJQuery; + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param element A DOM element to wrap in a jQuery object. + */ + (element: Element): ChaiJQuery; + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. + */ + (elementArray: Element[]): ChaiJQuery; + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param object A plain object to wrap in a jQuery object. + */ + (object: {}): ChaiJQuery; + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param object An existing jQuery object to clone. + */ + (object: JQuery): ChaiJQuery; + /** + * Specify a function to execute when the DOM is fully loaded. + */ + (): ChaiJQuery; + + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. + * @param ownerDocument A document in which the new elements will be created. + */ + (html: string, ownerDocument?: Document): ChaiJQuery; + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string defining a single, standalone, HTML element (e.g.
or
). + * @param attributes An object of attributes, events, and methods to call on the newly-created element. + */ + (html: string, attributes: Object): ChaiJQuery; + + /** + * Binds a function to be executed when the DOM has finished loading. + * + * @param callback A function to execute after the DOM is ready. + */ + (callback: Function): ChaiJQuery; + + /** + * Relinquish jQuery's control of the $ variable. + * + * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). + */ + noConflict(removeAll?: boolean): Object; + + /** + * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. + * + * @param deferreds One or more Deferred objects, or plain JavaScript objects. + */ + when(...deferreds: Array/* as JQueryDeferred */>): JQueryPromise; + + /** + * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties. + */ + cssHooks: { [key: string]: any; }; + cssNumber: any; + + /** + * Store arbitrary data associated with the specified element. Returns the value that was set. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + * @param value The new data value. + */ + data(element: Element, key: string, value: T): T; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + */ + data(element: Element, key: string): any; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. + * + * @param element The DOM element to associate with the data. + */ + data(element: Element): any; + + /** + * Execute the next function on the queue for the matched element. + * + * @param element A DOM element from which to remove and execute a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + dequeue(element: Element, queueName?: string): void; + + /** + * Determine whether an element has any jQuery data associated with it. + * + * @param element A DOM element to be checked for data. + */ + hasData(element: Element): boolean; + + /** + * Show the queue of functions to be executed on the matched element. + * + * @param element A DOM element to inspect for an attached queue. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + queue(element: Element, queueName?: string): any[]; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element where the array of queued functions is attached. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(element: Element, queueName: string, newQueue: Function[]): ChaiJQuery; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element on which to add a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue. + */ + queue(element: Element, queueName: string, callback: Function): ChaiJQuery; + + /** + * Remove a previously-stored piece of data. + * + * @param element A DOM element from which to remove data. + * @param name A string naming the piece of data to remove. + */ + removeData(element: Element, name?: string): ChaiJQuery; + + /** + * A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. + * + * @param beforeStart A function that is called just before the constructor returns. + */ + Deferred(beforeStart?: (deferred: JQueryDeferred) => any): JQueryDeferred; + + /** + * Effects + */ + fx: { + tick: () => void; + /** + * The rate (in milliseconds) at which animations fire. + */ + interval: number; + stop: () => void; + speeds: { slow: number; fast: number; }; + /** + * Globally disable all animations. + */ + off: boolean; + step: any; + }; + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fnction The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. + */ + proxy(fnction: (...args: any[]) => any, context: Object, ...additionalArguments: any[]): any; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param context The object to which the context (this) of the function should be set. + * @param name The name of the function whose context will be changed (should be a property of the context object). + * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. + */ + proxy(context: Object, name: string, ...additionalArguments: any[]): any; + + Event: JQueryEventConstructor; + + /** + * Takes a string and throws an exception containing it. + * + * @param message The message to send out. + */ + error(message: any): ChaiJQuery; + + expr: any; + fn: any; //TODO: Decide how we want to type this + + isReady: boolean; + + // Properties + support: JQuerySupport; + + /** + * Check to see if a DOM element is a descendant of another DOM element. + * + * @param container The DOM element that may contain the other element. + * @param contained The DOM element that may be contained by (a descendant of) the other element. + */ + contains(container: Element, contained: Element): boolean; + + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: T[], + callback: (indexInArray: number, valueOfElement: T) => any + ): any; + + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: any, + callback: (indexInArray: any, valueOfElement: any) => any + ): any; + + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(target: any, object1?: any, ...objectN: any[]): any; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(deep: boolean, target: any, object1?: any, ...objectN: any[]): any; + + /** + * Execute some JavaScript code globally. + * + * @param code The JavaScript code to execute. + */ + globalEval(code: string): any; + + /** + * Finds the elements of an array which satisfy a filter function. The original array is not affected. + * + * @param array The array to search through. + * @param func The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. + * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false. + */ + grep(array: T[], func: (elementOfArray: T, indexInArray: number) => boolean, invert?: boolean): T[]; + + /** + * Search for a specified value within an array and return its index (or -1 if not found). + * + * @param value The value to search for. + * @param array An array through which to search. + * @param fromIndex he index of the array at which to begin the search. The default is 0, which will search the whole array. + */ + inArray(value: T, array: T[], fromIndex?: number): number; + + /** + * Determine whether the argument is an array. + * + * @param obj Object to test whether or not it is an array. + */ + isArray(obj: any): boolean; + /** + * Check to see if an object is empty (contains no enumerable properties). + * + * @param obj The object that will be checked to see if it's empty. + */ + isEmptyObject(obj: any): boolean; + /** + * Determine if the argument passed is a Javascript function object. + * + * @param obj Object to test whether or not it is a function. + */ + isFunction(obj: any): boolean; + /** + * Determines whether its argument is a number. + * + * @param obj The value to be tested. + */ + isNumeric(value: any): boolean; + /** + * Check to see if an object is a plain object (created using "{}" or "new Object"). + * + * @param obj The object that will be checked to see if it's a plain object. + */ + isPlainObject(obj: any): boolean; + /** + * Determine whether the argument is a window. + * + * @param obj Object to test whether or not it is a window. + */ + isWindow(obj: any): boolean; + /** + * Check to see if a DOM node is within an XML document (or is an XML document). + * + * @param node he DOM node that will be checked to see if it's in an XML document. + */ + isXMLDoc(node: Node): boolean; + + /** + * Convert an array-like object into a true JavaScript array. + * + * @param obj Any object to turn into a native Array. + */ + makeArray(obj: any): any[]; + + /** + * Translate all items in an array or object to new array of items. + * + * @param array The Array to translate. + * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. + */ + map(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[]; + /** + * Translate all items in an array or object to new array of items. + * + * @param arrayOrObject The Array or Object to translate. + * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. + */ + map(arrayOrObject: any, callback: (value: any, indexOrKey: any) => any): any; + + /** + * Merge the contents of two arrays together into the first array. + * + * @param first The first array to merge, the elements of second added. + * @param second The second array to merge into the first, unaltered. + */ + merge(first: T[], second: T[]): T[]; + + /** + * An empty function. + */ + noop(): any; + + /** + * Return a number representing the current time. + */ + now(): number; + + /** + * Takes a well-formed JSON string and returns the resulting JavaScript object. + * + * @param json The JSON string to parse. + */ + parseJSON(json: string): any; + + /** + * Parses a string into an XML document. + * + * @param data a well-formed XML string to be parsed + */ + parseXML(data: string): XMLDocument; + + /** + * Remove the whitespace from the beginning and end of a string. + * + * @param str Remove the whitespace from the beginning and end of a string. + */ + trim(str: string): string; + + /** + * Determine the internal JavaScript [[Class]] of an object. + * + * @param obj Object to get the internal JavaScript [[Class]] of. + */ + type(obj: any): string; + + /** + * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. + * + * @param array The Array of DOM elements. + */ + unique(array: Element[]): Element[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: Document, keepScripts?: boolean): any[]; +} + +/** + * The chai-jquery instance members + */ +interface ChaiJQuery { + /** + * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. + * + * @param handler The function to be invoked. + */ + ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): ChaiJQuery; + /** + * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: any) => any): ChaiJQuery; + /** + * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) => any): ChaiJQuery; + /** + * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxStart(handler: () => any): ChaiJQuery; + /** + * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxStop(handler: () => any): ChaiJQuery; + /** + * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) => any): ChaiJQuery; + + /** + * Load data from the server and place the returned HTML into the matched element. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param complete A callback function that is executed when the request completes. + */ + load(url: string, data?: string|Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): ChaiJQuery; + + /** + * Encode a set of form elements as a string for submission. + */ + serialize(): string; + /** + * Encode a set of form elements as an array of names and values. + */ + serializeArray(): JQuerySerializeArrayElement[]; + + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param className One or more space-separated classes to be added to the class attribute of each matched element. + */ + addClass(className: string): ChaiJQuery; + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set. + */ + addClass(func: (index: number, className: string) => string): ChaiJQuery; + + /** + * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. + */ + addBack(selector?: string): ChaiJQuery; + + /** + * Get the value of an attribute for the first element in the set of matched elements. + * + * @param attributeName The name of the attribute to get. + */ + attr(attributeName: string): string; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributeName The name of the attribute to set. + * @param value A value to set for the attribute. + */ + attr(attributeName: string, value: string|number): ChaiJQuery; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributeName The name of the attribute to set. + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. + */ + attr(attributeName: string, func: (index: number, attr: string) => string|number): ChaiJQuery; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributes An object of attribute-value pairs to set. + */ + attr(attributes: Object): ChaiJQuery; + + /** + * Determine whether any of the matched elements are assigned the given class. + * + * @param className The class name to search for. + */ + hasClass(className: string): boolean; + + /** + * Get the HTML contents of the first element in the set of matched elements. + */ + html(): string; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param htmlString A string of HTML to set as the content of each matched element. + */ + html(htmlString: string): ChaiJQuery; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. + */ + html(func: (index: number, oldhtml: string) => string): ChaiJQuery; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. + */ + + /** + * Get the value of a property for the first element in the set of matched elements. + * + * @param propertyName The name of the property to get. + */ + prop(propertyName: string): any; + /** + * Set one or more properties for the set of matched elements. + * + * @param propertyName The name of the property to set. + * @param value A value to set for the property. + */ + prop(propertyName: string, value: string|number|boolean): ChaiJQuery; + /** + * Set one or more properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + */ + prop(properties: Object): ChaiJQuery; + /** + * Set one or more properties for the set of matched elements. + * + * @param propertyName The name of the property to set. + * @param func A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element. + */ + prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): ChaiJQuery; + + /** + * Remove an attribute from each element in the set of matched elements. + * + * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. + */ + removeAttr(attributeName: string): ChaiJQuery; + + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * + * @param className One or more space-separated classes to be removed from the class attribute of each matched element. + */ + removeClass(className?: string): ChaiJQuery; + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * + * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. + */ + removeClass(func: (index: number, className: string) => string): ChaiJQuery; + + /** + * Remove a property for the set of matched elements. + * + * @param propertyName The name of the property to remove. + */ + removeProp(propertyName: string): ChaiJQuery; + + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. + * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. + */ + toggleClass(className: string, swtch?: boolean): ChaiJQuery; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param swtch A boolean value to determine whether the class should be added or removed. + */ + toggleClass(swtch?: boolean): ChaiJQuery; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. + * @param swtch A boolean value to determine whether the class should be added or removed. + */ + toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): ChaiJQuery; + + /** + * Get the current value of the first element in the set of matched elements. + */ + val(): any; + /** + * Set the value of each element in the set of matched elements. + * + * @param value A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked. + */ + val(value: string|string[]): ChaiJQuery; + /** + * Set the value of each element in the set of matched elements. + * + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + val(func: (index: number, value: string) => string): ChaiJQuery; + + + /** + * Get the value of style properties for the first element in the set of matched elements. + * + * @param propertyName A CSS property. + */ + css(propertyName: string): string; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A value to set for the property. + */ + css(propertyName: string, value: string|number): ChaiJQuery; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + css(propertyName: string, value: (index: number, value: string) => string|number): ChaiJQuery; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + */ + css(properties: Object): ChaiJQuery; + + /** + * Get the current computed height for the first element in the set of matched elements. + */ + height(): number; + /** + * Set the CSS height of every matched element. + * + * @param value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string). + */ + height(value: number|string): ChaiJQuery; + /** + * Set the CSS height of every matched element. + * + * @param func A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set. + */ + height(func: (index: number, height: number) => number|string): ChaiJQuery; + + /** + * Get the current computed height for the first element in the set of matched elements, including padding but not border. + */ + innerHeight(): number; + + /** + * Sets the inner height on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerHeight(height: number|string): ChaiJQuery; + + /** + * Get the current computed width for the first element in the set of matched elements, including padding but not border. + */ + innerWidth(): number; + + /** + * Sets the inner width on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerWidth(width: number|string): ChaiJQuery; + + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the document. + */ + offset(): JQueryCoordinates; + /** + * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + * + * @param coordinates An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + */ + offset(coordinates: JQueryCoordinates): ChaiJQuery; + /** + * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + * + * @param func A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties. + */ + offset(func: (index: number, coords: JQueryCoordinates) => JQueryCoordinates): ChaiJQuery; + + /** + * Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements. + * + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + */ + outerHeight(includeMargin?: boolean): number; + + /** + * Sets the outer height on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerHeight(height: number|string): ChaiJQuery; + + /** + * Get the current computed width for the first element in the set of matched elements, including padding and border. + * + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + */ + outerWidth(includeMargin?: boolean): number; + + /** + * Sets the outer width on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerWidth(width: number|string): ChaiJQuery; + + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. + */ + position(): JQueryCoordinates; + + /** + * Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element. + */ + scrollLeft(): number; + /** + * Set the current horizontal position of the scroll bar for each of the set of matched elements. + * + * @param value An integer indicating the new position to set the scroll bar to. + */ + scrollLeft(value: number): ChaiJQuery; + + /** + * Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. + */ + scrollTop(): number; + /** + * Set the current vertical position of the scroll bar for each of the set of matched elements. + * + * @param value An integer indicating the new position to set the scroll bar to. + */ + scrollTop(value: number): ChaiJQuery; + + /** + * Get the current computed width for the first element in the set of matched elements. + */ + width(): number; + /** + * Set the CSS width of each element in the set of matched elements. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + width(value: number|string): ChaiJQuery; + /** + * Set the CSS width of each element in the set of matched elements. + * + * @param func A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set. + */ + width(func: (index: number, width: number) => number|string): ChaiJQuery; + + /** + * Remove from the queue all items that have not yet been run. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + clearQueue(queueName?: string): ChaiJQuery; + + /** + * Store arbitrary data associated with the matched elements. + * + * @param key A string naming the piece of data to set. + * @param value The new data value; it can be any Javascript type including Array or Object. + */ + data(key: string, value: any): ChaiJQuery; + /** + * Store arbitrary data associated with the matched elements. + * + * @param obj An object of key-value pairs of data to update. + */ + data(obj: { [key: string]: any; }): ChaiJQuery; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + * + * @param key Name of the data stored. + */ + data(key: string): any; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + */ + data(): any; + + /** + * Execute the next function on the queue for the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + dequeue(queueName?: string): ChaiJQuery; + + /** + * Remove a previously-stored piece of data. + * + * @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete. + */ + removeData(name: string): ChaiJQuery; + /** + * Remove a previously-stored piece of data. + * + * @param list An array of strings naming the pieces of data to delete. + */ + removeData(list: string[]): ChaiJQuery; + + /** + * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. + * + * @param type The type of queue that needs to be observed. (default: fx) + * @param target Object onto which the promise methods have to be attached + */ + promise(type?: string, target?: Object): JQueryPromise; + + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + animate(properties: Object, duration?: string|number, complete?: Function): ChaiJQuery; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. (default: swing) + * @param complete A function to call once the animation is complete. + */ + animate(properties: Object, duration?: string|number, easing?: string, complete?: Function): ChaiJQuery; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param options A map of additional options to pass to the method. + */ + animate(properties: Object, options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Set a timer to delay execution of subsequent items in the queue. + * + * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + delay(duration: number, queueName?: string): ChaiJQuery; + + /** + * Display the matched elements by fading them to opaque. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeIn(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Display the matched elements by fading them to opaque. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeIn(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Display the matched elements by fading them to opaque. + * + * @param options A map of additional options to pass to the method. + */ + fadeIn(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Hide the matched elements by fading them to transparent. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeOut(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Hide the matched elements by fading them to transparent. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeOut(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Hide the matched elements by fading them to transparent. + * + * @param options A map of additional options to pass to the method. + */ + fadeOut(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Adjust the opacity of the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param complete A function to call once the animation is complete. + */ + fadeTo(duration: string|number, opacity: number, complete?: Function): ChaiJQuery; + /** + * Adjust the opacity of the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeTo(duration: string|number, opacity: number, easing?: string, complete?: Function): ChaiJQuery; + + /** + * Display or hide the matched elements by animating their opacity. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeToggle(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Display or hide the matched elements by animating their opacity. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeToggle(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Display or hide the matched elements by animating their opacity. + * + * @param options A map of additional options to pass to the method. + */ + fadeToggle(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. + * + * @param queue The name of the queue in which to stop animations. + */ + finish(queue?: string): ChaiJQuery; + + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + hide(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + hide(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Hide the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + hide(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Display the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + show(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Display the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + show(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Display the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + show(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Display the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideDown(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Display the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideDown(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Display the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideDown(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Display or hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideToggle(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Display or hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideToggle(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Display or hide the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideToggle(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideUp(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideUp(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Hide the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideUp(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Stop the currently-running animation on the matched elements. + * + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + */ + stop(clearQueue?: boolean, jumpToEnd?: boolean): ChaiJQuery; + /** + * Stop the currently-running animation on the matched elements. + * + * @param queue The name of the queue in which to stop animations. + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + */ + stop(queue?: string, clearQueue?: boolean, jumpToEnd?: boolean): ChaiJQuery; + + /** + * Display or hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + toggle(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Display or hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + toggle(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Display or hide the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + toggle(options: JQueryAnimationOptions): ChaiJQuery; + /** + * Display or hide the matched elements. + * + * @param showOrHide A Boolean indicating whether to show or hide the elements. + */ + toggle(showOrHide: boolean): ChaiJQuery; + + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ + bind(eventType: string, eventData: any, preventBubble: boolean): ChaiJQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ + bind(eventType: string, preventBubble: boolean): ChaiJQuery; + /** + * Attach a handler to an event for the elements. + * + * @param events An object containing one or more DOM event types and functions to execute for them. + */ + bind(events: any): ChaiJQuery; + + /** + * Trigger the "blur" event on an element + */ + blur(): ChaiJQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + blur(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "change" event on an element. + */ + change(): ChaiJQuery; + /** + * Bind an event handler to the "change" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + change(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "change" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "click" event on an element. + */ + click(): ChaiJQuery; + /** + * Bind an event handler to the "click" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + */ + click(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "click" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "dblclick" event on an element. + */ + dblclick(): ChaiJQuery; + /** + * Bind an event handler to the "dblclick" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + dblclick(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "dblclick" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + delegate(selector: any, eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "focus" event on an element. + */ + focus(): ChaiJQuery; + /** + * Bind an event handler to the "focus" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focus(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "focus" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Bind an event handler to the "focusin" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focusin(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "focusin" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Bind an event handler to the "focusout" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focusout(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "focusout" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. + * + * @param handlerIn A function to execute when the mouse pointer enters the element. + * @param handlerOut A function to execute when the mouse pointer leaves the element. + */ + hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. + * + * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + */ + hover(handlerInOut: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "keydown" event on an element. + */ + keydown(): ChaiJQuery; + /** + * Bind an event handler to the "keydown" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keydown(handler: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "keydown" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; + + /** + * Trigger the "keypress" event on an element. + */ + keypress(): ChaiJQuery; + /** + * Bind an event handler to the "keypress" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keypress(handler: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "keypress" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; + + /** + * Trigger the "keyup" event on an element. + */ + keyup(): ChaiJQuery; + /** + * Bind an event handler to the "keyup" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keyup(handler: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "keyup" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; + + /** + * Bind an event handler to the "load" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + load(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "load" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mousedown" event on an element. + */ + mousedown(): ChaiJQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mousedown(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mouseenter" event on an element. + */ + mouseenter(): ChaiJQuery; + /** + * Bind an event handler to be fired when the mouse enters an element. + * + * @param handler A function to execute when the event is triggered. + */ + mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to be fired when the mouse enters an element. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mouseleave" event on an element. + */ + mouseleave(): ChaiJQuery; + /** + * Bind an event handler to be fired when the mouse leaves an element. + * + * @param handler A function to execute when the event is triggered. + */ + mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to be fired when the mouse leaves an element. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mousemove" event on an element. + */ + mousemove(): ChaiJQuery; + /** + * Bind an event handler to the "mousemove" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mousemove(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "mousemove" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mouseout" event on an element. + */ + mouseout(): ChaiJQuery; + /** + * Bind an event handler to the "mouseout" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseout(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "mouseout" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mouseover" event on an element. + */ + mouseover(): ChaiJQuery; + /** + * Bind an event handler to the "mouseover" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseover(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "mouseover" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mouseup" event on an element. + */ + mouseup(): ChaiJQuery; + /** + * Bind an event handler to the "mouseup" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseup(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "mouseup" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Remove an event handler. + */ + off(): ChaiJQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Remove an event handler. + * + * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + */ + off(events: { [key: string]: any; }, selector?: string): ChaiJQuery; + + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): ChaiJQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): ChaiJQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): ChaiJQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): ChaiJQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + on(events: { [key: string]: any; }, selector?: string, data?: any): ChaiJQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + on(events: { [key: string]: any; }, data?: any): ChaiJQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute at the time the event is triggered. + */ + one(events: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param data An object containing data that will be passed to the event handler. + * @param handler A function to execute at the time the event is triggered. + */ + one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + one(events: { [key: string]: any; }, selector?: string, data?: any): ChaiJQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + one(events: { [key: string]: any; }, data?: any): ChaiJQuery; + + + /** + * Specify a function to execute when the DOM is fully loaded. + * + * @param handler A function to execute after the DOM is ready. + */ + ready(handler: Function): ChaiJQuery; + + /** + * Trigger the "resize" event on an element. + */ + resize(): ChaiJQuery; + /** + * Bind an event handler to the "resize" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + resize(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "resize" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "scroll" event on an element. + */ + scroll(): ChaiJQuery; + /** + * Bind an event handler to the "scroll" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + scroll(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "scroll" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "select" event on an element. + */ + select(): ChaiJQuery; + /** + * Bind an event handler to the "select" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + select(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "select" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "submit" event on an element. + */ + submit(): ChaiJQuery; + /** + * Bind an event handler to the "submit" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + submit(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "submit" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(eventType: string, extraParameters?: any[]|Object): ChaiJQuery; + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param event A jQuery.Event object. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(event: JQueryEventObject, extraParameters?: any[]|Object): ChaiJQuery; + + /** + * Execute all handlers attached to an element for an event. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters An array of additional parameters to pass along to the event handler. + */ + triggerHandler(eventType: string, ...extraParameters: any[]): Object; + + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param handler The function that is to be no longer executed. + */ + unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). + */ + unbind(eventType: string, fls: boolean): ChaiJQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param evt A JavaScript event object as passed to an event handler. + */ + unbind(evt: any): ChaiJQuery; + + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + */ + undelegate(): ChaiJQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" + * @param handler A function to execute at the time the event is triggered. + */ + undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param events An object of one or more event types and previously bound functions to unbind from them. + */ + undelegate(selector: string, events: Object): ChaiJQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param namespace A string containing a namespace to unbind all events from. + */ + undelegate(namespace: string): ChaiJQuery; + + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ + unload(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. (DEPRECATED from v1.10) + */ + context: Element; + + jquery: string; + + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ + error(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + error(eventData: any, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + */ + pushStack(elements: any[]): ChaiJQuery; + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + * @param name The name of a jQuery method that generated the array of elements. + * @param arguments The arguments that were passed in to the jQuery method (for serialization). + */ + pushStack(elements: any[], name: string, arguments: any[]): ChaiJQuery; + + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. + */ + after(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): ChaiJQuery; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + after(func: (index: number, html: string) => string|Element|JQuery): ChaiJQuery; + + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + */ + append(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): ChaiJQuery; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + append(func: (index: number, html: string) => string|Element|JQuery): ChaiJQuery; + + /** + * Insert every element in the set of matched elements to the end of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. + */ + appendTo(target: JQuery|any[]|Element|string): ChaiJQuery; + + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + */ + before(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): ChaiJQuery; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + before(func: (index: number, html: string) => string|Element|JQuery): ChaiJQuery; + + /** + * Create a deep copy of the set of matched elements. + * + * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. + * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). + */ + clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): ChaiJQuery; + + /** + * Remove the set of matched elements from the DOM. + * + * param selector A selector expression that filters the set of matched elements to be removed. + */ + detach(selector?: string): ChaiJQuery; + + /** + * Remove all child nodes of the set of matched elements from the DOM. + */ + empty(): ChaiJQuery; + + /** + * Insert every element in the set of matched elements after the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + */ + insertAfter(target: JQuery|any[]|Element|Text|string): ChaiJQuery; + + /** + * Insert every element in the set of matched elements before the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + */ + insertBefore(target: JQuery|any[]|Element|Text|string): ChaiJQuery; + + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. + */ + prepend(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): ChaiJQuery; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + prepend(func: (index: number, html: string) => string|Element|JQuery): ChaiJQuery; + + /** + * Insert every element in the set of matched elements to the beginning of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. + */ + prependTo(target: JQuery|any[]|Element|string): ChaiJQuery; + + /** + * Remove the set of matched elements from the DOM. + * + * @param selector A selector expression that filters the set of matched elements to be removed. + */ + remove(selector?: string): ChaiJQuery; + + /** + * Replace each target element with the set of matched elements. + * + * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. + */ + replaceAll(target: JQuery|any[]|Element|string): ChaiJQuery; + + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. + */ + replaceWith(newContent: JQuery|any[]|Element|Text|string): ChaiJQuery; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param func A function that returns content with which to replace the set of matched elements. + */ + replaceWith(func: () => Element|JQuery): ChaiJQuery; + + /** + * Get the combined text contents of each element in the set of matched elements, including their descendants. + */ + text(): string; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. + */ + text(text: string|number|boolean): ChaiJQuery; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. + */ + text(func: (index: number, text: string) => string): ChaiJQuery; + + /** + * Retrieve all the elements contained in the jQuery set, as an array. + */ + toArray(): any[]; + + /** + * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. + */ + unwrap(): ChaiJQuery; + + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrap(wrappingElement: JQuery|Element|string): ChaiJQuery; + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrap(func: (index: number) => string|JQuery): ChaiJQuery; + + /** + * Wrap an HTML structure around all elements in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrapAll(wrappingElement: JQuery|Element|string): ChaiJQuery; + wrapAll(func: (index: number) => string): ChaiJQuery; + + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. + */ + wrapInner(wrappingElement: JQuery|Element|string): ChaiJQuery; + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrapInner(func: (index: number) => string): ChaiJQuery; + + /** + * Iterate over a jQuery object, executing a function for each matched element. + * + * @param func A function to execute for each matched element. + */ + each(func: (index: number, elem: Element) => any): ChaiJQuery; + + /** + * Retrieve one of the elements matched by the jQuery object. + * + * @param index A zero-based integer indicating which element to retrieve. + */ + get(index: number): HTMLElement; + /** + * Retrieve the elements matched by the jQuery object. + */ + get(): any[]; + + /** + * Search for a given element from among the matched elements. + */ + index(): number; + /** + * Search for a given element from among the matched elements. + * + * @param selector A selector representing a jQuery collection in which to look for an element. + */ + index(selector: string|JQuery|Element): number; + + /** + * The number of elements in the jQuery object. + */ + length: number; + /** + * A selector representing selector passed to jQuery(), if any, when creating the original set. + * version deprecated: 1.7, removed: 1.9 + */ + selector: string; + [index: string]: any; + [index: number]: HTMLElement; + + /** + * Add elements to the set of matched elements. + * + * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. + * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. + */ + add(selector: string, context?: Element): ChaiJQuery; + /** + * Add elements to the set of matched elements. + * + * @param elements One or more elements to add to the set of matched elements. + */ + add(...elements: Element[]): ChaiJQuery; + /** + * Add elements to the set of matched elements. + * + * @param html An HTML fragment to add to the set of matched elements. + */ + add(html: string): ChaiJQuery; + /** + * Add elements to the set of matched elements. + * + * @param obj An existing jQuery object to add to the set of matched elements. + */ + add(obj: JQuery): ChaiJQuery; + + /** + * Get the children of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + children(selector?: string): ChaiJQuery; + + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + */ + closest(selector: string): ChaiJQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ + closest(selector: string, context?: Element): ChaiJQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param obj A jQuery object to match elements against. + */ + closest(obj: JQuery): ChaiJQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param element An element to match elements against. + */ + closest(element: Element): ChaiJQuery; + + /** + * Get an array of all the elements and selectors matched against the current element up through the DOM tree. + * + * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ + closest(selectors: any, context?: Element): any[]; + + /** + * Get the children of each element in the set of matched elements, including text and comment nodes. + */ + contents(): ChaiJQuery; + + /** + * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. + */ + end(): ChaiJQuery; + + /** + * Reduce the set of matched elements to the one at the specified index. + * + * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. + * + */ + eq(index: number): ChaiJQuery; + + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param selector A string containing a selector expression to match the current set of elements against. + */ + filter(selector: string): ChaiJQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + filter(func: (index: number, element: Element) => any): ChaiJQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param element An element to match the current set of elements against. + */ + filter(element: Element): ChaiJQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + filter(obj: JQuery): ChaiJQuery; + + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param selector A string containing a selector expression to match elements against. + */ + find(selector: string): ChaiJQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param element An element to match elements against. + */ + find(element: Element): ChaiJQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param obj A jQuery object to match elements against. + */ + find(obj: JQuery): ChaiJQuery; + + /** + * Reduce the set of matched elements to the first in the set. + */ + first(): ChaiJQuery; + + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param selector A string containing a selector expression to match elements against. + */ + has(selector: string): ChaiJQuery; + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param contained A DOM element to match elements against. + */ + has(contained: Element): ChaiJQuery; + + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param selector A string containing a selector expression to match elements against. + */ + is(selector: string): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. + */ + is(func: (index: number, element: Element) => boolean): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + is(obj: JQuery): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param elements One or more elements to match the current set of elements against. + */ + is(elements: any): boolean; + + /** + * Reduce the set of matched elements to the final one in the set. + */ + last(): ChaiJQuery; + + /** + * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. + * + * @param callback A function object that will be invoked for each element in the current set. + */ + map(callback: (index: number, domElement: Element) => any): ChaiJQuery; + + /** + * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + next(selector?: string): ChaiJQuery; + + /** + * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + nextAll(selector?: string): ChaiJQuery; + + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(selector?: string, filter?: string): ChaiJQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(element?: Element, filter?: string): ChaiJQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(obj?: JQuery, filter?: string): ChaiJQuery; + + /** + * Remove elements from the set of matched elements. + * + * @param selector A string containing a selector expression to match elements against. + */ + not(selector: string): ChaiJQuery; + /** + * Remove elements from the set of matched elements. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + not(func: (index: number, element: Element) => boolean): ChaiJQuery; + /** + * Remove elements from the set of matched elements. + * + * @param elements One or more DOM elements to remove from the matched set. + */ + not(...elements: Element[]): ChaiJQuery; + /** + * Remove elements from the set of matched elements. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + not(obj: JQuery): ChaiJQuery; + + /** + * Get the closest ancestor element that is positioned. + */ + offsetParent(): ChaiJQuery; + + /** + * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + parent(selector?: string): ChaiJQuery; + + /** + * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + parents(selector?: string): ChaiJQuery; + + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(selector?: string, filter?: string): ChaiJQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(element?: Element, filter?: string): ChaiJQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(obj?: JQuery, filter?: string): ChaiJQuery; + + /** + * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + prev(selector?: string): ChaiJQuery; + + /** + * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + prevAll(selector?: string): ChaiJQuery; + + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(selector?: string, filter?: string): ChaiJQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(element?: Element, filter?: string): ChaiJQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(obj?: JQuery, filter?: string): ChaiJQuery; + + /** + * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + siblings(selector?: string): ChaiJQuery; + + /** + * Reduce the set of matched elements to a subset specified by a range of indices. + * + * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. + * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. + */ + slice(start: number, end?: number): ChaiJQuery; + + /** + * Show the queue of functions to be executed on the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + queue(queueName?: string): any[]; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(newQueue: Function[]): ChaiJQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(callback: Function): ChaiJQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(queueName: string, newQueue: Function[]): ChaiJQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(queueName: string, callback: Function): ChaiJQuery; + should: Chai.Assertion; +} diff --git a/chai-jquery/tsconfig.json b/chai-jquery/tsconfig.json new file mode 100644 index 0000000000..3026631bf7 --- /dev/null +++ b/chai-jquery/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chai-jquery-tests.ts" + ] +} \ No newline at end of file diff --git a/chai-string/chai-string-tests.ts b/chai-string/chai-string-tests.ts index f5380b0768..af18987bb5 100644 --- a/chai-string/chai-string-tests.ts +++ b/chai-string/chai-string-tests.ts @@ -1,6 +1,6 @@ -/// -/// -/// + +/// +/// var should = chai.should(); var assert = chai.assert; diff --git a/chai-string/chai-string.d.ts b/chai-string/chai-string.d.ts deleted file mode 100644 index ef75470cc7..0000000000 --- a/chai-string/chai-string.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Type definitions for chai-string 1.1.4 -// Project: https://github.com/onechiporenko/chai-string -// Definitions by: Nick Malaguti -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Chai { - interface Assertion extends LanguageChains, NumericComparison, TypeComparison { - startsWith(expected: string, message?: string): Assertion; - startWith(expected: string, message?: string): Assertion; - endsWith(expected: string, message?: string): Assertion; - endWith(expected: string, message?: string): Assertion; - equalIgnoreCase(expected: string, message?: string): Assertion; - equalIgnoreSpaces(expected: string, message?: string): Assertion; - singleLine(message?: string): Assertion; - reverseOf(message?: string): Assertion; - palindrome(message?: string): Assertion; - entriesCount(substr: string, expected: number, message?: string): Assertion; - } - - export interface Assert { - startsWith(val: string, exp: string, msg?: string): void; - notStartsWith(val: string, exp: string, msg?: string): void; - endsWith(val: string, exp: string, msg?: string): void; - notEndsWith(val: string, exp: string, msg?: string): void; - equalIgnoreCase(val: string, exp: string, msg?: string): void; - notEqualIgnoreCase(val: string, exp: string, msg?: string): void; - equalIgnoreSpaces(val: string, exp: string, msg?: string): void; - notEqualIgnoreSpaces(val: string, exp: string, msg?: string): void; - singleLine(val: string, msg?: string): void; - notSingleLine(val: string, msg?: string): void; - reverseOf(val: string, exp: string, msg?: string): void; - notReverseOf(val: string, exp: string, msg?: string): void; - palindrome(val: string, msg?: string): void; - notPalindrome(val: string, msg?: string): void; - entriesCount(str: string, substr: string, count: number, msg?: string): void; - } -} - -declare module 'chai-string' { - function chaiString(chai: any, utils: any): void; - namespace chaiString {} - export = chaiString; -} diff --git a/chai-string/index.d.ts b/chai-string/index.d.ts new file mode 100644 index 0000000000..1c880dc87e --- /dev/null +++ b/chai-string/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for chai-string 1.1.4 +// Project: https://github.com/onechiporenko/chai-string +// Definitions by: Nick Malaguti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare global { + namespace Chai { + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + startsWith(expected: string, message?: string): Assertion; + startWith(expected: string, message?: string): Assertion; + endsWith(expected: string, message?: string): Assertion; + endWith(expected: string, message?: string): Assertion; + equalIgnoreCase(expected: string, message?: string): Assertion; + equalIgnoreSpaces(expected: string, message?: string): Assertion; + singleLine(message?: string): Assertion; + reverseOf(message?: string): Assertion; + palindrome(message?: string): Assertion; + entriesCount(substr: string, expected: number, message?: string): Assertion; + } + + interface Assert { + startsWith(val: string, exp: string, msg?: string): void; + notStartsWith(val: string, exp: string, msg?: string): void; + endsWith(val: string, exp: string, msg?: string): void; + notEndsWith(val: string, exp: string, msg?: string): void; + equalIgnoreCase(val: string, exp: string, msg?: string): void; + notEqualIgnoreCase(val: string, exp: string, msg?: string): void; + equalIgnoreSpaces(val: string, exp: string, msg?: string): void; + notEqualIgnoreSpaces(val: string, exp: string, msg?: string): void; + singleLine(val: string, msg?: string): void; + notSingleLine(val: string, msg?: string): void; + reverseOf(val: string, exp: string, msg?: string): void; + notReverseOf(val: string, exp: string, msg?: string): void; + palindrome(val: string, msg?: string): void; + notPalindrome(val: string, msg?: string): void; + entriesCount(str: string, substr: string, count: number, msg?: string): void; + } + } +} + +declare function chaiString(chai: any, utils: any): void; +export = chaiString; diff --git a/chai-string/tsconfig.json b/chai-string/tsconfig.json new file mode 100644 index 0000000000..89290bf131 --- /dev/null +++ b/chai-string/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chai-string-tests.ts" + ] +} \ No newline at end of file diff --git a/chai-subset/chai-subset-tests.ts b/chai-subset/chai-subset-tests.ts index 8b88e5c6a3..d4c7ca3f2b 100644 --- a/chai-subset/chai-subset-tests.ts +++ b/chai-subset/chai-subset-tests.ts @@ -1,4 +1,4 @@ -/// + import chai = require('chai'); import chaiSubset = require('chai-subset'); diff --git a/chai-subset/chai-subset.d.ts b/chai-subset/chai-subset.d.ts deleted file mode 100644 index 7e2b3a159b..0000000000 --- a/chai-subset/chai-subset.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Type definitions for chai-subset 1.0.0 -// Project: https://github.com/e-conomic/chai-subset -// Definitions by: Sam Noedel , Andrew Brown -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Chai { - interface Assertion { - containSubset(obj: Object): Assertion; - } -} - -declare module "chai-subset" { - function chaiSubset(chai: any, utils: any): void; - export = chaiSubset; -} diff --git a/chai-subset/index.d.ts b/chai-subset/index.d.ts new file mode 100644 index 0000000000..89ee553945 --- /dev/null +++ b/chai-subset/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for chai-subset 1.0.0 +// Project: https://github.com/e-conomic/chai-subset +// Definitions by: Sam Noedel , Andrew Brown +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace Chai { + interface Assertion { + containSubset(obj: Object): Assertion; + } +} + +declare module "chai-subset" { + function chaiSubset(chai: any, utils: any): void; + export = chaiSubset; +} diff --git a/chai-subset/tsconfig.json b/chai-subset/tsconfig.json new file mode 100644 index 0000000000..0a1890207d --- /dev/null +++ b/chai-subset/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chai-subset-tests.ts" + ] +} \ No newline at end of file diff --git a/chai-things/chai-things-tests.ts b/chai-things/chai-things-tests.ts index de6a4c3ffe..a8337ce36f 100644 --- a/chai-things/chai-things-tests.ts +++ b/chai-things/chai-things-tests.ts @@ -1,4 +1,4 @@ -/// + import chai = require('chai'); import chaiThings = require('chai-things'); diff --git a/chai-things/chai-things.d.ts b/chai-things/chai-things.d.ts deleted file mode 100644 index 823329808c..0000000000 --- a/chai-things/chai-things.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Type definitions for chai-things -// Project: https://github.com/chaijs/chai-things -// Definitions by: David Broder-Rodgers -// Definitions: https://github.com/DavidBR-SW/DefinitelyTyped - -/// - -declare namespace Chai { - interface ArrayAssertion { - include: ArrayInclude; - contain: ArrayInclude; - not: ArrayAssertion; - all: Assertion; - } - - interface ArrayInclude { - (item: any): any; - a: Item; - an: Item; - one: Something; - some: Something; - something: Something; - any: Anything; - } - - interface Anything extends Assertion { - (): any; - that: Assertion - with: Assertion - } - - interface Something extends Assertion { - (): any; - that: Assertion - with: Assertion - } - - interface Item { - item: Something; - thing: Something; - } - - interface Deep { - equals: Equal; - } -} - -interface Array { - should: Chai.ArrayAssertion; -} - -declare module "chai-things" { - function chaiThings(chai: any, utils: any): void; - export = chaiThings; -} diff --git a/chai-things/index.d.ts b/chai-things/index.d.ts new file mode 100644 index 0000000000..21dd73a9a4 --- /dev/null +++ b/chai-things/index.d.ts @@ -0,0 +1,55 @@ +// Type definitions for chai-things +// Project: https://github.com/chaijs/chai-things +// Definitions by: David Broder-Rodgers +// Definitions: https://github.com/DavidBR-SW/DefinitelyTyped + +/// + +declare namespace Chai { + interface ArrayAssertion { + include: ArrayInclude; + contain: ArrayInclude; + not: ArrayAssertion; + all: Assertion; + } + + interface ArrayInclude { + (item: any): any; + a: Item; + an: Item; + one: Something; + some: Something; + something: Something; + any: Anything; + } + + interface Anything extends Assertion { + (): any; + that: Assertion + with: Assertion + } + + interface Something extends Assertion { + (): any; + that: Assertion + with: Assertion + } + + interface Item { + item: Something; + thing: Something; + } + + interface Deep { + equals: Equal; + } +} + +interface Array { + should: Chai.ArrayAssertion; +} + +declare module "chai-things" { + function chaiThings(chai: any, utils: any): void; + export = chaiThings; +} diff --git a/chai-things/tsconfig.json b/chai-things/tsconfig.json new file mode 100644 index 0000000000..59d3b38578 --- /dev/null +++ b/chai-things/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chai-things-tests.ts" + ] +} \ No newline at end of file diff --git a/chai/chai-3.2.0-tests.ts b/chai/chai-3.2.0-tests.ts index 9b646b1529..9578a54c2c 100644 --- a/chai/chai-3.2.0-tests.ts +++ b/chai/chai-3.2.0-tests.ts @@ -1,4 +1,4 @@ -/// + import chai = require('chai'); // ReSharper disable WrongExpressionStatement diff --git a/chai/chai-3.2.0.d.ts b/chai/chai-3.2.0.d.ts index 87b0c08e6f..124beead2e 100644 --- a/chai/chai-3.2.0.d.ts +++ b/chai/chai-3.2.0.d.ts @@ -6,7 +6,7 @@ // Olivier Chevet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// +// declare namespace Chai { diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index dbca4c11a1..7f104d07e5 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -1,4 +1,4 @@ -/// + import chai = require('chai'); // ReSharper disable WrongExpressionStatement diff --git a/chai/chai.d.ts b/chai/chai.d.ts deleted file mode 100644 index 0ebc855022..0000000000 --- a/chai/chai.d.ts +++ /dev/null @@ -1,401 +0,0 @@ -// Type definitions for chai 3.4.0 -// Project: http://chaijs.com/ -// Definitions by: Jed Mao , -// Bart van der Schoor , -// Andrew Brown , -// Olivier Chevet , -// Matt Wistrand -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// - -declare namespace Chai { - - interface ChaiStatic { - expect: ExpectStatic; - should(): Should; - /** - * Provides a way to extend the internals of Chai - */ - use(fn: (chai: any, utils: any) => void): ChaiStatic; - assert: AssertStatic; - config: Config; - AssertionError: typeof AssertionError; - } - - export interface ExpectStatic extends AssertionStatic { - fail(actual?: any, expected?: any, message?: string, operator?: string): void; - } - - export interface AssertStatic extends Assert { - } - - export interface AssertionStatic { - (target: any, message?: string): Assertion; - } - - interface ShouldAssertion { - equal(value1: any, value2: any, message?: string): void; - Throw: ShouldThrow; - throw: ShouldThrow; - exist(value: any, message?: string): void; - } - - interface Should extends ShouldAssertion { - not: ShouldAssertion; - fail(actual: any, expected: any, message?: string, operator?: string): void; - } - - interface ShouldThrow { - (actual: Function): void; - (actual: Function, expected: string|RegExp, message?: string): void; - (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; - } - - interface Assertion extends LanguageChains, NumericComparison, TypeComparison { - not: Assertion; - deep: Deep; - any: KeyFilter; - all: KeyFilter; - a: TypeComparison; - an: TypeComparison; - include: Include; - includes: Include; - contain: Include; - contains: Include; - ok: Assertion; - true: Assertion; - false: Assertion; - null: Assertion; - undefined: Assertion; - NaN: Assertion; - exist: Assertion; - empty: Assertion; - arguments: Assertion; - Arguments: Assertion; - equal: Equal; - equals: Equal; - eq: Equal; - eql: Equal; - eqls: Equal; - property: Property; - ownProperty: OwnProperty; - haveOwnProperty: OwnProperty; - ownPropertyDescriptor: OwnPropertyDescriptor; - haveOwnPropertyDescriptor: OwnPropertyDescriptor; - length: Length; - lengthOf: Length; - match: Match; - matches: Match; - string(string: string, message?: string): Assertion; - keys: Keys; - key(string: string): Assertion; - throw: Throw; - throws: Throw; - Throw: Throw; - respondTo: RespondTo; - respondsTo: RespondTo; - itself: Assertion; - satisfy: Satisfy; - satisfies: Satisfy; - closeTo: CloseTo; - approximately: CloseTo; - members: Members; - increase: PropertyChange; - increases: PropertyChange; - decrease: PropertyChange; - decreases: PropertyChange; - change: PropertyChange; - changes: PropertyChange; - extensible: Assertion; - sealed: Assertion; - frozen: Assertion; - oneOf(list: any[], message?: string): Assertion; - } - - interface LanguageChains { - to: Assertion; - be: Assertion; - been: Assertion; - is: Assertion; - that: Assertion; - which: Assertion; - and: Assertion; - has: Assertion; - have: Assertion; - with: Assertion; - at: Assertion; - of: Assertion; - same: Assertion; - } - - interface NumericComparison { - above: NumberComparer; - gt: NumberComparer; - greaterThan: NumberComparer; - least: NumberComparer; - gte: NumberComparer; - below: NumberComparer; - lt: NumberComparer; - lessThan: NumberComparer; - most: NumberComparer; - lte: NumberComparer; - within(start: number, finish: number, message?: string): Assertion; - } - - interface NumberComparer { - (value: number, message?: string): Assertion; - } - - interface TypeComparison { - (type: string, message?: string): Assertion; - instanceof: InstanceOf; - instanceOf: InstanceOf; - } - - interface InstanceOf { - (constructor: Object, message?: string): Assertion; - } - - interface CloseTo { - (expected: number, delta: number, message?: string): Assertion; - } - - interface Deep { - equal: Equal; - include: Include; - property: Property; - members: Members; - } - - interface KeyFilter { - keys: Keys; - } - - interface Equal { - (value: any, message?: string): Assertion; - } - - interface Property { - (name: string, value?: any, message?: string): Assertion; - } - - interface OwnProperty { - (name: string, message?: string): Assertion; - } - - interface OwnPropertyDescriptor { - (name: string, descriptor: PropertyDescriptor, message?: string): Assertion; - (name: string, message?: string): Assertion; - } - - interface Length extends LanguageChains, NumericComparison { - (length: number, message?: string): Assertion; - } - - interface Include { - (value: Object, message?: string): Assertion; - (value: string, message?: string): Assertion; - (value: number, message?: string): Assertion; - keys: Keys; - members: Members; - any: KeyFilter; - all: KeyFilter; - } - - interface Match { - (regexp: RegExp|string, message?: string): Assertion; - } - - interface Keys { - (...keys: string[]): Assertion; - (keys: any[]): Assertion; - (keys: Object): Assertion; - } - - interface Throw { - (): Assertion; - (expected: string, message?: string): Assertion; - (expected: RegExp, message?: string): Assertion; - (constructor: Error, expected?: string, message?: string): Assertion; - (constructor: Error, expected?: RegExp, message?: string): Assertion; - (constructor: Function, expected?: string, message?: string): Assertion; - (constructor: Function, expected?: RegExp, message?: string): Assertion; - } - - interface RespondTo { - (method: string, message?: string): Assertion; - } - - interface Satisfy { - (matcher: Function, message?: string): Assertion; - } - - interface Members { - (set: any[], message?: string): Assertion; - } - - interface PropertyChange { - (object: Object, prop: string, msg?: string): Assertion; - } - - export interface Assert { - /** - * @param expression Expression to test for truthiness. - * @param message Message to display on error. - */ - (expression: any, message?: string): void; - - fail(actual?: any, expected?: any, msg?: string, operator?: string): void; - - ok(val: any, msg?: string): void; - isOk(val: any, msg?: string): void; - notOk(val: any, msg?: string): void; - isNotOk(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; - - isNotTrue(val: any, msg?: string): void; - isNotFalse(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; - - isNaN(val: any, msg?: string): void; - isNotNaN(val: any, msg?: string): void; - - isAbove(val: number, abv: number, msg?: string): void; - isBelow(val: number, blw: number, msg?: string): void; - - isAtLeast(val: number, atlst: number, msg?: string): void; - isAtMost(val: number, atmst: number, 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; - approximately(act: number, exp: number, delta: number, msg?: string): void; - - sameMembers(set1: any[], set2: any[], msg?: string): void; - sameDeepMembers(set1: any[], set2: any[], msg?: string): void; - includeMembers(superset: any[], subset: any[], msg?: string): void; - - ifError(val: any, msg?: string): void; - - isExtensible(obj: {}, msg?: string): void; - extensible(obj: {}, msg?: string): void; - isNotExtensible(obj: {}, msg?: string): void; - notExtensible(obj: {}, msg?: string): void; - - isSealed(obj: {}, msg?: string): void; - sealed(obj: {}, msg?: string): void; - isNotSealed(obj: {}, msg?: string): void; - notSealed(obj: {}, msg?: string): void; - - isFrozen(obj: Object, msg?: string): void; - frozen(obj: Object, msg?: string): void; - isNotFrozen(obj: Object, msg?: string): void; - notFrozen(obj: Object, msg?: string): void; - - oneOf(inList: any, list: any[], msg?: string): void; - } - - export interface Config { - includeStack: boolean; - } - - export class AssertionError { - constructor(message: string, _props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; - } -} - -declare var chai: Chai.ChaiStatic; - -declare module "chai" { - export = chai; -} - -interface Object { - should: Chai.Assertion; -} diff --git a/chai/index.d.ts b/chai/index.d.ts new file mode 100644 index 0000000000..f8f9f733f0 --- /dev/null +++ b/chai/index.d.ts @@ -0,0 +1,401 @@ +// Type definitions for chai 3.4.0 +// Project: http://chaijs.com/ +// Definitions by: Jed Mao , +// Bart van der Schoor , +// Andrew Brown , +// Olivier Chevet , +// Matt Wistrand +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// + +declare namespace Chai { + + interface ChaiStatic { + expect: ExpectStatic; + should(): Should; + /** + * Provides a way to extend the internals of Chai + */ + use(fn: (chai: any, utils: any) => void): ChaiStatic; + assert: AssertStatic; + config: Config; + AssertionError: typeof AssertionError; + } + + export interface ExpectStatic extends AssertionStatic { + fail(actual?: any, expected?: any, message?: string, operator?: string): void; + } + + export interface AssertStatic extends Assert { + } + + export interface AssertionStatic { + (target: any, message?: string): Assertion; + } + + interface ShouldAssertion { + equal(value1: any, value2: any, message?: string): void; + Throw: ShouldThrow; + throw: ShouldThrow; + exist(value: any, message?: string): void; + } + + interface Should extends ShouldAssertion { + not: ShouldAssertion; + fail(actual: any, expected: any, message?: string, operator?: string): void; + } + + interface ShouldThrow { + (actual: Function): void; + (actual: Function, expected: string|RegExp, message?: string): void; + (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; + } + + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + not: Assertion; + deep: Deep; + any: KeyFilter; + all: KeyFilter; + a: TypeComparison; + an: TypeComparison; + include: Include; + includes: Include; + contain: Include; + contains: Include; + ok: Assertion; + true: Assertion; + false: Assertion; + null: Assertion; + undefined: Assertion; + NaN: Assertion; + exist: Assertion; + empty: Assertion; + arguments: Assertion; + Arguments: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + eql: Equal; + eqls: Equal; + property: Property; + ownProperty: OwnProperty; + haveOwnProperty: OwnProperty; + ownPropertyDescriptor: OwnPropertyDescriptor; + haveOwnPropertyDescriptor: OwnPropertyDescriptor; + length: Length; + lengthOf: Length; + match: Match; + matches: Match; + string(string: string, message?: string): Assertion; + keys: Keys; + key(string: string): Assertion; + throw: Throw; + throws: Throw; + Throw: Throw; + respondTo: RespondTo; + respondsTo: RespondTo; + itself: Assertion; + satisfy: Satisfy; + satisfies: Satisfy; + closeTo: CloseTo; + approximately: CloseTo; + members: Members; + increase: PropertyChange; + increases: PropertyChange; + decrease: PropertyChange; + decreases: PropertyChange; + change: PropertyChange; + changes: PropertyChange; + extensible: Assertion; + sealed: Assertion; + frozen: Assertion; + oneOf(list: any[], message?: string): Assertion; + } + + interface LanguageChains { + to: Assertion; + be: Assertion; + been: Assertion; + is: Assertion; + that: Assertion; + which: Assertion; + and: Assertion; + has: Assertion; + have: Assertion; + with: Assertion; + at: Assertion; + of: Assertion; + same: Assertion; + } + + interface NumericComparison { + above: NumberComparer; + gt: NumberComparer; + greaterThan: NumberComparer; + least: NumberComparer; + gte: NumberComparer; + below: NumberComparer; + lt: NumberComparer; + lessThan: NumberComparer; + most: NumberComparer; + lte: NumberComparer; + within(start: number, finish: number, message?: string): Assertion; + } + + interface NumberComparer { + (value: number, message?: string): Assertion; + } + + interface TypeComparison { + (type: string, message?: string): Assertion; + instanceof: InstanceOf; + instanceOf: InstanceOf; + } + + interface InstanceOf { + (constructor: Object, message?: string): Assertion; + } + + interface CloseTo { + (expected: number, delta: number, message?: string): Assertion; + } + + interface Deep { + equal: Equal; + include: Include; + property: Property; + members: Members; + } + + interface KeyFilter { + keys: Keys; + } + + interface Equal { + (value: any, message?: string): Assertion; + } + + interface Property { + (name: string, value?: any, message?: string): Assertion; + } + + interface OwnProperty { + (name: string, message?: string): Assertion; + } + + interface OwnPropertyDescriptor { + (name: string, descriptor: PropertyDescriptor, message?: string): Assertion; + (name: string, message?: string): Assertion; + } + + interface Length extends LanguageChains, NumericComparison { + (length: number, message?: string): Assertion; + } + + interface Include { + (value: Object, message?: string): Assertion; + (value: string, message?: string): Assertion; + (value: number, message?: string): Assertion; + keys: Keys; + members: Members; + any: KeyFilter; + all: KeyFilter; + } + + interface Match { + (regexp: RegExp|string, message?: string): Assertion; + } + + interface Keys { + (...keys: string[]): Assertion; + (keys: any[]): Assertion; + (keys: Object): Assertion; + } + + interface Throw { + (): Assertion; + (expected: string, message?: string): Assertion; + (expected: RegExp, message?: string): Assertion; + (constructor: Error, expected?: string, message?: string): Assertion; + (constructor: Error, expected?: RegExp, message?: string): Assertion; + (constructor: Function, expected?: string, message?: string): Assertion; + (constructor: Function, expected?: RegExp, message?: string): Assertion; + } + + interface RespondTo { + (method: string, message?: string): Assertion; + } + + interface Satisfy { + (matcher: Function, message?: string): Assertion; + } + + interface Members { + (set: any[], message?: string): Assertion; + } + + interface PropertyChange { + (object: Object, prop: string, msg?: string): Assertion; + } + + export interface Assert { + /** + * @param expression Expression to test for truthiness. + * @param message Message to display on error. + */ + (expression: any, message?: string): void; + + fail(actual?: any, expected?: any, msg?: string, operator?: string): void; + + ok(val: any, msg?: string): void; + isOk(val: any, msg?: string): void; + notOk(val: any, msg?: string): void; + isNotOk(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; + + isNotTrue(val: any, msg?: string): void; + isNotFalse(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; + + isNaN(val: any, msg?: string): void; + isNotNaN(val: any, msg?: string): void; + + isAbove(val: number, abv: number, msg?: string): void; + isBelow(val: number, blw: number, msg?: string): void; + + isAtLeast(val: number, atlst: number, msg?: string): void; + isAtMost(val: number, atmst: number, 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; + approximately(act: number, exp: number, delta: number, msg?: string): void; + + sameMembers(set1: any[], set2: any[], msg?: string): void; + sameDeepMembers(set1: any[], set2: any[], msg?: string): void; + includeMembers(superset: any[], subset: any[], msg?: string): void; + + ifError(val: any, msg?: string): void; + + isExtensible(obj: {}, msg?: string): void; + extensible(obj: {}, msg?: string): void; + isNotExtensible(obj: {}, msg?: string): void; + notExtensible(obj: {}, msg?: string): void; + + isSealed(obj: {}, msg?: string): void; + sealed(obj: {}, msg?: string): void; + isNotSealed(obj: {}, msg?: string): void; + notSealed(obj: {}, msg?: string): void; + + isFrozen(obj: Object, msg?: string): void; + frozen(obj: Object, msg?: string): void; + isNotFrozen(obj: Object, msg?: string): void; + notFrozen(obj: Object, msg?: string): void; + + oneOf(inList: any, list: any[], msg?: string): void; + } + + export interface Config { + includeStack: boolean; + } + + export class AssertionError { + constructor(message: string, _props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; + } +} + +declare var chai: Chai.ChaiStatic; + +declare module "chai" { + export = chai; +} + +interface Object { + should: Chai.Assertion; +} diff --git a/chai/tsconfig.json b/chai/tsconfig.json new file mode 100644 index 0000000000..5e194fef23 --- /dev/null +++ b/chai/tsconfig.json @@ -0,0 +1,17 @@ +{ + "files": [ + "index.d.ts", + "chai-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/chalk/chalk-tests.ts b/chalk/chalk-tests.ts index e159d34765..8b302aecb7 100644 --- a/chalk/chalk-tests.ts +++ b/chalk/chalk-tests.ts @@ -1,4 +1,4 @@ -/// + import chalk = require('chalk'); diff --git a/chalk/chalk.d.ts b/chalk/chalk.d.ts deleted file mode 100644 index 1ead986818..0000000000 --- a/chalk/chalk.d.ts +++ /dev/null @@ -1,122 +0,0 @@ -// Type definitions for chalk v0.4.0 -// Project: https://github.com/sindresorhus/chalk -// Definitions by: Diullei Gomes , Bart van der Schoor , Nico Jansen -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Chalk { - - export var enabled: boolean; - export var supportsColor: boolean; - export var styles: ChalkStyleMap; - - export function stripColor(value: string): any; - export function hasColor(str: string): boolean; - - export interface ChalkChain extends ChalkStyle { - (...text: string[]): string; - } - - export interface ChalkStyleElement { - open: string; - close: string; - } - - // General - export var reset: ChalkChain; - export var bold: ChalkChain; - export var italic: ChalkChain; - export var underline: ChalkChain; - export var inverse: ChalkChain; - export var strikethrough: ChalkChain; - - // Text colors - export var black: ChalkChain; - export var red: ChalkChain; - export var green: ChalkChain; - export var yellow: ChalkChain; - export var blue: ChalkChain; - export var magenta: ChalkChain; - export var cyan: ChalkChain; - export var white: ChalkChain; - export var gray: ChalkChain; - export var grey: ChalkChain; - - // Background colors - export var bgBlack: ChalkChain; - export var bgRed: ChalkChain; - export var bgGreen: ChalkChain; - export var bgYellow: ChalkChain; - export var bgBlue: ChalkChain; - export var bgMagenta: ChalkChain; - export var bgCyan: ChalkChain; - export var bgWhite: ChalkChain; - - - export interface ChalkStyle { - // General - reset: ChalkChain; - bold: ChalkChain; - italic: ChalkChain; - underline: ChalkChain; - inverse: ChalkChain; - strikethrough: ChalkChain; - - // Text colors - black: ChalkChain; - red: ChalkChain; - green: ChalkChain; - yellow: ChalkChain; - blue: ChalkChain; - magenta: ChalkChain; - cyan: ChalkChain; - white: ChalkChain; - gray: ChalkChain; - grey: ChalkChain; - - // Background colors - bgBlack: ChalkChain; - bgRed: ChalkChain; - bgGreen: ChalkChain; - bgYellow: ChalkChain; - bgBlue: ChalkChain; - bgMagenta: ChalkChain; - bgCyan: ChalkChain; - bgWhite: ChalkChain; - } - - export interface ChalkStyleMap { - // General - reset: ChalkStyleElement; - bold: ChalkStyleElement; - italic: ChalkStyleElement; - underline: ChalkStyleElement; - inverse: ChalkStyleElement; - strikethrough: ChalkStyleElement; - - // Text colors - black: ChalkStyleElement; - red: ChalkStyleElement; - green: ChalkStyleElement; - yellow: ChalkStyleElement; - blue: ChalkStyleElement; - magenta: ChalkStyleElement; - cyan: ChalkStyleElement; - white: ChalkStyleElement; - gray: ChalkStyleElement; - - // Background colors - bgBlack: ChalkStyleElement; - bgRed: ChalkStyleElement; - bgGreen: ChalkStyleElement; - bgYellow: ChalkStyleElement; - bgBlue: ChalkStyleElement; - bgMagenta: ChalkStyleElement; - bgCyan: ChalkStyleElement; - bgWhite: ChalkStyleElement; - } -} - -declare module "chalk" { - export = Chalk; -} - diff --git a/chalk/index.d.ts b/chalk/index.d.ts new file mode 100644 index 0000000000..97c7f7427a --- /dev/null +++ b/chalk/index.d.ts @@ -0,0 +1,120 @@ +// Type definitions for chalk v0.4.0 +// Project: https://github.com/sindresorhus/chalk +// Definitions by: Diullei Gomes , Bart van der Schoor , Nico Jansen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Chalk; + +declare namespace Chalk { + + export var enabled: boolean; + export var supportsColor: boolean; + export var styles: ChalkStyleMap; + + export function stripColor(value: string): any; + export function hasColor(str: string): boolean; + + export interface ChalkChain extends ChalkStyle { + (...text: string[]): string; + } + + export interface ChalkStyleElement { + open: string; + close: string; + } + + // General + export var reset: ChalkChain; + export var bold: ChalkChain; + export var italic: ChalkChain; + export var underline: ChalkChain; + export var inverse: ChalkChain; + export var strikethrough: ChalkChain; + + // Text colors + export var black: ChalkChain; + export var red: ChalkChain; + export var green: ChalkChain; + export var yellow: ChalkChain; + export var blue: ChalkChain; + export var magenta: ChalkChain; + export var cyan: ChalkChain; + export var white: ChalkChain; + export var gray: ChalkChain; + export var grey: ChalkChain; + + // Background colors + export var bgBlack: ChalkChain; + export var bgRed: ChalkChain; + export var bgGreen: ChalkChain; + export var bgYellow: ChalkChain; + export var bgBlue: ChalkChain; + export var bgMagenta: ChalkChain; + export var bgCyan: ChalkChain; + export var bgWhite: ChalkChain; + + + export interface ChalkStyle { + // General + reset: ChalkChain; + bold: ChalkChain; + italic: ChalkChain; + underline: ChalkChain; + inverse: ChalkChain; + strikethrough: ChalkChain; + + // Text colors + black: ChalkChain; + red: ChalkChain; + green: ChalkChain; + yellow: ChalkChain; + blue: ChalkChain; + magenta: ChalkChain; + cyan: ChalkChain; + white: ChalkChain; + gray: ChalkChain; + grey: ChalkChain; + + // Background colors + bgBlack: ChalkChain; + bgRed: ChalkChain; + bgGreen: ChalkChain; + bgYellow: ChalkChain; + bgBlue: ChalkChain; + bgMagenta: ChalkChain; + bgCyan: ChalkChain; + bgWhite: ChalkChain; + } + + export interface ChalkStyleMap { + // General + reset: ChalkStyleElement; + bold: ChalkStyleElement; + italic: ChalkStyleElement; + underline: ChalkStyleElement; + inverse: ChalkStyleElement; + strikethrough: ChalkStyleElement; + + // Text colors + black: ChalkStyleElement; + red: ChalkStyleElement; + green: ChalkStyleElement; + yellow: ChalkStyleElement; + blue: ChalkStyleElement; + magenta: ChalkStyleElement; + cyan: ChalkStyleElement; + white: ChalkStyleElement; + gray: ChalkStyleElement; + + // Background colors + bgBlack: ChalkStyleElement; + bgRed: ChalkStyleElement; + bgGreen: ChalkStyleElement; + bgYellow: ChalkStyleElement; + bgBlue: ChalkStyleElement; + bgMagenta: ChalkStyleElement; + bgCyan: ChalkStyleElement; + bgWhite: ChalkStyleElement; + } +} + diff --git a/chalk/tsconfig.json b/chalk/tsconfig.json new file mode 100644 index 0000000000..02f0e59176 --- /dev/null +++ b/chalk/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chalk-tests.ts" + ] +} \ No newline at end of file diff --git a/chance/chance-tests.ts b/chance/chance-tests.ts index d9b4153960..a426142d7f 100644 --- a/chance/chance-tests.ts +++ b/chance/chance-tests.ts @@ -1,4 +1,4 @@ -/// + // Instantiation var globalInstance: Chance.Chance = chance; diff --git a/chance/chance.d.ts b/chance/index.d.ts similarity index 100% rename from chance/chance.d.ts rename to chance/index.d.ts diff --git a/chance/tsconfig.json b/chance/tsconfig.json new file mode 100644 index 0000000000..4c3858d36c --- /dev/null +++ b/chance/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chance-tests.ts" + ] +} \ No newline at end of file diff --git a/change-case/change-case-tests.ts b/change-case/change-case-tests.ts index 2e80c8a0d9..67ef86405b 100644 --- a/change-case/change-case-tests.ts +++ b/change-case/change-case-tests.ts @@ -1,5 +1,3 @@ -/// - import changeCase = require("change-case"); var s: string; diff --git a/change-case/change-case.d.ts b/change-case/change-case.d.ts deleted file mode 100644 index d432db1c35..0000000000 --- a/change-case/change-case.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Type definitions for change-case -// Project: https://github.com/blakeembrey/change-case -// Definitions by: Asana -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "change-case" { - function dot(s: string): string; - function dotCase(s: string): string; - function swap(s: string): string; - function swapCase(s: string): string; - function path(s: string): string; - function pathCase(s: string): string; - function upper(s: string): string; - function upperCase(s: string): string; - function lower(s: string): string; - function lowerCase(s: string): string; - function camel(s: string): string; - function camelCase(s: string): string; - function snake(s: string): string; - function snakeCase(s: string): string; - function title(s: string): string; - function titleCase(s: string): string; - function param(s: string): string; - function paramCase(s: string): string; - function pascal(s: string): string; - function pascalCase(s: string): string; - function constant(s: string): string; - function constantCase(s: string): string; - function sentence(s: string): string; - function sentenceCase(s: string): string; - function isUpper(s: string): boolean; - function isUpperCase(s: string): boolean; - function isLower(s: string): boolean; - function isLowerCase(s: string): boolean; - function ucFirst(s: string): string; - function upperCaseFirst(s: string): string; - function lcFirst(s: string): string; - function lowerCaseFirst(s: string): string; -} diff --git a/change-case/index.d.ts b/change-case/index.d.ts new file mode 100644 index 0000000000..590597d621 --- /dev/null +++ b/change-case/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for change-case +// Project: https://github.com/blakeembrey/change-case +// Definitions by: Asana +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function dot(s: string): string; +export function dotCase(s: string): string; +export function swap(s: string): string; +export function swapCase(s: string): string; +export function path(s: string): string; +export function pathCase(s: string): string; +export function upper(s: string): string; +export function upperCase(s: string): string; +export function lower(s: string): string; +export function lowerCase(s: string): string; +export function camel(s: string): string; +export function camelCase(s: string): string; +export function snake(s: string): string; +export function snakeCase(s: string): string; +export function title(s: string): string; +export function titleCase(s: string): string; +export function param(s: string): string; +export function paramCase(s: string): string; +export function pascal(s: string): string; +export function pascalCase(s: string): string; +export function constant(s: string): string; +export function constantCase(s: string): string; +export function sentence(s: string): string; +export function sentenceCase(s: string): string; +export function isUpper(s: string): boolean; +export function isUpperCase(s: string): boolean; +export function isLower(s: string): boolean; +export function isLowerCase(s: string): boolean; +export function ucFirst(s: string): string; +export function upperCaseFirst(s: string): string; +export function lcFirst(s: string): string; +export function lowerCaseFirst(s: string): string; diff --git a/change-case/tsconfig.json b/change-case/tsconfig.json new file mode 100644 index 0000000000..09c8fe7baf --- /dev/null +++ b/change-case/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "change-case-tests.ts" + ] +} \ No newline at end of file diff --git a/chartist/chartist-tests.ts b/chartist/chartist-tests.ts index 22b10e8b03..2a4a362e7e 100644 --- a/chartist/chartist-tests.ts +++ b/chartist/chartist-tests.ts @@ -1,5 +1,4 @@ -/// - +import Chartist = require("chartist"); Chartist.escapingMap = { '&': '&', '<': '<', diff --git a/chartist/chartist.d.ts b/chartist/chartist.d.ts deleted file mode 100644 index ca2b4206d8..0000000000 --- a/chartist/chartist.d.ts +++ /dev/null @@ -1,559 +0,0 @@ -// Type definitions for Chartist v0.9.5 -// Project: https://github.com/gionkunz/chartist-js -// Definitions by: Matt Gibbs -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Chartist { - - interface ChartistStatic { - - /** - * Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number. - */ - precision: number; - - /** - * A map with characters to escape for strings to be safely used as attribute values. - */ - escapingMap: IChartistEscapeMap; - - Pie: IChartistPieChart; - Bar: IChartistBarChart; - Line: IChartistLineChart; - - FixedScaleAxis: IFixedScaleAxisStatic; - AutoScaleAxis: IAutoScaleAxisStatic; - StepAxis: IStepAxisStatic; - - Svg: ChartistSvgStatic; - Interpolation: ChartistInterpolationStatic; - - noop: Function; - - alphaNumerate(n: number): string; - extend(target: Object, ...sources: Object[]): Object; - - replaceAll(str: string, subStr: string, newSubStr: string): string; - ensureUnit(value: number, unit: string): string; - quantity(input: string | number): Object; - - query(query: Node | string): Node; - times(length: number): Array; - sum(previous: number, current: number): number; - mapMultiply(factor: number): (num: number) => number; - mapAdd(addend: number): (num: number) => number; - serialMap(arr: Array, cb: Function): Array; - roundWithPrecision(value: number, digits?: number): number; - - getMultiValue(value: any, dimension?: any): number; // this method is not documented, but it is used in the examples - - serialize(data: Object | string | number): string; - deserialize(data: string): Object | string | number; - - createSvg(container: Node, width: string, height: string, className: string): Object; // TODO: Figure out if this is returning a ChartistSVGWrapper or an actual SVGElement - - plugins: any; - } - - interface IChartistEscapeMap { - [Key: string]: string; - } - - interface IResponsiveOptionTuple extends Array { - 0: string; - 1: T; - } - - // these have no other purpose than to help define the types that can be placed on - // a line chart axisX - // in the actual chartist library these are classes that project their options onto - // the parent class - interface IFixedScaleAxisStatic { } - interface IAutoScaleAxisStatic { } - interface IStepAxisStatic { } - - // data formats are not well documented on all the ways they can be passed to the constructors - // this definition gives some intellisense, but does not protect the user from misuse - // TODO: come in and tidy this up and make it fit better - interface IChartistData { - labels?: Array | Array | Array; - series: Array | Array | Array>; - } - - interface IChartistSeriesData { - name?: string; - value?: number; - data?: Array; - className?: string; - meta?: string; // I assume this could probably be a number as well? - } - - interface IChartistBase { - container: any; - data: IChartistData; - defaultOptions: T; - options: T; - responsiveOptions: Array>; - - // this most likely doesn't need to be exposed to the user - eventEmitter: any; - - supportsForeignObject: boolean; - supportsAnimations: boolean; - resizeListener: any; - - plugins?: Array; // all of these plugins seem to be functions with options, but keeping type any for now - - update(data: Object, options?: T, override?: boolean): void; - detatch(): void; - - /** - * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop. - * - * @method on - * @param event {string} Name of the event. Check the examples for supported events. - * @param handler {Function} The handler function that will be called when an event with the given name was emitted. This function will receive a data argument which contains event data. See the example for more details. - */ - on(event: string, handler: Function): IChartistBase; - - /** - * Use this function to un-register event handlers. If the handler function parameter is omitted all handlers for the given event will be un-registered. - * - * @method off - * @param event {string} Name of the event for which a handler should be removed - * @param handler {Function} The handler function that that was previously used to register a new event handler. This handler will be removed from the event handler list. If this parameter is omitted then all event handlers for the given event are removed from the list. - */ - off(event: string, handler?: Function): IChartistBase; - } - - interface IChartistPieChart extends IChartistBase { - new (target: any, data: IChartistData, options?: IPieChartOptions, responsiveOptions?: Array>): IChartistPieChart; - } - - interface IChartistLineChart extends IChartistBase { - new (target: any, data: IChartistData, options?: ILineChartOptions, responsiveOptions?: Array>): IChartistLineChart; - } - - interface IChartistBarChart extends IChartistBase { - new (target: any, data: IChartistData, options?: IBarChartOptions, responsiveOptions?: Array>): IChartistBarChart; - } - - interface IChartOptions { - /** - * If true the whole data is reversed including labels, the series order as well as the whole series data arrays. - */ - reverseData?: boolean; - - plugins?: Array; - } - - interface IPieChartOptions extends IChartOptions { - /** - * Specify a fixed width for the chart as a string (i.e. '100px' or '50%') - */ - width?: number | string; - - /** - * Specify a fixed height for the chart as a string (i.e. '100px' or '50%') - */ - height?: number | string; - - /** - * Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5} - */ - chartPadding?: IChartPadding | number; - - /** - * Override the class names that are used to generate the SVG structure of the chart - */ - classNames?: IPieChartClasses; - - /** - * The start angle of the pie chart in degrees where 0 points north. A higher value offsets the start angle clockwise. - */ - startAngle?: number; - - /** - * An optional total you can specify. By specifying a total value, the sum of the values in the series must be this total in order to draw a full pie. You can use this parameter to draw only parts of a pie or gauge charts. - */ - total?: number; - - /** - * If specified the donut CSS classes will be used and strokes will be drawn instead of pie slices. - */ - donut?: boolean; - - /** - * Specify the donut stroke width, currently done in javascript for convenience. - */ - donutWidth?: number; - - /** - * Specify if a label should be shown or not - */ - showLabel?: boolean; - - /** - * Label position offset from the standard position which is half distance of the radius. This value can be either positive or negative. Positive values will position the label away from the center. - */ - labelOffset?: number; - - /** - * This option can be set to 'inside', 'outside' or 'center'. Positioned with 'inside' the labels will be placed on half the distance of the radius to the border of the Pie by respecting the 'labelOffset'. The 'outside' option will place the labels at the border of the pie and 'center' will place the labels in the absolute center point of the chart. The 'center' option only makes sense in conjunction with the 'labelOffset' option. - */ - labelPosition?: string; - - /** - * An interpolation function for the label value - */ - labelInterpolationFnc?: Function; - - /** - * Label direction can be 'neutral', 'explode' or 'implode'. Default is 'neutral'. The labels anchor will be positioned based on those settings as well as the fact if the labels are on the right or left side of the center of the chart. Usually explode is useful when labels are positioned far away from the center. - */ - labelDirection?: string; - } - - interface IChartPadding { - top?: number; - right?: number; - bottom?: number; - left?: number; - } - - interface IPieChartClasses { - chartPie?: string; - chartDonut?: string; - series?: string; - slicePie?: string; - sliceDonut?: string; - label?: string; - } - - interface IBarChartOptions extends IChartOptions { - axisX?: IBarChartAxis; - axisY?: IBarChartAxis; - width?: number | string; - height?: number | string; - high?: number; - low?: number; - ticks?: Array; - onlyInteger?: boolean; - chartPadding?: IChartPadding; - seriesBarDistance?: number; - - /** - * If set to true this property will cause the series bars to be stacked and form a total for each series point. This will also influence the y-axis and the overall bounds of the chart. In stacked mode the seriesBarDistance property will have no effect. - */ - stackBars?: boolean; - - horizontalBars?: boolean; - distributeSeries?: boolean; - } - - interface IBarChartAxis { - offset?: number; - position?: string; - labelOffset?: { - x?: number; - y?: number; - }; - showLabel?: boolean; - showGrid?: boolean; - labelInterpolationFnc?: Function; - scaleMinSpace?: number; - onlyInteger?: boolean; - } - - interface IBarChartClasses { - chart?: string; - horizontalBars?: string; - label?: string; - labelGroup?: string; - series?: string; - bar?: string; - grid?: string; - gridGroup?: string; - vertical?: string; - horizontal?: string; - start?: string; - end?: string; - } - - interface ILineChartOptions extends IChartOptions { - axisX?: IChartistStepAxis | IChartistFixedScaleAxis | IChartistAutoScaleAxis; - axisY?: IChartistStepAxis | IChartistFixedScaleAxis | IChartistAutoScaleAxis; - width?: number | string; - height?: number | string; - showLine?: boolean; - showPoint?: boolean; - showArea?: boolean; - areaBase?: number; - lineSmooth?: Function | boolean; - low?: number; - high?: number; - ticks?: Array; - chartPadding?: IChartPadding; - fullWidth?: boolean; - classNames?: ILineChartClasses; - } - - interface ILineChartAxis { - offset?: number; - position?: string; - labelOffset?: { - x?: number; - y?: number; - }; - showLabel?: boolean; - showGrid?: boolean; - labelInterpolationFnc?: Function; - } - - interface IChartistStepAxis extends ILineChartAxis { - type?: IStepAxisStatic; - ticks?: Array | Array; - stretch?: boolean; - } - - interface IChartistFixedScaleAxis extends ILineChartAxis { - type?: IFixedScaleAxisStatic; - high?: number; - low?: number; - divisor?: number; - ticks?: Array | Array; - } - - interface IChartistAutoScaleAxis extends ILineChartAxis { - high?: number; - low?: number; - scaleMinSpace?: number; - onlyInteger?: boolean; - referenceValue?: number; - type?: IAutoScaleAxisStatic; - } - - interface ILineChartClasses { - /** - * Default is 'ct-chart-line' - */ - chart?: string; - label?: string; - labelGroup?: string; - series?: string; - line?: string; - point?: string; - area?: string; - grid?: string; - gridGroup?: string; - vertical?: string; - horizontal?: string; - start?: string; - end?: string; - } - - interface ChartistSvgStatic { - new (name: HTMLElement | string, attributes: Object, className?: string, parent?: Object, insertFirst?: boolean): IChartistSvg; - - Easing: ChartistEasingStatic; - - /** - * This method checks for support of a given SVG feature like Extensibility, SVG-animation or the like. Check http://www.w3.org/TR/SVG11/feature for a detailed list. - */ - isSupported(feature: string): boolean; - } - - interface IChartistSvg { - - /** - * Set attributes on the current SVG element of the wrapper you're currently working on. - */ - attr(attributes: Object | string, ns: string): Object | string; - - /** - * Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily. - */ - elem(name: string, attributes?: Object, className?: string, insertFirst?: boolean): IChartistSvg; - - /** - * Returns the parent Chartist.SVG wrapper object - */ - parent(): IChartistSvg; - - /** - * This method returns a Chartist.Svg wrapper around the root SVG element of the current tree. - */ - root(): IChartistSvg; - - /** - * Find the first child SVG element of the current element that matches a CSS selector. The returned object is a Chartist.Svg wrapper. - */ - querySelector(selector: string): IChartistSvg; - - /** - * Find the all child SVG elements of the current element that match a CSS selector. The returned object is a Chartist.Svg.List wrapper. - */ - querySelectorAll(selector: string): any; // this returns an svg wrapper list in the docs, need to see if that's just an array or a special list - - /** - * This method creates a foreignObject (see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject) that allows to embed HTML content into a SVG graphic. With the help of foreignObjects you can enable the usage of regular HTML elements inside of SVG where they are subject for SVG positioning and transformation but the Browser will use the HTML rendering capabilities for the containing DOM. - */ - foreignObject(content: any, attributes?: Object, className?: string, insertFirst?: boolean): IChartistSvg; - - /** - * This method adds a new text element to the current Chartist.Svg wrapper. - */ - text(t: string): IChartistSvg; - - /** - * This method will clear all child nodes of the current wrapper object. - */ - empty(): IChartistSvg; - - /** - * This method will cause the current wrapper to remove itself from its parent wrapper. Use this method if you'd like to get rid of an element in a given DOM structure. - */ - remove(): IChartistSvg; - - /** - * This method will replace the element with a new element that can be created outside of the current DOM. - */ - replace(): IChartistSvg; - - /** - * This method will append an element to the current element as a child. - */ - append(): IChartistSvg; - - /** - * Returns an array of class names that are attached to the current wrapper element. This method can not be chained further. - */ - classes(): Array; - - /** - * Adds one or a space separated list of classes to the current element and ensures the classes are only existing once. - * - * @method addClass - * @param names {string} A white space separated list of class names - */ - addClass(names: string): IChartistSvg; - - /** - * Removes one or a space separated list of classes from the current element. - * - * @method removeClass - * @param names {string} A white space separated list of class names - */ - removeClass(names: string): IChartistSvg; - - /** - * Removes all classes from the current element. - */ - removeAllClasses(): IChartistSvg; - - /** - * Get element height with fallback to svg BoundingBox or parent container dimensions - */ - height(): number; - - /** - * The animate function lets you animate the current element with SMIL animations. You can add animations for multiple attributes at the same time by using an animation definition object. This object should contain SMIL animation attributes. - */ - animate(animations: IChartistAnimations, guided: boolean, eventEmitter: Object): IChartistSvg; - - /** - * "Safe" way to get property value from svg BoundingBox. This is a workaround. Firefox throws an NS_ERROR_FAILURE error if getBBox() is called on an invisible node. - * THIS IS A WORKAROUND - */ - getBBoxProperty(node: SVGElement, prop: string): string; // TODO: find a good example of this and add it to the tests, it might belong to static - } - - interface IChartistAnimations { - [Key: string]: IChartistAnimationOptions; - } - - interface IChartistAnimationOptions { - id?: string; - dur: string | number; - from: string | number; - to: string | number; - easing?: IChartistEasingDefinition | string; - fill?: string; - begin?: string; - } - - interface IChartistEasingDefinition { - 0: number; - 1: number; - 2: number; - 3: number; - } - - interface ChartistEasingStatic { - easeInSine: IChartistEasingDefinition; - easeOutSine: IChartistEasingDefinition; - easeInOutSine: IChartistEasingDefinition; - easeInQuad: IChartistEasingDefinition; - easeOutQuad: IChartistEasingDefinition; - easeInOutQuad: IChartistEasingDefinition; - easeInCubic: IChartistEasingDefinition; - easeOutCubic: IChartistEasingDefinition; - easeInOutCubic: IChartistEasingDefinition; - easeInQuart: IChartistEasingDefinition; - easeOutQuart: IChartistEasingDefinition; - easeInOutQuart: IChartistEasingDefinition; - easeInQuint: IChartistEasingDefinition; - easeOutQuint: IChartistEasingDefinition; - easeInOutQuint: IChartistEasingDefinition; - easeInExpo: IChartistEasingDefinition; - easeOutExpo: IChartistEasingDefinition; - easeInOutExpo: IChartistEasingDefinition; - easeInCirc: IChartistEasingDefinition; - easeOutCirc: IChartistEasingDefinition; - easeInOutCirc: IChartistEasingDefinition; - easeInBack: IChartistEasingDefinition; - easeOutBack: IChartistEasingDefinition; - easeInOutBack: IChartistEasingDefinition; - } - - interface ChartistInterpolationStatic { - - /** - * This interpolation function does not smooth the path and the result is only containing lines and no curves. - */ - none(options?: IChartistInterpolationOptions): Function; - - /** - * Simple smoothing creates horizontal handles that are positioned with a fraction of the length between two data points. You can use the divisor option to specify the amount of smoothing. - */ - simple(options?: IChartistSimpleInterpolationOptions): Function; - - /** - * Cardinal / Catmull-Rome spline interpolation is the default smoothing function in Chartist. It produces nice results where the splines will always meet the points. It produces some artifacts though when data values are increased or decreased rapidly. The line may not follow a very accurate path and if the line should be accurate this smoothing function does not produce the best results. - */ - cardinal(options?: IChartistCardinalInterpolationOptions): Function; - - /** - * Step interpolation will cause the line chart to move in steps rather than diagonal or smoothed lines. This interpolation will create additional points that will also be drawn when the showPoint option is enabled. - */ - step(options?: IChartistStepInterpolationOptions): Function; - } - - interface IChartistInterpolationOptions { - fillHoles?: boolean; - } - - interface IChartistSimpleInterpolationOptions extends IChartistInterpolationOptions { - divisor?: number; - } - - interface IChartistCardinalInterpolationOptions extends IChartistInterpolationOptions { - tension?: number; - } - - interface IChartistStepInterpolationOptions extends IChartistInterpolationOptions { - postpone?: boolean; - } -} - -declare var Chartist: Chartist.ChartistStatic; diff --git a/chartist/index.d.ts b/chartist/index.d.ts new file mode 100644 index 0000000000..117f0914ae --- /dev/null +++ b/chartist/index.d.ts @@ -0,0 +1,562 @@ +// Type definitions for Chartist v0.9.5 +// Project: https://github.com/gionkunz/chartist-js +// Definitions by: Matt Gibbs +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Chartist { + + interface ChartistStatic { + + /** + * Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number. + */ + precision: number; + + /** + * A map with characters to escape for strings to be safely used as attribute values. + */ + escapingMap: IChartistEscapeMap; + + Pie: IChartistPieChart; + Bar: IChartistBarChart; + Line: IChartistLineChart; + + FixedScaleAxis: IFixedScaleAxisStatic; + AutoScaleAxis: IAutoScaleAxisStatic; + StepAxis: IStepAxisStatic; + + Svg: ChartistSvgStatic; + Interpolation: ChartistInterpolationStatic; + + noop: Function; + + alphaNumerate(n: number): string; + extend(target: Object, ...sources: Object[]): Object; + + replaceAll(str: string, subStr: string, newSubStr: string): string; + ensureUnit(value: number, unit: string): string; + quantity(input: string | number): Object; + + query(query: Node | string): Node; + times(length: number): Array; + sum(previous: number, current: number): number; + mapMultiply(factor: number): (num: number) => number; + mapAdd(addend: number): (num: number) => number; + serialMap(arr: Array, cb: Function): Array; + roundWithPrecision(value: number, digits?: number): number; + + getMultiValue(value: any, dimension?: any): number; // this method is not documented, but it is used in the examples + + serialize(data: Object | string | number): string; + deserialize(data: string): Object | string | number; + + createSvg(container: Node, width: string, height: string, className: string): Object; // TODO: Figure out if this is returning a ChartistSVGWrapper or an actual SVGElement + + plugins: any; + } + + interface IChartistEscapeMap { + [Key: string]: string; + } + + interface IResponsiveOptionTuple extends Array { + 0: string; + 1: T; + } + + // these have no other purpose than to help define the types that can be placed on + // a line chart axisX + // in the actual chartist library these are classes that project their options onto + // the parent class + interface IFixedScaleAxisStatic { } + interface IAutoScaleAxisStatic { } + interface IStepAxisStatic { } + + // data formats are not well documented on all the ways they can be passed to the constructors + // this definition gives some intellisense, but does not protect the user from misuse + // TODO: come in and tidy this up and make it fit better + interface IChartistData { + labels?: Array | Array | Array; + series: Array | Array | Array>; + } + + interface IChartistSeriesData { + name?: string; + value?: number; + data?: Array; + className?: string; + meta?: string; // I assume this could probably be a number as well? + } + + interface IChartistBase { + container: any; + data: IChartistData; + defaultOptions: T; + options: T; + responsiveOptions: Array>; + + // this most likely doesn't need to be exposed to the user + eventEmitter: any; + + supportsForeignObject: boolean; + supportsAnimations: boolean; + resizeListener: any; + + plugins?: Array; // all of these plugins seem to be functions with options, but keeping type any for now + + update(data: Object, options?: T, override?: boolean): void; + detatch(): void; + + /** + * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop. + * + * @method on + * @param event {string} Name of the event. Check the examples for supported events. + * @param handler {Function} The handler function that will be called when an event with the given name was emitted. This function will receive a data argument which contains event data. See the example for more details. + */ + on(event: string, handler: Function): IChartistBase; + + /** + * Use this function to un-register event handlers. If the handler function parameter is omitted all handlers for the given event will be un-registered. + * + * @method off + * @param event {string} Name of the event for which a handler should be removed + * @param handler {Function} The handler function that that was previously used to register a new event handler. This handler will be removed from the event handler list. If this parameter is omitted then all event handlers for the given event are removed from the list. + */ + off(event: string, handler?: Function): IChartistBase; + } + + interface IChartistPieChart extends IChartistBase { + new (target: any, data: IChartistData, options?: IPieChartOptions, responsiveOptions?: Array>): IChartistPieChart; + } + + interface IChartistLineChart extends IChartistBase { + new (target: any, data: IChartistData, options?: ILineChartOptions, responsiveOptions?: Array>): IChartistLineChart; + } + + interface IChartistBarChart extends IChartistBase { + new (target: any, data: IChartistData, options?: IBarChartOptions, responsiveOptions?: Array>): IChartistBarChart; + } + + interface IChartOptions { + /** + * If true the whole data is reversed including labels, the series order as well as the whole series data arrays. + */ + reverseData?: boolean; + + plugins?: Array; + } + + interface IPieChartOptions extends IChartOptions { + /** + * Specify a fixed width for the chart as a string (i.e. '100px' or '50%') + */ + width?: number | string; + + /** + * Specify a fixed height for the chart as a string (i.e. '100px' or '50%') + */ + height?: number | string; + + /** + * Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5} + */ + chartPadding?: IChartPadding | number; + + /** + * Override the class names that are used to generate the SVG structure of the chart + */ + classNames?: IPieChartClasses; + + /** + * The start angle of the pie chart in degrees where 0 points north. A higher value offsets the start angle clockwise. + */ + startAngle?: number; + + /** + * An optional total you can specify. By specifying a total value, the sum of the values in the series must be this total in order to draw a full pie. You can use this parameter to draw only parts of a pie or gauge charts. + */ + total?: number; + + /** + * If specified the donut CSS classes will be used and strokes will be drawn instead of pie slices. + */ + donut?: boolean; + + /** + * Specify the donut stroke width, currently done in javascript for convenience. + */ + donutWidth?: number; + + /** + * Specify if a label should be shown or not + */ + showLabel?: boolean; + + /** + * Label position offset from the standard position which is half distance of the radius. This value can be either positive or negative. Positive values will position the label away from the center. + */ + labelOffset?: number; + + /** + * This option can be set to 'inside', 'outside' or 'center'. Positioned with 'inside' the labels will be placed on half the distance of the radius to the border of the Pie by respecting the 'labelOffset'. The 'outside' option will place the labels at the border of the pie and 'center' will place the labels in the absolute center point of the chart. The 'center' option only makes sense in conjunction with the 'labelOffset' option. + */ + labelPosition?: string; + + /** + * An interpolation function for the label value + */ + labelInterpolationFnc?: Function; + + /** + * Label direction can be 'neutral', 'explode' or 'implode'. Default is 'neutral'. The labels anchor will be positioned based on those settings as well as the fact if the labels are on the right or left side of the center of the chart. Usually explode is useful when labels are positioned far away from the center. + */ + labelDirection?: string; + } + + interface IChartPadding { + top?: number; + right?: number; + bottom?: number; + left?: number; + } + + interface IPieChartClasses { + chartPie?: string; + chartDonut?: string; + series?: string; + slicePie?: string; + sliceDonut?: string; + label?: string; + } + + interface IBarChartOptions extends IChartOptions { + axisX?: IBarChartAxis; + axisY?: IBarChartAxis; + width?: number | string; + height?: number | string; + high?: number; + low?: number; + ticks?: Array; + onlyInteger?: boolean; + chartPadding?: IChartPadding; + seriesBarDistance?: number; + + /** + * If set to true this property will cause the series bars to be stacked and form a total for each series point. This will also influence the y-axis and the overall bounds of the chart. In stacked mode the seriesBarDistance property will have no effect. + */ + stackBars?: boolean; + + horizontalBars?: boolean; + distributeSeries?: boolean; + } + + interface IBarChartAxis { + offset?: number; + position?: string; + labelOffset?: { + x?: number; + y?: number; + }; + showLabel?: boolean; + showGrid?: boolean; + labelInterpolationFnc?: Function; + scaleMinSpace?: number; + onlyInteger?: boolean; + } + + interface IBarChartClasses { + chart?: string; + horizontalBars?: string; + label?: string; + labelGroup?: string; + series?: string; + bar?: string; + grid?: string; + gridGroup?: string; + vertical?: string; + horizontal?: string; + start?: string; + end?: string; + } + + interface ILineChartOptions extends IChartOptions { + axisX?: IChartistStepAxis | IChartistFixedScaleAxis | IChartistAutoScaleAxis; + axisY?: IChartistStepAxis | IChartistFixedScaleAxis | IChartistAutoScaleAxis; + width?: number | string; + height?: number | string; + showLine?: boolean; + showPoint?: boolean; + showArea?: boolean; + areaBase?: number; + lineSmooth?: Function | boolean; + low?: number; + high?: number; + ticks?: Array; + chartPadding?: IChartPadding; + fullWidth?: boolean; + classNames?: ILineChartClasses; + } + + interface ILineChartAxis { + offset?: number; + position?: string; + labelOffset?: { + x?: number; + y?: number; + }; + showLabel?: boolean; + showGrid?: boolean; + labelInterpolationFnc?: Function; + } + + interface IChartistStepAxis extends ILineChartAxis { + type?: IStepAxisStatic; + ticks?: Array | Array; + stretch?: boolean; + } + + interface IChartistFixedScaleAxis extends ILineChartAxis { + type?: IFixedScaleAxisStatic; + high?: number; + low?: number; + divisor?: number; + ticks?: Array | Array; + } + + interface IChartistAutoScaleAxis extends ILineChartAxis { + high?: number; + low?: number; + scaleMinSpace?: number; + onlyInteger?: boolean; + referenceValue?: number; + type?: IAutoScaleAxisStatic; + } + + interface ILineChartClasses { + /** + * Default is 'ct-chart-line' + */ + chart?: string; + label?: string; + labelGroup?: string; + series?: string; + line?: string; + point?: string; + area?: string; + grid?: string; + gridGroup?: string; + vertical?: string; + horizontal?: string; + start?: string; + end?: string; + } + + interface ChartistSvgStatic { + new (name: HTMLElement | string, attributes: Object, className?: string, parent?: Object, insertFirst?: boolean): IChartistSvg; + + Easing: ChartistEasingStatic; + + /** + * This method checks for support of a given SVG feature like Extensibility, SVG-animation or the like. Check http://www.w3.org/TR/SVG11/feature for a detailed list. + */ + isSupported(feature: string): boolean; + } + + interface IChartistSvg { + + /** + * Set attributes on the current SVG element of the wrapper you're currently working on. + */ + attr(attributes: Object | string, ns: string): Object | string; + + /** + * Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily. + */ + elem(name: string, attributes?: Object, className?: string, insertFirst?: boolean): IChartistSvg; + + /** + * Returns the parent Chartist.SVG wrapper object + */ + parent(): IChartistSvg; + + /** + * This method returns a Chartist.Svg wrapper around the root SVG element of the current tree. + */ + root(): IChartistSvg; + + /** + * Find the first child SVG element of the current element that matches a CSS selector. The returned object is a Chartist.Svg wrapper. + */ + querySelector(selector: string): IChartistSvg; + + /** + * Find the all child SVG elements of the current element that match a CSS selector. The returned object is a Chartist.Svg.List wrapper. + */ + querySelectorAll(selector: string): any; // this returns an svg wrapper list in the docs, need to see if that's just an array or a special list + + /** + * This method creates a foreignObject (see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject) that allows to embed HTML content into a SVG graphic. With the help of foreignObjects you can enable the usage of regular HTML elements inside of SVG where they are subject for SVG positioning and transformation but the Browser will use the HTML rendering capabilities for the containing DOM. + */ + foreignObject(content: any, attributes?: Object, className?: string, insertFirst?: boolean): IChartistSvg; + + /** + * This method adds a new text element to the current Chartist.Svg wrapper. + */ + text(t: string): IChartistSvg; + + /** + * This method will clear all child nodes of the current wrapper object. + */ + empty(): IChartistSvg; + + /** + * This method will cause the current wrapper to remove itself from its parent wrapper. Use this method if you'd like to get rid of an element in a given DOM structure. + */ + remove(): IChartistSvg; + + /** + * This method will replace the element with a new element that can be created outside of the current DOM. + */ + replace(): IChartistSvg; + + /** + * This method will append an element to the current element as a child. + */ + append(): IChartistSvg; + + /** + * Returns an array of class names that are attached to the current wrapper element. This method can not be chained further. + */ + classes(): Array; + + /** + * Adds one or a space separated list of classes to the current element and ensures the classes are only existing once. + * + * @method addClass + * @param names {string} A white space separated list of class names + */ + addClass(names: string): IChartistSvg; + + /** + * Removes one or a space separated list of classes from the current element. + * + * @method removeClass + * @param names {string} A white space separated list of class names + */ + removeClass(names: string): IChartistSvg; + + /** + * Removes all classes from the current element. + */ + removeAllClasses(): IChartistSvg; + + /** + * Get element height with fallback to svg BoundingBox or parent container dimensions + */ + height(): number; + + /** + * The animate function lets you animate the current element with SMIL animations. You can add animations for multiple attributes at the same time by using an animation definition object. This object should contain SMIL animation attributes. + */ + animate(animations: IChartistAnimations, guided: boolean, eventEmitter: Object): IChartistSvg; + + /** + * "Safe" way to get property value from svg BoundingBox. This is a workaround. Firefox throws an NS_ERROR_FAILURE error if getBBox() is called on an invisible node. + * THIS IS A WORKAROUND + */ + getBBoxProperty(node: SVGElement, prop: string): string; // TODO: find a good example of this and add it to the tests, it might belong to static + } + + interface IChartistAnimations { + [Key: string]: IChartistAnimationOptions; + } + + interface IChartistAnimationOptions { + id?: string; + dur: string | number; + from: string | number; + to: string | number; + easing?: IChartistEasingDefinition | string; + fill?: string; + begin?: string; + } + + interface IChartistEasingDefinition { + 0: number; + 1: number; + 2: number; + 3: number; + } + + interface ChartistEasingStatic { + easeInSine: IChartistEasingDefinition; + easeOutSine: IChartistEasingDefinition; + easeInOutSine: IChartistEasingDefinition; + easeInQuad: IChartistEasingDefinition; + easeOutQuad: IChartistEasingDefinition; + easeInOutQuad: IChartistEasingDefinition; + easeInCubic: IChartistEasingDefinition; + easeOutCubic: IChartistEasingDefinition; + easeInOutCubic: IChartistEasingDefinition; + easeInQuart: IChartistEasingDefinition; + easeOutQuart: IChartistEasingDefinition; + easeInOutQuart: IChartistEasingDefinition; + easeInQuint: IChartistEasingDefinition; + easeOutQuint: IChartistEasingDefinition; + easeInOutQuint: IChartistEasingDefinition; + easeInExpo: IChartistEasingDefinition; + easeOutExpo: IChartistEasingDefinition; + easeInOutExpo: IChartistEasingDefinition; + easeInCirc: IChartistEasingDefinition; + easeOutCirc: IChartistEasingDefinition; + easeInOutCirc: IChartistEasingDefinition; + easeInBack: IChartistEasingDefinition; + easeOutBack: IChartistEasingDefinition; + easeInOutBack: IChartistEasingDefinition; + } + + interface ChartistInterpolationStatic { + + /** + * This interpolation function does not smooth the path and the result is only containing lines and no curves. + */ + none(options?: IChartistInterpolationOptions): Function; + + /** + * Simple smoothing creates horizontal handles that are positioned with a fraction of the length between two data points. You can use the divisor option to specify the amount of smoothing. + */ + simple(options?: IChartistSimpleInterpolationOptions): Function; + + /** + * Cardinal / Catmull-Rome spline interpolation is the default smoothing function in Chartist. It produces nice results where the splines will always meet the points. It produces some artifacts though when data values are increased or decreased rapidly. The line may not follow a very accurate path and if the line should be accurate this smoothing function does not produce the best results. + */ + cardinal(options?: IChartistCardinalInterpolationOptions): Function; + + /** + * Step interpolation will cause the line chart to move in steps rather than diagonal or smoothed lines. This interpolation will create additional points that will also be drawn when the showPoint option is enabled. + */ + step(options?: IChartistStepInterpolationOptions): Function; + } + + interface IChartistInterpolationOptions { + fillHoles?: boolean; + } + + interface IChartistSimpleInterpolationOptions extends IChartistInterpolationOptions { + divisor?: number; + } + + interface IChartistCardinalInterpolationOptions extends IChartistInterpolationOptions { + tension?: number; + } + + interface IChartistStepInterpolationOptions extends IChartistInterpolationOptions { + postpone?: boolean; + } +} + +declare var Chartist: Chartist.ChartistStatic; + +export = Chartist; +export as namespace Chartist; diff --git a/chartist/tsconfig.json b/chartist/tsconfig.json new file mode 100644 index 0000000000..d11b14393f --- /dev/null +++ b/chartist/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chartist-tests.ts" + ] +} \ No newline at end of file diff --git a/chartjs/chart-tests.ts b/chartjs/chart-tests.ts index 452ddbf623..d6b47d45bf 100644 --- a/chartjs/chart-tests.ts +++ b/chartjs/chart-tests.ts @@ -1,4 +1,4 @@ -/// + var canvas = document.getElementById('example-chart'); var ctx = canvas.getContext('2d'); diff --git a/chartjs/chart.d.ts b/chartjs/index.d.ts similarity index 100% rename from chartjs/chart.d.ts rename to chartjs/index.d.ts diff --git a/chartjs/tsconfig.json b/chartjs/tsconfig.json new file mode 100644 index 0000000000..efb0b03e22 --- /dev/null +++ b/chartjs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chart-tests.ts" + ] +} \ No newline at end of file diff --git a/checksum/checksum-tests.ts b/checksum/checksum-tests.ts index 2746bcb9e9..a5924bcb2f 100644 --- a/checksum/checksum-tests.ts +++ b/checksum/checksum-tests.ts @@ -1,4 +1,3 @@ -/// import checksum = require("checksum"); diff --git a/checksum/checksum.d.ts b/checksum/checksum.d.ts deleted file mode 100644 index 920164386f..0000000000 --- a/checksum/checksum.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Type definitions for checksum 0.1.1 -// Project: https://github.com/dshaw/checksum -// Definitions by: Rogier Schouten -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "checksum" { - - namespace checksum { - /** - * Options object for all functions - */ - interface ChecksumOptions { - /** - * Algorithm to use, default 'sha1' - * Can be 'sha1' or 'md5' (see module 'crypto'). - */ - algorithm?: string; - } - - /** - * Generate the checksum for a file on disk - * @param filename The file name - * @param callback Callback which is called with the result or an error - */ - function file(filename: string, callback: (error: Error, hash: string) => void): void; - /** - * Generate the checksum for a file on disk - * @param filename The file name - * @param options Options object to indicate hash algo - * @param callback Callback which is called with the result or an error - */ - function file(filename: string, options: ChecksumOptions, callback: (error: Error, hash: string) => void): void; - } - - /** - * Generates a checksum for the given value - * @param value Any value - * @param options Allows to set the algorithm - * @returns Checksum - */ - function checksum(value: any, options?: checksum.ChecksumOptions): string; - - export = checksum; -} diff --git a/checksum/index.d.ts b/checksum/index.d.ts new file mode 100644 index 0000000000..3c3620bbcf --- /dev/null +++ b/checksum/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for checksum 0.1.1 +// Project: https://github.com/dshaw/checksum +// Definitions by: Rogier Schouten +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + +declare namespace checksum { + /** + * Options object for all functions + */ + interface ChecksumOptions { + /** + * Algorithm to use, default 'sha1' + * Can be 'sha1' or 'md5' (see module 'crypto'). + */ + algorithm?: string; + } + + /** + * Generate the checksum for a file on disk + * @param filename The file name + * @param callback Callback which is called with the result or an error + */ + function file(filename: string, callback: (error: Error, hash: string) => void): void; + /** + * Generate the checksum for a file on disk + * @param filename The file name + * @param options Options object to indicate hash algo + * @param callback Callback which is called with the result or an error + */ + function file(filename: string, options: ChecksumOptions, callback: (error: Error, hash: string) => void): void; +} + +/** + * Generates a checksum for the given value + * @param value Any value + * @param options Allows to set the algorithm + * @returns Checksum + */ +declare function checksum(value: any, options?: checksum.ChecksumOptions): string; + +export = checksum; diff --git a/checksum/tsconfig.json b/checksum/tsconfig.json new file mode 100644 index 0000000000..f7b6cb3368 --- /dev/null +++ b/checksum/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "checksum-tests.ts" + ] +} \ No newline at end of file diff --git a/cheerio/cheerio-tests.ts b/cheerio/cheerio-tests.ts index c1b5eda894..add6938dea 100644 --- a/cheerio/cheerio-tests.ts +++ b/cheerio/cheerio-tests.ts @@ -1,4 +1,4 @@ -/// + import * as cheerio from 'cheerio'; diff --git a/cheerio/cheerio.d.ts b/cheerio/index.d.ts similarity index 100% rename from cheerio/cheerio.d.ts rename to cheerio/index.d.ts diff --git a/cheerio/tsconfig.json b/cheerio/tsconfig.json new file mode 100644 index 0000000000..91abb07530 --- /dev/null +++ b/cheerio/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "cheerio-tests.ts" + ] +} \ No newline at end of file diff --git a/chocolatechipjs/chocolatechipjs-tests.ts b/chocolatechipjs/chocolatechipjs-tests.ts index 111e69f638..465ea2b0a9 100644 --- a/chocolatechipjs/chocolatechipjs-tests.ts +++ b/chocolatechipjs/chocolatechipjs-tests.ts @@ -1,4 +1,4 @@ -/// +/// // ChocolateChipStatic -- DOM creation, etc. $(function() { alert('Ready to do stuff!'); diff --git a/chocolatechipjs/chocolatechipjs-tests.ts.tscparams b/chocolatechipjs/chocolatechipjs-tests.ts.tscparams deleted file mode 100644 index 1f3d85fb3b..0000000000 --- a/chocolatechipjs/chocolatechipjs-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ ---target es5 --noImplicitAny diff --git a/chocolatechipjs/chocolatechipjs.d.ts b/chocolatechipjs/chocolatechipjs.d.ts deleted file mode 100644 index df54d62951..0000000000 --- a/chocolatechipjs/chocolatechipjs.d.ts +++ /dev/null @@ -1,1484 +0,0 @@ -// Type definitions for chocolatechip v4.0.4 -// Project: https://github.com/chocolatechipui/ChocolateChipJS -// Definitions by: Robert Biggs -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface ChocolateChipStatic { - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param selector A string containing a selector expression - * @param context A DOM HTMLElement to use as context - * @return HTMLElement[] - */ - (selector: string | HTMLElement | Document, context?: HTMLElement | ChocolateChipElementArray): ChocolateChipElementArray; - - /** - * Binds a function to be executed when the DOM has finished loading. - * - * @param callback A function to execute after the DOM is ready. - * @return void - */ - (callback: () => any): void; - - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param element A DOM element to wrap in an array. - * @return HTMLElement[] - */ - (element: HTMLElement): ChocolateChipElementArray; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param elementArray An array of DOM elements to convert into a ChocolateChip Collection. - * @return HTMLElement[] - */ - (elementArray: ChocolateChipElementArray): ChocolateChipElementArray; - - /** - * Accepts the document element and returns it wrapped in an array. - * - * @param document The document object. - * @return document[] - */ - (document: Document): Document[]; - - /** - * If no argument is provided, return the document as a ChocolateChipElementArray. - * @return Document[] - */ - (): Document[]; - - /** - * Extend the ChocolateChipJS object itself with the provided object. - * - * @param object The object to add to ChocolateChipJS. - * @return The ChocolateChipJS object. - */ - extend(object: Object): Object; - - /** - * Extend a target object with another object. - * - * @param target An object to extend. - * @param object The object to add to the target. - * @return The extended object. - */ - extend(target: Object, object: Object): Object; - - /** - * The base for extending ChocolateChipJS collections, which are arrays of elements. - */ - fn: { - /** - * This method adds the provided object to the Array prototype to make it available to all arrays of HTML elements. - * - * @param object And object to add to element arrays. - * @return The extended array of elements. - */ - extend(object: Object): HTMLElement[]; - }; - - /** - * Contains the version of ChocolateChipJS in use. - */ - version: string; - - /** - * Contains the name of the library (ChocolateChip). - */ - libraryName: string; - - /** - * An empty function. - * - * @return void. - */ - noop(): void; - - /** - * Uuid number. - */ - uuid: number; - - /** - * Create a random number to use as a uuid. - * - * @return number. - */ - uuidNum(): number; - - /** - * Creates a uuid using uuidNum(). - * - * @return A string. - */ - makeUuid(): string; - - - /** - * Create a ChocolateChip collection object by creating elements from an HTML string. - * - * @param selector - * @return any - */ - make(selector: string): ChocolateChipElementArray; - - /** - * Create a ChocolateChip collection object by creating elements from an HTML string. This is an alias for $.make. - * - * @param selector - * @return any - */ - html(selector: string): ChocolateChipElementArray; - - /** - * Replace one element with another. - * - * @param new HTMLElement - * @param old HTMLElement - * @return HTMLElement[] - */ - replace(newElement: ChocolateChipElementArray, oldElement: ChocolateChipElementArray): void; - - /** - * Load a JavaScript file from a url, then execute it. - * - * @param url A string containing the URL where the script resides. - * @param callback A callback function that is executed after the script loads. - * @return void - */ - require(url: string, callback: Function): Function; - - /** - * Process JavaScript returned by Ajax request. An optional name can be used to create a custom variable name by which the data is exposed, otherwise it is exposed with the variable "data". - * - * @param url A string containing the URL where the script resides. - * @param callback A callback function that is executed after the script loads. - * @return Function - */ - processJSON(json: string, name?: string): any; - - /** - * This method takes a referenced form and serializes its element names and values, which it returns as a string. This is required if you want to send form data. - * - * @param element A string, HTML element or ChocolateChipElementArray containing a reference to a from. - * @return An encode string form element names and values. - */ - serialize(element: any): string; - - /** - * Parse the data in a Promise response as JSON. - * - * @param response The response from a Promise. - * @result - */ - json(reponse: Response): JSON; - - /** - * This method will defer the execution of a function until the call stack is clear. - * - * @param callback A function to execute. - * @param duration The number of milliseconds to delay execution. - * @return any - */ - delay(callback: Function, duration?: number): any; - - /** - * The method will defer the execution of its callback until the call stack is clear. - * - * @param callback A callback to execute after a delay. - * @return Function. - */ - defer(callback: Function): Function; - - /** - * This method makes sure a method always returns an array. If no values are available to return, it returns and empty array. This is to make sure that methods that expect a chainable array will not throw and exception. - * - * @param result The result of a method to test if it can be returned in an array. - * @return An array holding the results of a method, otherwise an empty array. - */ - returnResult(result: HTMLElement[]): any[]; - - /** - * This method allows you to execute a callback on each item in an array of elements. - * - * @param array An array of elements. - * @param callback A callback to execute on each element. This has two parameters: the context, followed by the index of the current iteration. - */ - each(array: T[], callback: (ctx: T, idx: number) => any): any; - - /** - * This method will concatenate strings or values as a cleaner alternative to using the '+' operator. - * - * @param string or number A comma separated series of strings to concatenate. - * @return string - */ - concat(...string: string[]): string; - - /** - * This method takes a space-delimited string of words and returns it as an array where the individual words are indices. - * - * @param string Any string with values separated by spaces. - * @return string[] - */ - w(string: string): string[]; - - /** - * This method converts a string of hyphenated tokens into a camel cased string. - * - * @param string A string of hyphenated tokens. - * @return string - */ - camelize(string: string): string; - - /** - * This method converts a camel case string into lowercase with hyphens. - * - * @param string A camel case string. - * @return string - */ - deCamelize(string: string): string; - - /** - * This method capitalizes the first letter of a string. - * - * @param string A string. - * @param boolean A boolean value. - * @return string - */ - capitalize(string: string, boolean?: boolean): string; - - /** - * Determine whether the argument is a string. - * - * @param obj Object to test whether or not it is a string. - * @return boolean - */ - isString(obj: any): boolean; - - /** - * Determine whether the argument is an array. - * - * @param obj Object to test whether or not it is an array. - * @return boolean - */ - isArray(obj: any): boolean; - - /** - * Determine whether the argument is a function. - * - * @param obj Object to test whether or not it is an function. - * @return boolean - */ - isFunction(obj: any): boolean; - - /** - * Determine whether the argument is an object. - * - * @param obj Object to test whether or not it is an object. - * @return boolean - */ - isObject(obj: any): boolean; - - /** - * Determine whether the argument is an empty object. - * - * @param obj Object to test whether or not it is an empty object. - * @return boolean - */ - isEmptyObject(obj: any): boolean; - - /** - * Determine whether the argument is an empty object. - * - * @param obj Object to test whether or not it is an empty object. - * @return boolean - */ - isEmptyObject(obj: any): boolean; - - /** - * Determine whether the argument is a number. - * - * @param obj Object to test whether or not it is a number. - * @return boolean - */ - isNumber(obj: any): boolean; - - /** - * Determine whether the argument is an integer. - * - * @param obj Object to test whether or not it is an integer. - * @return boolean - */ - isInteger(obj: any): boolean; - - /** - * Determine whether the argument is a float. - * - * @param obj Object to test whether or not it is a float. - * @return boolean - */ - isFloat(obj: any): boolean; - - /** - * Whether device is iPhone. - */ - isiPhone: boolean; - - /** - * Whether device is iPad. - */ - isiPad: boolean; - - /** - * Whether device is iPod. - */ - isiPod: boolean; - - /** - * Whether OS is iOS. - */ - isiOS: boolean; - - /** - * Whether OS is Android - */ - isAndroid: boolean; - - /** - * Whether OS is WebOS. - */ - isWebOS: boolean; - - /** - * Whether OS is Blackberry. - */ - isBlackberry: boolean; - - /** - * Whether OS supports touch events. - */ - isTouchEnabled: boolean; - - /** - * Whether there is a network connection. - */ - isOnline: boolean; - - /** - * Whether app is running in stanalone mode. - */ - isStandalone: boolean; - - /** - * Whether OS is iOS 6. - */ - isiOS6: boolean; - - /** - * Whether OS i iOS 7. - */ - isiOS7: boolean; - - /** - * Whether OS is Windows. - */ - isWin: boolean; - - /** - * Whether device is Windows Phone. - */ - isWinPhone: boolean; - - /** - * Whether browser is IE10. - */ - isIE10: boolean; - - /** - * Whether browser is IE11. - */ - isIE11: boolean; - - /** - * Whether browser is Webkit based. - */ - isWebkit: boolean; - - /** - * Whether browser is running on mobile device. - */ - isMobile: boolean; - - /** - * Whether browser is running on desktop. - */ - isDesktop: boolean; - - /** - * Whether browser is Safari. - */ - isSafari: boolean; - - /** - * Whether browser is Chrome. - */ - isChrome: boolean; - - /** - * Is native Android browser (not mobile Chrome). - */ - isNativeAndroid: boolean; - - /** - * Serialize - */ - serialize(form: HTMLFormElement | ChocolateChipElementArray): string; - - /** - * Grabs values from a form and converts them into a JSON object. - * - * @param rootNode: string | HTMLElement A form whose values you want to convert to JSON. - * @param delimiter string A delimiter to namespace your form values. The default is "." - * You use the form input's name to set up the namespace structure for your JSON, e.g. name="newUser.name.first". - */ - form2JSON(rootNode: string | HTMLElement, delimiter: string): Object; - - /** - * Subscribe to a publication. You provide the topic you want to subscribe to, as well as a callback to execute when a publication occurs. - * Any data passed by the publisher is exposed to the callback as its second parameter. The callback's first parameter is the published topic. - * - * @param topic string A topic to subscribe to. This can be a single term, or any type of namespaced term with delimiters. - * @data any You can receive any type: string, number, array, object, etc. - * @return any - */ - subscribe(topic: string, callback: (topic: string, data: any) => any): boolean; - - /** - * Unsubscribe from a topic. Pass this the topic you wish to unsubscribe from. The subscription will be terminated immediately. - * - * @param topic string The name of the topic to unsubscribe from. - * @return void - */ - unsubscribe(topic: string): void; - - /** - * Publish a topic with data for the topic's subscribers to receive. - * - * @param topic string The topic you wish to publish. - * @param data The data to send with the publication. This can be of any type: string, number, array, object, etc. - * @return void - */ - publish(topic: string, data: any): string; - - /** - * Object used to store string templates and parsed templates. - * - * @param string A string defining the template. - * @param string A label used to access an object's properties in the template. If none is provided it defaults to "data": [[= data.name]]. - * @return void - */ - templates: Object; - - /** - * This method returns a parsed template. - * - */ - template: { - - /** - * This method parses a string and an optoinal variable name and returns a parsed template in the form of a function. You can then pass this function data to get rendered nodes. - * - * @param template A string of markup to use as a template. - * @param variable An option name to use in the template. If it were "myData": [[= myData.name]]. Otherwise it defaults to "data": [[= data.name]]. - * @return A function. - */ - (template: string, variable?: string): Function; - - /** - * The repeater method used to rendering iterable template data. - */ - repeater: { - - /** - * Use this method to render declarative temlate repeaters. This expects a "data-repeater" attribute whose value points to data stored on $.template.data. - */ - (): void; - - /** - * A method to repeated output a template. - * - * @param element The target container into which the content will be inserted. - * @param template A string of markup. - * @param data The iterable data the template will consume. - * @return void. - */ - (element: ChocolateChipElementArray, template: string, data: any): void; - } - - /** - * An object that holds the reference to the controller for a repeater. - * This is used to cache the data that a repeater uses. After the repeater is rendered, the reference is deleted from this object. - * Example: $.template.data["myRepeater"] = [{name: "Joe"}, {name: "Sue"}]; - * - */ - data: any; - - /** - * Use this value to output an index value in a template repeater. - */ - index: number; - }; - - /** - * ATENTION: DO NOT TOUCH! This is the ChocolateChipJS cache. This is used to store details about registered events and data. You should not touch any of these values, even though they are exposed, as this can seriously impair the behavior of your app. - * - * data: this is used by $(element).data() to store data. - * events: this is used by the event system. - */ - chch_cache: { - /** - * DO NOT TOUCH! This hold data stored by $(element).data(). - */ - data: {}; - - /** - * DO NOT TOUCH! This stores information about registered events. - */ - events: { - keys: any[]; - values: any[]; - set: Function; - hasKey: Function; - _delete: Function; - } - } - -} - - -/** - * Interface for ChocolateChipJS Element Collections. - */ - -interface ChocolateChipElementArray extends Array { - - /** - * Iterate over an Array object, executing a function for each matched element. - * - * @param Function - * @return void - */ - each(func: (ctx: any, idx: number) => void): void; - - /** - * Sorts an array and removes duplicates before returning it. - * - * @return Array - */ - unique(): ChocolateChipElementArray; - - /** - * This method returns the element at the position in the array indicated by the argument. This is a zero-based number. - * When dealing with document nodes, this allows you to cherry pick a node from its collection based on its - * position amongst its siblings. - * - * @param number Index value indicating the node you wish to access from a collection. This is zero-based. - * @return HTMLElement - */ - eq(index: number): ChocolateChipElementArray; - - /** - * Search for a given element from among the matched elements on a collection. - * This method returns the index value as an integer. - * - * @return number - */ - index(): number; - - /** - * Search for a given element from among the matched elements on a collection. - * This method returns the index value as an integer. - * - * @param selector A selector representing an element to look for in a collection of elements. - * @return number - */ - index(selector: string | HTMLElement[]): number; - - /** - * Check the current matched set of elements against a selector or element and return it - * if it matches the given arguments. - * - * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] - */ - is(selector: string): ChocolateChipElementArray; - - /** - * Check the current matched set of elements against a selector or element and return it - * if it matches the given arguments. - * - * @param elements One or more elements to match the current set of elements against. - * @ return HTMLElement[] - */ - is(element: any): ChocolateChipElementArray; - - /** - * Check the current matched set of elements against a selector or element and return it - * if it does not match the given arguments. - * - * @param selector A string containing a selector expression to match elements against. - * @ return HTMLElement[] - */ - isnt(selector: string): ChocolateChipElementArray; - - /** - * Check the current matched set of elements against a selector or element and return it - * if it does not match the given arguments. - * - * @param elements One or more elements to match the current set of elements against. - * @ return HTMLElement[] - */ - isnt(element: any): ChocolateChipElementArray; - - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param selector A string containing a selector expression to match elements against. - * @ return HTMLElement[] - */ - has(selector: string): ChocolateChipElementArray; - - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param contained A DOM element to match elements against. - * @ return HTMLElement[] - */ - has(contained: HTMLElement): ChocolateChipElementArray; - - /** - * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. - * - * @param selector A string containing a selector expression to match elements against. - * @ return HTMLElement[] - */ - hasnt(selector: string): ChocolateChipElementArray; - - /** - * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. - * - * @param contained A DOM element to match elements against. - * @ return HTMLElement[] - */ - hasnt(contained: HTMLElement): ChocolateChipElementArray; - - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector or element. - * - * @param selector A string containing a selector expression to match elements against. - * @ return HTMLElement[] - */ - find(selector: string): ChocolateChipElementArray; - - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector or element. - * - * @param element An element to match elements against. - * @ return HTMLElement[] - */ - find(element: HTMLElement): ChocolateChipElementArray; - - /** - * Get the immediately preceding sibling of each element in the set of matched elements. - * - * @ return HTMLElement[] - */ - prev(): ChocolateChipElementArray; - - /** - * Get the immediately following sibling of each element in the set of matched elements. - * - * @ return HTMLElement[] - */ - next(): ChocolateChipElementArray; - - /** - * Reduce the set of matched elements to the first in the set. - */ - first(): ChocolateChipElementArray; - - /** - * Reduce the set of matched elements to the last in the set. - * - * @return HTMLElement[] - */ - last(): ChocolateChipElementArray; - - /** - * Get the children of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] - */ - children(selector?: string): ChocolateChipElementArray; - - /** - * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. - * If multiple elements have the same parent, only one instance of the parent is returned. - * - * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] - */ - parent(selector?: string): ChocolateChipElementArray; - - /** - * For each element in the set, get the first element that matches the selector by testing the element - * itself and traversing up through its ancestors in the DOM tree, or, if a number is provided, - * retrieving that ancestor based on its distance from the element. - * - * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] - */ - ancestor(selector: string | number): ChocolateChipElementArray; - - /** - * For each element in the set, get the first element that matches the selector by testing the element - * itself and traversing up through its ancestors in the DOM tree. - * - * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] - */ - closest(selector: string | number): ChocolateChipElementArray; - - /** - * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] - */ - siblings(selector?: string): ChocolateChipElementArray; - - /** - * Get the HTML contents of the first element in the set of matched elements. - * - * @return HTMLElement[] - */ - html(): ChocolateChipElementArray; - - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param htmlString A string of HTML to set as the content of each matched element. - * @return HTMLElement[] - */ - html(htmlString: string): ChocolateChipElementArray; - - /** - * Get the value of style properties for the first element in the set of matched elements. - * - * @param propertyName A CSS property. - * @return string - */ - css(propertyName: string): string; - - /** - * Set one or more CSS properties for the set of matched elements using a quoted string. - * - * @param propertyName A CSS property name. - * @param value A value to set for the property. - * @return HTMLElement[] - */ - css(propertyName: string, value: string): ChocolateChipElementArray; - - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param properties An object of property-value pairs to set. - * @return HTMLElement[] - */ - css(properties: Object): ChocolateChipElementArray; - - /** - * Get the value of an attribute for the first element in the set of matched elements. - * - * @param attributeName The name of the attribute to get. - * @return string - */ - attr(attributeName: string): string; - - /** - * Set an attribute for the set of matched elements. - * - * @param attributeName A string indicating the attribute to set. - * @param value A string indicating the value to set the attribute to. - * @return HTMLElement[] - */ - attr(attributeName: string, value: string): ChocolateChipElementArray; - - /** - * Remove an attribute from a node. - * - * @param attributeName A string indicating the attribute to remove. - * @return HTMLElement[] - */ - removeAttr(attributeName: string): ChocolateChipElementArray; - - /** - * Return any of the matched elements that have the given attribute. - * - * @param className The class name to search for. - * @return HTMLElement[] - */ - hasAttr(attributeName: string): ChocolateChipElementArray; - - /** - * Test whether an attribute exists on the first element in the set of matched elements. The value returned is a boolean. - * - * @param attributeName The name of the attribute to get. - * @return boolean - */ - prop(propertyName: string): boolean; - - /** - * Set an property for the set of matched elements. - * - * @param propertyName A string indicating the property to set. - * @param value A string indicating the value to set the property to. - * @return HTMLElement[] - */ - prop(propertyName: string, value: any | boolean): ChocolateChipElementArray; - - /** - * Remove an element property. - * - * @param property The property to remove. - * @return HTMLElement[] - */ - removeProp(property: string): ChocolateChipElementArray; - - /** - * Adds the specified class(es) to each of the set of matched elements. - * - * @param className One or more space-separated classes to be added to the class attribute of each matched element. - * @return HTMLElement[] - */ - addClass(className: string): ChocolateChipElementArray; - - /** - * Remove a single class or multiple classes from each element in the set of matched elements. - * - * @param className One or more space-separated classes to be removed from the class attribute of each matched element. - * @return HTMLElement[] - */ - removeClass(className?: string): ChocolateChipElementArray; - - /** - * Add or remove a classe from each element in the set of matched elements, depending on whether the class is present or not. - * - * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. - * @return HTMLElement[] - */ - toggleClass(className: string, swtch?: boolean): ChocolateChipElementArray; - - /** - * Return any of the matched elements that have the given class. - * - * @param className The class name to search for. - * @return HTMLElement[] - */ - hasClass(className: string): ChocolateChipElementArray; - - /** - * Store arbitrary data associated with the matched elements. - * - * @param key A string naming the piece of data to set. - * @param value The new data value; it can be any Javascript type including Array or Object. - * @return HTMLElement[] - */ - data(key: string, value: any): ChocolateChipElementArray; - - /** - * Return the value at the named data store for the first element in the element collection, as set by - * data(name). - * - * @param key Name of the data stored. - * @return any - */ - data(key: string): any; - - /** - * Remove the value at the named data store for the first element in the element collection, as set by data(name, value). - * - * @param key Name of the data stored. - * @return any - */ - removeData(key?: string): any; - - /** - * Store string data associated with the matched elements. - * - * @param key A string naming the piece of data to set. - * @param value The new data value; it must be a string. You can convert JSON into a string to use with this. - * @return HTMLElement[] - */ - dataset(key: string, value: any): ChocolateChipElementArray; - - /** - * Retrieve a dataset key's value for the first element in the element collection. - * - * @param key A string naming the piece of data to set. - * @return HTMLElement[] - */ - dataset(key: string): ChocolateChipElementArray; - - /** - * Return the value at the named data store for the first element in the element collection, as set by data(name, value). - * - * @param key Name of the data stored. - * @return any - */ - data(key: string): any; - - /** - * Store arbitrary data associated with the matched element. - * - * @param key A string naming the piece of data to set. - * @param value The new data value; it can be any Javascript type including Array or Object. - * @return HTMLElement[] - */ - data(key: string, value?: any): ChocolateChipElementArray; - - /** - * Get the current value of the first element in the set of matched elements. - */ - val(): any; - - /** - * Set the value of each element in the set of matched elements. - * - * @param value A string of text or an array of strings corresponding to the value of each matched element - * to set as selected/checked. - * @return any - */ - val(value: string): ChocolateChipElementArray; - - /** - * Set the property of an element to enabled by removing the "disabled" attribute. - * - * @return HTMLElement[] - */ - enable(): ChocolateChipElementArray; - - /** - * Set the property of an element to "disabled". - * - * @return HTMLElement[] - */ - disable(): ChocolateChipElementArray; - - /** - * Display the matched elements. - * - * @param speed A string or number determining how long the animation will run. - * @param callback A function to call once the animation is complete. - * @return HTMLElement[] - */ - show(duration?: number | string, callback?: Function): ChocolateChipElementArray; - - /** - * Hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param callback A function to call once the animation is complete. - * @return HTMLElement[] - */ - hide(duration?: number | string, callback?: Function): ChocolateChipElementArray; - - /** - * Insert content, specified by the parameter, before each element in the set of matched elements. - * - * @param content HTML string, DOM element, array of elements to insert before each element in the set of matched elements. - * @return HTMLElement[] - */ - before(content: ChocolateChipElementArray | HTMLElement | string): ChocolateChipElementArray; - - /** - * Insert content, specified by the parameter, after each element in the set of matched elements. - * - * @param content HTML string, DOM element, array of elements to insert after each element in the set of matched elements. - * @return HTMLElement[] - */ - after(content: ChocolateChipElementArray | HTMLElement | string): ChocolateChipElementArray; - - /** - * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * - * @param content DOM element, array of elements, or HTML string to insert at the end of each element in the set - * of matched elements. - * @return HTMLElement[] - */ - append(content: ChocolateChipElementArray | HTMLElement | Text | string): ChocolateChipElementArray; - - /** - * Insert content, specified by the parameter, at the beginning of each element in the set of matched elements. - * - * @param content DOM element, array of elements, or HTML string to insert at the beginning of each element in the set of matched elements. - * @return HTMLElement[] - */ - prepend(content: ChocolateChipElementArray | HTMLElement | Text | string): ChocolateChipElementArray; - - /** - * Insert every element in the set of matched elements to the beginning of the target. - * - * @param target A selector, element, or HTML string. The matched set of elements will be inserted at the beginning of the element specified by this parameter. - * @return HTMLElement[] - */ - prependTo(target: any[] | HTMLElement | string): ChocolateChipElementArray; - - /** - * Insert every element in the set of matched elements to the end of the target. - * - * @param target A selector, element, or HTML string. The matched set of elements will be inserted at the end of the element specified by this parameter. - * If no position value is provided it will simply append the content to the target. - * @return HTMLElement[] - */ - appendTo(target: any[] | HTMLElement | string): ChocolateChipElementArray; - - /** - * Insert element(s) into the target element. - * - * @return HTMLElement[] - */ - insert(content: string, position?: number | string): ChocolateChipElementArray; - - /** - * Create a copy of the set of matched elements. - * - * @param value A Boolean indicating whether to copy the element(s) with their children. A true value copies the children. - * @return HTMLElement[] - */ - clone(value?: boolean): ChocolateChipElementArray; - - /** - * Wrap an HTML structure around each element in the set of matched elements. - * - * @param wrappingElement A selector or HTML string specifying the structure to wrap around the matched elements. - * @return HTMLElement[] - */ - wrap(wrappingElement: string): ChocolateChipElementArray; - - /** - * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. - * - * @return HTMLElement[] - */ - unwrap(): ChocolateChipElementArray; - - /** - * Remove the set of matched elements from the DOM. If there are any attached events, this will remove them to prevent memory leaks. - * - * @param selector A selector expression that filters the set of matched elements to be removed. - * @return HTMLElement[] - */ - remove(selector?: string): ChocolateChipElementArray; - - /** - * Remove all child nodes of the set of matched elements from the DOM. - * - * @return HTMLElement[] - */ - empty(): ChocolateChipElementArray; - - /** - * Get an object of the current coordinates of the first element in the set of matched elements, relative to the document. - * These are: top, left, bottom and right. The values are numbers representing pixel values. - * @return Object - */ - offset(): { - top: number; - bottom: number; - left: number; - right: number; - }; - - /** - * Get the current computed width for the first element in the set of matched elements, - * including padding but excluding borders. - * - * @return number - */ - width(): number; - - /** - * Get the current computed height for the first element in the set of matched elements, - * including padding but excluding borders. - * - * @return number - */ - height(): number; - - /** - * Get the combined text contents of each element in the set of matched elements, including their descendants. - * - * @return string - */ - text(): string; - - /** - * Set the content of each element in the set of matched elements to the specified text. - * - * @param text The text to set as the content of each matched element. When Number is supplied, it will be converted to a String representation. To delete text, use ChocolateChipElementArray.empty() or ChocolateChipElementArray.remove(). - * @return HTMLElement - */ - text(text: string | number): HTMLElement; - - /** - * A method to animate DOM nodes using CSS. This uses CSS transitions. - * - * @param options And object of key value pairs define the CSS properties and values to animate. - * @param duration A string representing the time. Should have a time identifier: "200s", "200ms", etc. - * @param easing A string indicating the easing for the animation, such as "ease-out", "ease-in", "ease-in-out". - * @return void - */ - animate(options: Object, duration?: string, easing?: string): void; - - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute each time the event is triggered. - * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic - */ - bind(eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; - - /** - * Remove a handler for an event from the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute each time the event is triggered. - * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic - */ - unbind(eventType?: string, handler?: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; - - /** - * Add a delegated event to listen for the provided event on the descendant elements. - * - * @param selector A string defining the descendant elements to listen on for the designated event. - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute each time the event is triggered. The keyword "this" will refer - * to the element receiving the event. - * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic - */ - delegate(selector: any, eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; - - /** - * Add a delegated event to listen for the provided event on the descendant elements. - * - * @param selector A string defining the descendant elements are listening for the event. - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param handler A function handler assigned to this event. - * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic - */ - undelegate(selector?: any, eventType?: string, handler?: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; - - /** - * Add a handler to an event for elements. If a selector is provided as the second argument, this implements a delegated event. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param selector A string defining the descendant elements are listening for the event. - * @param handler A function handler assigned to this event. - * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic - */ - on(eventType: string, selector: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; - - /** - * Remove a handler for an event from the elements. If the second argument is a selector, it tries to undelegate the event. - * If no arugments are provided, it removes all events from the element(s). - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param selector A string defining the descendant elements are listening for the event. - * @param handler A function handler assigned to this event. - * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic - */ - off(eventType?: string, selector?: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; - - /** - * Trigger an event on an element. - * - * @param eventType The event to trigger. - * @return void - */ - trigger(eventType: string): void; -} - -/** - * Represents the completion of an asynchronous operation - */ -interface Promise { - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @return Promise A Promise for the completion of which ever callback is executed. - * @return Promise A new Promise - */ - then(onfulfilled?: (value: T) => TResult | Promise, onrejected?: (reason: any) => TResult | Promise): Promise; - - /** - * Attaches a callback for only the rejection of the Promise. - * - * @param onrejected The callback to execute when the Promise is rejected. - * @return Promise A Promise for the completion of the callback. - * @return Promise A new Promise - */ - catch(onrejected?: (reason: any) => T | Promise): Promise; -} - -interface PromiseConstructor { - /** - * A reference to the prototype. - */ - prototype: Promise; - - /** - * Creates a new Promise. - * - * @param init A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error. - * @return Promise A new Proimise - */ - new (init: (resolve: (value?: T | Promise) => void, reject: (reason?: any) => void) => void): Promise; - - (init: (resolve: (value?: T | Promise) => void, reject: (reason?: any) => void) => void): Promise; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected. - * - * @param values An array of Promises. - * @return Promise A new Promise. - */ - all(values: (T | Promise)[]): Promise; - - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected. - * - * @param values An array of values. - * @returns A new Promise. - */ - all(values: Promise[]): Promise; - - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved or rejected. - * - * @param values An array of Promises. - * @return Promise A new Promise. - */ - race(values: (T | Promise)[]): Promise; - - /** - * Creates a new rejected promise for the provided reason. - * - * @param reason The reason the promise was rejected. - * @return Promise A new rejected Promise. - */ - reject(reason: any): Promise; - - /** - * Creates a new rejected promise for the provided reason. - * - * @param reason The reason the promise was rejected. - * @return void A Promise is rejected. - */ - reject(reason: any): Promise; - - /** - * Creates a new resolved promise for the provided value. - * - * @param value A promise. - * @return Promise A promise whose internal state matches the provided promise. - */ - resolve(value: T | Promise): Promise; - - /** - * Creates a new resolved promise. - * - * @return Promise A resolved promise. - */ - resolve(): Promise; -} - -declare var Promise: PromiseConstructor; -declare type ByteString = string; -declare type USVString = string; -declare type DOMString = string; -declare type OpenEndedDictionary = Object; - -/** - * Interface for fetch API. - * - * @param input A string representing a valid url. - * @param init An object literal of key value pairs to set method, headers, body, credentials or cache. - * @return Promise. - */ -interface fetch { - (input: string, - init?: { - method?: string; - headers?: {}; - body?: any; - mode?: { - cors: string; - "no-cors": string; - "same-origin": string; - }; - credentials?: { - omit: string; - "same-origin": string; - include: string; - }; - cache?: { - default: string; - "no-store": string; - reload: string; - "no-cache": string; - "force-cache": string; - "only-if-cached": string; - }; - timeout?: number; - }): Promise; -} - -interface XMLHttpRequest { - responseURL: string; -} - -/** - * Headers Interface. This defines the methods exposed by the Headers object. - */ -interface Headers { - (headers?: any): void; - append(name: string, value: string): void; - delete(name: string): any; - get(name: string): any; - getAll(name: string): any; - has(name: string): any; - set(name: string, value: string): any; - forEach(callback: Function, thisArg: any): any; -} - -interface decode { - (body: any): FormData; -} - -/** - * Request Interface. This defines the properties and methods exposed by the Request object. - */ -interface Request { - (input: { - url: string; - request: Request; - }, init: Object): Request; - clone(): Request; - arrayBuffer(): ArrayBuffer; - blob(): Blob; - formData(): FormData; - json(): JSON; - text(): string; - - method: string; - url: string; - heaers: Headers; - context: any; - referrer: any; - mode: string; - credentials: any; - cache: string; - bodyUsed: boolean; -} - -interface URLSearchParams { - ():URLSearchParams; -} - -/** - * Resonse Interface. This defines the properties and methods exposed by the Response object. - */ -interface Response { - (body?: { - blob: Blob; - bormData: FormData; - urlParams: URLSearchParams; - url: string; - }, - init?: { - status?: string | number; - statusText?: string; - headers: Headers; - }): Response; - clone(): Response; - redirect(): Response; - arrayBuffer(): ArrayBuffer; - blob(): Blob; - formData(): FormData; - json(): JSON; - text(): string; - - type: string; - url: string; - useFinalURL: boolean; - ok: boolean; - statusText: string; - headers: Headers; - bodyUsed: boolean; -} - -interface ChocolateChipStatic { - - /** - * A cache to hold callbacks execute by the response from a JSONP request. This is an array of strings. By default these values get purged when the callback execute and exposes the data returned by the request. - */ - JSONPCallbacks: string[]; - /** - * Method to perform JSONP request. - * - * @param url A string defining the url to target. - * @param options And object literal of properties: {timeout? number, callbackName?: string, clear?: boolean} - */ - jsonp(url: string, options?: { - /** - * A number representing milliseconds to express when to refect a JSONP request. - */ - timeout?: number; - - /** - * The optional name for the callback when the server response will execute. The default value is "callback". However some sites may use a different name for their JSONP function. Consult the documentation on the site to ascertain the correct value for this callback. - */ - callbackName?: string; - - /** - * This value determines whether the callbacks and script associate with JSONP persist or are purged after the request returns. By default this is set to true, meaning that they will be purged. - */ - clear?: boolean; - }): any -} - -interface Window { - chocolatechipjs: ChocolateChipStatic; - $: ChocolateChipStatic; - jsonp: any; -} -declare var $: ChocolateChipStatic; -declare var fetch: fetch; - -declare var chocolatechipjs: ChocolateChipStatic; \ No newline at end of file diff --git a/chocolatechipjs/chocolatechipjs.d.ts.tscparams b/chocolatechipjs/chocolatechipjs.d.ts.tscparams deleted file mode 100644 index 1f3d85fb3b..0000000000 --- a/chocolatechipjs/chocolatechipjs.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ ---target es5 --noImplicitAny diff --git a/chocolatechipjs/index.d.ts b/chocolatechipjs/index.d.ts new file mode 100644 index 0000000000..9ac2ae8c52 --- /dev/null +++ b/chocolatechipjs/index.d.ts @@ -0,0 +1,1484 @@ +// Type definitions for chocolatechip v4.0.4 +// Project: https://github.com/chocolatechipui/ChocolateChipJS +// Definitions by: Robert Biggs +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +interface ChocolateChipStatic { + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param selector A string containing a selector expression + * @param context A DOM HTMLElement to use as context + * @return HTMLElement[] + */ + (selector: string | HTMLElement | Document, context?: HTMLElement | ChocolateChipElementArray): ChocolateChipElementArray; + + /** + * Binds a function to be executed when the DOM has finished loading. + * + * @param callback A function to execute after the DOM is ready. + * @return void + */ + (callback: () => any): void; + + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param element A DOM element to wrap in an array. + * @return HTMLElement[] + */ + (element: HTMLElement): ChocolateChipElementArray; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param elementArray An array of DOM elements to convert into a ChocolateChip Collection. + * @return HTMLElement[] + */ + (elementArray: ChocolateChipElementArray): ChocolateChipElementArray; + + /** + * Accepts the document element and returns it wrapped in an array. + * + * @param document The document object. + * @return document[] + */ + (document: Document): Document[]; + + /** + * If no argument is provided, return the document as a ChocolateChipElementArray. + * @return Document[] + */ + (): Document[]; + + /** + * Extend the ChocolateChipJS object itself with the provided object. + * + * @param object The object to add to ChocolateChipJS. + * @return The ChocolateChipJS object. + */ + extend(object: Object): Object; + + /** + * Extend a target object with another object. + * + * @param target An object to extend. + * @param object The object to add to the target. + * @return The extended object. + */ + extend(target: Object, object: Object): Object; + + /** + * The base for extending ChocolateChipJS collections, which are arrays of elements. + */ + fn: { + /** + * This method adds the provided object to the Array prototype to make it available to all arrays of HTML elements. + * + * @param object And object to add to element arrays. + * @return The extended array of elements. + */ + extend(object: Object): HTMLElement[]; + }; + + /** + * Contains the version of ChocolateChipJS in use. + */ + version: string; + + /** + * Contains the name of the library (ChocolateChip). + */ + libraryName: string; + + /** + * An empty function. + * + * @return void. + */ + noop(): void; + + /** + * Uuid number. + */ + uuid: number; + + /** + * Create a random number to use as a uuid. + * + * @return number. + */ + uuidNum(): number; + + /** + * Creates a uuid using uuidNum(). + * + * @return A string. + */ + makeUuid(): string; + + + /** + * Create a ChocolateChip collection object by creating elements from an HTML string. + * + * @param selector + * @return any + */ + make(selector: string): ChocolateChipElementArray; + + /** + * Create a ChocolateChip collection object by creating elements from an HTML string. This is an alias for $.make. + * + * @param selector + * @return any + */ + html(selector: string): ChocolateChipElementArray; + + /** + * Replace one element with another. + * + * @param new HTMLElement + * @param old HTMLElement + * @return HTMLElement[] + */ + replace(newElement: ChocolateChipElementArray, oldElement: ChocolateChipElementArray): void; + + /** + * Load a JavaScript file from a url, then execute it. + * + * @param url A string containing the URL where the script resides. + * @param callback A callback function that is executed after the script loads. + * @return void + */ + require(url: string, callback: Function): Function; + + /** + * Process JavaScript returned by Ajax request. An optional name can be used to create a custom variable name by which the data is exposed, otherwise it is exposed with the variable "data". + * + * @param url A string containing the URL where the script resides. + * @param callback A callback function that is executed after the script loads. + * @return Function + */ + processJSON(json: string, name?: string): any; + + /** + * This method takes a referenced form and serializes its element names and values, which it returns as a string. This is required if you want to send form data. + * + * @param element A string, HTML element or ChocolateChipElementArray containing a reference to a from. + * @return An encode string form element names and values. + */ + serialize(element: any): string; + + /** + * Parse the data in a Promise response as JSON. + * + * @param response The response from a Promise. + * @result + */ + json(reponse: Response): JSON; + + /** + * This method will defer the execution of a function until the call stack is clear. + * + * @param callback A function to execute. + * @param duration The number of milliseconds to delay execution. + * @return any + */ + delay(callback: Function, duration?: number): any; + + /** + * The method will defer the execution of its callback until the call stack is clear. + * + * @param callback A callback to execute after a delay. + * @return Function. + */ + defer(callback: Function): Function; + + /** + * This method makes sure a method always returns an array. If no values are available to return, it returns and empty array. This is to make sure that methods that expect a chainable array will not throw and exception. + * + * @param result The result of a method to test if it can be returned in an array. + * @return An array holding the results of a method, otherwise an empty array. + */ + returnResult(result: HTMLElement[]): any[]; + + /** + * This method allows you to execute a callback on each item in an array of elements. + * + * @param array An array of elements. + * @param callback A callback to execute on each element. This has two parameters: the context, followed by the index of the current iteration. + */ + each(array: T[], callback: (ctx: T, idx: number) => any): any; + + /** + * This method will concatenate strings or values as a cleaner alternative to using the '+' operator. + * + * @param string or number A comma separated series of strings to concatenate. + * @return string + */ + concat(...string: string[]): string; + + /** + * This method takes a space-delimited string of words and returns it as an array where the individual words are indices. + * + * @param string Any string with values separated by spaces. + * @return string[] + */ + w(string: string): string[]; + + /** + * This method converts a string of hyphenated tokens into a camel cased string. + * + * @param string A string of hyphenated tokens. + * @return string + */ + camelize(string: string): string; + + /** + * This method converts a camel case string into lowercase with hyphens. + * + * @param string A camel case string. + * @return string + */ + deCamelize(string: string): string; + + /** + * This method capitalizes the first letter of a string. + * + * @param string A string. + * @param boolean A boolean value. + * @return string + */ + capitalize(string: string, boolean?: boolean): string; + + /** + * Determine whether the argument is a string. + * + * @param obj Object to test whether or not it is a string. + * @return boolean + */ + isString(obj: any): boolean; + + /** + * Determine whether the argument is an array. + * + * @param obj Object to test whether or not it is an array. + * @return boolean + */ + isArray(obj: any): boolean; + + /** + * Determine whether the argument is a function. + * + * @param obj Object to test whether or not it is an function. + * @return boolean + */ + isFunction(obj: any): boolean; + + /** + * Determine whether the argument is an object. + * + * @param obj Object to test whether or not it is an object. + * @return boolean + */ + isObject(obj: any): boolean; + + /** + * Determine whether the argument is an empty object. + * + * @param obj Object to test whether or not it is an empty object. + * @return boolean + */ + isEmptyObject(obj: any): boolean; + + /** + * Determine whether the argument is an empty object. + * + * @param obj Object to test whether or not it is an empty object. + * @return boolean + */ + isEmptyObject(obj: any): boolean; + + /** + * Determine whether the argument is a number. + * + * @param obj Object to test whether or not it is a number. + * @return boolean + */ + isNumber(obj: any): boolean; + + /** + * Determine whether the argument is an integer. + * + * @param obj Object to test whether or not it is an integer. + * @return boolean + */ + isInteger(obj: any): boolean; + + /** + * Determine whether the argument is a float. + * + * @param obj Object to test whether or not it is a float. + * @return boolean + */ + isFloat(obj: any): boolean; + + /** + * Whether device is iPhone. + */ + isiPhone: boolean; + + /** + * Whether device is iPad. + */ + isiPad: boolean; + + /** + * Whether device is iPod. + */ + isiPod: boolean; + + /** + * Whether OS is iOS. + */ + isiOS: boolean; + + /** + * Whether OS is Android + */ + isAndroid: boolean; + + /** + * Whether OS is WebOS. + */ + isWebOS: boolean; + + /** + * Whether OS is Blackberry. + */ + isBlackberry: boolean; + + /** + * Whether OS supports touch events. + */ + isTouchEnabled: boolean; + + /** + * Whether there is a network connection. + */ + isOnline: boolean; + + /** + * Whether app is running in stanalone mode. + */ + isStandalone: boolean; + + /** + * Whether OS is iOS 6. + */ + isiOS6: boolean; + + /** + * Whether OS i iOS 7. + */ + isiOS7: boolean; + + /** + * Whether OS is Windows. + */ + isWin: boolean; + + /** + * Whether device is Windows Phone. + */ + isWinPhone: boolean; + + /** + * Whether browser is IE10. + */ + isIE10: boolean; + + /** + * Whether browser is IE11. + */ + isIE11: boolean; + + /** + * Whether browser is Webkit based. + */ + isWebkit: boolean; + + /** + * Whether browser is running on mobile device. + */ + isMobile: boolean; + + /** + * Whether browser is running on desktop. + */ + isDesktop: boolean; + + /** + * Whether browser is Safari. + */ + isSafari: boolean; + + /** + * Whether browser is Chrome. + */ + isChrome: boolean; + + /** + * Is native Android browser (not mobile Chrome). + */ + isNativeAndroid: boolean; + + /** + * Serialize + */ + serialize(form: HTMLFormElement | ChocolateChipElementArray): string; + + /** + * Grabs values from a form and converts them into a JSON object. + * + * @param rootNode: string | HTMLElement A form whose values you want to convert to JSON. + * @param delimiter string A delimiter to namespace your form values. The default is "." + * You use the form input's name to set up the namespace structure for your JSON, e.g. name="newUser.name.first". + */ + form2JSON(rootNode: string | HTMLElement, delimiter: string): Object; + + /** + * Subscribe to a publication. You provide the topic you want to subscribe to, as well as a callback to execute when a publication occurs. + * Any data passed by the publisher is exposed to the callback as its second parameter. The callback's first parameter is the published topic. + * + * @param topic string A topic to subscribe to. This can be a single term, or any type of namespaced term with delimiters. + * @data any You can receive any type: string, number, array, object, etc. + * @return any + */ + subscribe(topic: string, callback: (topic: string, data: any) => any): boolean; + + /** + * Unsubscribe from a topic. Pass this the topic you wish to unsubscribe from. The subscription will be terminated immediately. + * + * @param topic string The name of the topic to unsubscribe from. + * @return void + */ + unsubscribe(topic: string): void; + + /** + * Publish a topic with data for the topic's subscribers to receive. + * + * @param topic string The topic you wish to publish. + * @param data The data to send with the publication. This can be of any type: string, number, array, object, etc. + * @return void + */ + publish(topic: string, data: any): string; + + /** + * Object used to store string templates and parsed templates. + * + * @param string A string defining the template. + * @param string A label used to access an object's properties in the template. If none is provided it defaults to "data": [[= data.name]]. + * @return void + */ + templates: Object; + + /** + * This method returns a parsed template. + * + */ + template: { + + /** + * This method parses a string and an optoinal variable name and returns a parsed template in the form of a function. You can then pass this function data to get rendered nodes. + * + * @param template A string of markup to use as a template. + * @param variable An option name to use in the template. If it were "myData": [[= myData.name]]. Otherwise it defaults to "data": [[= data.name]]. + * @return A function. + */ + (template: string, variable?: string): Function; + + /** + * The repeater method used to rendering iterable template data. + */ + repeater: { + + /** + * Use this method to render declarative temlate repeaters. This expects a "data-repeater" attribute whose value points to data stored on $.template.data. + */ + (): void; + + /** + * A method to repeated output a template. + * + * @param element The target container into which the content will be inserted. + * @param template A string of markup. + * @param data The iterable data the template will consume. + * @return void. + */ + (element: ChocolateChipElementArray, template: string, data: any): void; + } + + /** + * An object that holds the reference to the controller for a repeater. + * This is used to cache the data that a repeater uses. After the repeater is rendered, the reference is deleted from this object. + * Example: $.template.data["myRepeater"] = [{name: "Joe"}, {name: "Sue"}]; + * + */ + data: any; + + /** + * Use this value to output an index value in a template repeater. + */ + index: number; + }; + + /** + * ATENTION: DO NOT TOUCH! This is the ChocolateChipJS cache. This is used to store details about registered events and data. You should not touch any of these values, even though they are exposed, as this can seriously impair the behavior of your app. + * + * data: this is used by $(element).data() to store data. + * events: this is used by the event system. + */ + chch_cache: { + /** + * DO NOT TOUCH! This hold data stored by $(element).data(). + */ + data: {}; + + /** + * DO NOT TOUCH! This stores information about registered events. + */ + events: { + keys: any[]; + values: any[]; + set: Function; + hasKey: Function; + _delete: Function; + } + } + +} + + +/** + * Interface for ChocolateChipJS Element Collections. + */ + +interface ChocolateChipElementArray extends Array { + + /** + * Iterate over an Array object, executing a function for each matched element. + * + * @param Function + * @return void + */ + each(func: (ctx: any, idx: number) => void): void; + + /** + * Sorts an array and removes duplicates before returning it. + * + * @return Array + */ + unique(): ChocolateChipElementArray; + + /** + * This method returns the element at the position in the array indicated by the argument. This is a zero-based number. + * When dealing with document nodes, this allows you to cherry pick a node from its collection based on its + * position amongst its siblings. + * + * @param number Index value indicating the node you wish to access from a collection. This is zero-based. + * @return HTMLElement + */ + eq(index: number): ChocolateChipElementArray; + + /** + * Search for a given element from among the matched elements on a collection. + * This method returns the index value as an integer. + * + * @return number + */ + index(): number; + + /** + * Search for a given element from among the matched elements on a collection. + * This method returns the index value as an integer. + * + * @param selector A selector representing an element to look for in a collection of elements. + * @return number + */ + index(selector: string | HTMLElement[]): number; + + /** + * Check the current matched set of elements against a selector or element and return it + * if it matches the given arguments. + * + * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] + */ + is(selector: string): ChocolateChipElementArray; + + /** + * Check the current matched set of elements against a selector or element and return it + * if it matches the given arguments. + * + * @param elements One or more elements to match the current set of elements against. + * @ return HTMLElement[] + */ + is(element: any): ChocolateChipElementArray; + + /** + * Check the current matched set of elements against a selector or element and return it + * if it does not match the given arguments. + * + * @param selector A string containing a selector expression to match elements against. + * @ return HTMLElement[] + */ + isnt(selector: string): ChocolateChipElementArray; + + /** + * Check the current matched set of elements against a selector or element and return it + * if it does not match the given arguments. + * + * @param elements One or more elements to match the current set of elements against. + * @ return HTMLElement[] + */ + isnt(element: any): ChocolateChipElementArray; + + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param selector A string containing a selector expression to match elements against. + * @ return HTMLElement[] + */ + has(selector: string): ChocolateChipElementArray; + + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param contained A DOM element to match elements against. + * @ return HTMLElement[] + */ + has(contained: HTMLElement): ChocolateChipElementArray; + + /** + * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. + * + * @param selector A string containing a selector expression to match elements against. + * @ return HTMLElement[] + */ + hasnt(selector: string): ChocolateChipElementArray; + + /** + * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. + * + * @param contained A DOM element to match elements against. + * @ return HTMLElement[] + */ + hasnt(contained: HTMLElement): ChocolateChipElementArray; + + /** + * Same overload as is present in the base type + */ + find(predicate: (value: HTMLElement, index: number, obj: HTMLElement[]) => boolean, thisArg?: any): HTMLElement; + + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector or element. + * + * @param selector A string containing a selector expression to match elements against. + * @ return HTMLElement[] + */ + find(selector: string): ChocolateChipElementArray; + + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector or element. + * + * @param element An element to match elements against. + * @ return HTMLElement[] + */ + find(element: HTMLElement): ChocolateChipElementArray; + + /** + * Get the immediately preceding sibling of each element in the set of matched elements. + * + * @ return HTMLElement[] + */ + prev(): ChocolateChipElementArray; + + /** + * Get the immediately following sibling of each element in the set of matched elements. + * + * @ return HTMLElement[] + */ + next(): ChocolateChipElementArray; + + /** + * Reduce the set of matched elements to the first in the set. + */ + first(): ChocolateChipElementArray; + + /** + * Reduce the set of matched elements to the last in the set. + * + * @return HTMLElement[] + */ + last(): ChocolateChipElementArray; + + /** + * Get the children of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] + */ + children(selector?: string): ChocolateChipElementArray; + + /** + * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. + * If multiple elements have the same parent, only one instance of the parent is returned. + * + * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] + */ + parent(selector?: string): ChocolateChipElementArray; + + /** + * For each element in the set, get the first element that matches the selector by testing the element + * itself and traversing up through its ancestors in the DOM tree, or, if a number is provided, + * retrieving that ancestor based on its distance from the element. + * + * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] + */ + ancestor(selector: string | number): ChocolateChipElementArray; + + /** + * For each element in the set, get the first element that matches the selector by testing the element + * itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] + */ + closest(selector: string | number): ChocolateChipElementArray; + + /** + * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] + */ + siblings(selector?: string): ChocolateChipElementArray; + + /** + * Get the HTML contents of the first element in the set of matched elements. + * + * @return HTMLElement[] + */ + html(): ChocolateChipElementArray; + + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param htmlString A string of HTML to set as the content of each matched element. + * @return HTMLElement[] + */ + html(htmlString: string): ChocolateChipElementArray; + + /** + * Get the value of style properties for the first element in the set of matched elements. + * + * @param propertyName A CSS property. + * @return string + */ + css(propertyName: string): string; + + /** + * Set one or more CSS properties for the set of matched elements using a quoted string. + * + * @param propertyName A CSS property name. + * @param value A value to set for the property. + * @return HTMLElement[] + */ + css(propertyName: string, value: string): ChocolateChipElementArray; + + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + * @return HTMLElement[] + */ + css(properties: Object): ChocolateChipElementArray; + + /** + * Get the value of an attribute for the first element in the set of matched elements. + * + * @param attributeName The name of the attribute to get. + * @return string + */ + attr(attributeName: string): string; + + /** + * Set an attribute for the set of matched elements. + * + * @param attributeName A string indicating the attribute to set. + * @param value A string indicating the value to set the attribute to. + * @return HTMLElement[] + */ + attr(attributeName: string, value: string): ChocolateChipElementArray; + + /** + * Remove an attribute from a node. + * + * @param attributeName A string indicating the attribute to remove. + * @return HTMLElement[] + */ + removeAttr(attributeName: string): ChocolateChipElementArray; + + /** + * Return any of the matched elements that have the given attribute. + * + * @param className The class name to search for. + * @return HTMLElement[] + */ + hasAttr(attributeName: string): ChocolateChipElementArray; + + /** + * Test whether an attribute exists on the first element in the set of matched elements. The value returned is a boolean. + * + * @param attributeName The name of the attribute to get. + * @return boolean + */ + prop(propertyName: string): boolean; + + /** + * Set an property for the set of matched elements. + * + * @param propertyName A string indicating the property to set. + * @param value A string indicating the value to set the property to. + * @return HTMLElement[] + */ + prop(propertyName: string, value: any | boolean): ChocolateChipElementArray; + + /** + * Remove an element property. + * + * @param property The property to remove. + * @return HTMLElement[] + */ + removeProp(property: string): ChocolateChipElementArray; + + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param className One or more space-separated classes to be added to the class attribute of each matched element. + * @return HTMLElement[] + */ + addClass(className: string): ChocolateChipElementArray; + + /** + * Remove a single class or multiple classes from each element in the set of matched elements. + * + * @param className One or more space-separated classes to be removed from the class attribute of each matched element. + * @return HTMLElement[] + */ + removeClass(className?: string): ChocolateChipElementArray; + + /** + * Add or remove a classe from each element in the set of matched elements, depending on whether the class is present or not. + * + * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. + * @return HTMLElement[] + */ + toggleClass(className: string, swtch?: boolean): ChocolateChipElementArray; + + /** + * Return any of the matched elements that have the given class. + * + * @param className The class name to search for. + * @return HTMLElement[] + */ + hasClass(className: string): ChocolateChipElementArray; + + /** + * Store arbitrary data associated with the matched elements. + * + * @param key A string naming the piece of data to set. + * @param value The new data value; it can be any Javascript type including Array or Object. + * @return HTMLElement[] + */ + data(key: string, value: any): ChocolateChipElementArray; + + /** + * Return the value at the named data store for the first element in the element collection, as set by + * data(name). + * + * @param key Name of the data stored. + * @return any + */ + data(key: string): any; + + /** + * Remove the value at the named data store for the first element in the element collection, as set by data(name, value). + * + * @param key Name of the data stored. + * @return any + */ + removeData(key?: string): any; + + /** + * Store string data associated with the matched elements. + * + * @param key A string naming the piece of data to set. + * @param value The new data value; it must be a string. You can convert JSON into a string to use with this. + * @return HTMLElement[] + */ + dataset(key: string, value: any): ChocolateChipElementArray; + + /** + * Retrieve a dataset key's value for the first element in the element collection. + * + * @param key A string naming the piece of data to set. + * @return HTMLElement[] + */ + dataset(key: string): ChocolateChipElementArray; + + /** + * Return the value at the named data store for the first element in the element collection, as set by data(name, value). + * + * @param key Name of the data stored. + * @return any + */ + data(key: string): any; + + /** + * Store arbitrary data associated with the matched element. + * + * @param key A string naming the piece of data to set. + * @param value The new data value; it can be any Javascript type including Array or Object. + * @return HTMLElement[] + */ + data(key: string, value?: any): ChocolateChipElementArray; + + /** + * Get the current value of the first element in the set of matched elements. + */ + val(): any; + + /** + * Set the value of each element in the set of matched elements. + * + * @param value A string of text or an array of strings corresponding to the value of each matched element + * to set as selected/checked. + * @return any + */ + val(value: string): ChocolateChipElementArray; + + /** + * Set the property of an element to enabled by removing the "disabled" attribute. + * + * @return HTMLElement[] + */ + enable(): ChocolateChipElementArray; + + /** + * Set the property of an element to "disabled". + * + * @return HTMLElement[] + */ + disable(): ChocolateChipElementArray; + + /** + * Display the matched elements. + * + * @param speed A string or number determining how long the animation will run. + * @param callback A function to call once the animation is complete. + * @return HTMLElement[] + */ + show(duration?: number | string, callback?: Function): ChocolateChipElementArray; + + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param callback A function to call once the animation is complete. + * @return HTMLElement[] + */ + hide(duration?: number | string, callback?: Function): ChocolateChipElementArray; + + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * @param content HTML string, DOM element, array of elements to insert before each element in the set of matched elements. + * @return HTMLElement[] + */ + before(content: ChocolateChipElementArray | HTMLElement | string): ChocolateChipElementArray; + + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * @param content HTML string, DOM element, array of elements to insert after each element in the set of matched elements. + * @return HTMLElement[] + */ + after(content: ChocolateChipElementArray | HTMLElement | string): ChocolateChipElementArray; + + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * @param content DOM element, array of elements, or HTML string to insert at the end of each element in the set + * of matched elements. + * @return HTMLElement[] + */ + append(content: ChocolateChipElementArray | HTMLElement | Text | string): ChocolateChipElementArray; + + /** + * Insert content, specified by the parameter, at the beginning of each element in the set of matched elements. + * + * @param content DOM element, array of elements, or HTML string to insert at the beginning of each element in the set of matched elements. + * @return HTMLElement[] + */ + prepend(content: ChocolateChipElementArray | HTMLElement | Text | string): ChocolateChipElementArray; + + /** + * Insert every element in the set of matched elements to the beginning of the target. + * + * @param target A selector, element, or HTML string. The matched set of elements will be inserted at the beginning of the element specified by this parameter. + * @return HTMLElement[] + */ + prependTo(target: any[] | HTMLElement | string): ChocolateChipElementArray; + + /** + * Insert every element in the set of matched elements to the end of the target. + * + * @param target A selector, element, or HTML string. The matched set of elements will be inserted at the end of the element specified by this parameter. + * If no position value is provided it will simply append the content to the target. + * @return HTMLElement[] + */ + appendTo(target: any[] | HTMLElement | string): ChocolateChipElementArray; + + /** + * Insert element(s) into the target element. + * + * @return HTMLElement[] + */ + insert(content: string, position?: number | string): ChocolateChipElementArray; + + /** + * Create a copy of the set of matched elements. + * + * @param value A Boolean indicating whether to copy the element(s) with their children. A true value copies the children. + * @return HTMLElement[] + */ + clone(value?: boolean): ChocolateChipElementArray; + + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param wrappingElement A selector or HTML string specifying the structure to wrap around the matched elements. + * @return HTMLElement[] + */ + wrap(wrappingElement: string): ChocolateChipElementArray; + + /** + * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. + * + * @return HTMLElement[] + */ + unwrap(): ChocolateChipElementArray; + + /** + * Remove the set of matched elements from the DOM. If there are any attached events, this will remove them to prevent memory leaks. + * + * @param selector A selector expression that filters the set of matched elements to be removed. + * @return HTMLElement[] + */ + remove(selector?: string): ChocolateChipElementArray; + + /** + * Remove all child nodes of the set of matched elements from the DOM. + * + * @return HTMLElement[] + */ + empty(): ChocolateChipElementArray; + + /** + * Get an object of the current coordinates of the first element in the set of matched elements, relative to the document. + * These are: top, left, bottom and right. The values are numbers representing pixel values. + * @return Object + */ + offset(): { + top: number; + bottom: number; + left: number; + right: number; + }; + + /** + * Get the current computed width for the first element in the set of matched elements, + * including padding but excluding borders. + * + * @return number + */ + width(): number; + + /** + * Get the current computed height for the first element in the set of matched elements, + * including padding but excluding borders. + * + * @return number + */ + height(): number; + + /** + * Get the combined text contents of each element in the set of matched elements, including their descendants. + * + * @return string + */ + text(): string; + + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param text The text to set as the content of each matched element. When Number is supplied, it will be converted to a String representation. To delete text, use ChocolateChipElementArray.empty() or ChocolateChipElementArray.remove(). + * @return HTMLElement + */ + text(text: string | number): HTMLElement; + + /** + * A method to animate DOM nodes using CSS. This uses CSS transitions. + * + * @param options And object of key value pairs define the CSS properties and values to animate. + * @param duration A string representing the time. Should have a time identifier: "200s", "200ms", etc. + * @param easing A string indicating the easing for the animation, such as "ease-out", "ease-in", "ease-in-out". + * @return void + */ + animate(options: Object, duration?: string, easing?: string): void; + + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. + * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. + * @return ChocolateChipStatic + */ + bind(eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; + + /** + * Remove a handler for an event from the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. + * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. + * @return ChocolateChipStatic + */ + unbind(eventType?: string, handler?: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; + + /** + * Add a delegated event to listen for the provided event on the descendant elements. + * + * @param selector A string defining the descendant elements to listen on for the designated event. + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. The keyword "this" will refer + * to the element receiving the event. + * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. + * @return ChocolateChipStatic + */ + delegate(selector: any, eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; + + /** + * Add a delegated event to listen for the provided event on the descendant elements. + * + * @param selector A string defining the descendant elements are listening for the event. + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function handler assigned to this event. + * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. + * @return ChocolateChipStatic + */ + undelegate(selector?: any, eventType?: string, handler?: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; + + /** + * Add a handler to an event for elements. If a selector is provided as the second argument, this implements a delegated event. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param selector A string defining the descendant elements are listening for the event. + * @param handler A function handler assigned to this event. + * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. + * @return ChocolateChipStatic + */ + on(eventType: string, selector: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; + + /** + * Remove a handler for an event from the elements. If the second argument is a selector, it tries to undelegate the event. + * If no arugments are provided, it removes all events from the element(s). + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param selector A string defining the descendant elements are listening for the event. + * @param handler A function handler assigned to this event. + * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. + * @return ChocolateChipStatic + */ + off(eventType?: string, selector?: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; + + /** + * Trigger an event on an element. + * + * @param eventType The event to trigger. + * @return void + */ + trigger(eventType: string): void; +} + +/** + * Represents the completion of an asynchronous operation + */ +interface Promise { + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @return Promise A Promise for the completion of which ever callback is executed. + * @return Promise A new Promise + */ + then(onfulfilled?: (value: T) => TResult | Promise, onrejected?: (reason: any) => TResult | Promise): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * + * @param onrejected The callback to execute when the Promise is rejected. + * @return Promise A Promise for the completion of the callback. + * @return Promise A new Promise + */ + catch(onrejected?: (reason: any) => T | Promise): Promise; +} + +interface PromiseConstructor { + /** + * Creates a new Promise. + * + * @param init A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error. + * @return Promise A new Proimise + */ + new (init: (resolve: (value?: T | Promise) => void, reject: (reason?: any) => void) => void): Promise; + + (init: (resolve: (value?: T | Promise) => void, reject: (reason?: any) => void) => void): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected. + * + * @param values An array of Promises. + * @return Promise A new Promise. + */ + all(values: (T | Promise)[]): Promise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected. + * + * @param values An array of values. + * @returns A new Promise. + */ + all(values: Promise[]): Promise; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved or rejected. + * + * @param values An array of Promises. + * @return Promise A new Promise. + */ + race(values: (T | Promise)[]): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * + * @param reason The reason the promise was rejected. + * @return Promise A new rejected Promise. + */ + reject(reason: any): Promise; + + /** + * Creates a new rejected promise for the provided reason. + * + * @param reason The reason the promise was rejected. + * @return void A Promise is rejected. + */ + reject(reason: any): Promise; + + /** + * Creates a new resolved promise for the provided value. + * + * @param value A promise. + * @return Promise A promise whose internal state matches the provided promise. + */ + resolve(value: T | Promise): Promise; + + /** + * Creates a new resolved promise. + * + * @return Promise A resolved promise. + */ + resolve(): Promise; +} + +declare var Promise: PromiseConstructor; +declare type ByteString = string; +declare type USVString = string; +declare type DOMString = string; +declare type OpenEndedDictionary = Object; + +/** + * Interface for fetch API. + * + * @param input A string representing a valid url. + * @param init An object literal of key value pairs to set method, headers, body, credentials or cache. + * @return Promise. + */ +interface fetch { + (input: string, + init?: { + method?: string; + headers?: {}; + body?: any; + mode?: { + cors: string; + "no-cors": string; + "same-origin": string; + }; + credentials?: { + omit: string; + "same-origin": string; + include: string; + }; + cache?: { + default: string; + "no-store": string; + reload: string; + "no-cache": string; + "force-cache": string; + "only-if-cached": string; + }; + timeout?: number; + }): Promise; +} + +interface XMLHttpRequest { + responseURL: string; +} + +/** + * Headers Interface. This defines the methods exposed by the Headers object. + */ +interface Headers { + (headers?: any): void; + append(name: string, value: string): void; + delete(name: string): any; + get(name: string): any; + getAll(name: string): any; + has(name: string): any; + set(name: string, value: string): any; + forEach(callback: Function, thisArg: any): any; +} + +interface decode { + (body: any): FormData; +} + +/** + * Request Interface. This defines the properties and methods exposed by the Request object. + */ +interface Request { + (input: { + url: string; + request: Request; + }, init: Object): Request; + clone(): Request; + arrayBuffer(): ArrayBuffer; + blob(): Blob; + formData(): FormData; + json(): JSON; + text(): string; + + method: string; + url: string; + heaers: Headers; + context: any; + referrer: any; + mode: string; + credentials: any; + cache: string; + bodyUsed: boolean; +} + +interface URLSearchParams { + ():URLSearchParams; +} + +/** + * Resonse Interface. This defines the properties and methods exposed by the Response object. + */ +interface Response { + (body?: { + blob: Blob; + bormData: FormData; + urlParams: URLSearchParams; + url: string; + }, + init?: { + status?: string | number; + statusText?: string; + headers: Headers; + }): Response; + clone(): Response; + redirect(): Response; + arrayBuffer(): ArrayBuffer; + blob(): Blob; + formData(): FormData; + json(): JSON; + text(): string; + + type: string; + url: string; + useFinalURL: boolean; + ok: boolean; + statusText: string; + headers: Headers; + bodyUsed: boolean; +} + +interface ChocolateChipStatic { + + /** + * A cache to hold callbacks execute by the response from a JSONP request. This is an array of strings. By default these values get purged when the callback execute and exposes the data returned by the request. + */ + JSONPCallbacks: string[]; + /** + * Method to perform JSONP request. + * + * @param url A string defining the url to target. + * @param options And object literal of properties: {timeout? number, callbackName?: string, clear?: boolean} + */ + jsonp(url: string, options?: { + /** + * A number representing milliseconds to express when to refect a JSONP request. + */ + timeout?: number; + + /** + * The optional name for the callback when the server response will execute. The default value is "callback". However some sites may use a different name for their JSONP function. Consult the documentation on the site to ascertain the correct value for this callback. + */ + callbackName?: string; + + /** + * This value determines whether the callbacks and script associate with JSONP persist or are purged after the request returns. By default this is set to true, meaning that they will be purged. + */ + clear?: boolean; + }): any +} + +interface Window { + chocolatechipjs: ChocolateChipStatic; + $: ChocolateChipStatic; + jsonp: any; +} +declare var $: ChocolateChipStatic; +declare var fetch: fetch; + +declare var chocolatechipjs: ChocolateChipStatic; \ No newline at end of file diff --git a/chocolatechipjs/tsconfig.json b/chocolatechipjs/tsconfig.json new file mode 100644 index 0000000000..f3f3090f3d --- /dev/null +++ b/chocolatechipjs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chocolatechipjs-tests.ts" + ] +} \ No newline at end of file diff --git a/chokidar/chokidar-tests.ts b/chokidar/chokidar-tests.ts index b89dd81a0b..9ff862789d 100644 --- a/chokidar/chokidar-tests.ts +++ b/chokidar/chokidar-tests.ts @@ -1,4 +1,4 @@ -/// + import fs = require('fs'); import chokidar = require('chokidar'); diff --git a/chokidar/chokidar.d.ts b/chokidar/chokidar.d.ts deleted file mode 100644 index 36f2f821c2..0000000000 --- a/chokidar/chokidar.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Type definitions for chokidar 1.4.3 -// Project: https://github.com/paulmillr/chokidar -// Definitions by: Stefan Steinhart -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "fs" -{ - interface FSWatcher - { - add(fileDirOrGlob:string):void; - add(filesDirsOrGlobs:Array):void; - unwatch(fileDirOrGlob:string):void; - unwatch(filesDirsOrGlobs:Array):void; - getWatched():any; - } -} - -declare module "chokidar" -{ - interface WatchOptions - { - persistent?:boolean; - ignored?:any; - ignoreInitial?:boolean; - followSymlinks?:boolean; - cwd?:string; - usePolling?:boolean; - useFsEvents?:boolean; - alwaysStat?:boolean; - depth?:number; - interval?:number; - binaryInterval?:number; - ignorePermissionErrors?:boolean; - atomic?:boolean; - awaitWriteFinish?:any; - } - - import fs = require("fs"); - - function watch(fileDirOrGlob:string, options?:WatchOptions):fs.FSWatcher; - function watch(filesDirsOrGlobs:Array, options?:WatchOptions):fs.FSWatcher; -} diff --git a/chokidar/index.d.ts b/chokidar/index.d.ts new file mode 100644 index 0000000000..aa0dd27ef5 --- /dev/null +++ b/chokidar/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for chokidar 1.4.3 +// Project: https://github.com/paulmillr/chokidar +// Definitions by: Stefan Steinhart +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "fs" +{ + interface FSWatcher + { + add(fileDirOrGlob:string):void; + add(filesDirsOrGlobs:Array):void; + unwatch(fileDirOrGlob:string):void; + unwatch(filesDirsOrGlobs:Array):void; + getWatched():any; + } +} + +declare module "chokidar" +{ + interface WatchOptions + { + persistent?:boolean; + ignored?:any; + ignoreInitial?:boolean; + followSymlinks?:boolean; + cwd?:string; + usePolling?:boolean; + useFsEvents?:boolean; + alwaysStat?:boolean; + depth?:number; + interval?:number; + binaryInterval?:number; + ignorePermissionErrors?:boolean; + atomic?:boolean; + awaitWriteFinish?:any; + } + + import fs = require("fs"); + + function watch(fileDirOrGlob:string, options?:WatchOptions):fs.FSWatcher; + function watch(filesDirsOrGlobs:Array, options?:WatchOptions):fs.FSWatcher; +} diff --git a/chokidar/tsconfig.json b/chokidar/tsconfig.json new file mode 100644 index 0000000000..6d78fa298c --- /dev/null +++ b/chokidar/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chokidar-tests.ts" + ] +} \ No newline at end of file diff --git a/chosen/chosen-tests.ts b/chosen/chosen-tests.ts index 818b1e1261..e5a97b0b59 100644 --- a/chosen/chosen-tests.ts +++ b/chosen/chosen-tests.ts @@ -1,4 +1,4 @@ -/// + $(".chzn-select").chosen({ no_results_text: "No results matched" }); $("#form_field").chosen().change(); diff --git a/chosen/chosen.jquery.d.ts b/chosen/chosen.jquery.d.ts deleted file mode 100644 index 0033bfdd1d..0000000000 --- a/chosen/chosen.jquery.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Type definitions for Chosen.JQuery 1.4.2 -// Project: http://harvesthq.github.com/chosen/ -// Definitions by: Boris Yankov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -/// - -interface ChosenOptions { - allow_single_deselect?: boolean; - disable_search?: boolean; - disable_search_threshold?: number; - enable_split_word_search?: boolean; - inherit_select_classes?: boolean; - max_selected_options?: number; - no_results_text?: string; - placeholder_text_multiple?: string; - placeholder_text_single?: string; - search_contains?: boolean; - single_backstroke_delete?: boolean; - width?: number|string; - display_disabled_options?: boolean; - display_selected_options?: boolean; - include_group_label_in_selected?: boolean; -} - -interface JQuery { - chosen(): JQuery; - chosen(options: ChosenOptions): JQuery; -} diff --git a/chosen/index.d.ts b/chosen/index.d.ts new file mode 100644 index 0000000000..836e64e19d --- /dev/null +++ b/chosen/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for Chosen.JQuery 1.4.2 +// Project: http://harvesthq.github.com/chosen/ +// Definitions by: Boris Yankov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +interface ChosenOptions { + allow_single_deselect?: boolean; + disable_search?: boolean; + disable_search_threshold?: number; + enable_split_word_search?: boolean; + inherit_select_classes?: boolean; + max_selected_options?: number; + no_results_text?: string; + placeholder_text_multiple?: string; + placeholder_text_single?: string; + search_contains?: boolean; + single_backstroke_delete?: boolean; + width?: number|string; + display_disabled_options?: boolean; + display_selected_options?: boolean; + include_group_label_in_selected?: boolean; +} + +interface JQuery { + chosen(): JQuery; + chosen(options: ChosenOptions): JQuery; +} diff --git a/chosen/tsconfig.json b/chosen/tsconfig.json new file mode 100644 index 0000000000..2785328efc --- /dev/null +++ b/chosen/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chosen-tests.ts" + ] +} \ No newline at end of file diff --git a/chroma-js/chroma-js-tests.ts b/chroma-js/chroma-js-tests.ts index 3240ac11f8..4bb67004fb 100644 --- a/chroma-js/chroma-js-tests.ts +++ b/chroma-js/chroma-js-tests.ts @@ -1,4 +1,4 @@ -/// + function test_chroma() { chroma("red"); diff --git a/chroma-js/chroma-js.d.ts b/chroma-js/index.d.ts similarity index 100% rename from chroma-js/chroma-js.d.ts rename to chroma-js/index.d.ts diff --git a/chroma-js/tsconfig.json b/chroma-js/tsconfig.json new file mode 100644 index 0000000000..b37d5e2914 --- /dev/null +++ b/chroma-js/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "chroma-js-tests.ts" + ] +} \ No newline at end of file diff --git a/chrome/chrome-app-tests.ts b/chrome/chrome-app-tests.ts index c7194b523b..8d1a6f548f 100644 --- a/chrome/chrome-app-tests.ts +++ b/chrome/chrome-app-tests.ts @@ -1,4 +1,4 @@ -/// + import runtime = chrome.app.runtime; import cwindow = chrome.app.window; diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index 1891b960e0..73ad3c75ee 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// +/// //////////////////// // App Runtime diff --git a/chrome/chrome-tests.ts b/chrome/chrome-tests.ts index e184a82167..02273f4385 100644 --- a/chrome/chrome-tests.ts +++ b/chrome/chrome-tests.ts @@ -1,6 +1,6 @@ -/// -/// -/// + +/// +/// // https://developer.chrome.com/extensions/examples/api/bookmarks/basic/popup.js function bookmarksExample() { diff --git a/chrome/chrome-tests.ts.tscparams b/chrome/chrome-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/chrome/chrome-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts deleted file mode 100644 index 9cdf8c3a5d..0000000000 --- a/chrome/chrome.d.ts +++ /dev/null @@ -1,7691 +0,0 @@ -// Type definitions for Chrome extension development -// Project: http://developer.chrome.com/extensions/ -// Definitions by: Matthew Kimber , otiai10 , couven92 , RReverser -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -//////////////////// -// Global object -//////////////////// -interface Window { - chrome: typeof chrome; -} - -//////////////////// -// Accessibility Features -//////////////////// -/** - * Use the chrome.accessibilityFeatures API to manage Chrome's accessibility features. This API relies on the ChromeSetting prototype of the type API for getting and setting individual accessibility features. In order to get feature states the extension must request accessibilityFeatures.read permission. For modifying feature state, the extension needs accessibilityFeatures.modify permission. Note that accessibilityFeatures.modify does not imply accessibilityFeatures.read permission. - * Availability: Since Chrome 37. - * Permissions: "accessibilityFeatures.read" - * Important: This API works only on Chrome OS. - */ -declare namespace chrome.accessibilityFeatures { - interface AccessibilityFeaturesGetArg { - /** Optional. Whether to return the value that applies to the incognito session (default false). */ - incognito?: boolean; - } - - interface AccessibilityFeaturesCallbackArg { - /** The value of the setting. */ - value: any; - /** - * One of - * • not_controllable: cannot be controlled by any extension - * • controlled_by_other_extensions: controlled by extensions with higher precedence - * • controllable_by_this_extension: can be controlled by this extension - * • controlled_by_this_extension: controlled by this extension - */ - levelOfControl: string; - /** Optional. Whether the effective value is specific to the incognito session. This property will only be present if the incognito property in the details parameter of get() was true. */ - incognitoSpecific?: boolean; - } - - interface AccessibilityFeaturesSetArg { - /** - * The value of the setting. - * Note that every setting has a specific value type, which is described together with the setting. An extension should not set a value of a different type. - */ - value: any; - /** - * Optional. - * The scope of the ChromeSetting. One of - * • regular: setting for the regular profile (which is inherited by the incognito profile if not overridden elsewhere), - * • regular_only: setting for the regular profile only (not inherited by the incognito profile), - * • incognito_persistent: setting for the incognito profile that survives browser restarts (overrides regular preferences), - * • incognito_session_only: setting for the incognito profile that can only be set during an incognito session and is deleted when the incognito session ends (overrides regular and incognito_persistent preferences). - */ - scope?: string; - } - - interface AccessibilityFeaturesClearArg { - /** - * Optional. - * The scope of the ChromeSetting. One of - * • regular: setting for the regular profile (which is inherited by the incognito profile if not overridden elsewhere), - * • regular_only: setting for the regular profile only (not inherited by the incognito profile), - * • incognito_persistent: setting for the incognito profile that survives browser restarts (overrides regular preferences), - * • incognito_session_only: setting for the incognito profile that can only be set during an incognito session and is deleted when the incognito session ends (overrides regular and incognito_persistent preferences). - */ - scope?: string; - } - - interface AccessibilityFeaturesSetting { - /** - * Gets the value of a setting. - * @param details Which setting to consider. - * @param callback The callback parameter should be a function that looks like this: - * function(object details) {...}; - */ - get(details: AccessibilityFeaturesGetArg, callback: (details: AccessibilityFeaturesCallbackArg) => void): void; - /** - * Sets the value of a setting. - * @param details Which setting to change. - * @param callback Called at the completion of the set operation. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - set(details: AccessibilityFeaturesSetArg, callback?: () => void): void; - /** - * Clears the setting, restoring any default value. - * @param details Which setting to clear. - * @param callback Called at the completion of the clear operation. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - clear(details: AccessibilityFeaturesClearArg, callback?: () => void): void; - } - - var spokenFeedback: AccessibilityFeaturesSetting; - var largeCursor: AccessibilityFeaturesSetting; - var stickyKeys: AccessibilityFeaturesSetting; - var highContrast: AccessibilityFeaturesSetting; - var screenMagnifier: AccessibilityFeaturesSetting; - var autoclick: AccessibilityFeaturesSetting; - var virtualKeyboard: AccessibilityFeaturesSetting; - var animationPolicy: AccessibilityFeaturesSetting; -} - -//////////////////// -// Alarms -//////////////////// -/** - * Use the chrome.alarms API to schedule code to run periodically or at a specified time in the future. - * Availability: Since Chrome 22. - * Permissions: "alarms" - */ -declare namespace chrome.alarms { - interface AlarmCreateInfo { - /** Optional. Length of time in minutes after which the onAlarm event should fire. */ - delayInMinutes?: number; - /** Optional. If set, the onAlarm event should fire every periodInMinutes minutes after the initial event specified by when or delayInMinutes. If not set, the alarm will only fire once. */ - periodInMinutes?: number; - /** Optional. Time at which the alarm should fire, in milliseconds past the epoch (e.g. Date.now() + n). */ - when?: number; - } - - interface Alarm { - /** Optional. If not null, the alarm is a repeating alarm and will fire again in periodInMinutes minutes. */ - periodInMinutes?: number; - /** Time at which this alarm was scheduled to fire, in milliseconds past the epoch (e.g. Date.now() + n). For performance reasons, the alarm may have been delayed an arbitrary amount beyond this. */ - scheduledTime: number; - /** Name of this alarm. */ - name: string; - } - - interface AlarmEvent extends chrome.events.Event<(alarm: Alarm) => void> {} - - /** - * Creates an alarm. Near the time(s) specified by alarmInfo, the onAlarm event is fired. If there is another alarm with the same name (or no name if none is specified), it will be cancelled and replaced by this alarm. - * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. when can be set to less than 1 minute after "now" without warning but won't actually cause the alarm to fire for at least 1 minute. - * To help you debug your app or extension, when you've loaded it unpacked, there's no limit to how often the alarm can fire. - * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes. - */ - export function create(alarmInfo: AlarmCreateInfo): void; - /** - * Creates an alarm. Near the time(s) specified by alarmInfo, the onAlarm event is fired. If there is another alarm with the same name (or no name if none is specified), it will be cancelled and replaced by this alarm. - * In order to reduce the load on the user's machine, Chrome limits alarms to at most once every 1 minute but may delay them an arbitrary amount more. That is, setting delayInMinutes or periodInMinutes to less than 1 will not be honored and will cause a warning. when can be set to less than 1 minute after "now" without warning but won't actually cause the alarm to fire for at least 1 minute. - * To help you debug your app or extension, when you've loaded it unpacked, there's no limit to how often the alarm can fire. - * @param name Optional name to identify this alarm. Defaults to the empty string. - * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes. - */ - export function create(name: string, alarmInfo: AlarmCreateInfo): void; - /** - * Gets an array of all the alarms. - * @param callback The callback parameter should be a function that looks like this: - * function(array of Alarm alarms) {...}; - */ - export function getAll(callback: (alarms: Alarm[]) => void): void; - /** - * Clears all alarms. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(boolean wasCleared) {...}; - */ - export function clearAll(callback?: (wasCleared: boolean) => void): void; - /** - * Clears the alarm with the given name. - * @param name The name of the alarm to clear. Defaults to the empty string. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(boolean wasCleared) {...}; - */ - export function clear(name?: string, callback?: (wasCleared: boolean) => void): void; - /** - * Clears the alarm without a name. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(boolean wasCleared) {...}; - */ - export function clear(callback: (wasCleared: boolean) => void): void; - /** - * Retrieves details about the specified alarm. - * @param callback The callback parameter should be a function that looks like this: - * function( Alarm alarm) {...}; - */ - export function get(callback: (alarm: Alarm) => void): void; - /** - * Retrieves details about the specified alarm. - * @param name The name of the alarm to get. Defaults to the empty string. - * @param callback The callback parameter should be a function that looks like this: - * function( Alarm alarm) {...}; - */ - export function get(name: string, callback: (alarm: Alarm) => void): void; - - /** Fired when an alarm has elapsed. Useful for event pages. */ - var onAlarm: AlarmEvent; -} - -/** - * Use the chrome.browser API to interact with the Chrome browser associated with - * the current application and Chrome profile. - */ -declare namespace chrome.browser { - interface Options { - /** The URL to navigate to when the new tab is initially opened. */ - url: string; - } - - /** - * Opens a new tab in a browser window associated with the current application - * and Chrome profile. If no browser window for the Chrome profile is opened, - * a new one is opened prior to creating the new tab. - * @param options Configures how the tab should be opened. - * @param callback Called when the tab was successfully - * created, or failed to be created. If failed, runtime.lastError will be set. - */ - export function openTab(options: Options, callback: () => void): void; - - /** - * Opens a new tab in a browser window associated with the current application - * and Chrome profile. If no browser window for the Chrome profile is opened, - * a new one is opened prior to creating the new tab. Since Chrome 42 only. - * @param options Configures how the tab should be opened. - */ - export function openTab(options: Options): void; -} - -//////////////////// -// Bookmarks -//////////////////// -/** - * Use the chrome.bookmarks API to create, organize, and otherwise manipulate bookmarks. Also see Override Pages, which you can use to create a custom Bookmark Manager page. - * Availability: Since Chrome 5. - * Permissions: "bookmarks" - */ -declare namespace chrome.bookmarks { - /** A node (either a bookmark or a folder) in the bookmark tree. Child nodes are ordered within their parent folder. */ - interface BookmarkTreeNode { - /** Optional. The 0-based position of this node within its parent folder. */ - index?: number; - /** Optional. When this node was created, in milliseconds since the epoch (new Date(dateAdded)). */ - dateAdded?: number; - /** The text displayed for the node. */ - title: string; - /** Optional. The URL navigated to when a user clicks the bookmark. Omitted for folders. */ - url?: string; - /** Optional. When the contents of this folder last changed, in milliseconds since the epoch. */ - dateGroupModified?: number; - /** The unique identifier for the node. IDs are unique within the current profile, and they remain valid even after the browser is restarted. */ - id: string; - /** Optional. The id of the parent folder. Omitted for the root node. */ - parentId?: string; - /** Optional. An ordered list of children of this node. */ - children?: BookmarkTreeNode[]; - /** - * Optional. - * Since Chrome 37. - * Indicates the reason why this node is unmodifiable. The managed value indicates that this node was configured by the system administrator or by the custodian of a supervised user. Omitted if the node can be modified by the user and the extension (default). - */ - unmodifiable?: any; - } - - interface BookmarkRemoveInfo { - index: number; - parentId: string; - } - - interface BookmarkMoveInfo { - index: number; - oldIndex: number; - parentId: string; - oldParentId: string; - } - - interface BookmarkChangeInfo { - url?: string; - title: string; - } - - interface BookmarkReorderInfo { - childIds: string[]; - } - - interface BookmarkRemovedEvent extends chrome.events.Event<(id: string, removeInfo: BookmarkRemoveInfo) => void> {} - - interface BookmarkImportEndedEvent extends chrome.events.Event<() => void> {} - - interface BookmarkMovedEvent extends chrome.events.Event<(id: string, moveInfo: BookmarkMoveInfo) => void> {} - - interface BookmarkImportBeganEvent extends chrome.events.Event<() => void> {} - - interface BookmarkChangedEvent extends chrome.events.Event<(id: string, changeInfo: BookmarkChangeInfo) => void> {} - - interface BookmarkCreatedEvent extends chrome.events.Event<(id: string, bookmark: BookmarkTreeNode) => void> {} - - interface BookmarkChildrenReordered extends chrome.events.Event<(id: string, reorderInfo: BookmarkReorderInfo) => void> {} - - interface BookmarkSearchQuery { - query?: string; - url?: string; - title?: string; - } - - interface BookmarkCreateArg { - /** Optional. Defaults to the Other Bookmarks folder. */ - parentId?: string; - index?: number; - title?: string; - url?: string; - } - - interface BookmarkDestinationArg { - parentId?: string; - index?: number; - } - - interface BookmarkChangesArg { - title?: string; - url?: string; - } - - /** @deprecated since Chrome 38. Bookmark write operations are no longer limited by Chrome. */ - var MAX_WRITE_OPERATIONS_PER_HOUR: number; - /** @deprecated since Chrome 38. Bookmark write operations are no longer limited by Chrome. */ - var MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: number; - - /** - * Searches for BookmarkTreeNodes matching the given query. Queries specified with an object produce BookmarkTreeNodes matching all specified properties. - * @param query A string of words and quoted phrases that are matched against bookmark URLs and titles. - * @param callback The callback parameter should be a function that looks like this: - * function(array of BookmarkTreeNode results) {...}; - */ - export function search(query: string, callback: (results: BookmarkTreeNode[]) => void): void; - /** - * Searches for BookmarkTreeNodes matching the given query. Queries specified with an object produce BookmarkTreeNodes matching all specified properties. - * @param query An object with one or more of the properties query, url, and title specified. Bookmarks matching all specified properties will be produced. - * @param callback The callback parameter should be a function that looks like this: - * function(array of BookmarkTreeNode results) {...}; - */ - export function search(query: BookmarkSearchQuery, callback: (results: BookmarkTreeNode[]) => void): void; - /** - * Retrieves the entire Bookmarks hierarchy. - * @param callback The callback parameter should be a function that looks like this: - * function(array of BookmarkTreeNode results) {...}; - */ - export function getTree(callback: (results: BookmarkTreeNode[]) => void): void; - /** - * Retrieves the recently added bookmarks. - * @param numberOfItems The maximum number of items to return. - * @param callback The callback parameter should be a function that looks like this: - * function(array of BookmarkTreeNode results) {...}; - */ - export function getRecent(numberOfItems: number, callback: (results: BookmarkTreeNode[]) => void): void; - /** - * Retrieves the specified BookmarkTreeNode. - * @param id A single string-valued id - * @param callback The callback parameter should be a function that looks like this: - * function(array of BookmarkTreeNode results) {...}; - */ - export function get(id: string, callback: (results: BookmarkTreeNode[]) => void): void; - /** - * Retrieves the specified BookmarkTreeNode. - * @param idList An array of string-valued ids - * @param callback The callback parameter should be a function that looks like this: - * function(array of BookmarkTreeNode results) {...}; - */ - export function get(idList: string[], callback: (results: BookmarkTreeNode[]) => void): void; - /** - * Creates a bookmark or folder under the specified parentId. If url is NULL or missing, it will be a folder. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function( BookmarkTreeNode result) {...}; - */ - export function create(bookmark: BookmarkCreateArg, callback?: (result: BookmarkTreeNode) => void): void; - /** - * Moves the specified BookmarkTreeNode to the provided location. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function( BookmarkTreeNode result) {...}; - */ - export function move(id: string, destination: BookmarkDestinationArg, callback?: (result: BookmarkTreeNode) => void): void; - /** - * Updates the properties of a bookmark or folder. Specify only the properties that you want to change; unspecified properties will be left unchanged. Note: Currently, only 'title' and 'url' are supported. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function( BookmarkTreeNode result) {...}; - */ - export function update(id: string, changes: BookmarkChangesArg, callback?: (result: BookmarkTreeNode) => void): void; - /** - * Removes a bookmark or an empty bookmark folder. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function remove(id: string, callback?: Function): void; - /** - * Retrieves the children of the specified BookmarkTreeNode id. - * @param callback The callback parameter should be a function that looks like this: - * function(array of BookmarkTreeNode results) {...}; - */ - export function getChildren(id: string, callback: (results: BookmarkTreeNode[]) => void): void; - /** - * Since Chrome 14. - * Retrieves part of the Bookmarks hierarchy, starting at the specified node. - * @param id The ID of the root of the subtree to retrieve. - * @param callback The callback parameter should be a function that looks like this: - * function(array of BookmarkTreeNode results) {...}; - */ - export function getSubTree(id: string, callback: (results: BookmarkTreeNode[]) => void): void; - /** - * Recursively removes a bookmark folder. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeTree(id: string, callback?: Function): void; - - /** Fired when a bookmark or folder is removed. When a folder is removed recursively, a single notification is fired for the folder, and none for its contents. */ - var onRemoved: BookmarkRemovedEvent; - /** Fired when a bookmark import session is ended. */ - var onImportEnded: BookmarkImportEndedEvent; - /** Fired when a bookmark import session is begun. Expensive observers should ignore onCreated updates until onImportEnded is fired. Observers should still handle other notifications immediately. */ - var onImportBegan: BookmarkImportBeganEvent; - /** Fired when a bookmark or folder changes. Note: Currently, only title and url changes trigger this. */ - var onChanged: BookmarkChangedEvent; - /** Fired when a bookmark or folder is moved to a different parent folder. */ - var onMoved: BookmarkMovedEvent; - /** Fired when a bookmark or folder is created. */ - var onCreated: BookmarkCreatedEvent; - /** Fired when the children of a folder have changed their order due to the order being sorted in the UI. This is not called as a result of a move(). */ - var onChildrenReordered: BookmarkChildrenReordered; -} - -//////////////////// -// Browser Action -//////////////////// -/** - * Use browser actions to put icons in the main Google Chrome toolbar, to the right of the address bar. In addition to its icon, a browser action can also have a tooltip, a badge, and a popup. - * Availability: Since Chrome 5. - * Manifest: "browser_action": {...} - */ -declare namespace chrome.browserAction { - interface BadgeBackgroundColorDetails { - /** An array of four integers in the range [0,255] that make up the RGBA color of the badge. For example, opaque red is [255, 0, 0, 255]. Can also be a string with a CSS value, with opaque red being #FF0000 or #F00. */ - color: any; - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ - tabId?: number; - } - - interface BadgeTextDetails { - /** Any number of characters can be passed, but only about four can fit in the space. */ - text: string; - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ - tabId?: number; - } - - interface TitleDetails { - /** The string the browser action should display when moused over. */ - title: string; - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ - tabId?: number; - } - - interface TabDetails { - /** Optional. Specify the tab to get the information. If no tab is specified, the non-tab-specific information is returned. */ - tabId?: number; - } - - interface TabIconDetails { - /** Optional. Either a relative image path or a dictionary {size -> relative image path} pointing to icon to be set. If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density. If the number of image pixels that fit into one screen space unit equals scale, then image with size scale * 19 will be selected. Initially only scales 1 and 2 will be supported. At least one image must be specified. Note that 'details.path = foo' is equivalent to 'details.imageData = {'19': foo}' */ - path?: any; - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ - tabId?: number; - /** Optional. Either an ImageData object or a dictionary {size -> ImageData} representing icon to be set. If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density. If the number of image pixels that fit into one screen space unit equals scale, then image with size scale * 19 will be selected. Initially only scales 1 and 2 will be supported. At least one image must be specified. Note that 'details.imageData = foo' is equivalent to 'details.imageData = {'19': foo}' */ - imageData?: ImageData; - } - - interface PopupDetails { - /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ - tabId?: number; - /** The html file to show in a popup. If set to the empty string (''), no popup is shown. */ - popup: string; - } - - interface BrowserClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> {} - - /** - * Since Chrome 22. - * Enables the browser action for a tab. By default, browser actions are enabled. - * @param tabId The id of the tab for which you want to modify the browser action. - */ - export function enable(tabId?: number): void; - /** Sets the background color for the badge. */ - export function setBadgeBackgroundColor(details: BadgeBackgroundColorDetails): void; - /** Sets the badge text for the browser action. The badge is displayed on top of the icon. */ - export function setBadgeText(details: BadgeTextDetails): void; - /** Sets the title of the browser action. This shows up in the tooltip. */ - export function setTitle(details: TitleDetails): void; - /** - * Since Chrome 19. - * Gets the badge text of the browser action. If no tab is specified, the non-tab-specific badge text is returned. - * @param callback The callback parameter should be a function that looks like this: - * function(string result) {...}; - */ - export function getBadgeText(details: TabDetails, callback: (result: string) => void): void; - /** Sets the html document to be opened as a popup when the user clicks on the browser action's icon. */ - export function setPopup(details: PopupDetails): void; - /** - * Since Chrome 22. - * Disables the browser action for a tab. - * @param tabId The id of the tab for which you want to modify the browser action. - */ - export function disable(tabId?: number): void; - /** - * Since Chrome 19. - * Gets the title of the browser action. - * @param callback The callback parameter should be a function that looks like this: - * function(string result) {...}; - */ - export function getTitle(details: TabDetails, callback: (result: string) => void): void; - /** - * Since Chrome 19. - * Gets the background color of the browser action. - * @param callback The callback parameter should be a function that looks like this: - * function( ColorArray result) {...}; - */ - export function getBadgeBackgroundColor(details: TabDetails, callback: (result: number[]) => void): void; - /** - * Since Chrome 19. - * Gets the html document set as the popup for this browser action. - * @param callback The callback parameter should be a function that looks like this: - * function(string result) {...}; - */ - export function getPopup(details: TabDetails, callback: (result: string) => void): void; - /** - * Sets the icon for the browser action. The icon can be specified either as the path to an image file or as the pixel data from a canvas element, or as dictionary of either one of those. Either the path or the imageData property must be specified. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function setIcon(details: TabIconDetails, callback?: Function): void; - - /** Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup. */ - var onClicked: BrowserClickedEvent; -} - -//////////////////// -// Browsing Data -//////////////////// -/** - * Use the chrome.browsingData API to remove browsing data from a user's local profile. - * Availability: Since Chrome 19. - * Permissions: "browsingData" - */ -declare namespace chrome.browsingData { - interface OriginTypes { - /** Optional. Websites that have been installed as hosted applications (be careful!). */ - protectedWeb?: boolean; - /** Optional. Extensions and packaged applications a user has installed (be _really_ careful!). */ - extension?: boolean; - /** Optional. Normal websites. */ - unprotectedWeb?: boolean; - } - - /** Options that determine exactly what data will be removed. */ - interface RemovalOptions { - /** - * Optional. - * Since Chrome 21. - * An object whose properties specify which origin types ought to be cleared. If this object isn't specified, it defaults to clearing only "unprotected" origins. Please ensure that you really want to remove application data before adding 'protectedWeb' or 'extensions'. - */ - originTypes?: OriginTypes; - /** Optional. Remove data accumulated on or after this date, represented in milliseconds since the epoch (accessible via the getTime method of the JavaScript Date object). If absent, defaults to 0 (which would remove all browsing data). */ - since?: number; - } - - /** - * Since Chrome 27. - * A set of data types. Missing data types are interpreted as false. - */ - interface DataTypeSet { - /** Optional. Websites' WebSQL data. */ - webSQL?: boolean; - /** Optional. Websites' IndexedDB data. */ - indexedDB?: boolean; - /** Optional. The browser's cookies. */ - cookies?: boolean; - /** Optional. Stored passwords. */ - passwords?: boolean; - /** Optional. Server-bound certificates. */ - serverBoundCertificates?: boolean; - /** Optional. The browser's download list. */ - downloads?: boolean; - /** Optional. The browser's cache. Note: when removing data, this clears the entire cache: it is not limited to the range you specify. */ - cache?: boolean; - /** Optional. Websites' appcaches. */ - appcache?: boolean; - /** Optional. Websites' file systems. */ - fileSystems?: boolean; - /** Optional. Plugins' data. */ - pluginData?: boolean; - /** Optional. Websites' local storage data. */ - localStorage?: boolean; - /** Optional. The browser's stored form data. */ - formData?: boolean; - /** Optional. The browser's history. */ - history?: boolean; - /** - * Optional. - * Since Chrome 39. - * Service Workers. - */ - serviceWorkers?: boolean; - } - - interface SettingsCallback { - options: RemovalOptions; - /** All of the types will be present in the result, with values of true if they are both selected to be removed and permitted to be removed, otherwise false. */ - dataToRemove: DataTypeSet; - /** All of the types will be present in the result, with values of true if they are permitted to be removed (e.g., by enterprise policy) and false if not. */ - dataRemovalPermitted: DataTypeSet; - } - - /** - * Since Chrome 26. - * Reports which types of data are currently selected in the 'Clear browsing data' settings UI. Note: some of the data types included in this API are not available in the settings UI, and some UI settings control more than one data type listed here. - * @param callback The callback parameter should be a function that looks like this: - * function(object result) {...}; - */ - export function settings(callback: (result: SettingsCallback) => void): void; - /** - * Clears plugins' data. - * @param callback Called when plugins' data has been cleared. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removePluginData(options: RemovalOptions, callback?: () => void): void; - /** - * Clears the browser's stored form data (autofill). - * @param callback Called when the browser's form data has been cleared. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeFormData(options: RemovalOptions, callback?: () => void): void; - /** - * Clears websites' file system data. - * @param callback Called when websites' file systems have been cleared. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeFileSystems(options: RemovalOptions, callback?: () => void): void; - /** - * Clears various types of browsing data stored in a user's profile. - * @param dataToRemove The set of data types to remove. - * @param callback Called when deletion has completed. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function remove(options: RemovalOptions, dataToRemove: DataTypeSet, callback?: () => void): void; - /** - * Clears the browser's stored passwords. - * @param callback Called when the browser's passwords have been cleared. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removePasswords(options: RemovalOptions, callback?: () => void): void; - /** - * Clears the browser's cookies and server-bound certificates modified within a particular timeframe. - * @param callback Called when the browser's cookies and server-bound certificates have been cleared. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeCookies(options: RemovalOptions, callback?: () => void): void; - /** - * Clears websites' WebSQL data. - * @param callback Called when websites' WebSQL databases have been cleared. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeWebSQL(options: RemovalOptions, callback?: () => void): void; - /** - * Clears websites' appcache data. - * @param callback Called when websites' appcache data has been cleared. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeAppcache(options: RemovalOptions, callback?: () => void): void; - /** - * Clears the browser's list of downloaded files (not the downloaded files themselves). - * @param callback Called when the browser's list of downloaded files has been cleared. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeDownloads(options: RemovalOptions, callback?: () => void): void; - /** - * Clears websites' local storage data. - * @param callback Called when websites' local storage has been cleared. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeLocalStorage(options: RemovalOptions, callback?: () => void): void; - /** - * Clears the browser's cache. - * @param callback Called when the browser's cache has been cleared. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeCache(options: RemovalOptions, callback?: () => void): void; - /** - * Clears the browser's history. - * @param callback Called when the browser's history has cleared. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeHistory(options: RemovalOptions, callback?: () => void): void; - /** - * Clears websites' IndexedDB data. - * @param callback Called when websites' IndexedDB data has been cleared. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeIndexedDB(options: RemovalOptions, callback?: () => void): void; -} - -//////////////////// -// Commands -//////////////////// -/** - * Use the commands API to add keyboard shortcuts that trigger actions in your extension, for example, an action to open the browser action or send a command to the extension. - * Availability: Since Chrome 25. - * Manifest: "commands": {...} - */ -declare namespace chrome.commands { - interface Command { - /** Optional. The name of the Extension Command */ - name?: string; - /** Optional. The Extension Command description */ - description?: string; - /** Optional. The shortcut active for this command, or blank if not active. */ - shortcut?: string; - } - - interface CommandEvent extends chrome.events.Event<(command: string) => void> {} - - /** - * Returns all the registered extension commands for this extension and their shortcut (if active). - * @param callback Called to return the registered commands. - * If you specify the callback parameter, it should be a function that looks like this: - * function(array of Command commands) {...}; - */ - export function getAll(callback: (commands: Command[]) => void): void; - - /** Fired when a registered command is activated using a keyboard shortcut. */ - var onCommand: CommandEvent; -} - -//////////////////// -// Content Settings -//////////////////// -/** - * Use the chrome.contentSettings API to change settings that control whether websites can use features such as cookies, JavaScript, and plugins. More generally speaking, content settings allow you to customize Chrome's behavior on a per-site basis instead of globally. - * Availability: Since Chrome 16. - * Permissions: "contentSettings" - */ -declare namespace chrome.contentSettings { - interface ClearDetails { - /** - * Optional. - * Where to clear the setting (default: regular). - * The scope of the ContentSetting. One of - * * regular: setting for regular profile (which is inherited by the incognito profile if not overridden elsewhere), - * * incognito_session_only: setting for incognito profile that can only be set during an incognito session and is deleted when the incognito session ends (overrides regular settings). - */ - scope?: string; - } - - interface SetDetails { - /** Optional. The resource identifier for the content type. */ - resourceIdentifier?: ResourceIdentifier; - /** The setting applied by this rule. See the description of the individual ContentSetting objects for the possible values. */ - setting: any; - /** Optional. The pattern for the secondary URL. Defaults to matching all URLs. For details on the format of a pattern, see Content Setting Patterns. */ - secondaryPattern?: string; - /** Optional. Where to set the setting (default: regular). */ - scope?: string; - /** The pattern for the primary URL. For details on the format of a pattern, see Content Setting Patterns. */ - primaryPattern: string; - } - - interface GetDetails { - /** Optional. The secondary URL for which the content setting should be retrieved. Defaults to the primary URL. Note that the meaning of a secondary URL depends on the content type, and not all content types use secondary URLs. */ - secondaryUrl?: string; - /** Optional. A more specific identifier of the type of content for which the settings should be retrieved. */ - resourceIdentifier?: ResourceIdentifier; - /** Optional. Whether to check the content settings for an incognito session. (default false) */ - incognito?: boolean; - /** The primary URL for which the content setting should be retrieved. Note that the meaning of a primary URL depends on the content type. */ - primaryUrl: string; - } - - interface ReturnedDetails { - /** The content setting. See the description of the individual ContentSetting objects for the possible values. */ - setting: any; - } - - interface ContentSetting { - /** - * Clear all content setting rules set by this extension. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - clear(details: ClearDetails, callback?: () => void): void; - /** - * Applies a new content setting rule. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - set(details: SetDetails, callback?: () => void): void; - /** - * @param callback The callback parameter should be a function that looks like this: - * function(array of ResourceIdentifier resourceIdentifiers) {...}; - * Parameter resourceIdentifiers: A list of resource identifiers for this content type, or undefined if this content type does not use resource identifiers. - */ - getResourceIdentifiers(callback: (resourceIdentifiers?: ResourceIdentifier[]) => void): void; - /** - * Gets the current content setting for a given pair of URLs. - * @param callback The callback parameter should be a function that looks like this: - * function(object details) {...}; - */ - get(details: GetDetails, callback: (details: ReturnedDetails) => void): void; - } - - /** The only content type using resource identifiers is contentSettings.plugins. For more information, see Resource Identifiers. */ - interface ResourceIdentifier { - /** The resource identifier for the given content type. */ - id: string; - /** Optional. A human readable description of the resource. */ - description?: string; - } - - /** - * Whether to allow cookies and other local data to be set by websites. One of - * allow: Accept cookies, - * block: Block cookies, - * session_only: Accept cookies only for the current session. - * Default is allow. - * The primary URL is the URL representing the cookie origin. The secondary URL is the URL of the top-level frame. - */ - var cookies: ContentSetting; - /** - * Whether to allow sites to show pop-ups. One of - * allow: Allow sites to show pop-ups, - * block: Don't allow sites to show pop-ups. - * Default is block. - * The primary URL is the URL of the top-level frame. The secondary URL is not used. - */ - var popups: ContentSetting; - /** - * Whether to run JavaScript. One of - * allow: Run JavaScript, - * block: Don't run JavaScript. - * Default is allow. - * The primary URL is the URL of the top-level frame. The secondary URL is not used. - */ - var javascript: ContentSetting; - /** - * Whether to allow sites to show desktop notifications. One of - * allow: Allow sites to show desktop notifications, - * block: Don't allow sites to show desktop notifications, - * ask: Ask when a site wants to show desktop notifications. - * Default is ask. - * The primary URL is the URL of the document which wants to show the notification. The secondary URL is not used. - */ - var notifications: ContentSetting; - /** - * Whether to run plugins. One of - * allow: Run plugins automatically, - * block: Don't run plugins automatically, - * detect_important_content: Only run automatically those plugins that are detected as the website's main content. - * Default is allow. - * The primary URL is the URL of the top-level frame. The secondary URL is not used. - */ - var plugins: ContentSetting; - /** - * Whether to show images. One of - * allow: Show images, - * block: Don't show images. - * Default is allow. - * The primary URL is the URL of the top-level frame. The secondary URL is the URL of the image. - */ - var images: ContentSetting; - /** - * Since Chrome 42. - * Whether to allow Geolocation. One of - * allow: Allow sites to track your physical location, - * block: Don't allow sites to track your physical location, - * ask: Ask before allowing sites to track your physical location. - * Default is ask. - * The primary URL is the URL of the document which requested location data. The secondary URL is the URL of the top-level frame (which may or may not differ from the requesting URL). - */ - var location: ContentSetting; - /** - * Since Chrome 42. - * Whether to allow sites to toggle the fullscreen mode. One of - * allow: Allow sites to toggle the fullscreen mode, - * ask: Ask when a site wants to toggle the fullscreen mode. - * Default is ask. - * The primary URL is the URL of the document which requested to toggle the fullscreen mode. The secondary URL is the URL of the top-level frame (which may or may not differ from the requesting URL). - */ - var fullscreen: ContentSetting; - /** - * Since Chrome 42. - * Whether to allow sites to disable the mouse cursor. One of - * allow: Allow sites to disable the mouse cursor, - * block: Don't allow sites to disable the mouse cursor, - * ask: Ask when a site wants to disable the mouse cursor. - * Default is ask. - * The primary URL is the URL of the top-level frame. The secondary URL is not used. - */ - var mouselock: ContentSetting; - /** - * Since Chrome 42. - * Whether to allow sites to run plugins unsandboxed. One of - * allow: Allow sites to run plugins unsandboxed, - * block: Don't allow sites to run plugins unsandboxed, - * ask: Ask when a site wants to run a plugin unsandboxed. - * Default is ask. - * The primary URL is the URL of the top-level frame. The secondary URL is not used. - */ - var unsandboxedPlugins: ContentSetting; - /** - * Since Chrome 42. - * Whether to allow sites to download multiple files automatically. One of - * allow: Allow sites to download multiple files automatically, - * block: Don't allow sites to download multiple files automatically, - * ask: Ask when a site wants to download files automatically after the first file. - * Default is ask. - * The primary URL is the URL of the top-level frame. The secondary URL is not used. - */ - var automaticDownloads: ContentSetting; -} - -//////////////////// -// Context Menus -//////////////////// -/** - * Use the chrome.contextMenus API to add items to Google Chrome's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages. - * Availability: Since Chrome 6. - * Permissions: "contextMenus" - */ -declare namespace chrome.contextMenus { - interface OnClickData { - /** - * Optional. - * Since Chrome 35. - * The text for the context selection, if any. - */ - selectionText?: string; - /** - * Optional. - * Since Chrome 35. - * A flag indicating the state of a checkbox or radio item after it is clicked. - */ - checked?: boolean; - /** - * Since Chrome 35. - * The ID of the menu item that was clicked. - */ - menuItemId: any; - /** - * Optional. - * Since Chrome 35. - * The URL of the frame of the element where the context menu was clicked, if it was in a frame. - */ - frameUrl?: string; - /** - * Since Chrome 35. - * A flag indicating whether the element is editable (text input, textarea, etc.). - */ - editable: boolean; - /** - * Optional. - * Since Chrome 35. - * One of 'image', 'video', or 'audio' if the context menu was activated on one of these types of elements. - */ - mediaType?: string; - /** - * Optional. - * Since Chrome 35. - * A flag indicating the state of a checkbox or radio item before it was clicked. - */ - wasChecked?: boolean; - /** - * Since Chrome 35. - * The URL of the page where the menu item was clicked. This property is not set if the click occured in a context where there is no current page, such as in a launcher context menu. - */ - pageUrl: string; - /** - * Optional. - * Since Chrome 35. - * If the element is a link, the URL it points to. - */ - linkUrl?: string; - /** - * Optional. - * Since Chrome 35. - * The parent ID, if any, for the item clicked. - */ - parentMenuItemId?: any; - /** - * Optional. - * Since Chrome 35. - * Will be present for elements with a 'src' URL. - */ - srcUrl?: string; - } - - interface CreateProperties { - /** Optional. Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see Match Patterns. */ - documentUrlPatterns?: string[]; - /** Optional. The initial state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items. */ - checked?: boolean; - /** Optional. The text to be displayed in the item; this is required unless type is 'separator'. When the context is 'selection', you can use %s within the string to show the selected text. For example, if this parameter's value is "Translate '%s' to Pig Latin" and the user selects the word "cool", the context menu item for the selection is "Translate 'cool' to Pig Latin". */ - title?: string; - /** Optional. List of contexts this menu item will appear in. Defaults to ['page'] if not specified. */ - contexts?: string[]; - /** - * Optional. - * Since Chrome 20. - * Whether this context menu item is enabled or disabled. Defaults to true. - */ - enabled?: boolean; - /** Optional. Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags. */ - targetUrlPatterns?: string[]; - /** - * Optional. - * A function that will be called back when the menu item is clicked. Event pages cannot use this; instead, they should register a listener for chrome.contextMenus.onClicked. - * @param info Information sent when a context menu item is clicked. - * @param tab The details of the tab where the click took place. Note: this parameter only present for extensions. - */ - onclick?: (info: OnClickData, tab: chrome.tabs.Tab) => void; - /** Optional. The ID of a parent menu item; this makes the item a child of a previously added item. */ - parentId?: any; - /** Optional. The type of menu item. Defaults to 'normal' if not specified. */ - type?: string; - /** - * Optional. - * Since Chrome 21. - * The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. - */ - id?: string; - } - - interface UpdateProperties { - documentUrlPatterns?: string[]; - checked?: boolean; - title?: string; - contexts?: string[]; - /** Optional. Since Chrome 20. */ - enabled?: boolean; - targetUrlPatterns?: string[]; - onclick?: Function; - /** Optional. Note: You cannot change an item to be a child of one of its own descendants. */ - parentId?: any; - type?: string; - } - - interface MenuClickedEvent extends chrome.events.Event<(info: OnClickData, tab?: chrome.tabs.Tab) => void> {} - - /** - * Since Chrome 38. - * The maximum number of top level extension items that can be added to an extension action context menu. Any items beyond this limit will be ignored. - */ - var ACTION_MENU_TOP_LEVEL_LIMIT: number; - - /** - * Removes all context menu items added by this extension. - * @param callback Called when removal is complete. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeAll(callback?: () => void): void; - /** - * Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in chrome.runtime.lastError). - * @param callback Called when the item has been created in the browser. If there were any problems creating the item, details will be available in chrome.runtime.lastError. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function create(createProperties: CreateProperties, callback?: () => void): void; - /** - * Updates a previously created context menu item. - * @param id The ID of the item to update. - * @param updateProperties The properties to update. Accepts the same values as the create function. - * @param callback Called when the context menu has been updated. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function update(id: string, updateProperties: UpdateProperties, callback?: () => void): void; - /** - * Updates a previously created context menu item. - * @param id The ID of the item to update. - * @param updateProperties The properties to update. Accepts the same values as the create function. - * @param callback Called when the context menu has been updated. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function update(id: number, updateProperties: UpdateProperties, callback?: () => void): void; - /** - * Removes a context menu item. - * @param menuItemId The ID of the context menu item to remove. - * @param callback Called when the context menu has been removed. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function remove(menuItemId: string, callback?: () => void): void; - /** - * Removes a context menu item. - * @param menuItemId The ID of the context menu item to remove. - * @param callback Called when the context menu has been removed. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function remove(menuItemId: number, callback?: () => void): void; - - /** - * Since Chrome 21. - * Fired when a context menu item is clicked. - */ - var onClicked: MenuClickedEvent; -} - -//////////////////// -// Cookies -//////////////////// -/** - * Use the chrome.cookies API to query and modify cookies, and to be notified when they change. - * Availability: Since Chrome 6. - * Permissions: "cookies", host permissions - */ -declare namespace chrome.cookies { - /** Represents information about an HTTP cookie. */ - interface Cookie { - /** The domain of the cookie (e.g. "www.google.com", "example.com"). */ - domain: string; - /** The name of the cookie. */ - name: string; - /** The ID of the cookie store containing this cookie, as provided in getAllCookieStores(). */ - storeId: string; - /** The value of the cookie. */ - value: string; - /** True if the cookie is a session cookie, as opposed to a persistent cookie with an expiration date. */ - session: boolean; - /** True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie). */ - hostOnly: boolean; - /** Optional. The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies. */ - expirationDate?: number; - /** The path of the cookie. */ - path: string; - /** True if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts). */ - httpOnly: boolean; - /** True if the cookie is marked as Secure (i.e. its scope is limited to secure channels, typically HTTPS). */ - secure: boolean; - } - - /** Represents a cookie store in the browser. An incognito mode window, for instance, uses a separate cookie store from a non-incognito window. */ - interface CookieStore { - /** The unique identifier for the cookie store. */ - id: string; - /** Identifiers of all the browser tabs that share this cookie store. */ - tabIds: number[]; - } - - interface GetAllDetails { - /** Optional. Restricts the retrieved cookies to those whose domains match or are subdomains of this one. */ - domain?: string; - /** Optional. Filters the cookies by name. */ - name?: string; - /** Optional. Restricts the retrieved cookies to those that would match the given URL. */ - url?: string; - /** Optional. The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used. */ - storeId?: string; - /** Optional. Filters out session vs. persistent cookies. */ - session?: boolean; - /** Optional. Restricts the retrieved cookies to those whose path exactly matches this string. */ - path?: string; - /** Optional. Filters the cookies by their Secure property. */ - secure?: boolean; - } - - interface SetDetails { - /** Optional. The domain of the cookie. If omitted, the cookie becomes a host-only cookie. */ - domain?: string; - /** Optional. The name of the cookie. Empty by default if omitted. */ - name?: string; - /** The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail. */ - url: string; - /** Optional. The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's cookie store. */ - storeId?: string; - /** Optional. The value of the cookie. Empty by default if omitted. */ - value?: string; - /** Optional. The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie. */ - expirationDate?: number; - /** Optional. The path of the cookie. Defaults to the path portion of the url parameter. */ - path?: string; - /** Optional. Whether the cookie should be marked as HttpOnly. Defaults to false. */ - httpOnly?: boolean; - /** Optional. Whether the cookie should be marked as Secure. Defaults to false. */ - secure?: boolean; - } - - interface Details { - name: string; - url: string; - storeId?: string; - } - - interface CookieChangeInfo { - /** Information about the cookie that was set or removed. */ - cookie: Cookie; - /** True if a cookie was removed. */ - removed: boolean; - /** - * Since Chrome 12. - * The underlying reason behind the cookie's change. - */ - cause: string; - } - - interface CookieChangedEvent extends chrome.events.Event<(changeInfo: CookieChangeInfo) => void> {} - - /** - * Lists all existing cookie stores. - * @param callback The callback parameter should be a function that looks like this: - * function(array of CookieStore cookieStores) {...}; - * Parameter cookieStores: All the existing cookie stores. - */ - export function getAllCookieStores(callback: (cookieStores: CookieStore[]) => void): void; - /** - * Retrieves all cookies from a single cookie store that match the given information. The cookies returned will be sorted, with those with the longest path first. If multiple cookies have the same path length, those with the earliest creation time will be first. - * @param details Information to filter the cookies being retrieved. - * @param callback The callback parameter should be a function that looks like this: - * function(array of Cookie cookies) {...}; - * Parameter cookies: All the existing, unexpired cookies that match the given cookie info. - */ - export function getAll(details: GetAllDetails, callback: (cookies: Cookie[]) => void): void; - /** - * Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. - * @param details Details about the cookie being set. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function( Cookie cookie) {...}; - * Optional parameter cookie: Contains details about the cookie that's been set. If setting failed for any reason, this will be "null", and "chrome.runtime.lastError" will be set. - */ - export function set(details: SetDetails, callback?: (cookie?: Cookie) => void): void; - /** - * Deletes a cookie by name. - * @param details Information to identify the cookie to remove. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(object details) {...}; - */ - export function remove(details: Details, callback?: (details: Details) => void): void; - /** - * Retrieves information about a single cookie. If more than one cookie of the same name exists for the given URL, the one with the longest path will be returned. For cookies with the same path length, the cookie with the earliest creation time will be returned. - * @param details Details to identify the cookie being retrieved. - * @param callback The callback parameter should be a function that looks like this: - * function( Cookie cookie) {...}; - * Parameter cookie: Contains details about the cookie. This parameter is null if no such cookie was found. - */ - export function get(details: Details, callback: (cookie?: Cookie) => void): void; - - /** Fired when a cookie is set or removed. As a special case, note that updating a cookie's properties is implemented as a two step process: the cookie to be updated is first removed entirely, generating a notification with "cause" of "overwrite" . Afterwards, a new cookie is written with the updated values, generating a second notification with "cause" "explicit". */ - var onChanged: CookieChangedEvent; -} - -//////////////////// -// Debugger -//////////////////// -/** - * The chrome.debugger API serves as an alternate transport for Chrome's remote debugging protocol. Use chrome.debugger to attach to one or more tabs to instrument network interaction, debug JavaScript, mutate the DOM and CSS, etc. Use the Debuggee tabId to target tabs with sendCommand and route events by tabId from onEvent callbacks. - * Availability: Since Chrome 18. - * Permissions: "debugger" - */ -declare module "chrome.debugger" { - /** Debuggee identifier. Either tabId or extensionId must be specified */ - interface Debuggee { - /** Optional. The id of the tab which you intend to debug. */ - tabId?: number; - /** - * Optional. - * Since Chrome 27. - * The id of the extension which you intend to debug. Attaching to an extension background page is only possible when 'silent-debugger-extension-api' flag is enabled on the target browser. - */ - extensionId?: string; - /** - * Optional. - * Since Chrome 28. - * The opaque id of the debug target. - */ - targetId?: string; - } - - /** - * Since Chrome 28. - * Debug target information - */ - interface TargetInfo { - /** Target type. */ - type: string; - /** Target id. */ - id: string; - /** - * Optional. - * Since Chrome 30. - * The tab id, defined if type == 'page'. - */ - tabId?: number; - /** - * Optional. - * Since Chrome 30. - * The extension id, defined if type = 'background_page'. - */ - extensionId?: string; - /** True if debugger is already attached. */ - attached: boolean; - /** Target page title. */ - title: string; - /** Target URL. */ - url: string; - /** Optional. Target favicon URL. */ - faviconUrl?: string; - } - - interface DebuggerDetachedEvent extends chrome.events.Event<(source: Debuggee, reason: string) => void> {} - - interface DebuggerEventEvent extends chrome.events.Event<(source: Debuggee, method: string, params?: Object) => void> {} - - /** - * Attaches debugger to the given target. - * @param target Debugging target to which you want to attach. - * @param requiredVersion Required debugging protocol version ("0.1"). One can only attach to the debuggee with matching major version and greater or equal minor version. List of the protocol versions can be obtained in the documentation pages. - * @param callback Called once the attach operation succeeds or fails. Callback receives no arguments. If the attach fails, runtime.lastError will be set to the error message. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function attach(target: Debuggee, requiredVersion: string, callback?: () => void): void; - /** - * Detaches debugger from the given target. - * @param target Debugging target from which you want to detach. - * @param callback Called once the detach operation succeeds or fails. Callback receives no arguments. If the detach fails, runtime.lastError will be set to the error message. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function detach(target: Debuggee, callback?: () => void): void; - /** - * Sends given command to the debugging target. - * @param target Debugging target to which you want to send the command. - * @param method Method name. Should be one of the methods defined by the remote debugging protocol. - * @param commandParams Since Chrome 22. - * JSON object with request parameters. This object must conform to the remote debugging params scheme for given method. - * @param callback Response body. If an error occurs while posting the message, the callback will be called with no arguments and runtime.lastError will be set to the error message. - * If you specify the callback parameter, it should be a function that looks like this: - * function(object result) {...}; - */ - export function sendCommand(target: Debuggee, method: string, commandParams?: Object, callback?: (result?: Object) => void): void; - /** - * Since Chrome 28. - * Returns the list of available debug targets. - * @param callback The callback parameter should be a function that looks like this: - * function(array of TargetInfo result) {...}; - * Parameter result: Array of TargetInfo objects corresponding to the available debug targets. - */ - export function getTargets(callback: (result: TargetInfo[]) => void): void; - - /** Fired when browser terminates debugging session for the tab. This happens when either the tab is being closed or Chrome DevTools is being invoked for the attached tab. */ - var onDetach: DebuggerDetachedEvent; - /** Fired whenever debugging target issues instrumentation event. */ - var onEvent: DebuggerEventEvent; -} - -//////////////////// -// Declarative Content -//////////////////// -/** - * Use the chrome.declarativeContent API to take actions depending on the content of a page, without requiring permission to read the page's content. - * Availability: Since Chrome 33. - * Permissions: "declarativeContent" - */ -declare namespace chrome.declarativeContent { - interface PageStateUrlDetails { - /** Optional. Matches if the host name of the URL contains a specified string. To test whether a host name component has a prefix 'foo', use hostContains: '.foo'. This matches 'www.foobar.com' and 'foo.com', because an implicit dot is added at the beginning of the host name. Similarly, hostContains can be used to match against component suffix ('foo.') and to exactly match against components ('.foo.'). Suffix- and exact-matching for the last components need to be done separately using hostSuffix, because no implicit dot is added at the end of the host name. */ - hostContains?: string; - /** Optional. Matches if the host name of the URL is equal to a specified string. */ - hostEquals?: string; - /** Optional. Matches if the host name of the URL starts with a specified string. */ - hostPrefix?: string; - /** Optional. Matches if the host name of the URL ends with a specified string. */ - hostSuffix?: string; - /** Optional. Matches if the path segment of the URL contains a specified string. */ - pathContains?: string; - /** Optional. Matches if the path segment of the URL is equal to a specified string. */ - pathEquals?: string; - /** Optional. Matches if the path segment of the URL starts with a specified string. */ - pathPrefix?: string; - /** Optional. Matches if the path segment of the URL ends with a specified string. */ - pathSuffix?: string; - /** Optional. Matches if the query segment of the URL contains a specified string. */ - queryContains?: string; - /** Optional. Matches if the query segment of the URL is equal to a specified string. */ - queryEquals?: string; - /** Optional. Matches if the query segment of the URL starts with a specified string. */ - queryPrefix?: string; - /** Optional. Matches if the query segment of the URL ends with a specified string. */ - querySuffix?: string; - /** Optional. Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlContains?: string; - /** Optional. Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlEquals?: string; - /** Optional. Matches if the URL (without fragment identifier) matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. */ - urlMatches?: string; - /** Optional. Matches if the URL without query segment and fragment identifier matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. */ - originAndPathMatches?: string; - /** Optional. Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlPrefix?: string; - /** Optional. Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlSuffix?: string; - /** Optional. Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ - schemes?: string[]; - /** Optional. Matches if the port of the URL is contained in any of the specified port lists. For example [80, 443, [1000, 1200]] matches all requests on port 80, 443 and in the range 1000-1200. */ - ports?: (number | number[])[]; - } - - /** Matches the state of a web page by various criteria. */ - interface PageStateMatcher { - /** Optional. Filters URLs for various criteria. See event filtering. All criteria are case sensitive. */ - pageUrl?: PageStateUrlDetails; - /** Optional. Matches if all of the CSS selectors in the array match displayed elements in a frame with the same origin as the page's main frame. All selectors in this array must be compound selectors to speed up matching. Note that listing hundreds of CSS selectors or CSS selectors that match hundreds of times per page can still slow down web sites. */ - css?: string[]; - /** - * Optional. - * Since Chrome 45. Warning: this is the current Beta channel. More information available on the API documentation pages. - * Matches if the bookmarked state of the page is equal to the specified value. Requres the bookmarks permission. - */ - isBookmarked?: boolean; - } -} - -//////////////////// -// Declarative Web Request -//////////////////// -declare namespace chrome.declarativeWebRequest { - interface HeaderFilter { - nameEquals?: string; - valueContains?: any; - nameSuffix?: string; - valueSuffix?: string; - valuePrefix?: string; - nameContains?: any; - valueEquals?: string; - namePrefix?: string; - } - - interface AddResponseHeader { - name: string; - value: string; - } - - interface RemoveResponseCookie { - filter: ResponseCookie; - } - - interface RemoveResponseHeader { - name: string; - value?: string; - } - - interface RequestMatcher { - contentType?: string[]; - url?: chrome.events.UrlFilter; - excludeContentType?: string[]; - excludeResponseHeader?: HeaderFilter[]; - resourceType?: string; - responseHeaders?: HeaderFilter[]; - } - - interface IgnoreRules { - lowerPriorityThan: number; - } - - interface RedirectToEmptyDocument { } - - interface RedirectRequest { - redirectUrl: string; - } - - interface ResponseCookie { - domain?: string; - name?: string; - expires?: string; - maxAge?: number; - value?: string; - path?: string; - httpOnly?: string; - secure?: string; - } - - interface AddResponseCookie { - cookie: ResponseCookie; - } - - interface EditResponseCookie { - filter: ResponseCookie; - modification: ResponseCookie; - } - - interface CancelRequest { } - - interface RemoveRequestHeader { - name: string; - } - - interface EditRequestCookie { - filter: RequestCookie; - modification: RequestCookie; - } - - interface SetRequestHeader { - name: string; - value: string; - } - - interface RequestCookie { - name?: string; - value?: string; - } - - interface RedirectByRegEx { - to: string; - from: string; - } - - interface RedirectToTransparentImage { } - - interface AddRequestCookie { - cookie: RequestCookie; - } - - interface RemoveRequestCookie { - filter: RequestCookie; - } - - interface RequestedEvent extends chrome.events.Event {} - - var onRequest: RequestedEvent; -} - -//////////////////// -// DesktopCapture -//////////////////// -/** - * Desktop Capture API that can be used to capture content of screen, individual windows or tabs. - * Availability: Since Chrome 34. - * Permissions: "desktopCapture" - */ -declare namespace chrome.desktopCapture { - /** - * Shows desktop media picker UI with the specified set of sources. - * @param sources Set of sources that should be shown to the user. - * @param callback The callback parameter should be a function that looks like this: - * function(string streamId) {...}; - * Parameter streamId: An opaque string that can be passed to getUserMedia() API to generate media stream that corresponds to the source selected by the user. If user didn't select any source (i.e. canceled the prompt) then the callback is called with an empty streamId. The created streamId can be used only once and expires after a few seconds when it is not used. - */ - export function chooseDesktopMedia(sources: string[], callback: (streamId: string) => void): number; - /** - * Shows desktop media picker UI with the specified set of sources. - * @param sources Set of sources that should be shown to the user. - * @param targetTab Optional tab for which the stream is created. If not specified then the resulting stream can be used only by the calling extension. The stream can only be used by frames in the given tab whose security origin matches tab.url. - * @param callback The callback parameter should be a function that looks like this: - * function(string streamId) {...}; - * Parameter streamId: An opaque string that can be passed to getUserMedia() API to generate media stream that corresponds to the source selected by the user. If user didn't select any source (i.e. canceled the prompt) then the callback is called with an empty streamId. The created streamId can be used only once and expires after a few seconds when it is not used. - */ - export function chooseDesktopMedia(sources: string[], targetTab: chrome.tabs.Tab, callback: (streamId: string) => void): number; - /** - * Hides desktop media picker dialog shown by chooseDesktopMedia(). - * @param desktopMediaRequestId Id returned by chooseDesktopMedia() - */ - export function cancelChooseDesktopMedia(desktopMediaRequestId: number): void; -} - -//////////////////// -// Dev Tools - Inspected Window -//////////////////// -/** - * Use the chrome.devtools.inspectedWindow API to interact with the inspected window: obtain the tab ID for the inspected page, evaluate the code in the context of the inspected window, reload the page, or obtain the list of resources within the page. - * Availability: Since Chrome 18. - */ -declare namespace chrome.devtools.inspectedWindow { - /** A resource within the inspected page, such as a document, a script, or an image. */ - interface Resource { - /** The URL of the resource. */ - url: string; - /** - * Gets the content of the resource. - * @param callback A function that receives resource content when the request completes. - * The callback parameter should be a function that looks like this: - * function(string content, string encoding) {...}; - * Parameter content: Content of the resource (potentially encoded). - * Parameter encoding: Empty if content is not encoded, encoding name otherwise. Currently, only base64 is supported. - */ - getContent(callback: (content: string, encoding: string) => void): void; - /** - * Sets the content of the resource. - * @param content New content of the resource. Only resources with the text type are currently supported. - * @param commit True if the user has finished editing the resource, and the new content of the resource should be persisted; false if this is a minor change sent in progress of the user editing the resource. - * @param callback A function called upon request completion. - * If you specify the callback parameter, it should be a function that looks like this: - * function(object error) {...}; - * Optional parameter error: Set to undefined if the resource content was set successfully; describes error otherwise. - */ - setContent(content: string, commit: boolean, callback?: (error: Object) => void): void; - } - - interface ReloadOptions { - /** Optional. If specified, the string will override the value of the User-Agent HTTP header that's sent while loading the resources of the inspected page. The string will also override the value of the navigator.userAgent property that's returned to any scripts that are running within the inspected page. */ - userAgent?: string; - /** Optional. When true, the loader will ignore the cache for all inspected page resources loaded before the load event is fired. The effect is similar to pressing Ctrl+Shift+R in the inspected window or within the Developer Tools window. */ - ignoreCache?: boolean; - /** Optional. If specified, the script will be injected into every frame of the inspected page immediately upon load, before any of the frame's scripts. The script will not be injected after subsequent reloads—for example, if the user presses Ctrl+R. */ - injectedScript?: boolean; - /** - * Optional. - * If specified, this script evaluates into a function that accepts three string arguments: the source to preprocess, the URL of the source, and a function name if the source is an DOM event handler. The preprocessorerScript function should return a string to be compiled by Chrome in place of the input source. In the case that the source is a DOM event handler, the returned source must compile to a single JS function. - * @deprecated Deprecated since Chrome 41. Please avoid using this parameter, it will be removed soon. - */ - preprocessorScript?: string; - } - - interface EvaluationExceptionInfo { - /** Set if the error occurred on the DevTools side before the expression is evaluated. */ - isError: boolean; - /** Set if the error occurred on the DevTools side before the expression is evaluated. */ - code: string; - /** Set if the error occurred on the DevTools side before the expression is evaluated. */ - description: string; - /** Set if the error occurred on the DevTools side before the expression is evaluated, contains the array of the values that may be substituted into the description string to provide more information about the cause of the error. */ - details: any[]; - /** Set if the evaluated code produces an unhandled exception. */ - isException: boolean; - /** Set if the evaluated code produces an unhandled exception. */ - value: string; - } - - interface ResourceAddedEvent extends chrome.events.Event<(resource: Resource) => void> {} - - interface ResourceContentCommittedEvent extends chrome.events.Event<(resource: Resource, content: string) => void> {} - - /** The ID of the tab being inspected. This ID may be used with chrome.tabs.* API. */ - var tabId: number; - - /** Reloads the inspected page. */ - export function reload(reloadOptions: ReloadOptions): void; - /** - * Evaluates a JavaScript expression in the context of the main frame of the inspected page. The expression must evaluate to a JSON-compliant object, otherwise an exception is thrown. The eval function can report either a DevTools-side error or a JavaScript exception that occurs during evaluation. In either case, the result parameter of the callback is undefined. In the case of a DevTools-side error, the isException parameter is non-null and has isError set to true and code set to an error code. In the case of a JavaScript error, isException is set to true and value is set to the string value of thrown object. - * @param expression An expression to evaluate. - * @param callback A function called when evaluation completes. - * If you specify the callback parameter, it should be a function that looks like this: - * function(object result, object exceptionInfo) {...}; - * Parameter result: The result of evaluation. - * Parameter exceptionInfo: An object providing details if an exception occurred while evaluating the expression. - */ - export function eval(expression: string, callback?: (result: Object, exceptionInfo: EvaluationExceptionInfo) => void): void; - /** - * Retrieves the list of resources from the inspected page. - * @param callback A function that receives the list of resources when the request completes. - * The callback parameter should be a function that looks like this: - * function(array of Resource resources) {...}; - */ - export function getResources(callback: (resources: Resource[]) => void): void; - - /** Fired when a new resource is added to the inspected page. */ - var onResourceAdded: ResourceAddedEvent; - /** Fired when a new revision of the resource is committed (e.g. user saves an edited version of the resource in the Developer Tools). */ - var onResourceContentCommitted: ResourceContentCommittedEvent; -} - -//////////////////// -// Dev Tools - Network -//////////////////// -/** - * Use the chrome.devtools.network API to retrieve the information about network requests displayed by the Developer Tools in the Network panel. - * Availability: Since Chrome 18. - */ -declare namespace chrome.devtools.network { - /** Represents a network request for a document resource (script, image and so on). See HAR Specification for reference. */ - interface Request { - /** - * Returns content of the response body. - * @param callback A function that receives the response body when the request completes. - * The callback parameter should be a function that looks like this: - * function(string content, string encoding) {...}; - * Parameter content: Content of the response body (potentially encoded). - * Parameter encoding: Empty if content is not encoded, encoding name otherwise. Currently, only base64 is supported. - */ - getContent(callback: (content: string, encoding: string) => void): void; - } - - interface RequestFinishedEvent extends chrome.events.Event<(request: Request) => void> {} - - interface NavigatedEvent extends chrome.events.Event<(url: string) => void> {} - - /** - * Returns HAR log that contains all known network requests. - * @param callback A function that receives the HAR log when the request completes. - * The callback parameter should be a function that looks like this: - * function(object harLog) {...}; - * Parameter harLog: A HAR log. See HAR specification for details. - */ - export function getHAR(callback: (harLog: Object) => void): void; - - /** Fired when a network request is finished and all request data are available. */ - var onRequestFinished: RequestFinishedEvent; - /** Fired when the inspected window navigates to a new page. */ - var onNavigated: NavigatedEvent; -} - -//////////////////// -// Dev Tools - Panels -//////////////////// -/** - * Use the chrome.devtools.panels API to integrate your extension into Developer Tools window UI: create your own panels, access existing panels, and add sidebars. - * Availability: Since Chrome 18. - */ -declare namespace chrome.devtools.panels { - interface PanelShownEvent extends chrome.events.Event<(window: chrome.windows.Window) => void> {} - - interface PanelHiddenEvent extends chrome.events.Event<() => void> {} - - interface PanelSearchEvent extends chrome.events.Event<(action: string, queryString?: string) => void> {} - - /** Represents a panel created by extension. */ - interface ExtensionPanel { - /** - * Appends a button to the status bar of the panel. - * @param iconPath Path to the icon of the button. The file should contain a 64x24-pixel image composed of two 32x24 icons. The left icon is used when the button is inactive; the right icon is displayed when the button is pressed. - * @param tooltipText Text shown as a tooltip when user hovers the mouse over the button. - * @param disabled Whether the button is disabled. - */ - createStatusBarButton(iconPath: string, tooltipText: string, disabled: boolean): Button; - /** Fired when the user switches to the panel. */ - onShown: PanelShownEvent; - /** Fired when the user switches away from the panel. */ - onHidden: PanelHiddenEvent; - /** Fired upon a search action (start of a new search, search result navigation, or search being canceled). */ - onSearch: PanelSearchEvent; - } - - interface ButtonClickedEvent extends chrome.events.Event<() => void> {} - - /** A button created by the extension. */ - interface Button { - /** - * Updates the attributes of the button. If some of the arguments are omitted or null, the corresponding attributes are not updated. - * @param iconPath Path to the new icon of the button. - * @param tooltipText Text shown as a tooltip when user hovers the mouse over the button. - * @param disabled Whether the button is disabled. - */ - update(iconPath?: string, tooltipText?: string, disabled?: boolean): void; - /** Fired when the button is clicked. */ - onClicked: ButtonClickedEvent; - } - - interface SelectionChangedEvent extends chrome.events.Event<() => void> {} - - /** Represents the Elements panel. */ - interface ElementsPanel { - /** - * Creates a pane within panel's sidebar. - * @param title Text that is displayed in sidebar caption. - * @param callback A callback invoked when the sidebar is created. - * If you specify the callback parameter, it should be a function that looks like this: - * function( ExtensionSidebarPane result) {...}; - * Parameter result: An ExtensionSidebarPane object for created sidebar pane. - */ - createSidebarPane(title: string, callback?: (result: ExtensionSidebarPane) => void): void; - /** Fired when an object is selected in the panel. */ - onSelectionChanged: SelectionChangedEvent; - } - - /** - * Since Chrome 41. - * Represents the Sources panel. - */ - interface SourcesPanel { - /** - * Creates a pane within panel's sidebar. - * @param title Text that is displayed in sidebar caption. - * @param callback A callback invoked when the sidebar is created. - * If you specify the callback parameter, it should be a function that looks like this: - * function( ExtensionSidebarPane result) {...}; - * Parameter result: An ExtensionSidebarPane object for created sidebar pane. - */ - createSidebarPane(title: string, callback?: (result: ExtensionSidebarPane) => void): void; - /** Fired when an object is selected in the panel. */ - onSelectionChanged: SelectionChangedEvent; - } - - interface ExtensionSidebarPaneShownEvent extends chrome.events.Event<(window: chrome.windows.Window) => void> {} - - interface ExtensionSidebarPaneHiddenEvent extends chrome.events.Event<() => void> {} - - /** A sidebar created by the extension. */ - interface ExtensionSidebarPane { - /** - * Sets the height of the sidebar. - * @param height A CSS-like size specification, such as '100px' or '12ex'. - */ - setHeight(height: string): void; - /** - * Sets an expression that is evaluated within the inspected page. The result is displayed in the sidebar pane. - * @param expression An expression to be evaluated in context of the inspected page. JavaScript objects and DOM nodes are displayed in an expandable tree similar to the console/watch. - * @param rootTitle An optional title for the root of the expression tree. - * @param callback A callback invoked after the sidebar pane is updated with the expression evaluation results. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - setExpression(expression: string, rootTitle?: string, callback?: () => void): void; - /** - * Sets an expression that is evaluated within the inspected page. The result is displayed in the sidebar pane. - * @param expression An expression to be evaluated in context of the inspected page. JavaScript objects and DOM nodes are displayed in an expandable tree similar to the console/watch. - * @param callback A callback invoked after the sidebar pane is updated with the expression evaluation results. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - setExpression(expression: string, callback?: () => void): void; - /** - * Sets a JSON-compliant object to be displayed in the sidebar pane. - * @param jsonObject An object to be displayed in context of the inspected page. Evaluated in the context of the caller (API client). - * @param rootTitle An optional title for the root of the expression tree. - * @param callback A callback invoked after the sidebar is updated with the object. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - setObject(jsonObject: string, rootTitle?: string, callback?: () => void): void; - /** - * Sets a JSON-compliant object to be displayed in the sidebar pane. - * @param jsonObject An object to be displayed in context of the inspected page. Evaluated in the context of the caller (API client). - * @param callback A callback invoked after the sidebar is updated with the object. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - setObject(jsonObject: string, callback?: () => void): void; - /** - * Sets an HTML page to be displayed in the sidebar pane. - * @param path Relative path of an extension page to display within the sidebar. - */ - setPage(path: string): void; - /** Fired when the sidebar pane becomes visible as a result of user switching to the panel that hosts it. */ - onShown: ExtensionSidebarPaneShownEvent; - /** Fired when the sidebar pane becomes hidden as a result of the user switching away from the panel that hosts the sidebar pane. */ - onHidden: ExtensionSidebarPaneHiddenEvent; - } - - /** Elements panel. */ - var elements: ElementsPanel; - /** - * Since Chrome 38. - * Sources panel. - */ - var sources: SourcesPanel; - - /** - * Creates an extension panel. - * @param title Title that is displayed next to the extension icon in the Developer Tools toolbar. - * @param iconPath Path of the panel's icon relative to the extension directory. - * @param pagePath Path of the panel's HTML page relative to the extension directory. - * @param callback A function that is called when the panel is created. - * If you specify the callback parameter, it should be a function that looks like this: - * function( ExtensionPanel panel) {...}; - * Parameter panel: An ExtensionPanel object representing the created panel. - */ - export function create(title: string, iconPath: string, pagePath: string, callback?: (panel: ExtensionPanel) => void): void; - /** - * Specifies the function to be called when the user clicks a resource link in the Developer Tools window. To unset the handler, either call the method with no parameters or pass null as the parameter. - * @param callback A function that is called when the user clicks on a valid resource link in Developer Tools window. Note that if the user clicks an invalid URL or an XHR, this function is not called. - * If you specify the callback parameter, it should be a function that looks like this: - * function( devtools.inspectedWindow.Resource resource) {...}; - * Parameter resource: A devtools.inspectedWindow.Resource object for the resource that was clicked. - */ - export function setOpenResourceHandler(callback?: (resource: chrome.devtools.inspectedWindow.Resource) => void): void; - /** - * Since Chrome 38. - * Requests DevTools to open a URL in a Developer Tools panel. - * @param url The URL of the resource to open. - * @param lineNumber Specifies the line number to scroll to when the resource is loaded. - * @param callback A function that is called when the resource has been successfully loaded. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function openResource(url: string, lineNumber: number, callback: () => void): void; -} - -//////////////////// -// Document Scan -//////////////////// -/** - * Use the chrome.documentScan API to discover and retrieve images from attached paper document scanners. - * Availability: Since Chrome 44. - * Permissions: "documentScan" - * Important: This API works only on Chrome OS. - */ -declare namespace chrome.documentScan { - interface DocumentScanOptions { - /** Optional. The MIME types that are accepted by the caller. */ - mimeTypes?: string[]; - /** Optional. The number of scanned images allowed (defaults to 1). */ - maxImages?: number; - } - - interface DocumentScanCallbackArg { - /** The data image URLs in a form that can be passed as the "src" value to an image tag. */ - dataUrls: string[]; - /** The MIME type of dataUrls. */ - mimeType: string; - } - - /** - * Performs a document scan. On success, the PNG data will be sent to the callback. - * @param options Object containing scan parameters. - * @param callback Called with the result and data from the scan. - * The callback parameter should be a function that looks like this: - * function(object result) {...}; - */ - export function scan(options: DocumentScanOptions, callback: (result: DocumentScanCallbackArg) => void): void; -} - -//////////////////// -// Dev Tools - Downloads -//////////////////// -/** - * Use the chrome.downloads API to programmatically initiate, monitor, manipulate, and search for downloads. - * Availability: Since Chrome 31. - * Permissions: "downloads" - */ -declare namespace chrome.downloads { - interface HeaderNameValuePair { - /** Name of the HTTP header. */ - name: string; - /** Value of the HTTP header. */ - value: string; - } - - interface DownloadOptions { - /** Optional. Post body. */ - body?: string; - /** Optional. Use a file-chooser to allow the user to select a filename regardless of whether filename is set or already exists. */ - saveAs?: boolean; - /** The URL to download. */ - url: string; - /** Optional. A file path relative to the Downloads directory to contain the downloaded file, possibly containing subdirectories. Absolute paths, empty paths, and paths containing back-references ".." will cause an error. onDeterminingFilename allows suggesting a filename after the file's MIME type and a tentative filename have been determined. */ - filename?: string; - /** Optional. Extra HTTP headers to send with the request if the URL uses the HTTP[s] protocol. Each header is represented as a dictionary containing the keys name and either value or binaryValue, restricted to those allowed by XMLHttpRequest. */ - headers?: HeaderNameValuePair[]; - /** Optional. The HTTP method to use if the URL uses the HTTP[S] protocol. */ - method?: string; - /** Optional. The action to take if filename already exists. */ - conflictAction?: string; - } - - interface DownloadDelta { - /** Optional. The change in danger, if any. */ - danger?: StringDelta; - /** Optional. The change in url, if any. */ - url?: StringDelta; - /** Optional. The change in totalBytes, if any. */ - totalBytes?: DoubleDelta; - /** Optional. The change in filename, if any. */ - filename?: StringDelta; - /** Optional. The change in paused, if any. */ - paused?: BooleanDelta; - /** Optional. The change in state, if any. */ - state?: StringDelta; - /** Optional. The change in mime, if any. */ - mime?: StringDelta; - /** Optional. The change in fileSize, if any. */ - fileSize?: DoubleDelta; - /** Optional. The change in startTime, if any. */ - startTime?: DoubleDelta; - /** Optional. The change in error, if any. */ - error?: StringDelta; - /** Optional. The change in endTime, if any. */ - endTime?: DoubleDelta; - /** The id of the DownloadItem that changed. */ - id: number; - /** Optional. The change in canResume, if any. */ - canResume?: BooleanDelta; - /** Optional. The change in exists, if any. */ - exists?: BooleanDelta; - } - - interface BooleanDelta { - current?: boolean; - previous?: boolean; - } - - /** Since Chrome 34. */ - interface DoubleDelta { - current?: number; - previous?: number; - } - - interface StringDelta { - current?: string; - previous?: string; - } - - interface DownloadItem { - /** Number of bytes received so far from the host, without considering file compression. */ - bytesReceived: number; - /** Indication of whether this download is thought to be safe or known to be suspicious. */ - danger: string; - /** Absolute URL. */ - url: string; - /** Number of bytes in the whole file, without considering file compression, or -1 if unknown. */ - totalBytes: number; - /** Absolute local path. */ - filename: string; - /** True if the download has stopped reading data from the host, but kept the connection open. */ - paused: boolean; - /** Indicates whether the download is progressing, interrupted, or complete. */ - state: string; - /** The file's MIME type. */ - mime: string; - /** Number of bytes in the whole file post-decompression, or -1 if unknown. */ - fileSize: number; - /** The time when the download began in ISO 8601 format. May be passed directly to the Date constructor: chrome.downloads.search({}, function(items){items.forEach(function(item){console.log(new Date(item.startTime))})}) */ - startTime: string; - /** Optional. Why the download was interrupted. Several kinds of HTTP errors may be grouped under one of the errors beginning with SERVER_. Errors relating to the network begin with NETWORK_, errors relating to the process of writing the file to the file system begin with FILE_, and interruptions initiated by the user begin with USER_. */ - error?: string; - /** Optional. The time when the download ended in ISO 8601 format. May be passed directly to the Date constructor: chrome.downloads.search({}, function(items){items.forEach(function(item){if (item.endTime) console.log(new Date(item.endTime))})}) */ - endTime?: string; - /** An identifier that is persistent across browser sessions. */ - id: number; - /** False if this download is recorded in the history, true if it is not recorded. */ - incognito: boolean; - /** Absolute URL. */ - referrer: string; - /** Optional. Estimated time when the download will complete in ISO 8601 format. May be passed directly to the Date constructor: chrome.downloads.search({}, function(items){items.forEach(function(item){if (item.estimatedEndTime) console.log(new Date(item.estimatedEndTime))})}) */ - estimatedEndTime?: string; - /** True if the download is in progress and paused, or else if it is interrupted and can be resumed starting from where it was interrupted. */ - canResume: boolean; - /** Whether the downloaded file still exists. This information may be out of date because Chrome does not automatically watch for file removal. Call search() in order to trigger the check for file existence. When the existence check completes, if the file has been deleted, then an onChanged event will fire. Note that search() does not wait for the existence check to finish before returning, so results from search() may not accurately reflect the file system. Also, search() may be called as often as necessary, but will not check for file existence any more frequently than once every 10 seconds. */ - exists: boolean; - /** Optional. The identifier for the extension that initiated this download if this download was initiated by an extension. Does not change once it is set. */ - byExtensionId?: string; - /** Optional. The localized name of the extension that initiated this download if this download was initiated by an extension. May change if the extension changes its name or if the user changes their locale. */ - byExtensionName?: string; - } - - interface GetFileIconOptions { - /** Optional. * The size of the returned icon. The icon will be square with dimensions size * size pixels. The default and largest size for the icon is 32x32 pixels. The only supported sizes are 16 and 32. It is an error to specify any other size. - */ - size?: number; - } - - interface DownloadQuery { - /** Optional. Set elements of this array to DownloadItem properties in order to sort search results. For example, setting orderBy=['startTime'] sorts the DownloadItem by their start time in ascending order. To specify descending order, prefix with a hyphen: '-startTime'. */ - orderBy?: string[]; - /** Optional. Limits results to DownloadItem whose url matches the given regular expression. */ - urlRegex?: string; - /** Optional. Limits results to DownloadItem that ended before the given ms since the epoch. */ - endedBefore?: number; - /** Optional. Limits results to DownloadItem whose totalBytes is greater than the given integer. */ - totalBytesGreater?: number; - /** Optional. Indication of whether this download is thought to be safe or known to be suspicious. */ - danger?: string; - /** Optional. Number of bytes in the whole file, without considering file compression, or -1 if unknown. */ - totalBytes?: number; - /** Optional. True if the download has stopped reading data from the host, but kept the connection open. */ - paused?: boolean; - /** Optional. Limits results to DownloadItem whose filename matches the given regular expression. */ - filenameRegex?: string; - /** Optional. This array of search terms limits results to DownloadItem whose filename or url contain all of the search terms that do not begin with a dash '-' and none of the search terms that do begin with a dash. */ - query?: string[]; - /** Optional. Limits results to DownloadItem whose totalBytes is less than the given integer. */ - totalBytesLess?: number; - /** Optional. The id of the DownloadItem to query. */ - id?: number; - /** Optional. Number of bytes received so far from the host, without considering file compression. */ - bytesReceived?: number; - /** Optional. Limits results to DownloadItem that ended after the given ms since the epoch. */ - endedAfter?: number; - /** Optional. Absolute local path. */ - filename?: string; - /** Optional. Indicates whether the download is progressing, interrupted, or complete. */ - state?: string; - /** Optional. Limits results to DownloadItem that started after the given ms since the epoch. */ - startedAfter?: number; - /** Optional. The file's MIME type. */ - mime?: string; - /** Optional. Number of bytes in the whole file post-decompression, or -1 if unknown. */ - fileSize?: number; - /** Optional. The time when the download began in ISO 8601 format. */ - startTime?: number; - /** Optional. Absolute URL. */ - url?: string; - /** Optional. Limits results to DownloadItem that started before the given ms since the epoch. */ - startedBefore?: number; - /** Optional. The maximum number of matching DownloadItem returned. Defaults to 1000. Set to 0 in order to return all matching DownloadItem. See search for how to page through results. */ - limit?: number; - /** Optional. Why a download was interrupted. */ - error?: number; - /** Optional. The time when the download ended in ISO 8601 format. */ - endTime?: number; - /** Optional. Whether the downloaded file exists; */ - exists?: boolean; - } - - interface DownloadFilenameSuggestion { - /** The DownloadItem's new target DownloadItem.filename, as a path relative to the user's default Downloads directory, possibly containing subdirectories. Absolute paths, empty paths, and paths containing back-references ".." will be ignored. */ - filename: string; - /** Optional. The action to take if filename already exists. */ - conflictAction?: string; - } - - interface DownloadChangedEvent extends chrome.events.Event<(downloadDelta: DownloadDelta) => void> {} - - interface DownloadCreatedEvent extends chrome.events.Event<(downloadItem: DownloadItem) => void> {} - - interface DownloadErasedEvent extends chrome.events.Event<(downloadId: number) => void> {} - - interface DownloadDeterminingFilenameEvent extends chrome.events.Event<(downloadItem: DownloadItem, suggest: (suggestion?: DownloadFilenameSuggestion) => void) => void> {} - - /** - * Find DownloadItem. Set query to the empty object to get all DownloadItem. To get a specific DownloadItem, set only the id field. To page through a large number of items, set orderBy: ['-startTime'], set limit to the number of items per page, and set startedAfter to the startTime of the last item from the last page. - * @param callback The callback parameter should be a function that looks like this: - * function(array of DownloadItem results) {...}; - */ - export function search(query: DownloadQuery, callback: (results: DownloadItem[]) => void): void; - /** - * Pause the download. If the request was successful the download is in a paused state. Otherwise runtime.lastError contains an error message. The request will fail if the download is not active. - * @param downloadId The id of the download to pause. - * @param callback Called when the pause request is completed. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function pause(downloadId: number, callback?: () => void): void; - /** - * Retrieve an icon for the specified download. For new downloads, file icons are available after the onCreated event has been received. The image returned by this function while a download is in progress may be different from the image returned after the download is complete. Icon retrieval is done by querying the underlying operating system or toolkit depending on the platform. The icon that is returned will therefore depend on a number of factors including state of the download, platform, registered file types and visual theme. If a file icon cannot be determined, runtime.lastError will contain an error message. - * @param downloadId The identifier for the download. - * @param callback A URL to an image that represents the download. - * The callback parameter should be a function that looks like this: - * function(string iconURL) {...}; - */ - export function getFileIcon(downloadId: number, callback: (iconURL: string) => void): void; - /** - * Retrieve an icon for the specified download. For new downloads, file icons are available after the onCreated event has been received. The image returned by this function while a download is in progress may be different from the image returned after the download is complete. Icon retrieval is done by querying the underlying operating system or toolkit depending on the platform. The icon that is returned will therefore depend on a number of factors including state of the download, platform, registered file types and visual theme. If a file icon cannot be determined, runtime.lastError will contain an error message. - * @param downloadId The identifier for the download. - * @param callback A URL to an image that represents the download. - * The callback parameter should be a function that looks like this: - * function(string iconURL) {...}; - */ - export function getFileIcon(downloadId: number, options: GetFileIconOptions, callback: (iconURL: string) => void): void; - /** - * Resume a paused download. If the request was successful the download is in progress and unpaused. Otherwise runtime.lastError contains an error message. The request will fail if the download is not active. - * @param downloadId The id of the download to resume. - * @param callback Called when the resume request is completed. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function resume(downloadId: number, callback?: () => void): void; - /** - * Cancel a download. When callback is run, the download is cancelled, completed, interrupted or doesn't exist anymore. - * @param downloadId The id of the download to cancel. - * @param callback Called when the cancel request is completed. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function cancel(downloadId: number, callback?: () => void): void; - /** - * Download a URL. If the URL uses the HTTP[S] protocol, then the request will include all cookies currently set for its hostname. If both filename and saveAs are specified, then the Save As dialog will be displayed, pre-populated with the specified filename. If the download started successfully, callback will be called with the new DownloadItem's downloadId. If there was an error starting the download, then callback will be called with downloadId=undefined and runtime.lastError will contain a descriptive string. The error strings are not guaranteed to remain backwards compatible between releases. Extensions must not parse it. - * @param options What to download and how. - * @param callback Called with the id of the new DownloadItem. - * If you specify the callback parameter, it should be a function that looks like this: - * function(integer downloadId) {...}; - */ - export function download(options: DownloadOptions, callback?: (downloadId: number) => void): void; - /** - * Open the downloaded file now if the DownloadItem is complete; otherwise returns an error through runtime.lastError. Requires the "downloads.open" permission in addition to the "downloads" permission. An onChanged event will fire when the item is opened for the first time. - * @param downloadId The identifier for the downloaded file. - */ - export function open(downloadId: number): void; - /** - * Show the downloaded file in its folder in a file manager. - * @param downloadId The identifier for the downloaded file. - */ - export function show(downloadId: number): void; - /** Show the default Downloads folder in a file manager. */ - export function showDefaultFolder(): void; - /** - * Erase matching DownloadItem from history without deleting the downloaded file. An onErased event will fire for each DownloadItem that matches query, then callback will be called. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(array of integer erasedIds) {...}; - */ - export function erase(query: DownloadQuery, callback: (erasedIds: number[]) => void): void; - /** - * Remove the downloaded file if it exists and the DownloadItem is complete; otherwise return an error through runtime.lastError. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeFile(downloadId: number, callback?: () => void): void; - /** - * Prompt the user to accept a dangerous download. Can only be called from a visible context (tab, window, or page/browser action popup). Does not automatically accept dangerous downloads. If the download is accepted, then an onChanged event will fire, otherwise nothing will happen. When all the data is fetched into a temporary file and either the download is not dangerous or the danger has been accepted, then the temporary file is renamed to the target filename, the |state| changes to 'complete', and onChanged fires. - * @param downloadId The identifier for the DownloadItem. - * @param callback Called when the danger prompt dialog closes. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function acceptDanger(downloadId: number, callback: () => void): void; - /** Initiate dragging the downloaded file to another application. Call in a javascript ondragstart handler. */ - export function drag(downloadId: number): void; - /** Enable or disable the gray shelf at the bottom of every window associated with the current browser profile. The shelf will be disabled as long as at least one extension has disabled it. Enabling the shelf while at least one other extension has disabled it will return an error through runtime.lastError. Requires the "downloads.shelf" permission in addition to the "downloads" permission. */ - export function setShelfEnabled(enabled: boolean): void; - - /** When any of a DownloadItem's properties except bytesReceived and estimatedEndTime changes, this event fires with the downloadId and an object containing the properties that changed. */ - var onChanged: DownloadChangedEvent; - /** This event fires with the DownloadItem object when a download begins. */ - var onCreated: DownloadCreatedEvent; - /** Fires with the downloadId when a download is erased from history. */ - var onErased: DownloadErasedEvent; - /** During the filename determination process, extensions will be given the opportunity to override the target DownloadItem.filename. Each extension may not register more than one listener for this event. Each listener must call suggest exactly once, either synchronously or asynchronously. If the listener calls suggest asynchronously, then it must return true. If the listener neither calls suggest synchronously nor returns true, then suggest will be called automatically. The DownloadItem will not complete until all listeners have called suggest. Listeners may call suggest without any arguments in order to allow the download to use downloadItem.filename for its filename, or pass a suggestion object to suggest in order to override the target filename. If more than one extension overrides the filename, then the last extension installed whose listener passes a suggestion object to suggest wins. In order to avoid confusion regarding which extension will win, users should not install extensions that may conflict. If the download is initiated by download and the target filename is known before the MIME type and tentative filename have been determined, pass filename to download instead. */ - var onDeterminingFilename: DownloadDeterminingFilenameEvent; -} - -//////////////////// -// Enterprise Platform Keys -//////////////////// -/** - * Use the chrome.enterprise.platformKeys API to generate hardware-backed keys and to install certificates for these keys. The certificates will be managed by the platform and can be used for TLS authentication, network access or by other extension through chrome.platformKeys. - * Availability: Since Chrome 37. - * Permissions: "enterprise.platformKeys" - * Important: This API works only on Chrome OS. - * Note: This API is only for extensions pre-installed by policy. - */ -declare namespace chrome.enterprise.platformKeys { - interface Token { - /** - * Uniquely identifies this Token. - * Static IDs are "user" and "system", referring to the platform's user-specific and the system-wide hardware token, respectively. Any other tokens (with other identifiers) might be returned by enterprise.platformKeys.getTokens. - */ - id: string; - /** - * Implements the WebCrypto's SubtleCrypto interface. The cryptographic operations, including key generation, are hardware-backed. - * Only non-extractable RSASSA-PKCS1-V1_5 keys with modulusLength up to 2048 can be generated. Each key can be used for signing data at most once. - * Keys generated on a specific Token cannot be used with any other Tokens, nor can they be used with window.crypto.subtle. Equally, Key objects created with window.crypto.subtle cannot be used with this interface. - */ - subtleCrypto: SubtleCrypto; - } - - /** - * Returns the available Tokens. In a regular user's session the list will always contain the user's token with id "user". If a system-wide TPM token is available, the returned list will also contain the system-wide token with id "system". The system-wide token will be the same for all sessions on this device (device in the sense of e.g. a Chromebook). - * @param callback Invoked by getTokens with the list of available Tokens. - * The callback parameter should be a function that looks like this: - * function(array of Token tokens) {...}; - * Parameter tokens: The list of available tokens. - */ - export function getToken(callback: (tokens: Token[]) => void): void; - /** - * Returns the list of all client certificates available from the given token. Can be used to check for the existence and expiration of client certificates that are usable for a certain authentication. - * @param tokenId The id of a Token returned by getTokens. - * @param callback Called back with the list of the available certificates. - * The callback parameter should be a function that looks like this: - * function(array of ArrayBuffer certificates) {...}; - * Parameter certificates: The list of certificates, each in DER encoding of a X.509 certificate. - */ - export function getCertificates(tokenId: string, callback: (certificates: ArrayBuffer) => void): void; - /** - * Imports certificate to the given token if the certified key is already stored in this token. After a successful certification request, this function should be used to store the obtained certificate and to make it available to the operating system and browser for authentication. - * @param tokenId The id of a Token returned by getTokens. - * @param certificate The DER encoding of a X.509 certificate. - * @param callback Called back when this operation is finished. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function importCertificate(tokenId: string, certificate: ArrayBuffer, callback?: () => void): void; - /** - * Removes certificate from the given token if present. Should be used to remove obsolete certificates so that they are not considered during authentication and do not clutter the certificate choice. Should be used to free storage in the certificate store. - * @param tokenId The id of a Token returned by getTokens. - * @param certificate The DER encoding of a X.509 certificate. - * @param callback Called back when this operation is finished. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeCertificate(tokenId: string, certificate: ArrayBuffer, callback?: () => void): void; -} - -//////////////////// -// Events -//////////////////// -/** - * The chrome.events namespace contains common types used by APIs dispatching events to notify you when something interesting happens. - * Availability: Since Chrome 21. - */ -declare namespace chrome.events { - /** Filters URLs for various criteria. See event filtering. All criteria are case sensitive. */ - interface UrlFilter { - /** Optional. Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ - schemes?: string[]; - /** - * Optional. - * Since Chrome 23. - * Matches if the URL (without fragment identifier) matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. - */ - urlMatches?: string; - /** Optional. Matches if the path segment of the URL contains a specified string. */ - pathContains?: string; - /** Optional. Matches if the host name of the URL ends with a specified string. */ - hostSuffix?: string; - /** Optional. Matches if the host name of the URL starts with a specified string. */ - hostPrefix?: string; - /** Optional. Matches if the host name of the URL contains a specified string. To test whether a host name component has a prefix 'foo', use hostContains: '.foo'. This matches 'www.foobar.com' and 'foo.com', because an implicit dot is added at the beginning of the host name. Similarly, hostContains can be used to match against component suffix ('foo.') and to exactly match against components ('.foo.'). Suffix- and exact-matching for the last components need to be done separately using hostSuffix, because no implicit dot is added at the end of the host name. */ - hostContains?: string; - /** Optional. Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlContains?: string; - /** Optional. Matches if the query segment of the URL ends with a specified string. */ - querySuffix?: string; - /** Optional. Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlPrefix?: string; - /** Optional. Matches if the host name of the URL is equal to a specified string. */ - hostEquals?: string; - /** Optional. Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlEquals?: string; - /** Optional. Matches if the query segment of the URL contains a specified string. */ - queryContains?: string; - /** Optional. Matches if the path segment of the URL starts with a specified string. */ - pathPrefix?: string; - /** Optional. Matches if the path segment of the URL is equal to a specified string. */ - pathEquals?: string; - /** Optional. Matches if the path segment of the URL ends with a specified string. */ - pathSuffix?: string; - /** Optional. Matches if the query segment of the URL is equal to a specified string. */ - queryEquals?: string; - /** Optional. Matches if the query segment of the URL starts with a specified string. */ - queryPrefix?: string; - /** Optional. Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlSuffix?: string; - /** Optional. Matches if the port of the URL is contained in any of the specified port lists. For example [80, 443, [1000, 1200]] matches all requests on port 80, 443 and in the range 1000-1200. */ - ports?: any[]; - /** - * Optional. - * Since Chrome 28. - * Matches if the URL without query segment and fragment identifier matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. - */ - originAndPathMatches?: string; - } - - /** An object which allows the addition and removal of listeners for a Chrome event. */ - interface Event { - /** - * Registers an event listener callback to an event. - * @param callback Called when an event occurs. The parameters of this function depend on the type of event. - * The callback parameter should be a function that looks like this: - * function() {...}; - */ - addListener(callback: T): void; - /** - * Returns currently registered rules. - * @param callback Called with registered rules. - * The callback parameter should be a function that looks like this: - * function(array of Rule rules) {...}; - * Parameter rules: Rules that were registered, the optional parameters are filled with values. - */ - getRules(callback: (rules: Rule[]) => void): void; - /** - * Returns currently registered rules. - * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are returned. - * @param callback Called with registered rules. - * The callback parameter should be a function that looks like this: - * function(array of Rule rules) {...}; - * Parameter rules: Rules that were registered, the optional parameters are filled with values. - */ - getRules(ruleIdentifiers: string[], callback: (rules: Rule[]) => void): void; - /** - * @param callback Listener whose registration status shall be tested. - */ - hasListener(callback: T): boolean; - /** - * Unregisters currently registered rules. - * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are unregistered. - * @param callback Called when rules were unregistered. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - removeRules(ruleIdentifiers?: string[], callback?: () => void): void; - /** - * Unregisters currently registered rules. - * @param callback Called when rules were unregistered. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - removeRules(callback?: () => void): void; - /** - * Registers rules to handle events. - * @param rules Rules to be registered. These do not replace previously registered rules. - * @param callback Called with registered rules. - * If you specify the callback parameter, it should be a function that looks like this: - * function(array of Rule rules) {...}; - * Parameter rules: Rules that were registered, the optional parameters are filled with values. - */ - addRules(rules: Rule[], callback?: (rules: Rule[]) => void): void; - /** - * Deregisters an event listener callback from an event. - * @param callback Listener that shall be unregistered. - * The callback parameter should be a function that looks like this: - * function() {...}; - */ - removeListener(callback: T): void; - hasListeners(): boolean; - } - - /** Description of a declarative rule for handling events. */ - interface Rule { - /** Optional. Optional priority of this rule. Defaults to 100. */ - priority?: number; - /** List of conditions that can trigger the actions. */ - conditions: any[]; - /** Optional. Optional identifier that allows referencing this rule. */ - id?: string; - /** List of actions that are triggered if one of the condtions is fulfilled. */ - actions: any[]; - /** - * Optional. - * Since Chrome 28. - * Tags can be used to annotate rules and perform operations on sets of rules. - */ - tags?: string[]; - } -} - -//////////////////// -// Extension -//////////////////// -/** - * The chrome.extension API has utilities that can be used by any extension page. It includes support for exchanging messages between an extension and its content scripts or between extensions, as described in detail in Message Passing. - * Availability: Since Chrome 5. - */ -declare namespace chrome.extension { - interface FetchProperties { - /** Optional. The window to restrict the search to. If omitted, returns all views. */ - windowId?: number; - /** Optional. The type of view to get. If omitted, returns all views (including background pages and tabs). Valid values: 'tab', 'notification', 'popup'. */ - type?: string; - } - - interface LastError { - /** Description of the error that has taken place. */ - message: string; - } - - interface OnRequestEvent extends chrome.events.Event<((request: any, sender: runtime.MessageSender, sendResponse: (response: any) => void) => void) | ((sender: runtime.MessageSender, sendResponse: (response: any) => void) => void)> {} - - /** - * Since Chrome 7. - * True for content scripts running inside incognito tabs, and for extension pages running inside an incognito process. The latter only applies to extensions with 'split' incognito_behavior. - */ - var inIncognitoContext: boolean; - /** Set for the lifetime of a callback if an ansychronous extension api has resulted in an error. If no error has occured lastError will be undefined. */ - var lastError: LastError; - - /** Returns the JavaScript 'window' object for the background page running inside the current extension. Returns null if the extension has no background page. */ - export function getBackgroundPage(): Window; - /** - * Converts a relative path within an extension install directory to a fully-qualified URL. - * @param path A path to a resource within an extension expressed relative to its install directory. - */ - export function getURL(path: string): string; - /** - * Sets the value of the ap CGI parameter used in the extension's update URL. This value is ignored for extensions that are hosted in the Chrome Extension Gallery. - * Since Chrome 9. - */ - export function setUpdateUrlData(data: string): void; - /** Returns an array of the JavaScript 'window' objects for each of the pages running inside the current extension. */ - export function getViews(fetchProperties?: FetchProperties): Window[]; - /** - * Retrieves the state of the extension's access to the 'file://' scheme (as determined by the user-controlled 'Allow access to File URLs' checkbox. - * Since Chrome 12. - * @param callback The callback parameter should be a function that looks like this: - * function(boolean isAllowedAccess) {...}; - * Parameter isAllowedAccess: True if the extension can access the 'file://' scheme, false otherwise. - */ - export function isAllowedFileSchemeAccess(callback: (isAllowedAccess: boolean) => void): void; - /** - * Retrieves the state of the extension's access to Incognito-mode (as determined by the user-controlled 'Allowed in Incognito' checkbox. - * Since Chrome 12. - * @param callback The callback parameter should be a function that looks like this: - * function(boolean isAllowedAccess) {...}; - * Parameter isAllowedAccess: True if the extension has access to Incognito mode, false otherwise. - */ - export function isAllowedIncognitoAccess(callback: (isAllowedAccess: boolean) => void): void; - /** - * Sends a single request to other listeners within the extension. Similar to runtime.connect, but only sends a single request with an optional response. The extension.onRequest event is fired in each page of the extension. - * @deprecated Deprecated since Chrome 33. Please use runtime.sendMessage. - * @param extensionId The extension ID of the extension you want to connect to. If omitted, default is your own extension. - * @param responseCallback If you specify the responseCallback parameter, it should be a function that looks like this: - * function(any response) {...}; - * Parameter response: The JSON response object sent by the handler of the request. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. - */ - export function sendRequest(extensionId: string, request: any, responseCallback?: (response: any) => void): void; - /** - * Sends a single request to other listeners within the extension. Similar to runtime.connect, but only sends a single request with an optional response. The extension.onRequest event is fired in each page of the extension. - * @deprecated Deprecated since Chrome 33. Please use runtime.sendMessage. - * @param responseCallback If you specify the responseCallback parameter, it should be a function that looks like this: - * function(any response) {...}; - * Parameter response: The JSON response object sent by the handler of the request. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. - */ - export function sendRequest(request: any, responseCallback?: (response: any) => void): void; - /** - * Returns an array of the JavaScript 'window' objects for each of the tabs running inside the current extension. If windowId is specified, returns only the 'window' objects of tabs attached to the specified window. - * @deprecated Deprecated since Chrome 33. Please use extension.getViews {type: "tab"}. - */ - export function getExtensionTabs(windowId?: number): Window[]; - - /** - * Fired when a request is sent from either an extension process or a content script. - * @deprecated Deprecated since Chrome 33. Please use runtime.onMessage. - */ - var onRequest: OnRequestEvent; - /** - * Fired when a request is sent from another extension. - * @deprecated Deprecated since Chrome 33. Please use runtime.onMessageExternal. - */ - var onRequestExternal: OnRequestEvent; -} - -//////////////////// -// File Browser Handler -//////////////////// -/** - * Use the chrome.fileBrowserHandler API to extend the Chrome OS file browser. For example, you can use this API to enable users to upload files to your website. - * Availability: Since Chrome 12. - * Permissions: "fileBrowserHandler" - * Important: This API works only on Chrome OS. - */ -declare namespace chrome.fileBrowserHandler { - interface SelectionParams { - /** - * Optional. - * List of file extensions that the selected file can have. The list is also used to specify what files to be shown in the select file dialog. Files with the listed extensions are only shown in the dialog. Extensions should not include the leading '.'. Example: ['jpg', 'png'] - * Since Chrome 23. - */ - allowedFileExtensions?: string[]; - /** Suggested name for the file. */ - suggestedName: string; - } - - interface SelectionResult { - /** Optional. Selected file entry. It will be null if a file hasn't been selected. */ - entry?: Object; - /** Whether the file has been selected. */ - success: boolean; - } - - /** Event details payload for fileBrowserHandler.onExecute event. */ - interface FileHandlerExecuteEventDetails { - /** Optional. The ID of the tab that raised this event. Tab IDs are unique within a browser session. */ - tab_id?: number; - /** Array of Entry instances representing files that are targets of this action (selected in ChromeOS file browser). */ - entries: any[]; - } - - interface FileBrowserHandlerExecuteEvent extends chrome.events.Event<(id: string, details: FileHandlerExecuteEventDetails) => void> {} - - /** - * Prompts user to select file path under which file should be saved. When the file is selected, file access permission required to use the file (read, write and create) are granted to the caller. The file will not actually get created during the function call, so function caller must ensure its existence before using it. The function has to be invoked with a user gesture. - * Since Chrome 21. - * @param selectionParams Parameters that will be used while selecting the file. - * @param callback Function called upon completion. - * The callback parameter should be a function that looks like this: - * function(object result) {...}; - * Parameter result: Result of the method. - */ - export function selectFile(selectionParams: SelectionParams, callback: (result: SelectionResult) => void): void; - - /** Fired when file system action is executed from ChromeOS file browser. */ - var onExecute: FileBrowserHandlerExecuteEvent; -} - -//////////////////// -// File System Provider -//////////////////// -/** - * Use the chrome.fileSystemProvider API to create file systems, that can be accessible from the file manager on Chrome OS. - * Availability: Since Chrome 40. - * Permissions: "fileSystemProvider" - * Important: This API works only on Chrome OS. - */ -declare namespace chrome.fileSystemProvider { - interface OpenedFileInfo { - /** A request ID to be be used by consecutive read/write and close requests. */ - openRequestId: number; - /** The path of the opened file. */ - filePath: string; - /** Whether the file was opened for reading or writing. */ - mode: string; - } - - interface FileWatchersInfo { - /** The path of the entry being observed. */ - entryPath: string; - /** Whether watching should include all child entries recursively. It can be true for directories only. */ - recursive: boolean; - /** Optional. Tag used by the last notification for the watcher. */ - lastTag?: string; - } - - interface EntryMetadata { - /** True if it is a directory. */ - isDirectory: boolean; - /** Name of this entry (not full path name). Must not contain '/'. For root it must be empty. */ - name: string; - /** File size in bytes. */ - size: number; - /** The last modified time of this entry. */ - modificationTime: Date; - /** Optional. Mime type for the entry. */ - mimeType?: string; - /** Optional. Thumbnail image as a data URI in either PNG, JPEG or WEBP format, at most 32 KB in size. Optional, but can be provided only when explicitly requested by the onGetMetadataRequested event. */ - thumbnail?: string; - } - - interface FileSystemInfo { - /** The identifier of the file system. */ - fileSystemId: string; - /** A human-readable name for the file system. */ - displayName: string; - /** Whether the file system supports operations which may change contents of the file system (such as creating, deleting or writing to files). */ - writable: boolean; - /** - * The maximum number of files that can be opened at once. If 0, then not limited. - * @since Since Chrome 42. - */ - openedFilesLimit: number; - /** - * List of currently opened files. - * @since Since Chrome 42. - */ - openedFiles: OpenedFileInfo[]; - /** - * Optional. - * Whether the file system supports the tag field for observing directories. - * @since Since Chrome 45. Warning: this is the current Beta channel. - */ - supportsNotifyTag?: boolean; - /** - * List of watchers. - * @since Since Chrome 45. Warning: this is the current Beta channel. - */ - watchers: FileWatchersInfo[]; - } - - /** @since Since Chrome 45. Warning: this is the current Beta channel. */ - interface GetActionsRequestedOptions { - /** The identifier of the file system related to this operation. */ - fileSystemId: string; - /** The unique identifier of this request. */ - requestId: number; - /** The path of the entry to return the list of actions for. */ - entryPath: string; - } - - /** @since Since Chrome 45. Warning: this is the current Beta channel. */ - interface Action { - /** The identifier of the action. Any string or CommonActionId for common actions. */ - id: string; - /** Optional. The title of the action. It may be ignored for common actions. */ - title?: string; - } - - /** @since Since Chrome 45. Warning: this is the current Beta channel. */ - interface ExecuteActionRequestedOptions { - /** The identifier of the file system related to this operation. */ - fileSystemId: string; - /** The unique identifier of this request. */ - requestId: number; - /** The path of the entry to be used for the action. */ - entryPath: string; - /** The identifier of the action to be executed. */ - actionId: string; - } - - interface MountOptions { - /** The string indentifier of the file system. Must be unique per each extension. */ - fileSystemId: string; - /** A human-readable name for the file system. */ - displayName: string; - /** Optional. Whether the file system supports operations which may change contents of the file system (such as creating, deleting or writing to files). */ - writable?: boolean; - /** - * Optional. - * The maximum number of files that can be opened at once. If not specified, or 0, then not limited. - * @since Since Chrome 41. - */ - openedFilesLimit?: number; - /** - * Optional. - * Whether the file system supports the tag field for observed directories. - * @since Since Chrome 45. Warning: this is the current Beta channel. - */ - supportsNotifyTag?: boolean; - } - - interface UnmountOptions { - /** The identifier of the file system to be unmounted. */ - fileSystemId: string; - } - - interface NotificationChange { - /** The path of the changed entry. */ - entryPath: string; - /** The type of the change which happened to the entry. */ - changeType: string; - } - - interface NotificationOptions { - /** The identifier of the file system related to this change. */ - fileSystemId: string; - /** The path of the observed entry. */ - observedPath: string; - /** Mode of the observed entry. */ - recursive: boolean; - /** The type of the change which happened to the observed entry. If it is DELETED, then the observed entry will be automatically removed from the list of observed entries. */ - changeType: string; - /** Optional. List of changes to entries within the observed directory (including the entry itself) */ - changes?: NotificationChange[]; - /** Optional. Tag for the notification. Required if the file system was mounted with the supportsNotifyTag option. Note, that this flag is necessary to provide notifications about changes which changed even when the system was shutdown. */ - tag?: string; - } - - interface RequestedEventOptions { - /** The identifier of the file system related to this operation. */ - fileSystemId: string; - /** The unique identifier of this request. */ - requestId: number; - } - - interface EntryPathRequestedEventOptions extends RequestedEventOptions { - /** The path of the entry to which this operation is related to. */ - entryPath: string; - } - - interface MetadataRequestedEventOptions extends EntryPathRequestedEventOptions { - /** Set to true if the thumbnail is requested. */ - thumbnail: boolean; - } - - interface DirectoryPathRequestedEventOptions extends RequestedEventOptions { - /** The path of the directory which is to be operated on. */ - directoryPath: string; - } - - interface FilePathRequestedEventOptions extends RequestedEventOptions { - /** The path of the entry for the operation */ - filePath: string; - } - - interface OpenFileRequestedEventOptions extends FilePathRequestedEventOptions { - /** Whether the file will be used for reading or writing. */ - mode: string; - } - - interface OpenedFileRequestedEventOptions extends RequestedEventOptions { - /** A request ID used to open the file. */ - openRequestId: number; - } - - interface OpenedFileOffsetRequestedEventOptions extends OpenedFileRequestedEventOptions { - /** Position in the file (in bytes) to start reading from. */ - offset: number; - /** Number of bytes to be returned. */ - length: number; - } - - interface DirectoryPathRecursiveRequestedEventOptions extends DirectoryPathRequestedEventOptions { - /** Whether the operation is recursive (for directories only). */ - recursive: boolean; - } - - interface EntryPathRecursiveRequestedEventOptions extends EntryPathRequestedEventOptions { - /** Whether the operation is recursive (for directories only). */ - recursive: boolean; - } - - interface SourceTargetPathRequestedEventOptions extends RequestedEventOptions { - /** The source path for the operation. */ - sourcePath: string; - /** The destination path for the operation. */ - targetPath: string; - } - - interface FilePathLengthRequestedEventOptions extends FilePathRequestedEventOptions { - /** Number of bytes to be retained after the operation completes. */ - length: number; - } - - interface OpenedFileIoRequestedEventOptions extends OpenedFileRequestedEventOptions { - /** Position in the file (in bytes) to start operating from. */ - offset: number; - /** Buffer of bytes to be operated on the file. */ - data: ArrayBuffer; - } - - interface OperationRequestedEventOptions extends RequestedEventOptions { - /** An ID of the request to which this operation is related. */ - operationRequestId: number; - } - - interface RequestedEvent extends chrome.events.Event<(options: RequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - - interface MetadataRequestedEvent extends chrome.events.Event<(options: MetadataRequestedEventOptions, successCallback: (metadata: EntryMetadata) => void, errorCallback: (error: string) => void) => void> {} - - interface DirectoryPathRequestedEvent extends chrome.events.Event<(options: DirectoryPathRequestedEventOptions, successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, errorCallback: (error: string) => void) => void> {} - - interface OpenFileRequestedEvent extends chrome.events.Event<(options: OpenFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - - interface OpenedFileRequestedEvent extends chrome.events.Event<(options: OpenedFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - - interface OpenedFileOffsetRequestedEvent extends chrome.events.Event<(options: OpenedFileOffsetRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, errorCallback: (error: string) => void) => void> {} - - interface DirectoryPathRecursiveRequestedEvent extends chrome.events.Event<(options: DirectoryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - - interface EntryPathRecursiveRequestedEvent extends chrome.events.Event<(options: EntryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - - interface FilePathRequestedEvent extends chrome.events.Event<(options: FilePathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - - interface SourceTargetPathRequestedEvent extends chrome.events.Event<(options: SourceTargetPathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - - interface FilePathLengthRequestedEvent extends chrome.events.Event<(options: FilePathLengthRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - - interface OpenedFileIoRequestedEvent extends chrome.events.Event<(options: OpenedFileIoRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - - interface OperationRequestedEvent extends chrome.events.Event<(options: OperationRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> {} - - interface OptionlessRequestedEvent extends chrome.events.Event<(successCallback: Function, errorCallback: (error: string) => void) => void> {} - - /** - * Mounts a file system with the given fileSystemId and displayName. displayName will be shown in the left panel of Files.app. displayName can contain any characters including '/', but cannot be an empty string. displayName must be descriptive but doesn't have to be unique. The fileSystemId must not be an empty string. - * Depending on the type of the file system being mounted, the source option must be set appropriately. - * In case of an error, runtime.lastError will be set with a corresponding error code. - * @param callback A generic result callback to indicate success or failure. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function mount(options: MountOptions, callback?: () => void): void; - /** - * Unmounts a file system with the given fileSystemId. It must be called after onUnmountRequested is invoked. Also, the providing extension can decide to perform unmounting if not requested (eg. in case of lost connection, or a file error). - * In case of an error, runtime.lastError will be set with a corresponding error code. - * @param callback A generic result callback to indicate success or failure. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function unmount(options: UnmountOptions, callback?: () => void): void; - /** - * Returns all file systems mounted by the extension. - * @param callback Callback to receive the result of getAll function. - * The callback parameter should be a function that looks like this: - * function(array of FileSystemInfo fileSystems) {...}; - */ - export function getAll(callback: (fileSystems: FileSystemInfo[]) => void): void; - /** - * Returns information about a file system with the passed fileSystemId. - * @since Since Chrome 42. - * @param callback Callback to receive the result of get function. - * The callback parameter should be a function that looks like this: - * function(FileSystemInfo fileSystem) {...}; - */ - export function get(fileSystemId: string, callback: (fileSystem: FileSystemInfo) => void): void; - /** - * Notifies about changes in the watched directory at observedPath in recursive mode. If the file system is mounted with supportsNofityTag, then tag must be provided, and all changes since the last notification always reported, even if the system was shutdown. The last tag can be obtained with getAll. - * To use, the file_system_provider.notify manifest option must be set to true. - * Value of tag can be any string which is unique per call, so it's possible to identify the last registered notification. Eg. if the providing extension starts after a reboot, and the last registered notification's tag is equal to "123", then it should call notify for all changes which happened since the change tagged as "123". It cannot be an empty string. - * Not all providers are able to provide a tag, but if the file system has a changelog, then the tag can be eg. a change number, or a revision number. - * Note that if a parent directory is removed, then all descendant entries are also removed, and if they are watched, then the API must be notified about the fact. Also, if a directory is renamed, then all descendant entries are in fact removed, as there is no entry under their original paths anymore. - * In case of an error, runtime.lastError will be set will a corresponding error code. - * @param callback A generic result callback to indicate success or failure. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function notify(options: NotificationOptions, callback: () => void): void; - - /** Raised when unmounting for the file system with the fileSystemId identifier is requested. In the response, the unmount API method must be called together with successCallback. If unmounting is not possible (eg. due to a pending operation), then errorCallback must be called. */ - var onUnmountRequested: RequestedEvent; - /** Raised when metadata of a file or a directory at entryPath is requested. The metadata must be returned with the successCallback call. In case of an error, errorCallback must be called. */ - var onGetMetadataRequested: MetadataRequestedEvent; - /** Raised when contents of a directory at directoryPath are requested. The results must be returned in chunks by calling the successCallback several times. In case of an error, errorCallback must be called. */ - var onReadDirectoryRequested: DirectoryPathRequestedEvent; - /** Raised when opening a file at filePath is requested. If the file does not exist, then the operation must fail. Maximum number of files opened at once can be specified with MountOptions. */ - var onOpenFileRequested: OpenFileRequestedEvent; - /** Raised when opening a file previously opened with openRequestId is requested to be closed. */ - var onCloseFileRequested: OpenedFileRequestedEvent; - /** Raised when reading contents of a file opened previously with openRequestId is requested. The results must be returned in chunks by calling successCallback several times. In case of an error, errorCallback must be called. */ - var onReadFileRequested: OpenedFileOffsetRequestedEvent; - /** Raised when creating a directory is requested. The operation must fail with the EXISTS error if the target directory already exists. If recursive is true, then all of the missing directories on the directory path must be created. */ - var onCreateDirectoryRequested: DirectoryPathRecursiveRequestedEvent; - /** Raised when deleting an entry is requested. If recursive is true, and the entry is a directory, then all of the entries inside must be recursively deleted as well. */ - var onDeleteEntryRequested: EntryPathRecursiveRequestedEvent; - /** Raised when creating a file is requested. If the file already exists, then errorCallback must be called with the "EXISTS" error code. */ - var onCreateFileRequested: FilePathRequestedEvent; - /** Raised when copying an entry (recursively if a directory) is requested. If an error occurs, then errorCallback must be called. */ - var onCopyEntryRequested: SourceTargetPathRequestedEvent; - /** Raised when moving an entry (recursively if a directory) is requested. If an error occurs, then errorCallback must be called. */ - var onMoveEntryRequested: SourceTargetPathRequestedEvent; - /** Raised when truncating a file to a desired length is requested. If an error occurs, then errorCallback must be called. */ - var onTruncateRequested: FilePathLengthRequestedEvent; - /** Raised when writing contents to a file opened previously with openRequestId is requested. */ - var onWriteFileRequested: OpenedFileIoRequestedEvent; - /** Raised when aborting an operation with operationRequestId is requested. The operation executed with operationRequestId must be immediately stopped and successCallback of this abort request executed. If aborting fails, then errorCallback must be called. Note, that callbacks of the aborted operation must not be called, as they will be ignored. Despite calling errorCallback, the request may be forcibly aborted. */ - var onAbortRequested: OperationRequestedEvent; - /** - * Raised when showing a configuration dialog for fileSystemId is requested. If it's handled, the file_system_provider.configurable manfiest option must be set to true. - * @since Since Chrome 44. - */ - var onConfigureRequested: RequestedEvent; - /** - * Raised when showing a dialog for mounting a new file system is requested. If the extension/app is a file handler, then this event shouldn't be handled. Instead app.runtime.onLaunched should be handled in order to mount new file systems when a file is opened. For multiple mounts, the file_system_provider.multiple_mounts manifest option must be set to true. - * @since Since Chrome 44. - */ - var onMountRequested: OptionlessRequestedEvent; - /** - * Raised when setting a new directory watcher is requested. If an error occurs, then errorCallback must be called. - * @since Since Chrome 45. Warning: this is the current Beta channel. - */ - var onAddWatcherRequested: EntryPathRecursiveRequestedEvent; - /** - * Raised when the watcher should be removed. If an error occurs, then errorCallback must be called. - * @since Since Chrome 45. Warning: this is the current Beta channel. - */ - var onRemoveWatcherRequested: EntryPathRecursiveRequestedEvent; -} - -//////////////////// -// Font Settings -//////////////////// -/** - * Use the chrome.fontSettings API to manage Chrome's font settings. - * Availability: Since Chrome 22. - * Permissions: "fontSettings" - */ -declare namespace chrome.fontSettings { - /** Represents a font name. */ - interface FontName { - /** The display name of the font. */ - displayName: string; - /** The font ID. */ - fontId: string; - } - - interface DefaultFontSizeDetails { - /** The font size in pixels. */ - pixelSize: number; - } - - interface FontDetails { - /** The generic font family for the font. */ - genericFamily: string; - /** Optional. The script for the font. If omitted, the global script font setting is affected. */ - script?: string; - } - - interface FullFontDetails { - /** The generic font family for which the font setting has changed. */ - genericFamily: string; - /** The level of control this extension has over the setting. */ - levelOfControl: string; - /** Optional. The script code for which the font setting has changed. */ - script?: string; - /** The font ID. See the description in getFont. */ - fontId: string; - } - - interface FontDetailsResult { - /** The level of control this extension has over the setting. */ - levelOfControl: string; - /** The font ID. Rather than the literal font ID preference value, this may be the ID of the font that the system resolves the preference value to. So, fontId can differ from the font passed to setFont, if, for example, the font is not available on the system. The empty string signifies fallback to the global script font setting. */ - fontId: string; - } - - interface FontSizeDetails { - /** The font size in pixels. */ - pixelSize: number; - /** The level of control this extension has over the setting. */ - levelOfControl: string; - } - - interface SetFontSizeDetails { - /** The font size in pixels. */ - pixelSize: number; - } - - interface SetFontDetails extends FontDetails { - /** The font ID. The empty string means to fallback to the global script font setting. */ - fontId: string; - } - - interface DefaultFixedFontSizeChangedEvent extends chrome.events.Event<(details: FontSizeDetails) => void> {} - - interface DefaultFontSizeChangedEvent extends chrome.events.Event<(details: FontSizeDetails) => void> {} - - interface MinimumFontSizeChangedEvent extends chrome.events.Event<(details: FontSizeDetails) => void> {} - - interface FontChangedEvent extends chrome.events.Event<(details: FullFontDetails) => void> {} - - /** - * Sets the default font size. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function setDefaultFontSize(details: DefaultFontSizeDetails, callback?: Function): void; - /** - * Gets the font for a given script and generic font family. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(object details) {...}; - */ - export function getFont(details: FontDetails, callback?: (details: FontDetailsResult) => void): void; - /** - * Gets the default font size. - * @param details This parameter is currently unused. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(object details) {...}; - */ - export function getDefaultFontSize(details?: Object, callback?: (options: FontSizeDetails) => void): void; - /** - * Gets the minimum font size. - * @param details This parameter is currently unused. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(object details) {...}; - */ - export function getMinimumFontSize(details?: FontSizeDetails, callback?: (options: FontSizeDetails) => void): void; - /** - * Sets the minimum font size. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function setMinimumFontSize(details: SetFontSizeDetails, callback?: Function): void; - /** - * Gets the default size for fixed width fonts. - * @param details This parameter is currently unused. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(object details) {...}; - */ - export function getDefaultFixedFontSize(details?: Object, callback?: (details: FontSizeDetails) => void): void; - /** - * Clears the default font size set by this extension, if any. - * @param details This parameter is currently unused. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function clearDefaultFontSize(details?: Object, callback?: Function): void; - /** - * Sets the default size for fixed width fonts. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function setDefaultFixedFontSize(details: SetFontSizeDetails, callback?: Function): void; - /** - * Clears the font set by this extension, if any. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function clearFont(details: FontDetails, callback?: Function): void; - /** - * Sets the font for a given script and generic font family. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(object details) {...}; - */ - export function setFont(details: SetFontDetails, callback?: Function): void; - /** - * Clears the minimum font size set by this extension, if any. - * @param details This parameter is currently unused. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function clearMinimumFontSize(details?: Object, callback?: Function): void; - /** - * Gets a list of fonts on the system. - * @param callback The callback parameter should be a function that looks like this: - * function(array of FontName results) {...}; - */ - export function getFontList(callback: (results: FontName[]) => void): void; - /** - * Clears the default fixed font size set by this extension, if any. - * @param details This parameter is currently unused. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function clearDefaultFixedFontSize(details: Object, callback?: Function): void; - - /** Fired when the default fixed font size setting changes. */ - var onDefaultFixedFontSizeChanged: DefaultFixedFontSizeChangedEvent; - /** Fired when the default font size setting changes. */ - var onDefaultFontSizeChanged: DefaultFontSizeChangedEvent; - /** Fired when the minimum font size setting changes. */ - var onMinimumFontSizeChanged: MinimumFontSizeChangedEvent; - /** Fired when a font setting changes. */ - var onFontChanged: FontChangedEvent; -} - -//////////////////// -// Google Cloud Messaging -//////////////////// -/** - * Use chrome.gcm to enable apps and extensions to send and receive messages through the Google Cloud Messaging Service. - * Availability: Since Chrome 35. - * Permissions: "gcm" - */ -declare namespace chrome.gcm { - interface OutgoingMessage { - /** The ID of the server to send the message to as assigned by Google API Console. */ - destinationId: string; - /** The ID of the message. It must be unique for each message in scope of the applications. See the Cloud Messaging documentation for advice for picking and handling an ID. */ - messageId: string; - /** Optional. Time-to-live of the message in seconds. If it is not possible to send the message within that time, an onSendError event will be raised. A time-to-live of 0 indicates that the message should be sent immediately or fail if it's not possible. The maximum and a default value of time-to-live is 86400 seconds (1 day). */ - timeToLive?: number; - /** Message data to send to the server. Case-insensitive goog. and google, as well as case-sensitive collapse_key are disallowed as key prefixes. Sum of all key/value pairs should not exceed gcm.MAX_MESSAGE_SIZE. */ - data: Object; - } - - interface IncomingMessage { - /** The message data. */ - data: Object; - /** - * Optional. - * The sender who issued the message. - * @since Since Chrome 41. - */ - from?: string; - /** - * Optional. - * The collapse key of a message. See Collapsible Messages section of Cloud Messaging documentation for details. - */ - collapseKey?: string; - } - - interface GcmError { - /** The error message describing the problem. */ - errorMessage: string; - /** Optional. The ID of the message with this error, if error is related to a specific message. */ - messageId?: string; - /** Additional details related to the error, when available. */ - detail: Object; - } - - interface MessageReceptionEvent extends chrome.events.Event<(message: IncomingMessage) => void> {} - - interface MessageDeletionEvent extends chrome.events.Event<() => void> {} - - interface GcmErrorEvent extends chrome.events.Event<(error: GcmError) => void> {} - - /** The maximum size (in bytes) of all key/value pairs in a message. */ - var MAX_MESSAGE_SIZE: number; - - /** - * Registers the application with GCM. The registration ID will be returned by the callback. If register is called again with the same list of senderIds, the same registration ID will be returned. - * @param senderIds A list of server IDs that are allowed to send messages to the application. It should contain at least one and no more than 100 sender IDs. - * @param callback Function called when registration completes. It should check runtime.lastError for error when registrationId is empty. - * The callback parameter should be a function that looks like this: - * function(string registrationId) {...}; - * Parameter registrationId: A registration ID assigned to the application by the GCM. - */ - export function register(senderIds: string[], callback: (registrationId: string) => void): void; - /** - * Unregisters the application from GCM. - * @param callback A function called after the unregistration completes. Unregistration was successful if runtime.lastError is not set. - * The callback parameter should be a function that looks like this: - * function() {...}; - */ - export function unregister(callback: () => void): void; - /** - * Sends a message according to its contents. - * @param message A message to send to the other party via GCM. - * @param callback A function called after the message is successfully queued for sending. runtime.lastError should be checked, to ensure a message was sent without problems. - * The callback parameter should be a function that looks like this: - * function(string messageId) {...}; - * Parameter messageId: The ID of the message that the callback was issued for. - */ - export function send(message: OutgoingMessage, callback: (messageId: string) => void): void; - - /** Fired when a message is received through GCM. */ - var onMessage: MessageReceptionEvent; - /** Fired when a GCM server had to delete messages sent by an app server to the application. See Messages deleted event section of Cloud Messaging documentation for details on handling this event. */ - var onMessagesDeleted: MessageDeletionEvent; - /** Fired when it was not possible to send a message to the GCM server. */ - var onSendError: GcmErrorEvent; -} - -//////////////////// -// History -//////////////////// -/** - * Use the chrome.history API to interact with the browser's record of visited pages. You can add, remove, and query for URLs in the browser's history. To override the history page with your own version, see Override Pages. - * Availability: Since Chrome 5. - * Permissions: "history" - */ -declare namespace chrome.history { - /** An object encapsulating one visit to a URL. */ - interface VisitItem { - /** The transition type for this visit from its referrer. */ - transition: string; - /** Optional. When this visit occurred, represented in milliseconds since the epoch. */ - visitTime?: number; - /** The unique identifier for this visit. */ - visitId: string; - /** The visit ID of the referrer. */ - referringVisitId: string; - /** The unique identifier for the item. */ - id: string; - } - - /** An object encapsulating one result of a history query. */ - interface HistoryItem { - /** Optional. The number of times the user has navigated to this page by typing in the address. */ - typedCount?: number; - /** Optional. The title of the page when it was last loaded. */ - title?: string; - /** Optional. The URL navigated to by a user. */ - url?: string; - /** Optional. When this page was last loaded, represented in milliseconds since the epoch. */ - lastVisitTime?: number; - /** Optional. The number of times the user has navigated to this page. */ - visitCount?: number; - /** The unique identifier for the item. */ - id: string; - } - - interface HistoryQuery { - /** A free-text query to the history service. Leave empty to retrieve all pages. */ - text: string; - /** Optional. The maximum number of results to retrieve. Defaults to 100. */ - maxResults?: number; - /** Optional. Limit results to those visited after this date, represented in milliseconds since the epoch. */ - startTime?: number; - /** Optional. Limit results to those visited before this date, represented in milliseconds since the epoch. */ - endTime?: number; - } - - interface Url { - /** The URL for the operation. It must be in the format as returned from a call to history.search. */ - url: string; - } - - interface Range { - /** Items added to history before this date, represented in milliseconds since the epoch. */ - endTime: number; - /** Items added to history after this date, represented in milliseconds since the epoch. */ - startTime: number; - } - - interface RemovedResult { - /** True if all history was removed. If true, then urls will be empty. */ - allHistory: boolean; - /** Optional. */ - urls?: string[]; - } - - interface HistoryVisitedEvent extends chrome.events.Event<(result: HistoryItem) => void> {} - - interface HistoryVisitRemovedEvent extends chrome.events.Event<(removed: RemovedResult) => void> {} - - /** - * Searches the history for the last visit time of each page matching the query. - * @param callback The callback parameter should be a function that looks like this: - * function(array of HistoryItem results) {...}; - */ - export function search(query: HistoryQuery, callback: (results: HistoryItem[]) => void): void; - /** - * Adds a URL to the history at the current time with a transition type of "link". - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function addUrl(details: Url, callback?: () => void): void; - /** - * Removes all items within the specified date range from the history. Pages will not be removed from the history unless all visits fall within the range. - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - export function deleteRange(range: Range, callback: () => void): void; - /** - * Deletes all items from the history. - * @param callback The callback parameter should be a function that looks like this: - * function() {...}; - */ - export function deleteAll(callback: () => void): void; - /** - * Retrieves information about visits to a URL. - * @param callback The callback parameter should be a function that looks like this: - * function(array of VisitItem results) {...}; - */ - export function getVisits(details: Url, callback: (results: VisitItem[]) => void): void; - /** - * Removes all occurrences of the given URL from the history. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function deleteUrl(details: Url, callback?: () => void): void; - - /** Fired when a URL is visited, providing the HistoryItem data for that URL. This event fires before the page has loaded. */ - var onVisited: HistoryVisitedEvent; - /** Fired when one or more URLs are removed from the history service. When all visits have been removed the URL is purged from history. */ - var onVisitRemoved: HistoryVisitRemovedEvent; -} - -//////////////////// -// i18n -//////////////////// -/** - * Use the chrome.i18n infrastructure to implement internationalization across your whole app or extension. - * @since Chrome 5. - */ -declare namespace chrome.i18n { - /** - * Gets the accept-languages of the browser. This is different from the locale used by the browser; to get the locale, use i18n.getUILanguage. - * @param callback The callback parameter should be a function that looks like this: - * function(array of string languages) {...}; - * Parameter languages: Array of the accept languages of the browser, such as en-US,en,zh-CN - */ - export function getAcceptLanguages(callback: (languages: string[]) => void): void; - /** - * Gets the localized string for the specified message. If the message is missing, this method returns an empty string (''). If the format of the getMessage() call is wrong — for example, messageName is not a string or the substitutions array has more than 9 elements — this method returns undefined. - * @param messageName The name of the message, as specified in the messages.json file. - * @param substitutions Optional. Up to 9 substitution strings, if the message requires any. - */ - export function getMessage(messageName: string, substitutions?: any): string; - /** - * Gets the browser UI language of the browser. This is different from i18n.getAcceptLanguages which returns the preferred user languages. - * @since Chrome 35. - */ - export function getUILanguage(): string; -} - -//////////////////// -// Identity -//////////////////// -/** - * Use the chrome.identity API to get OAuth2 access tokens. - * Permissions: "identity" - * @since Chrome 29. - */ -declare namespace chrome.identity { - /** @since Chrome 32. */ - interface AccountInfo { - /** A unique identifier for the account. This ID will not change for the lifetime of the account. */ - id: string; - } - - interface TokenDetails { - /** - * Optional. - * Fetching a token may require the user to sign-in to Chrome, or approve the application's requested scopes. If the interactive flag is true, getAuthToken will prompt the user as necessary. When the flag is false or omitted, getAuthToken will return failure any time a prompt would be required. - */ - interactive?: boolean; - /** - * Optional. - * The account ID whose token should be returned. If not specified, the primary account for the profile will be used. - * account is only supported when the "enable-new-profile-management" flag is set. - * @since Chrome 37. - */ - account?: AccountInfo; - /** - * Optional. - * A list of OAuth2 scopes to request. - * When the scopes field is present, it overrides the list of scopes specified in manifest.json. - * @since Chrome 37. - */ - scopes?: string[]; - } - - interface UserInfo { - /** An email address for the user account signed into the current profile. Empty if the user is not signed in or the identity.email manifest permission is not specified. */ - email: string; - /** A unique identifier for the account. This ID will not change for the lifetime of the account. Empty if the user is not signed in or (in M41+) the identity.email manifest permission is not specified. */ - id: string; - } - - interface TokenInformation { - /** The specific token that should be removed from the cache. */ - token: string; - } - - interface WebAuthFlowOptions { - /** The URL that initiates the auth flow. */ - url: string; - /** - * Optional. - * Whether to launch auth flow in interactive mode. - * Since some auth flows may immediately redirect to a result URL, launchWebAuthFlow hides its web view until the first navigation either redirects to the final URL, or finishes loading a page meant to be displayed. - * If the interactive flag is true, the window will be displayed when a page load completes. If the flag is false or omitted, launchWebAuthFlow will return with an error if the initial navigation does not complete the flow. - */ - interactive?: boolean; - } - - interface SignInChangeEvent extends chrome.events.Event<(account: AccountInfo, signedIn: boolean) => void> {} - - /** - * Retrieves a list of AccountInfo objects describing the accounts present on the profile. - * getAccounts is only supported on dev channel. - * Dev channel only. - */ - export function getAccounts(callback: (accounts: AccountInfo[]) => void): void; - /** - * Gets an OAuth2 access token using the client ID and scopes specified in the oauth2 section of manifest.json. - * The Identity API caches access tokens in memory, so it's ok to call getAuthToken non-interactively any time a token is required. The token cache automatically handles expiration. - * For a good user experience it is important interactive token requests are initiated by UI in your app explaining what the authorization is for. Failing to do this will cause your users to get authorization requests, or Chrome sign in screens if they are not signed in, with with no context. In particular, do not use getAuthToken interactively when your app is first launched. - * @param details Token options. - * @param callback Called with an OAuth2 access token as specified by the manifest, or undefined if there was an error. - * If you specify the callback parameter, it should be a function that looks like this: - * function(string token) {...}; - */ - export function getAuthToken(details: TokenDetails, callback?: (token: string) => void): void; - /** - * Retrieves email address and obfuscated gaia id of the user signed into a profile. - * This API is different from identity.getAccounts in two ways. The information returned is available offline, and it only applies to the primary account for the profile. - * @since Chrome 37. - */ - export function getProfileUserInfo(callback: (userInfo: UserInfo) => void): void; - /** - * Removes an OAuth2 access token from the Identity API's token cache. - * If an access token is discovered to be invalid, it should be passed to removeCachedAuthToken to remove it from the cache. The app may then retrieve a fresh token with getAuthToken. - * @param details Token information. - * @param callback Called when the token has been removed from the cache. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function removeCachedAuthToken(details: TokenInformation, callback?: () => void): void; - /** - * Starts an auth flow at the specified URL. - * This method enables auth flows with non-Google identity providers by launching a web view and navigating it to the first URL in the provider's auth flow. When the provider redirects to a URL matching the pattern https://.chromiumapp.org/*, the window will close, and the final redirect URL will be passed to the callback function. - * For a good user experience it is important interactive auth flows are initiated by UI in your app explaining what the authorization is for. Failing to do this will cause your users to get authorization requests with no context. In particular, do not launch an interactive auth flow when your app is first launched. - * @param details WebAuth flow options. - * @param callback Called with the URL redirected back to your application. - * The callback parameter should be a function that looks like this: - * function(string responseUrl) {...}; - */ - export function launchWebAuthFlow(details: WebAuthFlowOptions, callback: (responseUrl?: string) => void): void; - /** - * Generates a redirect URL to be used in launchWebAuthFlow. - * The generated URLs match the pattern https://.chromiumapp.org/*. - * @since Chrome 33. - * @param path Optional. The path appended to the end of the generated URL. - */ - export function getRedirectURL(path?: string): string; - - /** - * Fired when signin state changes for an account on the user's profile. - * @since Chrome 33. - */ - var onSignInChanged: SignInChangeEvent; -} - -//////////////////// -// Idle -//////////////////// -/** - * Use the chrome.idle API to detect when the machine's idle state changes. - * Permissions: "idle" - * @since Chrome 6. - */ -declare namespace chrome.idle { - interface IdleStateChangedEvent extends chrome.events.Event<(newState: string) => void> {} - - /** - * Returns "locked" if the system is locked, "idle" if the user has not generated any input for a specified number of seconds, or "active" otherwise. - * @param detectionIntervalInSeconds The system is considered idle if detectionIntervalInSeconds seconds have elapsed since the last user input detected. - * Since Chrome 25. - * @param callback The callback parameter should be a function that looks like this: - * function( IdleState newState) {...}; - */ - export function queryState(detectionIntervalInSeconds: number, callback: (newState: string) => void): void; - /** - * Sets the interval, in seconds, used to determine when the system is in an idle state for onStateChanged events. The default interval is 60 seconds. - * @since Chrome 25. - * @param intervalInSeconds Threshold, in seconds, used to determine when the system is in an idle state. - */ - export function setDetectionInterval(intervalInSeconds: number): void; - - /** Fired when the system changes to an active, idle or locked state. The event fires with "locked" if the screen is locked or the screensaver activates, "idle" if the system is unlocked and the user has not generated any input for a specified number of seconds, and "active" when the user generates input on an idle system. */ - var onStateChanged: IdleStateChangedEvent; -} - -//////////////////// -// Input - IME -//////////////////// -/** - * Use the chrome.input.ime API to implement a custom IME for Chrome OS. This allows your extension to handle keystrokes, set the composition, and manage the candidate window. - * Permissions: "input" - * @since Chrome 21. - */ -declare namespace chrome.input.ime { - /** See http://www.w3.org/TR/DOM-Level-3-Events/#events-KeyboardEvent */ - interface KeyboardEvent { - /** - * Optional. - * Whether or not the SHIFT key is pressed. - */ - shiftKey?: boolean; - /** - * Optional. - * Whether or not the ALT key is pressed. - */ - altKey?: boolean; - /** The ID of the request. */ - requestId: string; - /** Value of the key being pressed */ - key: string; - /** - * Optional. - * Whether or not the CTRL key is pressed. - */ - ctrlKey?: boolean; - /** One of keyup or keydown. */ - type: string; - /** - * Optional. - * The extension ID of the sender of this keyevent. - * @since Chrome 34. - */ - extensionId?: string; - /** - * Optional. - * Value of the physical key being pressed. The value is not affected by current keyboard layout or modifier state. - * @since Chrome 26. - */ - code: string; - /** - * Optional. - * The deprecated HTML keyCode, which is system- and implementation-dependent numerical code signifying the unmodified identifier associated with the key pressed. - * @since Chrome 37. - */ - keyCode?: number; - /** - * Optional. - * Whether or not the CAPS_LOCK is enabled. - * @since Chrome 29. - */ - capsLock?: boolean; - } - - /** Describes an input Context */ - interface InputContext { - /** This is used to specify targets of text field operations. This ID becomes invalid as soon as onBlur is called. */ - contextID: number; - /** Type of value this text field edits, (Text, Number, URL, etc) */ - type: string; - /** - * Whether the text field wants auto-correct. - * @since Chrome 40. - */ - autoCorrect: boolean; - /** - * Whether the text field wants auto-complete. - * @since Chrome 40. - */ - autoComplete: boolean; - /** - * Whether the text field wants spell-check. - * @since Chrome 40. - */ - spellCheck: boolean; - } - - /** - * A menu item used by an input method to interact with the user from the language menu. - * @since Chrome 30. - */ - interface MenuItem { - /** String that will be passed to callbacks referencing this MenuItem. */ - id: string; - /** Optional. Text displayed in the menu for this item. */ - label?: string; - /** Optional. The type of menu item. */ - style?: string; - /** Optional. Indicates this item is visible. */ - visible?: boolean; - /** Indicates this item should be drawn with a check. */ - checked?: boolean; - /** Indicates this item is enabled. */ - enabled?: boolean; - } - - interface ImeParameters { - /** MenuItems to use. */ - items: MenuItem[]; - /** ID of the engine to use */ - engineID: string; - } - - interface CommitTextParameters { - /** The text to commit */ - text: string; - /** ID of the context where the text will be committed */ - contextID: number; - } - - interface CandidateUsage { - /** The title string of details description. */ - title: string; - /** The body string of detail description. */ - body: string; - } - - interface CandidateTemplate { - /** The candidate */ - candidate: string; - /** The candidate's id */ - id: number; - /** - * Optional. - * The id to add these candidates under - */ - parentId?: number; - /** - * Optional. - * Short string displayed to next to the candidate, often the shortcut key or index - */ - label?: string; - /** - * Optional. - * Additional text describing the candidate - */ - annotation?: string; - /** - * Optional. - * The usage or detail description of word. - */ - usage?: CandidateUsage; - } - - interface CandidatesParameters { - /** ID of the context that owns the candidate window. */ - contextID: number; - /** List of candidates to show in the candidate window */ - candidates: CandidateTemplate[]; - } - - interface CompositionParameterSegment { - /** Index of the character to start this segment at */ - start: number; - /** Index of the character to end this segment after. */ - end: number; - /** The type of the underline to modify this segment. */ - style: string; - } - - interface CompositionParameters { - /** ID of the context where the composition text will be set */ - contextID: number; - /** Text to set */ - text: string; - /** Optional. List of segments and their associated types. */ - segments: CompositionParameterSegment[]; - /** Position in the text of the cursor. */ - cursor: number; - /** Optional. Position in the text that the selection starts at. */ - selectionStart?: number; - /** Optional. Position in the text that the selection ends at. */ - selectionEnd?: number; - } - - interface MenuItemParameters { - items: Object[]; - engineId: string; - } - - interface CandidateWindowParameterProperties { - /** - * Optional. - * True to show the cursor, false to hide it. - */ - cursorVisible?: boolean; - /** - * Optional. - * True if the candidate window should be rendered vertical, false to make it horizontal. - */ - vertical?: boolean; - /** - * Optional. - * The number of candidates to display per page. - */ - pageSize?: number; - /** - * Optional. - * True to display the auxiliary text, false to hide it. - */ - auxiliaryTextVisible?: boolean; - /** - * Optional. - * Text that is shown at the bottom of the candidate window. - */ - auxiliaryText?: string; - /** - * Optional. - * True to show the Candidate window, false to hide it. - */ - visible?: boolean; - /** - * Optional. - * Where to display the candidate window. - * @since Chrome 28. - */ - windowPosition?: string; - } - - interface CandidateWindowParameter { - /** ID of the engine to set properties on. */ - engineID: string; - properties: CandidateWindowParameterProperties; - } - - interface ClearCompositionParameters { - /** ID of the context where the composition will be cleared */ - contextID: number; - } - - interface CursorPositionParameters { - /** ID of the candidate to select. */ - candidateID: number; - /** ID of the context that owns the candidate window. */ - contextID: number; - } - - interface SendKeyEventParameters { - /** ID of the context where the key events will be sent, or zero to send key events to non-input field. */ - contextID: number; - /** Data on the key event. */ - keyData: KeyboardEvent[]; - } - - interface DeleteSurroundingTextParameters { - /** ID of the engine receiving the event. */ - engineID: string; - /** ID of the context where the surrounding text will be deleted. */ - contextID: number; - /** The offset from the caret position where deletion will start. This value can be negative. */ - offset: number; - /** The number of characters to be deleted */ - length: number; - } - - interface SurroundingTextInfo { - /** The text around cursor. */ - text: string; - /** The ending position of the selection. This value indicates caret position if there is no selection. */ - focus: number; - /** The beginning position of the selection. This value indicates caret position if is no selection. */ - anchor: number; - } - - interface BlurEvent extends chrome.events.Event<(contextID: number) => void> {} - - interface CandidateClickedEvent extends chrome.events.Event<(engineID: string, candidateID: number, button: string) => void> {} - - interface KeyEventEvent extends chrome.events.Event<(engineID: string, keyData: KeyboardEvent) => void> {} - - interface DeactivatedEvent extends chrome.events.Event<(engineID: string) => void> {} - - interface InputContextUpdateEvent extends chrome.events.Event<(context: InputContext) => void> {} - - interface ActivateEvent extends chrome.events.Event<(engineID: string, screen: string) => void> {} - - interface FocusEvent extends chrome.events.Event<(context: InputContext) => void> {} - - interface MenuItemActivatedEvent extends chrome.events.Event<(engineID: string, name: string) => void> {} - - interface SurroundingTextChangedEvent extends chrome.events.Event<(engineID: string, surroundingInfo: SurroundingTextInfo) => void> {} - - interface InputResetEvent extends chrome.events.Event<(engineID: string) => void> {} - - /** - * Adds the provided menu items to the language menu when this IME is active. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function setMenuItems(parameters: ImeParameters, callback?: () => void): void; - /** - * Commits the provided text to the current input. - * @param callback Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, chrome.runtime.lastError is set. - * If you specify the callback parameter, it should be a function that looks like this: - * function(boolean success) {...}; - */ - export function commitText(parameters: CommitTextParameters, callback?: (success: boolean) => void): void; - /** - * Sets the current candidate list. This fails if this extension doesn't own the active IME - * @param callback Called when the operation completes. - * If you specify the callback parameter, it should be a function that looks like this: - * function(boolean success) {...}; - */ - export function setCandidates(parameters: CandidatesParameters, callback?: (success: boolean) => void): void; - /** - * Set the current composition. If this extension does not own the active IME, this fails. - * @param callback Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, chrome.runtime.lastError is set. - * If you specify the callback parameter, it should be a function that looks like this: - * function(boolean success) {...}; - */ - export function setComposition(parameters: CompositionParameters, callback?: (success: boolean) => void): void; - /** - * Updates the state of the MenuItems specified - * @param callback Called when the operation completes - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function updateMenuItems(parameters: MenuItemParameters, callback?: () => void): void; - /** - * Sets the properties of the candidate window. This fails if the extension doesn't own the active IME - * @param callback Called when the operation completes. - * If you specify the callback parameter, it should be a function that looks like this: - * function(boolean success) {...}; - */ - export function setCandidateWindowProperties(parameters: CandidateWindowParameter, callback?: (success: boolean) => void): void; - /** - * Clear the current composition. If this extension does not own the active IME, this fails. - * @param callback Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, chrome.runtime.lastError is set. - * If you specify the callback parameter, it should be a function that looks like this: - * function(boolean success) {...}; - */ - export function clearComposition(parameters: ClearCompositionParameters, callback?: (success: boolean) => void): void; - /** - * Set the position of the cursor in the candidate window. This is a no-op if this extension does not own the active IME. - * @param callback Called when the operation completes - * If you specify the callback parameter, it should be a function that looks like this: - * function(boolean success) {...}; - */ - export function setCursorPosition(parameters: CursorPositionParameters, callback?: (success: boolean) => void): void; - /** - * Sends the key events. This function is expected to be used by virtual keyboards. When key(s) on a virtual keyboard is pressed by a user, this function is used to propagate that event to the system. - * @since Chrome 33. - * @param callback Called when the operation completes. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function sendKeyEvents(parameters: SendKeyEventParameters, callback?: () => void): void; - /** - * Hides the input view window, which is popped up automatically by system. If the input view window is already hidden, this function will do nothing. - * @since Chrome 34. - */ - export function hideInputView(): void; - /** - * Deletes the text around the caret. - * @since Chrome 27. - */ - export function deleteSurroundingText(parameters: DeleteSurroundingTextParameters, callback?: () => void): void; - /** - * Indicates that the key event received by onKeyEvent is handled. This should only be called if the onKeyEvent listener is asynchronous. - * @since Chrome 25. - * @param requestId Request id of the event that was handled. This should come from keyEvent.requestId - * @param response True if the keystroke was handled, false if not - */ - export function keyEventHandled(requestId: string, response: boolean): void; - - /** This event is sent when focus leaves a text box. It is sent to all extensions that are listening to this event, and enabled by the user. */ - var onBlur: BlurEvent; - /** This event is sent if this extension owns the active IME. */ - var onCandidateClicked: CandidateClickedEvent; - /** This event is sent if this extension owns the active IME. */ - var onKeyEvent: KeyEventEvent; - /** This event is sent when an IME is deactivated. It signals that the IME will no longer be receiving onKeyPress events. */ - var onDeactivated: DeactivatedEvent; - /** This event is sent when the properties of the current InputContext change, such as the the type. It is sent to all extensions that are listening to this event, and enabled by the user. */ - var onInputContextUpdate: InputContextUpdateEvent; - /** This event is sent when an IME is activated. It signals that the IME will be receiving onKeyPress events. */ - var onActivate: ActivateEvent; - /** This event is sent when focus enters a text box. It is sent to all extensions that are listening to this event, and enabled by the user. */ - var onFocus: FocusEvent; - /** Called when the user selects a menu item */ - var onMenuItemActivated: MenuItemActivatedEvent; - /** - * Called when the editable string around caret is changed or when the caret position is moved. The text length is limited to 100 characters for each back and forth direction. - * @since Chrome 27. - */ - var onSurroundingTextChanged: SurroundingTextChangedEvent; - /** - * This event is sent when chrome terminates ongoing text input session. - * @since Chrome 29. - */ - var onReset: InputResetEvent; -} - -//////////////////// -// Management -//////////////////// -/** - * The chrome.management API provides ways to manage the list of extensions/apps that are installed and running. It is particularly useful for extensions that override the built-in New Tab page. - * Permissions: "management" - * @since Chrome 8. - */ -declare namespace chrome.management { - /** Information about an installed extension, app, or theme. */ - interface ExtensionInfo { - /** - * Optional. - * A reason the item is disabled. - * @since Chrome 17. - */ - disabledReason?: string; - /** Optional. The launch url (only present for apps). */ - appLaunchUrl?: string; - /** - * The description of this extension, app, or theme. - * @since Chrome 9. - */ - description: string; - /** - * Returns a list of API based permissions. - * @since Chrome 9. - */ - permissions: string[]; - /** - * Optional. - * A list of icon information. Note that this just reflects what was declared in the manifest, and the actual image at that url may be larger or smaller than what was declared, so you might consider using explicit width and height attributes on img tags referencing these images. See the manifest documentation on icons for more details. - */ - icons?: IconInfo[]; - /** - * Returns a list of host based permissions. - * @since Chrome 9. - */ - hostPermissions: string[]; - /** Whether it is currently enabled or disabled. */ - enabled: boolean; - /** - * Optional. - * The URL of the homepage of this extension, app, or theme. - * @since Chrome 11. - */ - homepageUrl?: string; - /** - * Whether this extension can be disabled or uninstalled by the user. - * @since Chrome 12. - */ - mayDisable: boolean; - /** - * How the extension was installed. - * @since Chrome 22. - */ - installType: string; - /** The version of this extension, app, or theme. */ - version: string; - /** The extension's unique identifier. */ - id: string; - /** - * Whether the extension, app, or theme declares that it supports offline. - * @since Chrome 15. - */ - offlineEnabled: boolean; - /** - * Optional. - * The update URL of this extension, app, or theme. - * @since Chrome 16. - */ - updateUrl?: string; - /** - * The type of this extension, app, or theme. - * @since Chrome 23. - */ - type: string; - /** The url for the item's options page, if it has one. */ - optionsUrl: string; - /** The name of this extension, app, or theme. */ - name: string; - /** - * A short version of the name of this extension, app, or theme. - * @since Chrome 31. - */ - shortName: string; - /** - * True if this is an app. - * @deprecated since Chrome 33. Please use management.ExtensionInfo.type. - */ - isApp: boolean; - /** - * Optional. - * The app launch type (only present for apps). - * @since Chrome 37. - */ - launchType?: string; - /** - * Optional. - * The currently available launch types (only present for apps). - * @since Chrome 37. - */ - availableLaunchTypes?: string[]; - } - - /** Information about an icon belonging to an extension, app, or theme. */ - interface IconInfo { - /** The URL for this icon image. To display a grayscale version of the icon (to indicate that an extension is disabled, for example), append ?grayscale=true to the URL. */ - url: string; - /** A number representing the width and height of the icon. Likely values include (but are not limited to) 128, 48, 24, and 16. */ - size: number; - } - - interface UninstallOptions { - /** - * Optional. - * Whether or not a confirm-uninstall dialog should prompt the user. Defaults to false for self uninstalls. If an extension uninstalls another extension, this parameter is ignored and the dialog is always shown. - */ - showConfirmDialog?: boolean; - } - - interface ManagementDisabledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> {} - - interface ManagementUninstalledEvent extends chrome.events.Event<(id: string) => void> {} - - interface ManagementInstalledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> {} - - interface ManagementEnabledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> {} - - /** - * Enables or disables an app or extension. - * @param id This should be the id from an item of management.ExtensionInfo. - * @param enabled Whether this item should be enabled or disabled. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function setEnabled(id: string, enabled: boolean, callback?: () => void): void; - /** - * Returns a list of permission warnings for the given extension id. - * @since Chrome 15. - * @param id The ID of an already installed extension. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(array of string permissionWarnings) {...}; - */ - export function getPermissionWarningsById(id: string, callback?: (permissionWarnings: string[]) => void): void; - /** - * Returns information about the installed extension, app, or theme that has the given ID. - * @since Chrome 9. - * @param id The ID from an item of management.ExtensionInfo. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function( ExtensionInfo result) {...}; - */ - export function get(id: string, callback?: (result: ExtensionInfo) => void): void; - /** - * Returns a list of information about installed extensions and apps. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(array of ExtensionInfo result) {...}; - */ - export function getAll(callback?: (result: ExtensionInfo[]) => void): void; - /** - * Returns a list of permission warnings for the given extension manifest string. Note: This function can be used without requesting the 'management' permission in the manifest. - * @since Chrome 15. - * @param manifestStr Extension manifest JSON string. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(array of string permissionWarnings) {...}; - */ - export function getPermissionWarningsByManifest(manifestStr: string, callback?: (permissionwarnings: string[]) => void): void; - /** - * Launches an application. - * @param id The extension id of the application. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function launchApp(id: string, callback?: () => void): void; - /** - * Uninstalls a currently installed app or extension. - * @since Chrome 21. - * @param id This should be the id from an item of management.ExtensionInfo. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function uninstall(id: string, options?: UninstallOptions, callback?: () => void): void; - /** - * Uninstalls a currently installed app or extension. - * @deprecated since Chrome 21. The options parameter was added to this function. - * @param id This should be the id from an item of management.ExtensionInfo. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function uninstall(id: string, callback?: () => void): void; - /** - * Returns information about the calling extension, app, or theme. Note: This function can be used without requesting the 'management' permission in the manifest. - * @since Chrome 39. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function( ExtensionInfo result) {...}; - */ - export function getSelf(callback?: (result: ExtensionInfo) => void): void; - /** - * Uninstalls the calling extension. - * Note: This function can be used without requesting the 'management' permission in the manifest. - * @since Chrome 26. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function uninstallSelf(options?: UninstallOptions, callback?: () => void): void; - /** - * Uninstalls the calling extension. - * Note: This function can be used without requesting the 'management' permission in the manifest. - * @since Chrome 26. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function uninstallSelf(callback?: () => void): void; - /** - * Display options to create shortcuts for an app. On Mac, only packaged app shortcuts can be created. - * @since Chrome 37. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function createAppShortcut(id: string, callback?: () => void): void; - /** - * Set the launch type of an app. - * @since Chrome 37. - * @param id This should be the id from an app item of management.ExtensionInfo. - * @param launchType The target launch type. Always check and make sure this launch type is in ExtensionInfo.availableLaunchTypes, because the available launch types vary on different platforms and configurations. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function setLaunchType(id: string, launchType: string, callback?: () => void): void; - /** - * Generate an app for a URL. Returns the generated bookmark app. - * @since Chrome 37. - * @param url The URL of a web page. The scheme of the URL can only be "http" or "https". - * @param title The title of the generated app. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function( ExtensionInfo result) {...}; - */ - export function generateAppForLink(url: string, title: string, callback?: (result: ExtensionInfo) => void): void; - - /** Fired when an app or extension has been disabled. */ - var onDisabled: ManagementDisabledEvent; - /** Fired when an app or extension has been uninstalled. */ - var onUninstalled: ManagementUninstalledEvent; - /** Fired when an app or extension has been installed. */ - var onInstalled: ManagementInstalledEvent; - /** Fired when an app or extension has been enabled. */ - var onEnabled: ManagementEnabledEvent; -} - -//////////////////// -// Notifications -//////////////////// -/** - * Use the networking.config API to authenticate to captive portals. - * Permissions: "networking.config" - * Important: This API works only on Chrome OS. - * @since Chrome 43. - */ -declare namespace chrome.networking.config { - interface NetworkInfo { - /** Currently only WiFi supported. */ - Type: string; - /** Optional. A unique identifier of the network. */ - GUID?: string; - /** Optional. A hex-encoded byte sequence. */ - HexSSID?: string; - /** Optional. The decoded SSID of the network (default encoding is UTF-8). To filter for non-UTF-8 SSIDs, use HexSSID instead. */ - SSID?: string; - /** Optional. The basic service set identification (BSSID) uniquely identifying the basic service set. BSSID is represented as a human readable, hex-encoded string with bytes separated by colons, e.g. 45:67:89:ab:cd:ef. */ - BSSID?: string; - /** Optional. Identifier indicating the security type of the network. Valid values are None, WEP-PSK, WPA-PSK and WPA-EAP. */ - Security?: string; - } - - interface CaptivePorttalDetectedEvent extends chrome.events.Event<(networkInfo: NetworkInfo) => void> {} - - /** - * Allows an extension to define network filters for the networks it can handle. A call to this function will remove all filters previously installed by the extension before setting the new list. - * @param networks Network filters to set. Every NetworkInfo must either have the SSID or HexSSID set. Other fields will be ignored. - * @param callback Called back when this operation is finished. - * The callback parameter should be a function that looks like this: - * function() {...}; - */ - export function setNetworkFilter(networks: NetworkInfo[], callback: () => void): void; - /** - * Called by the extension to notify the network config API that it finished a captive portal authentication attempt and hand over the result of the attempt. This function must only be called with the GUID of the latest onCaptivePortalDetected event. - * @param GUID Unique network identifier obtained from onCaptivePortalDetected. - * @param result The result of the authentication attempt. - * unhandled: The extension does not handle this network or captive portal (e.g. server end-point not found or not compatible). - * succeeded: The extension handled this network and authenticated successfully. - * rejected: The extension handled this network, tried to authenticate, however was rejected by the server. - * failed: The extension handled this network, tried to authenticate, however failed due to an unspecified error. - * @param callback Called back when this operation is finished. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function finishAuthentication(GUID: string, result: string, callback?: () => void): void; - - /** This event fires everytime a captive portal is detected on a network matching any of the currently registered network filters and the user consents to use the extension for authentication. Network filters may be set using the setNetworkFilter. Upon receiving this event the extension should start its authentication attempt with the captive portal. When the extension finishes its attempt, it must call finishAuthentication with the GUID received with this event and the appropriate authentication result. */ - var onCaptivePortalDetected: CaptivePorttalDetectedEvent; -} - -//////////////////// -// Notifications -// https://developer.chrome.com/extensions/notifications -//////////////////// -/** - * Use the chrome.notifications API to create rich notifications using templates and show these notifications to users in the system tray. - * Permissions: "notifications" - * @since Chrome 28. - */ -declare namespace chrome.notifications { - interface ButtonOptions { - title: string; - iconUrl?: string; - } - - interface ItemOptions { - /** Title of one item of a list notification. */ - title: string; - /** Additional details about this item. */ - message: string; - } - - interface NotificationOptions { - /** Optional. Which type of notification to display. Required for notifications.create method. */ - type?: string; - /** - * Optional. - * A URL to the sender's avatar, app icon, or a thumbnail for image notifications. - * URLs can be a data URL, a blob URL, or a URL relative to a resource within this extension's .crx file Required for notifications.create method. - */ - iconUrl?: string; - /** Optional. Title of the notification (e.g. sender name for email). Required for notifications.create method. */ - title?: string; - /** Optional. Main notification content. Required for notifications.create method. */ - message?: string; - /** - * Optional. - * Alternate notification content with a lower-weight font. - * @since Chrome 31. - */ - contextMessage?: string; - /** Optional. Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default. */ - priority?: number; - /** Optional. A timestamp associated with the notification, in milliseconds past the epoch (e.g. Date.now() + n). */ - eventTime?: number; - /** Optional. Text and icons for up to two notification action buttons. */ - buttons?: ButtonOptions[]; - /** Optional. Items for multi-item notifications. */ - items?: ItemOptions[]; - /** - * Optional. - * Current progress ranges from 0 to 100. - * @since Chrome 30. - */ - progress?: number; - /** - * Optional. - * Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification. - * @since Chrome 32. - */ - isClickable?: boolean; - /** - * Optional. - * A URL to the app icon mask. URLs have the same restrictions as iconUrl. The app icon mask should be in alpha channel, as only the alpha channel of the image will be considered. - * @since Chrome 38. - */ - appIconMaskUrl?: string; - /** Optional. A URL to the image thumbnail for image-type notifications. URLs have the same restrictions as iconUrl. */ - imageUrl?: string; - } - - interface NotificationClosedEvent extends chrome.events.Event<(notificationId: string, byUser: boolean) => void> {} - - interface NotificationClickedEvent extends chrome.events.Event<(notificationId: string) => void> {} - - interface NotificationButtonClickedEvent extends chrome.events.Event<(notificationId: string, buttonIndex: number) => void> {} - - interface NotificationPermissionLevelChangedEvent extends chrome.events.Event<(level: string) => void> {} - - interface NotificationShowSettingsEvent extends chrome.events.Event<() => void> {} - - /** The notification closed, either by the system or by user action. */ - export var onClosed: NotificationClosedEvent; - /** The user clicked in a non-button area of the notification. */ - export var onClicked: NotificationClickedEvent; - /** The user pressed a button in the notification. */ - export var onButtonClicked: NotificationButtonClickedEvent; - /** - * The user changes the permission level. - * @since Chrome 32. - */ - export var onPermissionLevelChanged: NotificationPermissionLevelChangedEvent; - /** - * The user clicked on a link for the app's notification settings. - * @since Chrome 32. - */ - export var onShowSettings: NotificationShowSettingsEvent; - - /** - * Creates and displays a notification. - * @param notificationId Identifier of the notification. If not set or empty, an ID will automatically be generated. If it matches an existing notification, this method first clears that notification before proceeding with the create operation. - * The notificationId parameter is required before Chrome 42. - * @param options Contents of the notification. - * @param callback Returns the notification id (either supplied or generated) that represents the created notification. - * The callback is required before Chrome 42. - * If you specify the callback parameter, it should be a function that looks like this: - * function(string notificationId) {...}; - */ - export function create(notificationId: string, options: NotificationOptions, callback?: (notificationId: string) => void): void; - /** - * Creates and displays a notification. - * @param notificationId Identifier of the notification. If not set or empty, an ID will automatically be generated. If it matches an existing notification, this method first clears that notification before proceeding with the create operation. - * The notificationId parameter is required before Chrome 42. - * @param options Contents of the notification. - * @param callback Returns the notification id (either supplied or generated) that represents the created notification. - * The callback is required before Chrome 42. - * If you specify the callback parameter, it should be a function that looks like this: - * function(string notificationId) {...}; - */ - export function create(options: NotificationOptions, callback?: (notificationId: string) => void): void; - /** - * Updates an existing notification. - * @param notificationId The id of the notification to be updated. This is returned by notifications.create method. - * @param options Contents of the notification to update to. - * @param callback Called to indicate whether a matching notification existed. - * The callback is required before Chrome 42. - * If you specify the callback parameter, it should be a function that looks like this: - * function(boolean wasUpdated) {...}; - */ - export function update(notificationId: string, options: NotificationOptions, callback?: (wasUpdated: boolean) => void): void; - /** - * Clears the specified notification. - * @param notificationId The id of the notification to be cleared. This is returned by notifications.create method. - * @param callback Called to indicate whether a matching notification existed. - * The callback is required before Chrome 42. - * If you specify the callback parameter, it should be a function that looks like this: - * function(boolean wasCleared) {...}; - */ - export function clear(notificationId: string, callback?: (wasCleared: boolean) => void): void; - /** - * Retrieves all the notifications. - * @since Chrome 29. - * @param callback Returns the set of notification_ids currently in the system. - * The callback parameter should be a function that looks like this: - * function(object notifications) {...}; - */ - export function getAll(callback: (notifications: Object) => void): void; - /** - * Retrieves whether the user has enabled notifications from this app or extension. - * @since Chrome 32. - * @param callback Returns the current permission level. - * The callback parameter should be a function that looks like this: - * function( PermissionLevel level) {...}; - */ - export function getPermissionLevel(callback: (level: string) => void): void; -} - -//////////////////// -// Omnibox -//////////////////// -/** - * The omnibox API allows you to register a keyword with Google Chrome's address bar, which is also known as the omnibox. - * Manifest: "omnibox": {...} - * @since Chrome 9. - */ -declare namespace chrome.omnibox { - /** A suggest result. */ - interface SuggestResult { - /** The text that is put into the URL bar, and that is sent to the extension when the user chooses this entry. */ - content: string; - /** The text that is displayed in the URL dropdown. Can contain XML-style markup for styling. The supported tags are 'url' (for a literal URL), 'match' (for highlighting text that matched what the user's query), and 'dim' (for dim helper text). The styles can be nested, eg. dimmed match. You must escape the five predefined entities to display them as text: stackoverflow.com/a/1091953/89484 */ - description: string; - } - - interface Suggestion { - /** The text that is displayed in the URL dropdown. Can contain XML-style markup for styling. The supported tags are 'url' (for a literal URL), 'match' (for highlighting text that matched what the user's query), and 'dim' (for dim helper text). The styles can be nested, eg. dimmed match. */ - description: string; - } - - interface OmniboxInputEnteredEvent extends chrome.events.Event<(text: string) => void> {} - - interface OmniboxInputChangedEvent extends chrome.events.Event<(text: string, suggest: (suggestResults: SuggestResult[]) => void) => void> {} - - interface OmniboxInputStartedEvent extends chrome.events.Event<() => void> {} - - interface OmniboxInputCancelledEvent extends chrome.events.Event<() => void> {} - - /** - * Sets the description and styling for the default suggestion. The default suggestion is the text that is displayed in the first suggestion row underneath the URL bar. - * @param suggestion A partial SuggestResult object, without the 'content' parameter. - */ - export function setDefaultSuggestion(suggestion: Suggestion): void; - - /** User has accepted what is typed into the omnibox. */ - var onInputEntered: OmniboxInputEnteredEvent; - /** User has changed what is typed into the omnibox. */ - var onInputChanged: OmniboxInputChangedEvent; - /** User has started a keyword input session by typing the extension's keyword. This is guaranteed to be sent exactly once per input session, and before any onInputChanged events. */ - var onInputStarted: OmniboxInputStartedEvent; - /** User has ended the keyword input session without accepting the input. */ - var onInputCancelled: OmniboxInputCancelledEvent; -} - -//////////////////// -// Page Action -//////////////////// -/** - * Use the chrome.pageAction API to put icons inside the address bar. Page actions represent actions that can be taken on the current page, but that aren't applicable to all pages. - * Manifest: "page_action": {...} - * @since Chrome 5. - */ -declare namespace chrome.pageAction { - interface PageActionClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> {} - - interface TitleDetails { - /** The id of the tab for which you want to modify the page action. */ - tabId: number; - /** The tooltip string. */ - title: string; - } - - interface GetDetails { - /** Specify the tab to get the title from. */ - tabId: number; - } - - interface PopupDetails { - /** The id of the tab for which you want to modify the page action. */ - tabId: number; - /** The html file to show in a popup. If set to the empty string (''), no popup is shown. */ - popup: string; - } - - interface IconDetails { - /** The id of the tab for which you want to modify the page action. */ - tabId: number; - /** - * Optional. - * @deprecated This argument is ignored. - */ - iconIndex?: number; - /** - * Optional. - * Either an ImageData object or a dictionary {size -> ImageData} representing icon to be set. If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density. If the number of image pixels that fit into one screen space unit equals scale, then image with size scale * 19 will be selected. Initially only scales 1 and 2 will be supported. At least one image must be specified. Note that 'details.imageData = foo' is equivalent to 'details.imageData = {'19': foo}' - */ - imageData?: ImageData; - /** - * Optional. - * Either a relative image path or a dictionary {size -> relative image path} pointing to icon to be set. If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density. If the number of image pixels that fit into one screen space unit equals scale, then image with size scale * 19 will be selected. Initially only scales 1 and 2 will be supported. At least one image must be specified. Note that 'details.path = foo' is equivalent to 'details.imageData = {'19': foo}' - */ - path?: any; - } - - /** - * Shows the page action. The page action is shown whenever the tab is selected. - * @param tabId The id of the tab for which you want to modify the page action. - */ - export function hide(tabId: number): void; - /** - * Shows the page action. The page action is shown whenever the tab is selected. - * @param tabId The id of the tab for which you want to modify the page action. - */ - export function show(tabId: number): void; - /** Sets the title of the page action. This is displayed in a tooltip over the page action. */ - export function setTitle(details: TitleDetails): void; - /** Sets the html document to be opened as a popup when the user clicks on the page action's icon. */ - export function setPopup(details: PopupDetails): void; - /** - * Gets the title of the page action. - * @since Chrome 19. - * @param callback The callback parameter should be a function that looks like this: - * function(string result) {...}; - */ - export function getTitle(details: GetDetails, callback: (result: string) => void): void; - /** - * Gets the html document set as the popup for this page action. - * @since Chrome 19. - * @param callback The callback parameter should be a function that looks like this: - * function(string result) {...}; - */ - export function getPopup(details: GetDetails, callback: (result: string) => void): void; - /** - * Sets the icon for the page action. The icon can be specified either as the path to an image file or as the pixel data from a canvas element, or as dictionary of either one of those. Either the path or the imageData property must be specified. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function setIcon(details: IconDetails, callback?: () => void): void; - - /** Fired when a page action icon is clicked. This event will not fire if the page action has a popup. */ - var onClicked: PageActionClickedEvent; -} - -//////////////////// -// Page Capture -//////////////////// -/** - * Use the chrome.pageCapture API to save a tab as MHTML. - * Permissions: "pageCapture" - * @since Chrome 18. - */ -declare namespace chrome.pageCapture { - interface SaveDetails { - /** The id of the tab to save as MHTML. */ - tabId: number; - } - - /** - * Saves the content of the tab with given id as MHTML. - * @param callback Called when the MHTML has been generated. - * The callback parameter should be a function that looks like this: - * function(binary mhtmlData) {...}; - * Parameter mhtmlData: The MHTML data as a Blob. - */ - export function saveAsMHTML(details: SaveDetails, callback: (mhtmlData: any) => void): void; -} - -//////////////////// -// Permissions -//////////////////// -/** - * Use the chrome.permissions API to request declared optional permissions at run time rather than install time, so users understand why the permissions are needed and grant only those that are necessary. - * @since Chrome 16. - */ -declare namespace chrome.permissions { - interface Permissions { - /** - * Optional. - * List of named permissions (does not include hosts or origins). Anything listed here must appear in the optional_permissions list in the manifest. - */ - origins?: string[]; - /** - * Optional. - * List of origin permissions. Anything listed here must be a subset of a host that appears in the optional_permissions list in the manifest. For example, if http://*.example.com/ or http://* appears in optional_permissions, you can request an origin of http://help.example.com/. Any path is ignored. - */ - permissions?: string[]; - } - - interface PermissionsRemovedEvent { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Permissions permissions) {...}; - * Parameter permissions: The permissions that have been removed. - */ - addListener(callback: (permissions: Permissions) => void): void; - } - - interface PermissionsAddedEvent { - /** - * @param callback The callback parameter should be a function that looks like this: - * function( Permissions permissions) {...}; - * Parameter permissions: The newly acquired permissions. - */ - addListener(callback: (permissions: Permissions) => void): void; - } - - /** - * Checks if the extension has the specified permissions. - * @param callback The callback parameter should be a function that looks like this: - * function(boolean result) {...}; - * Parameter result: True if the extension has the specified permissions. - */ - export function contains(permissions: Permissions, callback: (result: boolean) => void): void; - /** - * Gets the extension's current set of permissions. - * @param callback The callback parameter should be a function that looks like this: - * function( Permissions permissions) {...}; - * Parameter permissions: The extension's active permissions. - */ - export function getAll(callback: (permissions: Permissions) => void): void; - /** - * Requests access to the specified permissions. These permissions must be defined in the optional_permissions field of the manifest. If there are any problems requesting the permissions, runtime.lastError will be set. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(boolean granted) {...}; - * Parameter granted: True if the user granted the specified permissions. - */ - export function request(permissions: Permissions, callback?: (granted: boolean) => void): void; - /** - * Removes access to the specified permissions. If there are any problems removing the permissions, runtime.lastError will be set. - * @param callback If you specify the callback parameter, it should be a function that looks like this: - * function(boolean removed) {...}; - * Parameter removed: True if the permissions were removed. - */ - export function remove(permissions: Permissions, callback?: (removed: boolean) => void): void; - - /** Fired when access to permissions has been removed from the extension. */ - var onRemoved: PermissionsRemovedEvent; - /** Fired when the extension acquires new permissions. */ - var onAdded: PermissionsAddedEvent; -} - -//////////////////// -// Platform Keys -//////////////////// -/** - * Use the chrome.platformKeys API to access client certificates managed by the platform. If the user or policy grants the permission, an extension can use such a certficate in its custom authentication protocol. E.g. this allows usage of platform managed certificates in third party VPNs (see chrome.vpnProvider). - * Permissions: "platformKeys" - * Important: This API works only on Chrome OS. - * @since Chrome 45. - */ -declare namespace chrome.platformKeys { - interface Match { - /** The DER encoding of a X.509 certificate. */ - certificate: ArrayBuffer; - /** The KeyAlgorithm of the certified key. This contains algorithm parameters that are inherent to the key of the certificate (e.g. the key length). Other parameters like the hash function used by the sign function are not included. */ - keyAlgorithm: KeyAlgorithm; - } - - interface ClientCertificateSelectRequestDetails { - /** This field is a list of the types of certificates requested, sorted in order of the server's preference. Only certificates of a type contained in this list will be retrieved. If certificateTypes is the empty list, however, certificates of any type will be returned. */ - certificateTypes: string[]; - /** List of distinguished names of certificate authorities allowed by the server. Each entry must be a DER-encoded X.509 DistinguishedName. */ - certificateAuthorities: ArrayBuffer[]; - } - - interface ClientCertificateSelectDetails { - /** Only certificates that match this request will be returned. */ - request: ClientCertificateSelectRequestDetails; - /** - * Optional. - * If given, the selectClientCertificates operates on this list. Otherwise, obtains the list of all certificates from the platform's certificate stores that are available to this extensions. Entries that the extension doesn't have permission for or which doesn't match the request, are removed. - */ - clientCerts?: ArrayBuffer[]; - /** If true, the filtered list is presented to the user to manually select a certificate and thereby granting the extension access to the certificate(s) and key(s). Only the selected certificate(s) will be returned. If is false, the list is reduced to all certificates that the extension has been granted access to (automatically or manually). */ - interactive: boolean; - } - - interface ServerCertificateVerificationDetails { - /** Each chain entry must be the DER encoding of a X.509 certificate, the first entry must be the server certificate and each entry must certify the entry preceding it. */ - serverCertificateChain: ArrayBuffer[]; - /** The hostname of the server to verify the certificate for, e.g. the server that presented the serverCertificateChain. */ - hostname: string; - } - - interface ServerCertificateVerificationResult { - /** The result of the trust verification: true if trust for the given verification details could be established and false if trust is rejected for any reason. */ - trusted: boolean; - /** - * If the trust verification failed, this array contains the errors reported by the underlying network layer. Otherwise, this array is empty. - * Note: This list is meant for debugging only and may not contain all relevant errors. The errors returned may change in future revisions of this API, and are not guaranteed to be forwards or backwards compatible. - */ - debug_errors: string[]; - } - - /** - * This function filters from a list of client certificates the ones that are known to the platform, match request and for which the extension has permission to access the certificate and its private key. If interactive is true, the user is presented a dialog where he can select from matching certificates and grant the extension access to the certificate. The selected/filtered client certificates will be passed to callback. - * @param callback The callback parameter should be a function that looks like this: - * function(array of Match matches) {...}; - * Parameter matches: The list of certificates that match the request, that the extension has permission for and, if interactive is true, that were selected by the user. - */ - export function selectClientCertificates(details: ClientCertificateSelectDetails, callback: (matches: Match[]) => void): void; - /** - * Passes the key pair of certificate for usage with platformKeys.subtleCrypto to callback. - * @param certificate The certificate of a Match returned by selectClientCertificates. - * @param parameters Determines signature/hash algorithm parameters additionally to the parameters fixed by the key itself. The same parameters are accepted as by WebCrypto's importKey function, e.g. RsaHashedImportParams for a RSASSA-PKCS1-v1_5 key. For RSASSA-PKCS1-v1_5 keys, additionally the parameters { 'hash': { 'name': 'none' } } are supported. The sign function will then apply PKCS#1 v1.5 padding and but not hash the given data. - * @param callback The public and private CryptoKey of a certificate which can only be used with platformKeys.subtleCrypto. - * The callback parameter should be a function that looks like this: - * function(object publicKey, object privateKey) {...}; - * Optional parameter privateKey: Might be null if this extension does not have access to it. - */ - export function getKeyPair(certificate: ArrayBuffer, parameters: Object, callback: (publicKey: CryptoKey, privateKey?: CryptoKey) => void): void; - /** An implementation of WebCrypto's SubtleCrypto that allows crypto operations on keys of client certificates that are available to this extension. */ - export function subtleCrypto(): SubtleCrypto; - /** - * Checks whether details.serverCertificateChain can be trusted for details.hostname according to the trust settings of the platform. Note: The actual behavior of the trust verification is not fully specified and might change in the future. The API implementation verifies certificate expiration, validates the certification path and checks trust by a known CA. The implementation is supposed to respect the EKU serverAuth and to support subject alternative names. - * @param callback The callback parameter should be a function that looks like this: - * function(object result) {...}; - */ - export function verifyTLSServerCertificate(details: ServerCertificateVerificationDetails, callback: (result: ServerCertificateVerificationResult) => void): void; -} - -//////////////////// -// Power -//////////////////// -/** - * Use the chrome.power API to override the system's power management features. - * Permissions: "power" - * @since Chrome 27. - */ -declare namespace chrome.power { - /** Requests that power management be temporarily disabled. |level| describes the degree to which power management should be disabled. If a request previously made by the same app is still active, it will be replaced by the new request. */ - export function requestKeepAwake(level: string): void; - /** Releases a request previously made via requestKeepAwake(). */ - export function releaseKeepAwake(): void; -} - -//////////////////// -// Printer Provider -//////////////////// -/** - * The chrome.printerProvider API exposes events used by print manager to query printers controlled by extensions, to query their capabilities and to submit print jobs to these printers. - * Permissions: "printerProvider" - * @since Chrome 44. - */ -declare namespace chrome.printerProvider { - interface PrinterInfo { - /** Unique printer ID. */ - id: string; - /** Printer's human readable name. */ - name: string; - /** Optional. Printer's human readable description. */ - description?: string; - } - - interface PrinterCapabilities { - /** Device capabilities in CDD format. */ - capabilities: any; - } - - interface PrintJob { - /** ID of the printer which should handle the job. */ - printerId: string; - /** The print job title. */ - title: string; - /** Print ticket in CJT format. */ - ticket: Object; - /** The document content type. Supported formats are "application/pdf" and "image/pwg-raster". */ - contentType: string; - /** Blob containing the document data to print. Format must match |contentType|. */ - document: Blob; - } - - interface PrinterRequestedEvent extends chrome.events.Event<(resultCallback: (printerInfo: PrinterInfo[]) => void) => void> {} - - interface PrinterInfoRequestedEvent extends chrome.events.Event<(device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void> {} - - interface CapabilityRequestedEvent extends chrome.events.Event<(printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void> {} - - interface PrintRequestedEvent extends chrome.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void> {} - - /** Event fired when print manager requests printers provided by extensions. */ - export var onGetPrintersRequested: PrinterRequestedEvent; - /** - * Event fired when print manager requests information about a USB device that may be a printer. - * Note: An application should not rely on this event being fired more than once per device. If a connected device is supported it should be returned in the onGetPrintersRequested event. - * @since Chrome 45. - */ - export var onGetUsbPrinterInfoRequested: PrinterInfoRequestedEvent; - /** Event fired when print manager requests printer capabilities. */ - export var onGetCapabilityRequested: CapabilityRequestedEvent; - /** Event fired when print manager requests printing. */ - export var onPrintRequested: PrintRequestedEvent; -} - -//////////////////// -// Privacy -//////////////////// -/** - * Use the chrome.privacy API to control usage of the features in Chrome that can affect a user's privacy. This API relies on the ChromeSetting prototype of the type API for getting and setting Chrome's configuration. - * Permissions: "privacy" - * The Chrome Privacy Whitepaper gives background detail regarding the features which this API can control. - * @since Chrome 18. - */ -declare namespace chrome.privacy { - interface Services { - /** since Chrome 20. */ - spellingServiceEnabled: chrome.types.ChromeSetting; - searchSuggestEnabled: chrome.types.ChromeSetting; - instantEnabled: chrome.types.ChromeSetting; - alternateErrorPagesEnabled: chrome.types.ChromeSetting; - safeBrowsingEnabled: chrome.types.ChromeSetting; - autofillEnabled: chrome.types.ChromeSetting; - translationServiceEnabled: chrome.types.ChromeSetting; - /** @since Chrome 38. */ - passwordSavingEnabled: chrome.types.ChromeSetting; - /** @since Chrome 42. */ - hotwordSearchEnabled: chrome.types.ChromeSetting; - /** @since Chrome 42. */ - safeBrowsingExtendedReportingEnabled: chrome.types.ChromeSetting; - } - - interface Network { - networkPredictionEnabled: chrome.types.ChromeSetting; - /** @since Chrome 42. */ - webRTCMultipleRoutesEnabled: chrome.types.ChromeSetting; - /** @since Chrome 47. Warning: this is the current Dev channel. */ - webRTCNonProxiedUdpEnabled: chrome.types.ChromeSetting; - } - - interface Websites { - thirdPartyCookiesAllowed: chrome.types.ChromeSetting; - referrersEnabled: chrome.types.ChromeSetting; - hyperlinkAuditingEnabled: chrome.types.ChromeSetting; - /** @since Chrome 21. */ - protectedContentEnabled: chrome.types.ChromeSetting; - } - - /** Settings that enable or disable features that require third-party network services provided by Google and your default search provider. */ - var services: Services; - /** Settings that influence Chrome's handling of network connections in general. */ - var network: Network; - /** Settings that determine what information Chrome makes available to websites. */ - var websites: Websites; -} - -//////////////////// -// Proxy -//////////////////// -/** - * Use the chrome.proxy API to manage Chrome's proxy settings. This API relies on the ChromeSetting prototype of the type API for getting and setting the proxy configuration. - * Permissions: "proxy" - * @since Chrome 13. - */ -declare namespace chrome.proxy { - /** An object holding proxy auto-config information. Exactly one of the fields should be non-empty. */ - interface PacScript { - /** Optional. URL of the PAC file to be used. */ - url?: string; - /** Optional. If true, an invalid PAC script will prevent the network stack from falling back to direct connections. Defaults to false. */ - mandatory?: boolean; - /** Optional. A PAC script. */ - data?: string; - } - - /** An object encapsulating a complete proxy configuration. */ - interface ProxyConfig { - /** Optional. The proxy rules describing this configuration. Use this for 'fixed_servers' mode. */ - rules?: ProxyRules; - /** Optional. The proxy auto-config (PAC) script for this configuration. Use this for 'pac_script' mode. */ - pacScript?: PacScript; - /** - * 'direct' = Never use a proxy - * 'auto_detect' = Auto detect proxy settings - * 'pac_script' = Use specified PAC script - * 'fixed_servers' = Manually specify proxy servers - * 'system' = Use system proxy settings - */ - mode: string; - } - - /** An object encapsulating a single proxy server's specification. */ - interface ProxyServer { - /** The URI of the proxy server. This must be an ASCII hostname (in Punycode format). IDNA is not supported, yet. */ - host: string; - /** Optional. The scheme (protocol) of the proxy server itself. Defaults to 'http'. */ - scheme?: string; - /** Optional. The port of the proxy server. Defaults to a port that depends on the scheme. */ - port?: number; - } - - /** An object encapsulating the set of proxy rules for all protocols. Use either 'singleProxy' or (a subset of) 'proxyForHttp', 'proxyForHttps', 'proxyForFtp' and 'fallbackProxy'. */ - interface ProxyRules { - /** Optional. The proxy server to be used for FTP requests. */ - proxyForFtp?: ProxyServer; - /** Optional. The proxy server to be used for HTTP requests. */ - proxyForHttp?: ProxyServer; - /** Optional. The proxy server to be used for everthing else or if any of the specific proxyFor... is not specified. */ - fallbackProxy?: ProxyServer; - /** Optional. The proxy server to be used for all per-URL requests (that is http, https, and ftp). */ - singleProxy?: ProxyServer; - /** Optional. The proxy server to be used for HTTPS requests. */ - proxyForHttps?: ProxyServer; - /** Optional. List of servers to connect to without a proxy server. */ - bypassList?: string[]; - } - - interface ErrorDetails { - /** Additional details about the error such as a JavaScript runtime error. */ - details: string; - /** The error description. */ - error: string; - /** If true, the error was fatal and the network transaction was aborted. Otherwise, a direct connection is used instead. */ - fatal: boolean; - } - - interface ProxyErrorEvent extends chrome.events.Event<(details: ErrorDetails) => void> {} - - var settings: chrome.types.ChromeSetting; - /** Notifies about proxy errors. */ - var onProxyError: ProxyErrorEvent; -} - -//////////////////// -// Runtime -//////////////////// -/** - * Use the chrome.runtime API to retrieve the background page, return details about the manifest, and listen for and respond to events in the app or extension lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs. - * @since Chrome 22 - */ -declare namespace chrome.runtime { - /** This will be defined during an API method callback if there was an error */ - var lastError: LastError; - /** The ID of the extension/app. */ - var id: string; - - interface LastError { - /** Optional. Details about the error which occurred. */ - message?: string; - } - - interface ConnectInfo { - name?: string; - } - - interface InstalledDetails { - /** - * The reason that this event is being dispatched. - * One of: "install", "update", "chrome_update", or "shared_module_update" - */ - reason: string; - /** - * Optional. - * Indicates the previous version of the extension, which has just been updated. This is present only if 'reason' is 'update'. - */ - previousVersion?: string; - /** - * Optional. - * Indicates the ID of the imported shared module extension which updated. This is present only if 'reason' is 'shared_module_update'. - * @since Chrome 29. - */ - id?: string; - } - - interface MessageOptions { - /** Whether the TLS channel ID will be passed into onMessageExternal for processes that are listening for the connection event. */ - includeTlsChannelId?: boolean; - } - - /** - * An object containing information about the script context that sent a message or request. - * @since Chrome 26. - */ - interface MessageSender { - /** The ID of the extension or app that opened the connection, if any. */ - id?: string; - /** The tabs.Tab which opened the connection, if any. This property will only be present when the connection was opened from a tab (including content scripts), and only if the receiver is an extension, not an app. */ - tab?: chrome.tabs.Tab; - /** - * The frame that opened the connection. 0 for top-level frames, positive for child frames. This will only be set when tab is set. - * @since Chrome 41. - */ - frameId?: number; - /** - * The URL of the page or frame that opened the connection. If the sender is in an iframe, it will be iframe's URL not the URL of the page which hosts it. - * @since Chrome 28. - */ - url?: string; - /** - * The TLS channel ID of the page or frame that opened the connection, if requested by the extension or app, and if available. - * @since Chrome 32. - */ - tlsChannelId?: string; - } - - /** - * An object containing information about the current platform. - * @since Chrome 36. - */ - interface PlatformInfo { - /** - * The operating system chrome is running on. - * One of: "mac", "win", "android", "cros", "linux", or "openbsd" - */ - os: string; - /** - * The machine's processor architecture. - * One of: "arm", "x86-32", or "x86-64" - */ - arch: string; - /** - * The native client architecture. This may be different from arch on some platforms. - * One of: "arm", "x86-32", or "x86-64" - */ - nacl_arch: string; - } - - /** - * An object which allows two way communication with other pages. - * @since Chrome 26. - */ - interface Port { - postMessage: (message: Object) => void; - disconnect: () => void; - /** - * Optional. - * This property will only be present on ports passed to onConnect/onConnectExternal listeners. - */ - sender?: MessageSender; - /** An object which allows the addition and removal of listeners for a Chrome event. */ - onDisconnect: chrome.events.Event<() => void>; - /** An object which allows the addition and removal of listeners for a Chrome event. */ - onMessage: PortMessageEvent; - name: string; - } - - interface UpdateAvailableDetails { - /** The version number of the available update. */ - version: string; - } - - interface UpdateCheckDetails { - /** The version of the available update. */ - version: string; - } - - interface PortMessageEvent extends chrome.events.Event<(message: Object, port: Port) => void> {} - - interface ExtensionMessageEvent extends chrome.events.Event<(message: any, sender: MessageSender, sendResponse: (response: any) => void) => void> {} - - interface ExtensionConnectEvent extends chrome.events.Event<(port: Port) => void> {} - - interface RuntimeInstalledEvent extends chrome.events.Event<(details: InstalledDetails) => void> {} - - interface RuntimeEvent extends chrome.events.Event<() => void> {} - - interface RuntimeRestartRequiredEvent extends chrome.events.Event<(reason: string) => void> {} - - interface RuntimeUpdateAvailableEvent extends chrome.events.Event<(details: UpdateAvailableDetails) => void> {} - - interface ManifestIcons { - [size: number]: string; - } - - interface ManifestAction { - default_icon?: ManifestIcons; - default_title?: string; - default_popup?: string; - } - - interface SearchProvider { - name?: string; - keyword?: string; - favicon_url?: string; - search_url: string; - encoding?: string; - suggest_url?: string; - instant_url?: string; - image_url?: string; - search_url_post_params?: string; - suggest_url_post_params?: string; - instant_url_post_params?: string; - image_url_post_params?: string; - alternate_urls?: string[]; - prepopulated_id?: number; - is_default?: boolean; - } - - interface Manifest { - // Required - manifest_version: number; - name: string; - version: string; - - // Recommended - default_locale?: string; - description?: string; - icons?: ManifestIcons; - - // Pick one (or none) - browser_action?: ManifestAction; - page_action?: ManifestAction; - - // Optional - author?: any; - automation?: any; - background?: { - scripts?: string[]; - page?: string; - persistent?: boolean; - }; - background_page?: string; - chrome_settings_overrides?: { - homepage?: string; - search_provider?: SearchProvider; - startup_pages?: string[]; - }; - chrome_ui_overrides?: { - bookmarks_ui?: { - remove_bookmark_shortcut?: boolean; - remove_button?: boolean; - } - }; - chrome_url_overrides?: { - bookmarks?: string; - history?: string; - newtab?: string; - }; - commands?: { - [name: string]: { - suggested_key?: { - default?: string; - windows?: string; - mac?: string; - chromeos?: string; - linux?: string; - }; - description?: string; - global?: boolean - } - }; - content_capabilities?: { - matches?: string[]; - permissions?: string[]; - }; - content_scripts?: { - matches?: string[]; - exclude_matches?: string[]; - css?: string[]; - js?: string[]; - run_at?: string; - all_frames?: boolean; - include_globs?: string[]; - exclude_globs?: string[]; - }[]; - content_security_policy?: string; - converted_from_user_script?: boolean; - copresence?: any; - current_locale?: string; - devtools_page?: string; - event_rules?: { - event?: string; - actions?: { - type: string; - }[]; - conditions?: chrome.declarativeContent.PageStateMatcher[] - }[]; - externally_connectable?: { - ids?: string[]; - matches?: string[]; - accepts_tls_channel_id?: boolean; - }; - file_browser_handlers?: { - id?: string; - default_title?: string; - file_filters?: string[]; - }[]; - file_system_provider_capabilities?: { - configurable?: boolean; - watchable?: boolean; - multiple_mounts?: boolean; - source?: string; - }; - homepage_url?: string; - import?: { - id: string; - minimum_version?: string - }[]; - export?: { - whitelist?: string[] - }; - incognito?: string; - input_components?: { - name?: string; - type?: string; - id?: string; - description?: string; - language?: string; - layouts?: any[]; - }[]; - key?: string; - minimum_chrome_version?: string; - nacl_modules?: { - path: string; - mime_type: string; - }[]; - oauth2?: { - client_id: string; - scopes?: string[]; - }; - offline_enabled?: boolean; - omnibox?: { - keyword: string; - }; - optional_permissions?: string[]; - options_page?: string; - options_ui?: { - page?: string; - chrome_style?: boolean; - open_in_tab?: boolean; - }; - permissions?: string[]; - platforms?: { - nacl_arch?: string; - sub_package_path: string; - }[]; - plugins?: { - path: string; - }[]; - requirements?: { - '3D'?: { - features?: string[] - }; - plugins?: { - npapi?: boolean; - } - }; - sandbox?: { - pages: string[]; - content_security_policy?: string; - }; - short_name?: string; - signature?: any; - spellcheck?: { - dictionary_language?: string; - dictionary_locale?: string; - dictionary_format?: string; - dictionary_path?: string; - }; - storage?: { - managed_schema: string - }; - system_indicator?: any; - tts_engine?: { - voices: { - voice_name: string; - lang?: string; - gender?: string; - event_types?: string[]; - }[] - }; - update_url?: string; - version_name?: string; - web_accessible_resources?: string[]; - [key: string]: any; - } - - /** - * Attempts to connect to connect listeners within an extension/app (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and web messaging. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via tabs.connect. - * @since Chrome 26. - */ - export function connect(connectInfo?: ConnectInfo): Port; - /** - * Attempts to connect to connect listeners within an extension/app (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and web messaging. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via tabs.connect. - * @since Chrome 26. - * @param extensionId Optional. - * The ID of the extension or app to connect to. If omitted, a connection will be attempted with your own extension. Required if sending messages from a web page for web messaging. - */ - export function connect(extensionId: string, connectInfo?: ConnectInfo): Port; - /** - * Connects to a native application in the host machine. - * @since Chrome 28. - * @param application The name of the registered application to connect to. - */ - export function connectNative(application: string): Port; - /** Retrieves the JavaScript 'window' object for the background page running inside the current extension/app. If the background page is an event page, the system will ensure it is loaded before calling the callback. If there is no background page, an error is set. */ - export function getBackgroundPage(callback: (backgroundPage?: Window) => void): void; - /** - * Returns details about the app or extension from the manifest. The object returned is a serialization of the full manifest file. - * @returns The manifest details. - */ - export function getManifest(): Manifest; - /** - * Returns a DirectoryEntry for the package directory. - * @since Chrome 29. - */ - export function getPackageDirectoryEntry(callback: (directoryEntry: DirectoryEntry) => void): void; - /** - * Returns information about the current platform. - * @since Chrome 29. - * @param callback Called with results - */ - export function getPlatformInfo(callback: (platformInfo: PlatformInfo) => void): void; - /** - * Converts a relative path within an app/extension install directory to a fully-qualified URL. - * @param path A path to a resource within an app/extension expressed relative to its install directory. - */ - export function getURL(path: string): string; - /** - * Reloads the app or extension. - * @since Chrome 25. - */ - export function reload(): void; - /** - * Requests an update check for this app/extension. - * @since Chrome 25. - * @param callback - * Parameter status: Result of the update check. One of: "throttled", "no_update", or "update_available" - * Optional parameter details: If an update is available, this contains more information about the available update. - */ - export function requestUpdateCheck(callback: (status: string, details?: UpdateCheckDetails) => void): void; - /** - * Restart the ChromeOS device when the app runs in kiosk mode. Otherwise, it's no-op. - * @since Chrome 32. - */ - export function restart(): void; - /** - * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. - * @since Chrome 26. - * @param responseCallback Optional - * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. - */ - export function sendMessage(message: any, responseCallback?: (response: any) => void): void; - /** - * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. - * @since Chrome 32. - * @param responseCallback Optional - * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. - */ - export function sendMessage(message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; - /** - * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. - * @since Chrome 26. - * @param extensionId The ID of the extension/app to send the message to. If omitted, the message will be sent to your own extension/app. Required if sending messages from a web page for web messaging. - * @param responseCallback Optional - * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. - */ - export function sendMessage(extensionId: string, message: any, responseCallback?: (response: any) => void): void; - /** - * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. - * @since Chrome 32. - * @param extensionId The ID of the extension/app to send the message to. If omitted, the message will be sent to your own extension/app. Required if sending messages from a web page for web messaging. - * @param responseCallback Optional - * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. - */ - export function sendMessage(extensionId: string, message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; - /** - * Send a single message to a native application. - * @since Chrome 28. - * @param application The of the native messaging host. - * @param message The message that will be passed to the native messaging host. - * @param responseCallback Optional. - * Parameter response: The response message sent by the native messaging host. If an error occurs while connecting to the native messaging host, the callback will be called with no arguments and runtime.lastError will be set to the error message. - */ - export function sendNativeMessage(application: string, message: Object, responseCallback?: (response: any) => void): void; - /** - * Sets the URL to be visited upon uninstallation. This may be used to clean up server-side data, do analytics, and implement surveys. Maximum 255 characters. - * @since Chrome 41. - * @param url Since Chrome 34. - * URL to be opened after the extension is uninstalled. This URL must have an http: or https: scheme. Set an empty string to not open a new tab upon uninstallation. - * @param callback Called when the uninstall URL is set. If the given URL is invalid, runtime.lastError will be set. - */ - export function setUninstallURL(url: string, callback?: () => void): void; - /** - * Open your Extension's options page, if possible. - * The precise behavior may depend on your manifest's options_ui or options_page key, or what Chrome happens to support at the time. For example, the page may be opened in a new tab, within chrome://extensions, within an App, or it may just focus an open options page. It will never cause the caller page to reload. - * If your Extension does not declare an options page, or Chrome failed to create one for some other reason, the callback will set lastError. - * @since Chrome 42. - */ - export function openOptionsPage(callback?: () => void): void; - - /** - * Fired when a connection is made from either an extension process or a content script. - * @since Chrome 26. - */ - var onConnect: ExtensionConnectEvent; - /** - * Fired when a connection is made from another extension. - * @since Chrome 26. - */ - var onConnectExternal: ExtensionConnectEvent; - /** Sent to the event page just before it is unloaded. This gives the extension opportunity to do some clean up. Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete. If more activity for the event page occurs before it gets unloaded the onSuspendCanceled event will be sent and the page won't be unloaded. */ - var onSuspend: RuntimeEvent; - /** - * Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started, even if this extension is operating in 'split' incognito mode. - * @since Chrome 23. - */ - var onStartup: RuntimeEvent; - /** Fired when the extension is first installed, when the extension is updated to a new version, and when Chrome is updated to a new version. */ - var onInstalled: RuntimeInstalledEvent; - /** Sent after onSuspend to indicate that the app won't be unloaded after all. */ - var onSuspendCanceled: RuntimeEvent; - /** - * Fired when a message is sent from either an extension process or a content script. - * @since Chrome 26. - */ - var onMessage: ExtensionMessageEvent; - /** - * Fired when a message is sent from another extension/app. Cannot be used in a content script. - * @since Chrome 26. - */ - var onMessageExternal: ExtensionMessageEvent; - /** - * Fired when an app or the device that it runs on needs to be restarted. The app should close all its windows at its earliest convenient time to let the restart to happen. If the app does nothing, a restart will be enforced after a 24-hour grace period has passed. Currently, this event is only fired for Chrome OS kiosk apps. - * @since Chrome 29. - */ - var onRestartRequired: RuntimeRestartRequiredEvent; - /** - * Fired when an update is available, but isn't installed immediately because the app is currently running. If you do nothing, the update will be installed the next time the background page gets unloaded, if you want it to be installed sooner you can explicitly call chrome.runtime.reload(). If your extension is using a persistent background page, the background page of course never gets unloaded, so unless you call chrome.runtime.reload() manually in response to this event the update will not get installed until the next time chrome itself restarts. If no handlers are listening for this event, and your extension has a persistent background page, it behaves as if chrome.runtime.reload() is called in response to this event. - * @since Chrome 25. - */ - var onUpdateAvailable: RuntimeUpdateAvailableEvent; - /** - * @deprecated since Chrome 33. Please use chrome.runtime.onRestartRequired. - * Fired when a Chrome update is available, but isn't installed immediately because a browser restart is required. - */ - var onBrowserUpdateAvailable: RuntimeEvent; -} - -//////////////////// -// Script Badge -//////////////////// -declare namespace chrome.scriptBadge { - interface GetPopupDetails { - tabId: number; - } - - interface AttentionDetails { - tabId: number; - } - - interface SetPopupDetails { - tabId: number; - popup: string; - } - - interface ScriptBadgeClickedEvent extends chrome.events.Event<(tab: chrome.tabs.Tab) => void> {} - - export function getPopup(details: GetPopupDetails, callback: Function): void; - export function getAttention(details: AttentionDetails): void; - export function setPopup(details: SetPopupDetails): void; - - var onClicked: ScriptBadgeClickedEvent; -} - -//////////////////// -// Sessions -//////////////////// -/** - * Use the chrome.sessions API to query and restore tabs and windows from a browsing session. - * Permissions: "sessions" - * @since Chrome 37. - */ -declare namespace chrome.sessions { - interface Filter { - /** - * Optional. - * The maximum number of entries to be fetched in the requested list. Omit this parameter to fetch the maximum number of entries (sessions.MAX_SESSION_RESULTS). - */ - maxResults?: number; - } - - interface Session { - /** The time when the window or tab was closed or modified, represented in milliseconds since the epoch. */ - lastModified: number; - /** - * Optional. - * The tabs.Tab, if this entry describes a tab. Either this or sessions.Session.window will be set. - */ - tab?: tabs.Tab; - /** - * Optional. - * The windows.Window, if this entry describes a window. Either this or sessions.Session.tab will be set. - */ - window?: windows.Window; - } - - interface Device { - /** The name of the foreign device. */ - deviceName: string; - /** A list of open window sessions for the foreign device, sorted from most recently to least recently modified session. */ - sessions: Session[]; - } - - interface SessionChangedEvent extends chrome.events.Event<() => void> {} - - /** The maximum number of sessions.Session that will be included in a requested list. */ - export var MAX_SESSION_RESULTS: number; - - /** - * Gets the list of recently closed tabs and/or windows. - * @param callback - * Parameter sessions: The list of closed entries in reverse order that they were closed (the most recently closed tab or window will be at index 0). The entries may contain either tabs or windows. - */ - export function getRecentlyClosed(filter: Filter, callback: (sessions: Session[]) => void): void; - /** - * Gets the list of recently closed tabs and/or windows. - * @param callback - * Parameter sessions: The list of closed entries in reverse order that they were closed (the most recently closed tab or window will be at index 0). The entries may contain either tabs or windows. - */ - export function getRecentlyClosed(callback: (sessions: Session[]) => void): void; - /** - * Retrieves all devices with synced sessions. - * @param callback - * Parameter devices: The list of sessions.Device objects for each synced session, sorted in order from device with most recently modified session to device with least recently modified session. tabs.Tab objects are sorted by recency in the windows.Window of the sessions.Session objects. - */ - export function getDevices(filter: Filter, callback: (devices: Device[]) => void): void; - /** - * Retrieves all devices with synced sessions. - * @param callback - * Parameter devices: The list of sessions.Device objects for each synced session, sorted in order from device with most recently modified session to device with least recently modified session. tabs.Tab objects are sorted by recency in the windows.Window of the sessions.Session objects. - */ - export function getDevices(callback: (devices: Device[]) => void): void; - /** - * Reopens a windows.Window or tabs.Tab, with an optional callback to run when the entry has been restored. - * @param sessionId Optional. - * The windows.Window.sessionId, or tabs.Tab.sessionId to restore. If this parameter is not specified, the most recently closed session is restored. - * @param callback Optional. - * Parameter restoredSession: A sessions.Session containing the restored windows.Window or tabs.Tab object. - */ - export function restore(sessionId?: string, callback?: (restoredSession: Session) => void): void; - - /** Fired when recently closed tabs and/or windows are changed. This event does not monitor synced sessions changes. */ - export var onChanged: SessionChangedEvent; -} - -//////////////////// -// Storage -//////////////////// -/** - * Use the chrome.storage API to store, retrieve, and track changes to user data. - * Permissions: "storage" - * @since Chrome 20. - */ -declare namespace chrome.storage { - interface StorageArea { - /** - * Gets the amount of space (in bytes) being used by one or more items. - * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). - * Parameter bytesInUse: Amount of space being used in storage, in bytes. - */ - getBytesInUse(callback: (bytesInUse: number) => void): void; - /** - * Gets the amount of space (in bytes) being used by one or more items. - * @param key A single key to get the total usage for. Pass in null to get the total usage of all of storage. - * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). - * Parameter bytesInUse: Amount of space being used in storage, in bytes. - */ - getBytesInUse(key: string, callback: (bytesInUse: number) => void): void; - /** - * Gets the amount of space (in bytes) being used by one or more items. - * @param keys A list of keys to get the total usage for. An empty list will return 0. Pass in null to get the total usage of all of storage. - * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). - * Parameter bytesInUse: Amount of space being used in storage, in bytes. - */ - getBytesInUse(keys: string[], callback: (bytesInUse: number) => void): void; - /** - * Removes all items from storage. - * @param callback Optional. - * Callback on success, or on failure (in which case runtime.lastError will be set). - */ - clear(callback?: () => void): void; - /** - * Sets multiple items. - * @param items An object which gives each key/value pair to update storage with. Any other key/value pairs in storage will not be affected. - * Primitive values such as numbers will serialize as expected. Values with a typeof "object" and "function" will typically serialize to {}, with the exception of Array (serializes as expected), Date, and Regex (serialize using their String representation). - * @param callback Optional. - * Callback on success, or on failure (in which case runtime.lastError will be set). - */ - set(items: Object, callback?: () => void): void; - /** - * Removes one item from storage. - * @param key A single key for items to remove. - * @param callback Optional. - * Callback on success, or on failure (in which case runtime.lastError will be set). - */ - remove(key: string, callback?: () => void): void; - /** - * Removes items from storage. - * @param keys A list of keys for items to remove. - * @param callback Optional. - * Callback on success, or on failure (in which case runtime.lastError will be set). - */ - remove(keys: string[], callback?: () => void): void; - /** - * Gets one or more items from storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). - * Parameter items: Object with items in their key-value mappings. - */ - get(callback: (items: { [key: string]: any }) => void): void; - /** - * Gets one or more items from storage. - * @param key A single key to get. Pass in null to get the entire contents of storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). - * Parameter items: Object with items in their key-value mappings. - */ - get(key: string, callback: (items: { [key: string]: any }) => void): void; - /** - * Gets one or more items from storage. - * @param keys A list of keys to get. An empty list or object will return an empty result object. Pass in null to get the entire contents of storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). - * Parameter items: Object with items in their key-value mappings. - */ - get(keys: string[], callback: (items: { [key: string]: any }) => void): void; - /** - * Gets one or more items from storage. - * @param keys A dictionary specifying default values. Pass in null to get the entire contents of storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). - * Parameter items: Object with items in their key-value mappings. - */ - get(keys: Object, callback: (items: { [key: string]: any }) => void): void; - } - - interface StorageChange { - /** Optional. The new value of the item, if there is a new value. */ - newValue?: any; - /** Optional. The old value of the item, if there was an old value. */ - oldValue?: any; - } - - interface LocalStorageArea extends StorageArea { - /** The maximum amount (in bytes) of data that can be stored in local storage, as measured by the JSON stringification of every value plus every key's length. This value will be ignored if the extension has the unlimitedStorage permission. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ - QUOTA_BYTES: number; - } - - interface SyncStorageArea extends StorageArea { - /** @deprecated since Chrome 40. The storage.sync API no longer has a sustained write operation quota. */ - MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: number; - /** The maximum total amount (in bytes) of data that can be stored in sync storage, as measured by the JSON stringification of every value plus every key's length. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ - QUOTA_BYTES: number; - /** The maximum size (in bytes) of each individual item in sync storage, as measured by the JSON stringification of its value plus its key length. Updates containing items larger than this limit will fail immediately and set runtime.lastError. */ - QUOTA_BYTES_PER_ITEM: number; - /** The maximum number of items that can be stored in sync storage. Updates that would cause this limit to be exceeded will fail immediately and set runtime.lastError. */ - MAX_ITEMS: number; - /** - * The maximum number of set, remove, or clear operations that can be performed each hour. This is 1 every 2 seconds, a lower ceiling than the short term higher writes-per-minute limit. - * Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. - */ - MAX_WRITE_OPERATIONS_PER_HOUR: number; - /** - * The maximum number of set, remove, or clear operations that can be performed each minute. This is 2 per second, providing higher throughput than writes-per-hour over a shorter period of time. - * Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. - * @since Chrome 40. - */ - MAX_WRITE_OPERATIONS_PER_MINUTE: number; - } - - interface StorageChangedEvent extends chrome.events.Event<(changes: { [key: string]: StorageChange }, areaName: string) => void> {} - - /** Items in the local storage area are local to each machine. */ - var local: LocalStorageArea; - /** Items in the sync storage area are synced using Chrome Sync. */ - var sync: SyncStorageArea; - - /** - * Items in the managed storage area are set by the domain administrator, and are read-only for the extension; trying to modify this namespace results in an error. - * @since Chrome 33. - */ - var managed: StorageArea; - - /** Fired when one or more items change. */ - var onChanged: StorageChangedEvent; -} - -//////////////////// -// Socket -//////////////////// -declare namespace chrome.socket { - interface CreateInfo { - socketId: number; - } - - interface AcceptInfo { - resultCode: number; - socketId?: number; - } - - interface ReadInfo { - resultCode: number; - data: ArrayBuffer; - } - - interface WriteInfo { - bytesWritten: number; - } - - interface RecvFromInfo { - resultCode: number; - data: ArrayBuffer; - port: number; - address: string; - } - - interface SocketInfo { - socketType: string; - localPort?: number; - peerAddress?: string; - peerPort?: number; - localAddress?: string; - connected: boolean; - } - - interface NetworkInterface { - name: string; - address: string; - } - - export function create(type: string, options?: Object, callback?: (createInfo: CreateInfo) => void): void; - export function destroy(socketId: number): void; - export function connect(socketId: number, hostname: string, port: number, callback: (result: number) => void): void; - export function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; - export function disconnect(socketId: number): void; - export function read(socketId: number, bufferSize?: number, callback?: (readInfo: ReadInfo) => void): void; - export function write(socketId: number, data: ArrayBuffer, callback?: (writeInfo: WriteInfo) => void): void; - export function recvFrom(socketId: number, bufferSize?: number, callback?: (recvFromInfo: RecvFromInfo) => void): void; - export function sendTo(socketId: number, data: ArrayBuffer, address: string, port: number, callback?: (writeInfo: WriteInfo) => void): void; - export function listen(socketId: number, address: string, port: number, backlog?: number, callback?: (result: number) => void): void; - export function accept(socketId: number, callback?: (acceptInfo: AcceptInfo) => void): void; - export function setKeepAlive(socketId: number, enable: boolean, delay?: number, callback?: (result: boolean) => void): void; - export function setNoDelay(socketId: number, noDelay: boolean, callback?: (result: boolean) => void): void; - export function getInfo(socketId: number, callback: (result: SocketInfo) => void): void; - export function getNetworkList(callback: (result: NetworkInterface[]) => void): void; -} - -//////////////////// -// System CPU -//////////////////// -/** - * Use the system.cpu API to query CPU metadata. - * Permissions: "system.cpu" - * @since Chrome 32. - */ -declare namespace chrome.system.cpu { - interface ProcessorUsage { - /** The cumulative time used by userspace programs on this processor. */ - user: number; - /** The cumulative time used by kernel programs on this processor. */ - kernel: number; - /** The cumulative time spent idle by this processor. */ - idle: number; - /** The total cumulative time for this processor. This value is equal to user + kernel + idle. */ - total: number; - } - - interface ProcessorInfo { - /** Cumulative usage info for this logical processor. */ - usage: ProcessorUsage; - } - - interface CpuInfo { - /** The number of logical processors. */ - numOfProcessors: number; - /** The architecture name of the processors. */ - archName: string; - /** The model name of the processors. */ - modelName: string; - /** - * A set of feature codes indicating some of the processor's capabilities. - * The currently supported codes are "mmx", "sse", "sse2", "sse3", "ssse3", "sse4_1", "sse4_2", and "avx". - */ - features: string[]; - /** Information about each logical processor. */ - processors: ProcessorInfo[]; - } - - /** Queries basic CPU information of the system. */ - export function getInfo(callback: (info: CpuInfo) => void): void; -} - -//////////////////// -// System Memory -//////////////////// -/** - * The chrome.system.memory API. - * Permissions: "system.memory" - * @since Chrome 32. - */ -declare namespace chrome.system.memory { - interface MemoryInfo { - /** The total amount of physical memory capacity, in bytes. */ - capacity: number; - /** The amount of available capacity, in bytes. */ - availableCapacity: number; - } - - /** Get physical memory information. */ - export function getInfo(callback: (info: MemoryInfo) => void): void; -} - -//////////////////// -// System Storage -//////////////////// -/** - * Use the chrome.system.storage API to query storage device information and be notified when a removable storage device is attached and detached. - * Permissions: "system.storage" - * @since Chrome 30. - */ -declare namespace chrome.system.storage { - interface StorageUnitInfo { - /** The transient ID that uniquely identifies the storage device. This ID will be persistent within the same run of a single application. It will not be a persistent identifier between different runs of an application, or between different applications. */ - id: string; - /** The name of the storage unit. */ - name: string; - /** - * The media type of the storage unit. - * fixed: The storage has fixed media, e.g. hard disk or SSD. - * removable: The storage is removable, e.g. USB flash drive. - * unknown: The storage type is unknown. - */ - type: string; - /** The total amount of the storage space, in bytes. */ - capacity: number; - } - - interface StorageCapacityInfo { - /** A copied |id| of getAvailableCapacity function parameter |id|. */ - id: string; - /** The available capacity of the storage device, in bytes. */ - availableCapacity: number; - } - - interface SystemStorageAttachedEvent extends chrome.events.Event<(info: StorageUnitInfo) => void> {} - - interface SystemStorageDetachedEvent extends chrome.events.Event<(id: string) => void> {} - - /** Get the storage information from the system. The argument passed to the callback is an array of StorageUnitInfo objects. */ - export function getInfo(callback: (info: StorageUnitInfo[]) => void): void; - /** - * Ejects a removable storage device. - * @param callback - * Parameter result: success: The ejection command is successful -- the application can prompt the user to remove the device; in_use: The device is in use by another application. The ejection did not succeed; the user should not remove the device until the other application is done with the device; no_such_device: There is no such device known. failure: The ejection command failed. - */ - export function ejectDevice(id: string, callback: (result: string) => void): void; - /** - * Get the available capacity of a specified |id| storage device. The |id| is the transient device ID from StorageUnitInfo. - * @since Dev channel only. - */ - export function getAvailableCapacity(id: string, callback: (info: StorageCapacityInfo) => void): void; - - /** Fired when a new removable storage is attached to the system. */ - export var onAttached: SystemStorageAttachedEvent; - /** Fired when a removable storage is detached from the system. */ - export var onDetached: SystemStorageDetachedEvent; -} - -//////////////////// -// TabCapture -//////////////////// -/** - * Use the chrome.tabCapture API to interact with tab media streams. - * Permissions: "tabCapture" - * @since Chrome 31. - */ -declare namespace chrome.tabCapture { - interface CaptureInfo { - /** The id of the tab whose status changed. */ - tabId: number; - /** - * The new capture status of the tab. - * One of: "pending", "active", "stopped", or "error" - */ - status: string; - /** Whether an element in the tab being captured is in fullscreen mode. */ - fullscreen: boolean; - } - - interface CaptureOptions { - /** Optional. */ - audio?: boolean; - /** Optional. */ - video?: boolean; - /** Optional. */ - audioConstraints?: MediaStreamConstraints; - /** Optional. */ - videoConstraints?: MediaStreamConstraints; - } - - interface CaptureStatusChangedEvent extends chrome.events.Event<(info: CaptureInfo) => void> {} - - /** - * Captures the visible area of the currently active tab. Capture can only be started on the currently active tab after the extension has been invoked. Capture is maintained across page navigations within the tab, and stops when the tab is closed, or the media stream is closed by the extension. - * @param options Configures the returned media stream. - * @param callback Callback with either the tab capture stream or null. - */ - export function capture(options: CaptureOptions, callback: (stream: MediaStream) => void): void; - /** - * Returns a list of tabs that have requested capture or are being captured, i.e. status != stopped and status != error. This allows extensions to inform the user that there is an existing tab capture that would prevent a new tab capture from succeeding (or to prevent redundant requests for the same tab). - * @param callback Callback invoked with CaptureInfo[] for captured tabs. - */ - export function getCapturedTabs(callback: (result: CaptureInfo[]) => void): void; - - /** Event fired when the capture status of a tab changes. This allows extension authors to keep track of the capture status of tabs to keep UI elements like page actions in sync. */ - var onStatusChanged: CaptureStatusChangedEvent; -} - -//////////////////// -// Tabs -//////////////////// -/** - * Use the chrome.tabs API to interact with the browser's tab system. You can use this API to create, modify, and rearrange tabs in the browser. - * Permissions: The majority of the chrome.tabs API can be used without declaring any permission. However, the "tabs" permission is required in order to populate the url, title, and favIconUrl properties of Tab. - * @since Chrome 5. - */ -declare namespace chrome.tabs { - /** - * Tab muted state and the reason for the last state change. - * @since Chrome 46. Warning: this is the current Beta channel. - */ - interface MutedInfo { - /** Whether the tab is prevented from playing sound (but hasn't necessarily recently produced sound). Equivalent to whether the muted audio indicator is showing. */ - muted: boolean; - /** - * Optional. - * The reason the tab was muted or unmuted. Not set if the tab's mute state has never been changed. - * "user": A user input action has set/overridden the muted state. - * "capture": Tab capture started, forcing a muted state change. - * "extension": An extension, identified by the extensionId field, set the muted state. - */ - reason?: string; - /** - * Optional. - * The ID of the extension that changed the muted state. Not set if an extension was not the reason the muted state last changed. - */ - extensionId?: string; - } - - interface Tab { - /** - * Optional. - * Either loading or complete. - */ - status?: string; - /** The zero-based index of the tab within its window. */ - index: number; - /** - * Optional. - * The ID of the tab that opened this tab, if any. This property is only present if the opener tab still exists. - * @since Chrome 18. - */ - openerTabId?: number; - /** - * Optional. - * The title of the tab. This property is only present if the extension's manifest includes the "tabs" permission. - */ - title?: string; - /** - * Optional. - * The URL the tab is displaying. This property is only present if the extension's manifest includes the "tabs" permission. - */ - url?: string; - /** - * Whether the tab is pinned. - * @since Chrome 9. - */ - pinned: boolean; - /** - * Whether the tab is highlighted. - * @since Chrome 16. - */ - highlighted: boolean; - /** The ID of the window the tab is contained within. */ - windowId: number; - /** - * Whether the tab is active in its window. (Does not necessarily mean the window is focused.) - * @since Chrome 16. - */ - active: boolean; - /** - * Optional. - * The URL of the tab's favicon. This property is only present if the extension's manifest includes the "tabs" permission. It may also be an empty string if the tab is loading. - */ - favIconUrl?: string; - /** - * Optional. - * The ID of the tab. Tab IDs are unique within a browser session. Under some circumstances a Tab may not be assigned an ID, for example when querying foreign tabs using the sessions API, in which case a session ID may be present. Tab ID can also be set to chrome.tabs.TAB_ID_NONE for apps and devtools windows. - */ - id?: number; - /** Whether the tab is in an incognito window. */ - incognito: boolean; - /** - * Whether the tab is selected. - * @deprecated since Chrome 33. Please use tabs.Tab.highlighted. - */ - selected: boolean; - /** - * Optional. - * Whether the tab has produced sound over the past couple of seconds (but it might not be heard if also muted). Equivalent to whether the speaker audio indicator is showing. - * @since Chrome 45. - */ - audible?: boolean; - /** - * Optional. - * Current tab muted state and the reason for the last state change. - * @since Chrome 46. Warning: this is the current Beta channel. - */ - mutedInfo?: MutedInfo; - /** - * Optional. The width of the tab in pixels. - * @since Chrome 31. - */ - width?: number; - /** - * Optional. The height of the tab in pixels. - * @since Chrome 31. - */ - height?: number; - /** - * Optional. The session ID used to uniquely identify a Tab obtained from the sessions API. - * @since Chrome 31. - */ - sessionId?: string; - } - - /** - * Defines how zoom changes in a tab are handled and at what scope. - * @since Chrome 38. - */ - interface ZoomSettings { - /** - * Optional. - * Defines how zoom changes are handled, i.e. which entity is responsible for the actual scaling of the page; defaults to "automatic". - * "automatic": Zoom changes are handled automatically by the browser. - * "manual": Overrides the automatic handling of zoom changes. The onZoomChange event will still be dispatched, and it is the responsibility of the extension to listen for this event and manually scale the page. This mode does not support per-origin zooming, and will thus ignore the scope zoom setting and assume per-tab. - * "disabled": Disables all zooming in the tab. The tab will revert to the default zoom level, and all attempted zoom changes will be ignored. - */ - mode?: string; - /** - * Optional. - * Defines whether zoom changes will persist for the page's origin, or only take effect in this tab; defaults to per-origin when in automatic mode, and per-tab otherwise. - * "per-origin": Zoom changes will persist in the zoomed page's origin, i.e. all other tabs navigated to that same origin will be zoomed as well. Moreover, per-origin zoom changes are saved with the origin, meaning that when navigating to other pages in the same origin, they will all be zoomed to the same zoom factor. The per-origin scope is only available in the automatic mode. - * "per-tab": Zoom changes only take effect in this tab, and zoom changes in other tabs will not affect the zooming of this tab. Also, per-tab zoom changes are reset on navigation; navigating a tab will always load pages with their per-origin zoom factors. - */ - scope?: string; - /** - * Optional. - * Used to return the default zoom level for the current tab in calls to tabs.getZoomSettings. - * @since Chrome 43. - */ - defaultZoomFactor?: number; - } - - interface InjectDetails { - /** - * Optional. - * If allFrames is true, implies that the JavaScript or CSS should be injected into all frames of current page. By default, it's false and is only injected into the top frame. - */ - allFrames?: boolean; - /** - * Optional. JavaScript or CSS code to inject. - * Warning: Be careful using the code parameter. Incorrect use of it may open your extension to cross site scripting attacks. - */ - code?: string; - /** - * Optional. The soonest that the JavaScript or CSS will be injected into the tab. - * One of: "document_start", "document_end", or "document_idle" - * @since Chrome 20. - */ - runAt?: string; - /** Optional. JavaScript or CSS file to inject. */ - file?: string; - /** - * Optional. - * If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default it is false. - * @since Chrome 39. - */ - matchAboutBlank?: boolean; - } - - interface CreateProperties { - /** Optional. The position the tab should take in the window. The provided value will be clamped to between zero and the number of tabs in the window. */ - index?: number; - /** - * Optional. - * The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as the newly created tab. - * @since Chrome 18. - */ - openerTabId?: number; - /** - * Optional. - * The URL to navigate the tab to initially. Fully-qualified URLs must include a scheme (i.e. 'http://www.google.com', not 'www.google.com'). Relative URLs will be relative to the current page within the extension. Defaults to the New Tab Page. - */ - url?: string; - /** - * Optional. Whether the tab should be pinned. Defaults to false - * @since Chrome 9. - */ - pinned?: boolean; - /** Optional. The window to create the new tab in. Defaults to the current window. */ - windowId?: number; - /** - * Optional. - * Whether the tab should become the active tab in the window. Does not affect whether the window is focused (see windows.update). Defaults to true. - * @since Chrome 16. - */ - active?: boolean; - /** - * Optional. Whether the tab should become the selected tab in the window. Defaults to true - * @deprecated since Chrome 33. Please use active. - */ - selected?: boolean; - } - - interface MoveProperties { - /** The position to move the window to. -1 will place the tab at the end of the window. */ - index: number; - /** Optional. Defaults to the window the tab is currently in. */ - windowId?: number; - } - - interface UpdateProperties { - /** - * Optional. Whether the tab should be pinned. - * @since Chrome 9. - */ - pinned?: boolean; - /** - * Optional. The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as this tab. - * @since Chrome 18. - */ - openerTabId?: number; - /** Optional. A URL to navigate the tab to. */ - url?: string; - /** - * Optional. Adds or removes the tab from the current selection. - * @since Chrome 16. - */ - highlighted?: boolean; - /** - * Optional. Whether the tab should be active. Does not affect whether the window is focused (see windows.update). - * @since Chrome 16. - */ - active?: boolean; - /** - * Optional. Whether the tab should be selected. - * @deprecated since Chrome 33. Please use highlighted. - */ - selected?: boolean; - /** - * Optional. Whether the tab should be muted. - * @since Chrome 45. - */ - muted?: boolean; - } - - interface CaptureVisibleTabOptions { - /** - * Optional. - * When format is "jpeg", controls the quality of the resulting image. This value is ignored for PNG images. As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store it will decrease. - */ - quality?: number; - /** - * Optional. The format of an image. - * One of: "jpeg", or "png" - */ - format?: string; - } - - interface ReloadProperties { - /** Optional. Whether using any local cache. Default is false. */ - bypassCache?: boolean; - } - - interface ConnectInfo { - /** Optional. Will be passed into onConnect for content scripts that are listening for the connection event. */ - name?: string; - /** - * Open a port to a specific frame identified by frameId instead of all frames in the tab. - * @since Chrome 41. - */ - frameId?: number; - } - - interface MessageSendOptions { - /** Optional. Send a message to a specific frame identified by frameId instead of all frames in the tab. */ - frameId?: number; - } - - interface HighlightInfo { - /** One or more tab indices to highlight. */ - tabs: number | number[]; - /** Optional. The window that contains the tabs. */ - windowId?: number; - } - - interface QueryInfo { - /** - * Optional. Whether the tabs have completed loading. - * One of: "loading", or "complete" - */ - status?: string; - /** - * Optional. Whether the tabs are in the last focused window. - * @since Chrome 19. - */ - lastFocusedWindow?: boolean; - /** Optional. The ID of the parent window, or windows.WINDOW_ID_CURRENT for the current window. */ - windowId?: number; - /** - * Optional. The type of window the tabs are in. - * One of: "normal", "popup", "panel", "app", or "devtools" - */ - windowType?: string; - /** Optional. Whether the tabs are active in their windows. */ - active?: boolean; - /** - * Optional. The position of the tabs within their windows. - * @since Chrome 18. - */ - index?: number; - /** Optional. Match page titles against a pattern. */ - title?: string; - /** Optional. Match tabs against one or more URL patterns. Note that fragment identifiers are not matched. */ - url?: string | string[]; - /** - * Optional. Whether the tabs are in the current window. - * @since Chrome 19. - */ - currentWindow?: boolean; - /** Optional. Whether the tabs are highlighted. */ - highlighted?: boolean; - /** Optional. Whether the tabs are pinned. */ - pinned?: boolean; - /** - * Optional. Whether the tabs are audible. - * @since Chrome 45. - */ - audible?: boolean; - /** - * Optional. Whether the tabs are muted. - * @since Chrome 45. - */ - muted?: boolean; - } - - interface TabHighlightInfo { - windowId: number; - tabIds: number[]; - } - - interface TabRemoveInfo { - /** - * The window whose tab is closed. - * @since Chrome 25. - */ - windowId: number; - /** True when the tab is being closed because its window is being closed. */ - isWindowClosing: boolean; - } - - interface TabAttachInfo { - newPosition: number; - newWindowId: number; - } - - interface TabChangeInfo { - /** Optional. The status of the tab. Can be either loading or complete. */ - status?: string; - /** - * The tab's new pinned state. - * @since Chrome 9. - */ - pinned?: boolean; - /** Optional. The tab's URL if it has changed. */ - url?: string; - /** - * The tab's new audible state. - * @since Chrome 45. - */ - audible?: boolean; - /** - * The tab's new muted state and the reason for the change. - * @since Chrome 46. Warning: this is the current Beta channel. - */ - mutedInfo?: MutedInfo; - /** - * The tab's new favicon URL. - * @since Chrome 27. - */ - faviconUrl?: string; - } - - interface TabMoveInfo { - toIndex: number; - windowId: number; - fromIndex: number; - } - - interface TabDetachInfo { - oldWindowId: number; - oldPosition: number; - } - - interface TabActiveInfo { - /** The ID of the tab that has become active. */ - tabId: number; - /** The ID of the window the active tab changed inside of. */ - windowId: number; - } - - interface TabWindowInfo { - /** The ID of the window of where the tab is located. */ - windowId: number; - } - - interface ZoomChangeInfo { - tabId: number; - oldZoomFactor: number; - newZoomFactor: number; - zoomSettings: ZoomSettings; - } - - interface TabHighlightedEvent extends chrome.events.Event<(highlightInfo: HighlightInfo) => void> {} - - interface TabRemovedEvent extends chrome.events.Event<(tabId: number, removeInfo: TabRemoveInfo) => void> {} - - interface TabUpdatedEvent extends chrome.events.Event<(tabId: number, changeInfo: TabChangeInfo, tab: Tab) => void> {} - - interface TabAttachedEvent extends chrome.events.Event<(tabId: number, attachInfo: TabAttachInfo) => void> {} - - interface TabMovedEvent extends chrome.events.Event<(tabId: number, moveInfo: TabMoveInfo) => void> {} - - interface TabDetachedEvent extends chrome.events.Event<(tabId: number, detachInfo: TabDetachInfo) => void> {} - - interface TabCreatedEvent extends chrome.events.Event<(tab: Tab) => void> {} - - interface TabActivatedEvent extends chrome.events.Event<(activeInfo: TabActiveInfo) => void> {} - - interface TabReplacedEvent extends chrome.events.Event<(addedTabId: number, removedTabId: number) => void> {} - - interface TabSelectedEvent extends chrome.events.Event<(tabId: number, selectInfo: TabWindowInfo) => void> {} - - interface TabZoomChangeEvent extends chrome.events.Event<(ZoomChangeInfo: ZoomChangeInfo) => void> {} - - /** - * Injects JavaScript code into a page. For details, see the programmatic injection section of the content scripts doc. - * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. - * @param callback Optional. Called after all the JavaScript has been executed. - * Parameter result: The result of the script in every injected frame. - */ - export function executeScript(details: InjectDetails, callback?: (result: any[]) => void): void; - /** - * Injects JavaScript code into a page. For details, see the programmatic injection section of the content scripts doc. - * @param tabId Optional. The ID of the tab in which to run the script; defaults to the active tab of the current window. - * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. - * @param callback Optional. Called after all the JavaScript has been executed. - * Parameter result: The result of the script in every injected frame. - */ - export function executeScript(tabId: number, details: InjectDetails, callback?: (result: any[]) => void): void; - /** Retrieves details about the specified tab. */ - export function get(tabId: number, callback: (tab: Tab) => void): void; - /** - * Gets details about all tabs in the specified window. - * @deprecated since Chrome 33. Please use tabs.query {windowId: windowId}. - */ - export function getAllInWindow(callback: (tab: Tab) => void): void; - /** - * Gets details about all tabs in the specified window. - * @deprecated since Chrome 33. Please use tabs.query {windowId: windowId}. - * @param windowId Optional. Defaults to the current window. - */ - export function getAllInWindow(windowId: number, callback: (tab: Tab) => void): void; - /** Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view). */ - export function getCurrent(callback: (tab?: Tab) => void): void; - /** - * Gets the tab that is selected in the specified window. - * @deprecated since Chrome 33. Please use tabs.query {active: true}. - */ - export function getSelected(callback: (tab: Tab) => void): void; - /** - * Gets the tab that is selected in the specified window. - * @deprecated since Chrome 33. Please use tabs.query {active: true}. - * @param windowId Optional. Defaults to the current window. - */ - export function getSelected(windowId: number, callback: (tab: Tab) => void): void; - /** - * Creates a new tab. - * @param callback Optional. - * Parameter tab: Details about the created tab. Will contain the ID of the new tab. - */ - export function create(createProperties: CreateProperties, callback?: (tab: Tab) => void): void; - /** - * Moves one or more tabs to a new position within its window, or to a new window. Note that tabs can only be moved to and from normal (window.type === "normal") windows. - * @param tabId The tab to move. - * @param callback Optional. - * Parameter tab: Details about the moved tab. - */ - export function move(tabId: number, moveProperties: MoveProperties, callback?: (tab: Tab) => void): void; - /** - * Moves one or more tabs to a new position within its window, or to a new window. Note that tabs can only be moved to and from normal (window.type === "normal") windows. - * @param tabIds The tabs to move. - * @param callback Optional. - * Parameter tabs: Details about the moved tabs. - */ - export function move(tabIds: number[], moveProperties: MoveProperties, callback?: (tabs: Tab[]) => void): void; - /** - * Modifies the properties of a tab. Properties that are not specified in updateProperties are not modified. - * @param callback Optional. - * Optional parameter tab: Details about the updated tab. The tabs.Tab object doesn't contain url, title and favIconUrl if the "tabs" permission has not been requested. - */ - export function update(updateProperties: UpdateProperties, callback?: (tab?: Tab) => void): void; - /** - * Modifies the properties of a tab. Properties that are not specified in updateProperties are not modified. - * @param tabId Defaults to the selected tab of the current window. - * @param callback Optional. - * Optional parameter tab: Details about the updated tab. The tabs.Tab object doesn't contain url, title and favIconUrl if the "tabs" permission has not been requested. - */ - export function update(tabId: number, updateProperties: UpdateProperties, callback?: (tab?: Tab) => void): void; - /** - * Closes a tab. - * @param tabId The tab to close. - */ - export function remove(tabId: number, callback?: Function): void; - /** - * Closes several tabs. - * @param tabIds The list of tabs to close. - */ - export function remove(tabIds: number[], callback?: Function): void; - /** - * Captures the visible area of the currently active tab in the specified window. You must have permission to use this method. - * @param callback - * Parameter dataUrl: A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. - */ - export function captureVisibleTab(callback: (dataUrl: string) => void): void; - /** - * Captures the visible area of the currently active tab in the specified window. You must have permission to use this method. - * @param windowId Optional. The target window. Defaults to the current window. - * @param callback - * Parameter dataUrl: A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. - */ - export function captureVisibleTab(windowId: number, callback: (dataUrl: string) => void): void; - /** - * Captures the visible area of the currently active tab in the specified window. You must have permission to use this method. - * @param options Optional. Details about the format and quality of an image. - * @param callback - * Parameter dataUrl: A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. - */ - export function captureVisibleTab(options: CaptureVisibleTabOptions, callback: (dataUrl: string) => void): void; - /** - * Captures the visible area of the currently active tab in the specified window. You must have permission to use this method. - * @param windowId Optional. The target window. Defaults to the current window. - * @param options Optional. Details about the format and quality of an image. - * @param callback - * Parameter dataUrl: A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. - */ - export function captureVisibleTab(windowId: number, options: CaptureVisibleTabOptions, callback: (dataUrl: string) => void): void; - /** - * Reload a tab. - * @since Chrome 16. - * @param tabId The ID of the tab to reload; defaults to the selected tab of the current window. - */ - export function reload(tabId: number, reloadProperties?: ReloadProperties, callback?: () => void): void; - /** - * Reload the selected tab of the current window. - * @since Chrome 16. - */ - export function reload(reloadProperties: ReloadProperties, callback?: () => void): void; - /** - * Reload the selected tab of the current window. - * @since Chrome 16. - */ - export function reload(callback?: () => void): void; - /** - * Duplicates a tab. - * @since Chrome 23. - * @param tabId The ID of the tab which is to be duplicated. - * @param callback Optional. - * Optional parameter tab: Details about the duplicated tab. The tabs.Tab object doesn't contain url, title and favIconUrl if the "tabs" permission has not been requested. - */ - export function duplicate(tabId: number, callback?: (tab?: Tab) => void): void; - /** - * Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The runtime.onMessage event is fired in each content script running in the specified tab for the current extension. - * @since Chrome 20. - */ - export function sendMessage(tabId: number, message: any, responseCallback?: (response: any) => void): void; - /** - * Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The runtime.onMessage event is fired in each content script running in the specified tab for the current extension. - * @since Chrome 41. - * @param responseCallback Optional. - * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the specified tab, the callback will be called with no arguments and runtime.lastError will be set to the error message. - */ - export function sendMessage(tabId: number, message: any, options: MessageSendOptions, responseCallback?: (response: any) => void): void; - /** - * Sends a single request to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The extension.onRequest event is fired in each content script running in the specified tab for the current extension. - * @deprecated since Chrome 33. Please use runtime.sendMessage. - * @param responseCallback Optional. - * Parameter response: The JSON response object sent by the handler of the request. If an error occurs while connecting to the specified tab, the callback will be called with no arguments and runtime.lastError will be set to the error message. - */ - export function sendRequest(tabId: number, request: any, responseCallback?: (response: any) => void): void; - /** Connects to the content script(s) in the specified tab. The runtime.onConnect event is fired in each content script running in the specified tab for the current extension. */ - export function connect(tabId: number, connectInfo?: ConnectInfo): runtime.Port; - /** - * Injects CSS into a page. For details, see the programmatic injection section of the content scripts doc. - * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. - * @param callback Optional. Called when all the CSS has been inserted. - */ - export function insertCSS(details: InjectDetails, callback?: Function): void; - /** - * Injects CSS into a page. For details, see the programmatic injection section of the content scripts doc. - * @param tabId Optional. The ID of the tab in which to insert the CSS; defaults to the active tab of the current window. - * @param details Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. - * @param callback Optional. Called when all the CSS has been inserted. - */ - export function insertCSS(tabId: number, details: InjectDetails, callback?: Function): void; - /** - * Highlights the given tabs. - * @since Chrome 16. - * @param callback Optional. - * Parameter window: Contains details about the window whose tabs were highlighted. - */ - export function highlight(highlightInfo: HighlightInfo, callback: (window: chrome.windows.Window) => void): void; - /** - * Gets all tabs that have the specified properties, or all tabs if no properties are specified. - * @since Chrome 16. - */ - export function query(queryInfo: QueryInfo, callback: (result: Tab[]) => void): void; - /** - * Detects the primary language of the content in a tab. - * @param callback - * Parameter language: An ISO language code such as en or fr. For a complete list of languages supported by this method, see kLanguageInfoTable. The 2nd to 4th columns will be checked and the first non-NULL value will be returned except for Simplified Chinese for which zh-CN will be returned. For an unknown language, und will be returned. - */ - export function detectLanguage(callback: (language: string) => void): void; - /** - * Detects the primary language of the content in a tab. - * @param tabId Optional. Defaults to the active tab of the current window. - * @param callback - * Parameter language: An ISO language code such as en or fr. For a complete list of languages supported by this method, see kLanguageInfoTable. The 2nd to 4th columns will be checked and the first non-NULL value will be returned except for Simplified Chinese for which zh-CN will be returned. For an unknown language, und will be returned. - */ - export function detectLanguage(tabId: number, callback: (language: string) => void): void; - /** - * Zooms a specified tab. - * @since Chrome 42. - * @param zoomFactor The new zoom factor. Use a value of 0 here to set the tab to its current default zoom factor. Values greater than zero specify a (possibly non-default) zoom factor for the tab. - * @param callback Optional. Called after the zoom factor has been changed. - */ - export function setZoom(zoomFactor: number, callback?: () => void): void; - /** - * Zooms a specified tab. - * @since Chrome 42. - * @param tabId Optional. The ID of the tab to zoom; defaults to the active tab of the current window. - * @param zoomFactor The new zoom factor. Use a value of 0 here to set the tab to its current default zoom factor. Values greater than zero specify a (possibly non-default) zoom factor for the tab. - * @param callback Optional. Called after the zoom factor has been changed. - */ - export function setZoom(tabId: number, zoomFactor: number, callback?: () => void): void; - /** - * Gets the current zoom factor of a specified tab. - * @since Chrome 42. - * @param callback Called with the tab's current zoom factor after it has been fetched. - * Parameter zoomFactor: The tab's current zoom factor. - */ - export function getZoom(callback: (zoomFactor: number) => void): void; - /** - * Gets the current zoom factor of a specified tab. - * @since Chrome 42. - * @param tabId Optional. The ID of the tab to get the current zoom factor from; defaults to the active tab of the current window. - * @param callback Called with the tab's current zoom factor after it has been fetched. - * Parameter zoomFactor: The tab's current zoom factor. - */ - export function getZoom(tabId: number, callback: (zoomFactor: number) => void): void; - /** - * Sets the zoom settings for a specified tab, which define how zoom changes are handled. These settings are reset to defaults upon navigating the tab. - * @since Chrome 42. - * @param zoomSettings Defines how zoom changes are handled and at what scope. - * @param callback Optional. Called after the zoom settings have been changed. - */ - export function setZoomSettings(zoomSettings: ZoomSettings, callback?: () => void): void; - /** - * Sets the zoom settings for a specified tab, which define how zoom changes are handled. These settings are reset to defaults upon navigating the tab. - * @since Chrome 42. - * @param tabId Optional. The ID of the tab to change the zoom settings for; defaults to the active tab of the current window. - * @param zoomSettings Defines how zoom changes are handled and at what scope. - * @param callback Optional. Called after the zoom settings have been changed. - */ - export function setZoomSettings(tabId: number, zoomSettings: ZoomSettings, callback?: () => void): void; - /** - * Gets the current zoom settings of a specified tab. - * @since Chrome 42. - * @param callback Called with the tab's current zoom settings. - * Paramater zoomSettings: The tab's current zoom settings. - */ - export function getZoomSettings(callback: (zoomSettings: ZoomSettings) => void): void; - /** - * Gets the current zoom settings of a specified tab. - * @since Chrome 42. - * @param tabId Optional. The ID of the tab to get the current zoom settings from; defaults to the active tab of the current window. - * @param callback Called with the tab's current zoom settings. - * Paramater zoomSettings: The tab's current zoom settings. - */ - export function getZoomSettings(tabId: number, callback: (zoomSettings: ZoomSettings) => void): void; - - /** - * Fired when the highlighted or selected tabs in a window changes. - * @since Chrome 18. - */ - var onHighlighted: TabHighlightedEvent; - /** Fired when a tab is closed. */ - var onRemoved: TabRemovedEvent; - /** Fired when a tab is updated. */ - var onUpdated: TabUpdatedEvent; - /** Fired when a tab is attached to a window, for example because it was moved between windows. */ - var onAttached: TabAttachedEvent; - /** - * Fired when a tab is moved within a window. Only one move event is fired, representing the tab the user directly moved. Move events are not fired for the other tabs that must move in response. This event is not fired when a tab is moved between windows. For that, see tabs.onDetached. - */ - var onMoved: TabMovedEvent; - /** Fired when a tab is detached from a window, for example because it is being moved between windows. */ - var onDetached: TabDetachedEvent; - /** Fired when a tab is created. Note that the tab's URL may not be set at the time this event fired, but you can listen to onUpdated events to be notified when a URL is set. */ - var onCreated: TabCreatedEvent; - /** - * Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to onUpdated events to be notified when a URL is set. - * @since Chrome 18. - */ - var onActivated: TabActivatedEvent; - /** - * Fired when a tab is replaced with another tab due to prerendering or instant. - * @since Chrome 26. - */ - var onReplaced: TabReplacedEvent; - /** - * @deprecated since Chrome 33. Please use tabs.onActivated. - * Fires when the selected tab in a window changes. - */ - var onSelectionChanged: TabSelectedEvent; - /** - * @deprecated since Chrome 33. Please use tabs.onActivated. - * Fires when the selected tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to tabs.onUpdated events to be notified when a URL is set. - */ - var onActiveChanged: TabSelectedEvent; - /** - * @deprecated since Chrome 33. Please use tabs.onHighlighted. - * Fired when the highlighted or selected tabs in a window changes. - */ - var onHighlightChanged: TabHighlightedEvent; - /** - * Fired when a tab is zoomed. - * @since Chrome 38. - */ - var onZoomChange: TabZoomChangeEvent; -} - -//////////////////// -// Top Sites -//////////////////// -/** - * Use the chrome.topSites API to access the top sites that are displayed on the new tab page. - * Permissions: "topSites" - * @since Chrome 19. - */ -declare namespace chrome.topSites { - /** An object encapsulating a most visited URL, such as the URLs on the new tab page. */ - interface MostVisitedURL { - /** The most visited URL. */ - url: string; - /** The title of the page */ - title: string; - } - - /** Gets a list of top sites. */ - export function get(callback: (data: MostVisitedURL[]) => void): void; -} - -//////////////////// -// Text to Speech -//////////////////// -/** - * Use the chrome.tts API to play synthesized text-to-speech (TTS). See also the related ttsEngine API, which allows an extension to implement a speech engine. - * Permissions: "tts" - * @since Chrome 14. - */ -declare namespace chrome.tts { - /** An event from the TTS engine to communicate the status of an utterance. */ - interface TtsEvent { - /** Optional. The index of the current character in the utterance. */ - charIndex?: number; - /** Optional. The error description, if the event type is 'error'. */ - errorMessage?: string; - /** - * The type can be 'start' as soon as speech has started, 'word' when a word boundary is reached, 'sentence' when a sentence boundary is reached, 'marker' when an SSML mark element is reached, 'end' when the end of the utterance is reached, 'interrupted' when the utterance is stopped or interrupted before reaching the end, 'cancelled' when it's removed from the queue before ever being synthesized, or 'error' when any other error occurs. When pausing speech, a 'pause' event is fired if a particular utterance is paused in the middle, and 'resume' if an utterance resumes speech. Note that pause and resume events may not fire if speech is paused in-between utterances. - * One of: "start", "end", "word", "sentence", "marker", "interrupted", "cancelled", "error", "pause", or "resume" - */ - type: string; - } - - /** A description of a voice available for speech synthesis. */ - interface TtsVoice { - /** Optional. The language that this voice supports, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ - lang?: string; - /** - * Optional. This voice's gender. - * One of: "male", or "female" - */ - gender?: string; - /** Optional. The name of the voice. */ - voiceName?: string; - /** The ID of the extension providing this voice. */ - extensionsId?: string; - /** All of the callback event types that this voice is capable of sending. */ - eventTypes?: string[]; - /** - * If true, the synthesis engine is a remote network resource. It may be higher latency and may incur bandwidth costs. - * @since Chrome 33. - */ - remote?: boolean; - } - - interface SpeakOptions { - /** Optional. Speaking volume between 0 and 1 inclusive, with 0 being lowest and 1 being highest, with a default of 1.0. */ - volume?: number; - /** - * Optional. - * If true, enqueues this utterance if TTS is already in progress. If false (the default), interrupts any current speech and flushes the speech queue before speaking this new utterance. - */ - enqueue?: boolean; - /** - * Optional. - * Speaking rate relative to the default rate for this voice. 1.0 is the default rate, normally around 180 to 220 words per minute. 2.0 is twice as fast, and 0.5 is half as fast. Values below 0.1 or above 10.0 are strictly disallowed, but many voices will constrain the minimum and maximum rates further—for example a particular voice may not actually speak faster than 3 times normal even if you specify a value larger than 3.0. - */ - rate?: number; - /** - * Optional. This function is called with events that occur in the process of speaking the utterance. - * @param event The update event from the text-to-speech engine indicating the status of this utterance. - */ - onEvent?: (event: TtsEvent) => void; - /** - * Optional. - * Speaking pitch between 0 and 2 inclusive, with 0 being lowest and 2 being highest. 1.0 corresponds to a voice's default pitch. - */ - pitch?: number; - /** Optional. The language to be used for synthesis, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ - lang?: string; - /** Optional. The name of the voice to use for synthesis. If empty, uses any available voice. */ - voiceName?: string; - /** Optional. The extension ID of the speech engine to use, if known. */ - extensionId?: string; - /** - * Optional. Gender of voice for synthesized speech. - * One of: "male", or "female" - */ - gender?: string; - /** Optional. The TTS event types the voice must support. */ - requiredEventTypes?: string[]; - /** Optional. The TTS event types that you are interested in listening to. If missing, all event types may be sent. */ - desiredEventTypes?: string[]; - } - - /** Checks whether the engine is currently speaking. On Mac OS X, the result is true whenever the system speech engine is speaking, even if the speech wasn't initiated by Chrome. */ - export function isSpeaking(callback?: (speaking: boolean) => void): void; - /** Stops any current speech and flushes the queue of any pending utterances. In addition, if speech was paused, it will now be un-paused for the next call to speak. */ - export function stop(): void; - /** Gets an array of all available voices. */ - export function getVoices(callback?: (voices: TtsVoice[]) => void): void; - /** - * Speaks text using a text-to-speech engine. - * @param utterance The text to speak, either plain text or a complete, well-formed SSML document. Speech engines that do not support SSML will strip away the tags and speak the text. The maximum length of the text is 32,768 characters. - * @param callback Optional. Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback. - */ - export function speak(utterance: string, callback?: Function): void; - /** - * Speaks text using a text-to-speech engine. - * @param utterance The text to speak, either plain text or a complete, well-formed SSML document. Speech engines that do not support SSML will strip away the tags and speak the text. The maximum length of the text is 32,768 characters. - * @param options Optional. The speech options. - * @param callback Optional. Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback. - */ - export function speak(utterance: string, options: SpeakOptions, callback?: Function): void; - /** - * Pauses speech synthesis, potentially in the middle of an utterance. A call to resume or stop will un-pause speech. - * @since Chrome 29. - */ - export function pause(): void; - /** - * If speech was paused, resumes speaking where it left off. - * @since Chrome 29. - */ - export function resume(): void; -} - -//////////////////// -// Text to Speech Engine -//////////////////// -/** - * Use the chrome.ttsEngine API to implement a text-to-speech(TTS) engine using an extension. If your extension registers using this API, it will receive events containing an utterance to be spoken and other parameters when any extension or Chrome App uses the tts API to generate speech. Your extension can then use any available web technology to synthesize and output the speech, and send events back to the calling function to report the status. - * Permissions: "ttsEngine" - * @since Chrome 14. - */ -declare namespace chrome.ttsEngine { - interface SpeakOptions { - /** Optional. The language to be used for synthesis, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ - lang?: string; - /** Optional. The name of the voice to use for synthesis. */ - voiceName?: string; - /** - * Optional. Gender of voice for synthesized speech. - * One of: "male", or "female" - */ - gender?: string; - /** Optional. Speaking volume between 0 and 1 inclusive, with 0 being lowest and 1 being highest, with a default of 1.0. */ - volume?: number; - /** - * Optional. - * Speaking rate relative to the default rate for this voice. 1.0 is the default rate, normally around 180 to 220 words per minute. 2.0 is twice as fast, and 0.5 is half as fast. This value is guaranteed to be between 0.1 and 10.0, inclusive. When a voice does not support this full range of rates, don't return an error. Instead, clip the rate to the range the voice supports. - */ - rate?: number; - /** Optional. Speaking pitch between 0 and 2 inclusive, with 0 being lowest and 2 being highest. 1.0 corresponds to this voice's default pitch. */ - pitch?: number; - } - - interface TtsEngineSpeakEvent extends chrome.events.Event<(utterance: string, options: SpeakOptions, sendTtsEvent: (event: chrome.tts.TtsEvent) => void) => void> {} - - /** Called when the user makes a call to tts.speak() and one of the voices from this extension's manifest is the first to match the options object. */ - var onSpeak: TtsEngineSpeakEvent; - /** Fired when a call is made to tts.stop and this extension may be in the middle of speaking. If an extension receives a call to onStop and speech is already stopped, it should do nothing (not raise an error). If speech is in the paused state, this should cancel the paused state. */ - var onStop: chrome.events.Event<() => void>; - /** - * Optional: if an engine supports the pause event, it should pause the current utterance being spoken, if any, until it receives a resume event or stop event. Note that a stop event should also clear the paused state. - * @since Chrome 29. - */ - var onPause: chrome.events.Event<() => void>; - /** - * Optional: if an engine supports the pause event, it should also support the resume event, to continue speaking the current utterance, if any. Note that a stop event should also clear the paused state. - * @since Chrome 29. - */ - var onResume: chrome.events.Event<() => void>; -} - -//////////////////// -// Types -//////////////////// -/** - * The chrome.types API contains type declarations for Chrome. - * @since Chrome 13. - */ -declare namespace chrome.types { - interface ChromeSettingClearDetails { - /** - * Optional. - * The scope of the ChromeSetting. One of - * • regular: setting for the regular profile (which is inherited by the incognito profile if not overridden elsewhere), - * • regular_only: setting for the regular profile only (not inherited by the incognito profile), - * • incognito_persistent: setting for the incognito profile that survives browser restarts (overrides regular preferences), - * • incognito_session_only: setting for the incognito profile that can only be set during an incognito session and is deleted when the incognito session ends (overrides regular and incognito_persistent preferences). - */ - scope?: string; - } - - interface ChromeSettingSetDetails extends ChromeSettingClearDetails { - /** - * The value of the setting. - * Note that every setting has a specific value type, which is described together with the setting. An extension should not set a value of a different type. - */ - value: any; - /** - * Optional. - * The scope of the ChromeSetting. One of - * • regular: setting for the regular profile (which is inherited by the incognito profile if not overridden elsewhere), - * • regular_only: setting for the regular profile only (not inherited by the incognito profile), - * • incognito_persistent: setting for the incognito profile that survives browser restarts (overrides regular preferences), - * • incognito_session_only: setting for the incognito profile that can only be set during an incognito session and is deleted when the incognito session ends (overrides regular and incognito_persistent preferences). - */ - scope?: string; - } - - interface ChromeSettingGetDetails { - /** Optional. Whether to return the value that applies to the incognito session (default false). */ - incognito?: boolean; - } - - /** - * @param details Details of the currently effective value. - */ - type DetailsCallback = (details: ChromeSettingGetResultDetails) => void; - - interface ChromeSettingGetResultDetails { - /** - * One of - * • not_controllable: cannot be controlled by any extension - * • controlled_by_other_extensions: controlled by extensions with higher precedence - * • controllable_by_this_extension: can be controlled by this extension - * • controlled_by_this_extension: controlled by this extension - */ - levelOfControl: string; - /** The value of the setting. */ - value: any; - /** - * Optional. - * Whether the effective value is specific to the incognito session. - * This property will only be present if the incognito property in the details parameter of get() was true. - */ - incognitoSpecific?: boolean; - } - - interface ChromeSettingChangedEvent extends chrome.events.Event {} - - /** An interface that allows access to a Chrome browser setting. See accessibilityFeatures for an example. */ - interface ChromeSetting { - /** - * Sets the value of a setting. - * @param details Which setting to change. - * @param callback Optional. Called at the completion of the set operation. - */ - set(details: ChromeSettingSetDetails, callback?: Function): void; - /** - * Gets the value of a setting. - * @param details Which setting to consider. - */ - get(details: ChromeSettingGetDetails, callback?: DetailsCallback): void; - /** - * Clears the setting, restoring any default value. - * @param details Which setting to clear. - * @param callback Optional. Called at the completion of the clear operation. - */ - clear(details: ChromeSettingClearDetails, callback?: Function): void; - /** Fired after the setting changes. */ - onChange: ChromeSettingChangedEvent; - } -} - -//////////////////// -// VPN Provider -//////////////////// -/** - * Use the chrome.vpnProvider API to implement a VPN client. - * Permissions: "vpnProvider" - * Important: This API works only on Chrome OS. - * @since Chrome 43. - */ -declare namespace chrome.vpnProvider { - interface VpnSessionParameters { - /** IP address for the VPN interface in CIDR notation. IPv4 is currently the only supported mode. */ - address: string; - /** Optional. Broadcast address for the VPN interface. (default: deduced from IP address and mask) */ - broadcastAddress?: string; - /** Optional. MTU setting for the VPN interface. (default: 1500 bytes) */ - mtu?: string; - /** - * Exclude network traffic to the list of IP blocks in CIDR notation from the tunnel. This can be used to bypass traffic to and from the VPN server. When many rules match a destination, the rule with the longest matching prefix wins. Entries that correspond to the same CIDR block are treated as duplicates. Such duplicates in the collated (exclusionList + inclusionList) list are eliminated and the exact duplicate entry that will be eliminated is undefined. - */ - exclusionList: string[]; - /** - * Include network traffic to the list of IP blocks in CIDR notation to the tunnel. This parameter can be used to set up a split tunnel. By default no traffic is directed to the tunnel. Adding the entry "0.0.0.0/0" to this list gets all the user traffic redirected to the tunnel. When many rules match a destination, the rule with the longest matching prefix wins. Entries that correspond to the same CIDR block are treated as duplicates. Such duplicates in the collated (exclusionList + inclusionList) list are eliminated and the exact duplicate entry that will be eliminated is undefined. - */ - inclusionList: string[]; - /** Optional. A list of search domains. (default: no search domain) */ - domainSearch?: string[]; - /** A list of IPs for the DNS servers. */ - dnsServer: string[]; - } - - interface VpnPlatformMessageEvent extends chrome.events.Event<(id: string, message: string, error: string) => void> {} - - interface VpnPacketReceptionEvent extends chrome.events.Event<(data: ArrayBuffer) => void> {} - - interface VpnConfigRemovalEvent extends chrome.events.Event<(id: string) => void> {} - - interface VpnConfigCreationEvent extends chrome.events.Event<(id: string, name: string, data: Object) => void> {} - - interface VpnUiEvent extends chrome.events.Event<(event: string, id?: string) => void> {} - - /** - * Creates a new VPN configuration that persists across multiple login sessions of the user. - * @param name The name of the VPN configuration. - * @param callback Called when the configuration is created or if there is an error. - * Parameter id: A unique ID for the created configuration, empty string on failure. - */ - export function createConfig(name: string, callback: (id: string) => void): void; - /** - * Destroys a VPN configuration created by the extension. - * @param id ID of the VPN configuration to destroy. - * @param callback Optional. Called when the configuration is destroyed or if there is an error. - */ - export function destroyConfig(id: string, callback?: Function): void; - /** - * Sets the parameters for the VPN session. This should be called immediately after "connected" is received from the platform. This will succeed only when the VPN session is owned by the extension. - * @param parameters The parameters for the VPN session. - * @param callback Called when the parameters are set or if there is an error. - */ - export function setParameters(parameters: VpnSessionParameters, callback: Function): void; - /** - * Sends an IP packet through the tunnel created for the VPN session. This will succeed only when the VPN session is owned by the extension. - * @param data The IP packet to be sent to the platform. - * @param callback Optional. Called when the packet is sent or if there is an error. - */ - export function sendPacket(data: ArrayBuffer, callback?: Function): void; - /** - * Notifies the VPN session state to the platform. This will succeed only when the VPN session is owned by the extension. - * @param state The VPN session state of the VPN client. - * connected: VPN connection was successful. - * failure: VPN connection failed. - * @param callback Optional. Called when the notification is complete or if there is an error. - */ - export function notifyConnectionStateChanged(state: string, callback?: Function): void; - - /** Triggered when a message is received from the platform for a VPN configuration owned by the extension. */ - var onPlatformMessage: VpnPlatformMessageEvent; - /** Triggered when an IP packet is received via the tunnel for the VPN session owned by the extension. */ - var onPacketReceived: VpnPacketReceptionEvent; - /** Triggered when a configuration created by the extension is removed by the platform. */ - var onConfigRemoved: VpnConfigRemovalEvent; - /** Triggered when a configuration is created by the platform for the extension. */ - var onConfigCreated: VpnConfigCreationEvent; - /** Triggered when there is a UI event for the extension. UI events are signals from the platform that indicate to the app that a UI dialog needs to be shown to the user. */ - var onUIEvent: VpnUiEvent; -} - -//////////////////// -// Wallpaper -//////////////////// -/** - * Use the chrome.wallpaper API to change the ChromeOS wallpaper. - * Permissions: "wallpaper" - * Important: This API works only on Chrome OS. - * @since Chrome 43. - */ -declare namespace chrome.wallpaper { - interface WallpaperDetails { - /** Optional. The jpeg or png encoded wallpaper image. */ - data?: any; - /** Optional. The URL of the wallpaper to be set. */ - url?: string; - /** - * The supported wallpaper layouts. - * One of: "STRETCH", "CENTER", or "CENTER_CROPPED" - */ - layout: string; - /** The file name of the saved wallpaper. */ - filename: string; - /** Optional. True if a 128x60 thumbnail should be generated. */ - thumbnail?: boolean; - } - - /** - * Sets wallpaper to the image at url or wallpaperData with the specified layout - * @param callback - * Optional parameter thumbnail: The jpeg encoded wallpaper thumbnail. It is generated by resizing the wallpaper to 128x60. - */ - export function setWallpaper(details: WallpaperDetails, callback: (thumbnail: any) => void): void; -} - -//////////////////// -// Web Navigation -//////////////////// -/** - * Use the chrome.webNavigation API to receive notifications about the status of navigation requests in-flight. - * Permissions: "webNavigation" - * @since Chrome 16. - */ -declare namespace chrome.webNavigation { - interface GetFrameDetails { - /** - * The ID of the process runs the renderer for this tab. - * @since Chrome 22. - */ - processId: number; - /** The ID of the tab in which the frame is. */ - tabId: number; - /** The ID of the frame in the given tab. */ - frameId: number; - } - - interface GetFrameResultDetails { - /** The URL currently associated with this frame, if the frame identified by the frameId existed at one point in the given tab. The fact that an URL is associated with a given frameId does not imply that the corresponding frame still exists. */ - url: string; - /** True if the last navigation in this frame was interrupted by an error, i.e. the onErrorOccurred event fired. */ - errorOccurred: boolean; - /** ID of frame that wraps the frame. Set to -1 of no parent frame exists. */ - parentFrameId: number; - } - - interface GetAllFrameDetails { - /** The ID of the tab. */ - tabId: number; - } - - interface GetAllFrameResultDetails extends GetFrameResultDetails { - /** The ID of the process runs the renderer for this tab. */ - processId: number; - /** The ID of the frame. 0 indicates that this is the main frame; a positive value indicates the ID of a subframe. */ - frameId: number; - } - - interface WebNavigationCallbackDetails { - /** The ID of the tab in which the navigation is about to occur. */ - tabId: number; - /** The time when the browser was about to start the navigation, in milliseconds since the epoch. */ - timeStamp: number; - } - - interface WebNavigationUrlCallbackDetails extends WebNavigationCallbackDetails { - url: string; - } - - interface WebNavigationReplacementCallbackDetails extends WebNavigationCallbackDetails { - /** The ID of the tab that was replaced. */ - replacedTabId: number; - } - - interface WebNavigationFramedCallbackDetails extends WebNavigationUrlCallbackDetails { - /** 0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique for a given tab and process. */ - frameId: number; - /** - * The ID of the process runs the renderer for this tab. - * @since Chrome 22. - */ - processId: number; - } - - interface WebNavigationFramedErrorCallbackDetails extends WebNavigationFramedCallbackDetails { - /** The error description. */ - error: string; - } - - interface WebNavigationSourceCallbackDetails extends WebNavigationUrlCallbackDetails { - /** The ID of the tab in which the navigation is triggered. */ - sourceTabId: number; - /** - * The ID of the process runs the renderer for the source tab. - * @since Chrome 22. - */ - sourceProcessId: number; - /** The ID of the frame with sourceTabId in which the navigation is triggered. 0 indicates the main frame. */ - sourceFrameId: number; - } - - interface WebNavigationParentedCallbackDetails extends WebNavigationFramedCallbackDetails { - /** - * ID of frame that wraps the frame. Set to -1 of no parent frame exists. - * @since Chrome 24. - */ - parentFrameId: number; - } - - interface WebNavigationTransitionCallbackDetails extends WebNavigationFramedCallbackDetails { - /** - * Cause of the navigation. - * One of: "link", "typed", "auto_bookmark", "auto_subframe", "manual_subframe", "generated", "start_page", "form_submit", "reload", "keyword", or "keyword_generated" - */ - transitionType: string; - /** - * A list of transition qualifiers. - * Each element one of: "client_redirect", "server_redirect", "forward_back", or "from_address_bar" - */ - transitionQualifiers: string[]; - } - - interface WebNavigationEventFilter { - /** Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event. */ - url: chrome.events.UrlFilter[]; - } - - interface WebNavigationEvent extends chrome.events.Event<(details: T) => void> { - addListener(callback: (details: T) => void, filters?: WebNavigationEventFilter): void; - } - - interface WebNavigationFramedEvent extends WebNavigationEvent {} - - interface WebNavigationFramedErrorEvent extends WebNavigationEvent {} - - interface WebNavigationSourceEvent extends WebNavigationEvent {} - - interface WebNavigationParentedEvent extends WebNavigationEvent {} - - interface WebNavigationTransitionalEvent extends WebNavigationEvent {} - - interface WebNavigationReplacementEvent extends WebNavigationEvent {} - - /** - * Retrieves information about the given frame. A frame refers to an ' + */ + iframe_markup?: string; + + /** + * @default '
{content}
' + */ + inline_markup?: string; + + /** + * @default '' + */ + custom_markup?: string; + + /** + * Markup for social tools, set to html or false to disable + * @default '
' + */ + social_tools?: any; + } + + interface moduleJQuery { + /** + * Initialises prettyPhoto + */ + (): JQuery; + + /** + * Initialises prettyPhoto specificying overrides for the defaults + * @param pp_settings custom prettyPhoto settings + */ + (pp_settings: PrettyPhotoSettings): JQuery; + } + + interface moduleJQueryStatic { + /** + * prettyPhoto version number + */ + version: string; + + /** + * Opens the prettyPhoto modal box. + * Note: Always returns false. + */ + open(): boolean; + + /** + * Opens the prettyPhoto modal box. + * Note: Always returns false. + * @param image {String} Full path to the image to be open, can also be an array containing full images paths. + * @param title {String} The title to be displayed with the picture, can also be an array containing all the titles. + * @param description {String} The description to be displayed with the picture, can also be an array containing all the descriptions. + */ + open(image: string, title: string, description: string): boolean; + + /** + * Opens the prettyPhoto modal box. + * Note: Always returns false. + * @param image {Array} Full path to the image to be open, can also be an array containing full images paths. + * @param title {Array} The title to be displayed with the picture, can also be an array containing all the titles. + * @param description {Array} The description to be displayed with the picture, can also be an array containing all the descriptions. + */ + open(images: string[], titles: string[], descriptions: string[]): boolean; + + /** + * Change page in the prettyPhoto modal box + * @param direction {String} Direction of the paging, previous or next. + */ + changePage(direction: string): void; + + /** + * Change gallery page in the prettyPhoto modal box + * @param direction {String} Direction of the paging, previous or next. + */ + changeGalleryPage(direction: string): void; + + /** + * Start the slideshow... + */ + startSlideshow(): void; + + /** + * Stop the slideshow... + */ + stopSlideshow(): void; + + /** + * Closes prettyPhoto. + */ + close(): void; + } +} + +interface JQuery { + prettyPhoto: scaron_prettyPhoto.moduleJQuery; +} + +interface JQueryStatic { + prettyPhoto: scaron_prettyPhoto.moduleJQueryStatic; +} diff --git a/jquery.prettyphoto/jquery.prettyphoto-tests.ts b/jquery.prettyphoto/jquery.prettyphoto-tests.ts index 1cf3b40a89..54198cc265 100644 --- a/jquery.prettyphoto/jquery.prettyphoto-tests.ts +++ b/jquery.prettyphoto/jquery.prettyphoto-tests.ts @@ -1,7 +1,7 @@ // Tests for prettyPhoto library -/// -/// +/// + // JQUERY diff --git a/jquery.prettyphoto/jquery.prettyphoto.d.ts b/jquery.prettyphoto/jquery.prettyphoto.d.ts deleted file mode 100644 index dc0003212d..0000000000 --- a/jquery.prettyphoto/jquery.prettyphoto.d.ts +++ /dev/null @@ -1,290 +0,0 @@ -// Type definitions for jQuery prettyPhoto 3.1.5 -// Project: https://github.com/scaron/prettyphoto -// Definitions by: pgaske -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace scaron_prettyPhoto { - /** - * Pretty photo settings - */ - interface PrettyPhotoSettings { - /** - * the attribute tag to use for prettyPhoto hooks. For HTML5, use "data-rel" or similar. - * @default 'rel' - */ - hook?: string; - - /** - * fast/slow/normal - * @default 'fast' - */ - animation_speed?: string; - - - ajaxcallback?: () => void; - - /** - * false OR interval time in ms - * @default 5000 - */ - slideshow?: any; - - /** - * true/false - * @default false - */ - autoplay_slideshow?: boolean; - - /** - * Value between 0 and 1 - * @default 0.80 - */ - opacity?: number; - - /** - * true/false - * @default true - */ - show_title?: boolean; - - /** - * Resize the photos bigger than viewport. true/false - * @default true - */ - allow_resize?: boolean; - - /** - * Allow the user to expand a resized image. true/false - * @default true - */ - allow_expand?: boolean; - - /** - * Pixels - * @default 500 - */ - default_width?: number; - - /** - * Pixels - * @default 344 - */ - default_height?: number; - - /** - * The separator for the gallery counter 1 "of" 2 - * @default '/' - */ - counter_separator_label?: string; - - /** - * light_rounded / dark_rounded / light_square / dark_square / facebook - * @default 'pp_default' - */ - theme?: string; - - /** - * The padding on each side of the picture - * @default 20 - */ - horizontal_padding?: number; - - /** - * Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto - * @default false - */ - hideflash?: boolean; - - /** - * Set the flash wmode attribute - * @default 'opaque' - */ - wmode?: string; - - /** - * Automatically start videos: True/False - * @default true - */ - autoplay?: boolean; - - /** - * If set to true, only the close button will close the window - * @default false - */ - modal?: boolean; - - /** - * Allow prettyPhoto to update the url to enable deeplinking. - * @default true - */ - deeplinking?: boolean; - - /** - * If set to true, a gallery will overlay the fullscreen image on mouse over - * @default true - */ - overlay_gallery?: boolean; - - /** - * Maximum number of pictures in the overlay gallery - * @default 30 - */ - overlay_gallery_max?: number; - - /** - * Set to false if you open forms inside prettyPhoto - * @default true - */ - keyboard_shortcuts?: boolean; - - /** - * Called everytime an item is shown/changed - * @default function () { } - */ - changepicturecallback?: () => void; - - /** - * Called when prettyPhoto is closed - * @default function () { } - */ - callback?: () => void; - - /** - * @default true - */ - ie6_fallback?: boolean; - - /** - * Markup for pretty photo - * @default omitted for brevity - */ - markup?: string; - - /** - * Markup for pretty photo gallery - * @default omitted for brevity - */ - gallery_markup?: string; - - /** - * Markup for image - * @default '' - */ - image_markup?: string; - - /** - * Markup for flash - * @default '' - */ - flash_markup?: string; - - /** - * Markup for quicktime - * @default '' - */ - quicktime_markup?: string; - - /** - * Markup for iframe - * @default '' - */ - iframe_markup?: string; - - /** - * @default '
{content}
' - */ - inline_markup?: string; - - /** - * @default '' - */ - custom_markup?: string; - - /** - * Markup for social tools, set to html or false to disable - * @default '' - */ - social_tools?: any; - } - - interface moduleJQuery { - /** - * Initialises prettyPhoto - */ - (): JQuery; - - /** - * Initialises prettyPhoto specificying overrides for the defaults - * @param pp_settings custom prettyPhoto settings - */ - (pp_settings: PrettyPhotoSettings): JQuery; - } - - interface moduleJQueryStatic { - /** - * prettyPhoto version number - */ - version: string; - - /** - * Opens the prettyPhoto modal box. - * Note: Always returns false. - */ - open(): boolean; - - /** - * Opens the prettyPhoto modal box. - * Note: Always returns false. - * @param image {String} Full path to the image to be open, can also be an array containing full images paths. - * @param title {String} The title to be displayed with the picture, can also be an array containing all the titles. - * @param description {String} The description to be displayed with the picture, can also be an array containing all the descriptions. - */ - open(image: string, title: string, description: string): boolean; - - /** - * Opens the prettyPhoto modal box. - * Note: Always returns false. - * @param image {Array} Full path to the image to be open, can also be an array containing full images paths. - * @param title {Array} The title to be displayed with the picture, can also be an array containing all the titles. - * @param description {Array} The description to be displayed with the picture, can also be an array containing all the descriptions. - */ - open(images: string[], titles: string[], descriptions: string[]): boolean; - - /** - * Change page in the prettyPhoto modal box - * @param direction {String} Direction of the paging, previous or next. - */ - changePage(direction: string): void; - - /** - * Change gallery page in the prettyPhoto modal box - * @param direction {String} Direction of the paging, previous or next. - */ - changeGalleryPage(direction: string): void; - - /** - * Start the slideshow... - */ - startSlideshow(): void; - - /** - * Stop the slideshow... - */ - stopSlideshow(): void; - - /** - * Closes prettyPhoto. - */ - close(): void; - } -} - -interface JQuery { - prettyPhoto: scaron_prettyPhoto.moduleJQuery; -} - -interface JQueryStatic { - prettyPhoto: scaron_prettyPhoto.moduleJQueryStatic; -} diff --git a/jquery.prettyphoto/tsconfig.json b/jquery.prettyphoto/tsconfig.json new file mode 100644 index 0000000000..15326adc30 --- /dev/null +++ b/jquery.prettyphoto/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.prettyphoto-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.qrcode/index.d.ts b/jquery.qrcode/index.d.ts new file mode 100644 index 0000000000..94504d4dda --- /dev/null +++ b/jquery.qrcode/index.d.ts @@ -0,0 +1,127 @@ +// Type definitions for jQuery.qrcode v0.12.0 +// Project: https://github.com/lrsjng/jquery-qrcode +// Definitions by: Dan Manastireanu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace JQueryQRCode { + /** + * One of the possible mode types. + */ + export const enum Mode { + NORMAL, + LABEL_STRIP, + LABEL_BOX, + IMAGE_STRIP, + IMAGE_BOX + } + + interface Options { + /** + * Render method: 'canvas', 'image' or 'div' + * @default 'canvas' + */ + render?: string, + + /** + * Start of version range, somewhere in 1 .. 40 + * @default 1 + */ + minVersion?: number, + /** + * End of version range, somewhere in 1 .. 40 + * @default 40 + */ + maxVersion?: number, + + /** + * Error correction level: 'L', 'M', 'Q' or 'H' + * @default 'L' + */ + ecLevel?: string, + + /** + * Left offset in pixels, if drawn onto existing canvas + * @default 0 + */ + left?: number, + /** + * Top offset in pixels, if drawn onto existing canvas + * @default 0 + */ + top?: number, + + /** + * Size in pixel + * @default 200 + */ + size?: number, + + /** + * Code color or image element + * @default '#000' + */ + fill?: string, + + /** + * Background color or image element, null for transparent background + * @default null + */ + background?: string, + + /** + * The text content of the QR code. + * @default 'no text' + */ + text?: string, + + /** + * Corner radius relative to module width: 0.0 .. 0.5 + * @default 0 + */ + radius?: number, + + /** + * Quiet zone in modules + * @default 0 + */ + quiet?: number, + + /** + * Mode + * @default Mode.NORMAL + */ + mode?: Mode, + + + /** @default 0.1 */ + mSize?: number, + /** @default 0.5 */ + mPosX?: number, + /** @default 0.5 */ + mPosY?: number, + + /** @default 'no label' */ + label?: string, + /** @default 'sans' */ + fontname?: string, + /** @default '#000' */ + fontcolor?: string, + + /** @default null */ + image?: string + } + + +} + + + +interface JQuery { + /** + * Create a QR Code inside the selected container. + * @param options + */ + qrcode(options?: JQueryQRCode.Options): JQuery; +} diff --git a/jquery.qrcode/jquery.qrcode-tests.ts b/jquery.qrcode/jquery.qrcode-tests.ts index 716010c516..a634bd6f07 100644 --- a/jquery.qrcode/jquery.qrcode-tests.ts +++ b/jquery.qrcode/jquery.qrcode-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// // Examples from website (note: the examples use color instead of fill, which is not supported) $('.container').qrcode(); diff --git a/jquery.qrcode/jquery.qrcode.d.ts b/jquery.qrcode/jquery.qrcode.d.ts deleted file mode 100644 index 0abc536ab6..0000000000 --- a/jquery.qrcode/jquery.qrcode.d.ts +++ /dev/null @@ -1,127 +0,0 @@ -// Type definitions for jQuery.qrcode v0.12.0 -// Project: https://github.com/lrsjng/jquery-qrcode -// Definitions by: Dan Manastireanu -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace JQueryQRCode { - /** - * One of the possible mode types. - */ - export const enum Mode { - NORMAL, - LABEL_STRIP, - LABEL_BOX, - IMAGE_STRIP, - IMAGE_BOX - } - - interface Options { - /** - * Render method: 'canvas', 'image' or 'div' - * @default 'canvas' - */ - render?: string, - - /** - * Start of version range, somewhere in 1 .. 40 - * @default 1 - */ - minVersion?: number, - /** - * End of version range, somewhere in 1 .. 40 - * @default 40 - */ - maxVersion?: number, - - /** - * Error correction level: 'L', 'M', 'Q' or 'H' - * @default 'L' - */ - ecLevel?: string, - - /** - * Left offset in pixels, if drawn onto existing canvas - * @default 0 - */ - left?: number, - /** - * Top offset in pixels, if drawn onto existing canvas - * @default 0 - */ - top?: number, - - /** - * Size in pixel - * @default 200 - */ - size?: number, - - /** - * Code color or image element - * @default '#000' - */ - fill?: string, - - /** - * Background color or image element, null for transparent background - * @default null - */ - background?: string, - - /** - * The text content of the QR code. - * @default 'no text' - */ - text?: string, - - /** - * Corner radius relative to module width: 0.0 .. 0.5 - * @default 0 - */ - radius?: number, - - /** - * Quiet zone in modules - * @default 0 - */ - quiet?: number, - - /** - * Mode - * @default Mode.NORMAL - */ - mode?: Mode, - - - /** @default 0.1 */ - mSize?: number, - /** @default 0.5 */ - mPosX?: number, - /** @default 0.5 */ - mPosY?: number, - - /** @default 'no label' */ - label?: string, - /** @default 'sans' */ - fontname?: string, - /** @default '#000' */ - fontcolor?: string, - - /** @default null */ - image?: string - } - - -} - - - -interface JQuery { - /** - * Create a QR Code inside the selected container. - * @param options - */ - qrcode(options?: JQueryQRCode.Options): JQuery; -} diff --git a/jquery.qrcode/tsconfig.json b/jquery.qrcode/tsconfig.json new file mode 100644 index 0000000000..40d335bbb2 --- /dev/null +++ b/jquery.qrcode/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.qrcode-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.rowGrid/index.d.ts b/jquery.rowGrid/index.d.ts new file mode 100644 index 0000000000..ed6284b54e --- /dev/null +++ b/jquery.rowGrid/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for jQuery rowGrid.js plugin (v1.0.2) +// Project: https://github.com/brunjo/rowGrid.js +// Definitions by: Vinayak Garg +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQueryRowGridJSOptions { + minMargin?: number; + maxMargin?: number; + itemSelector: string; +} + +interface JQuery { + rowGrid(options?: JQueryRowGridJSOptions): JQuery; + rowGrid(appended: string): JQuery; +} \ No newline at end of file diff --git a/jquery.rowGrid/jquery.rowGrid-tests.ts b/jquery.rowGrid/jquery.rowGrid-tests.ts index cb11d65964..ba3e5f822d 100644 --- a/jquery.rowGrid/jquery.rowGrid-tests.ts +++ b/jquery.rowGrid/jquery.rowGrid-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// /* * Test different options diff --git a/jquery.rowGrid/jquery.rowGrid.d.ts b/jquery.rowGrid/jquery.rowGrid.d.ts deleted file mode 100644 index 1613d6d59c..0000000000 --- a/jquery.rowGrid/jquery.rowGrid.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Type definitions for jQuery rowGrid.js plugin (v1.0.2) -// Project: https://github.com/brunjo/rowGrid.js -// Definitions by: Vinayak Garg -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface JQueryRowGridJSOptions { - minMargin?: number; - maxMargin?: number; - itemSelector: string; -} - -interface JQuery { - rowGrid(options?: JQueryRowGridJSOptions): JQuery; - rowGrid(appended: string): JQuery; -} \ No newline at end of file diff --git a/jquery.rowGrid/tsconfig.json b/jquery.rowGrid/tsconfig.json new file mode 100644 index 0000000000..0e3e6885d2 --- /dev/null +++ b/jquery.rowGrid/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.rowGrid-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.scrollTo/index.d.ts b/jquery.scrollTo/index.d.ts new file mode 100644 index 0000000000..3a4f13d1a8 --- /dev/null +++ b/jquery.scrollTo/index.d.ts @@ -0,0 +1,116 @@ +// Type definitions for jQuery.scrollTo.js 1.4.4 +// Project: https://github.com/flesler/jquery.scrollTo +// Definitions by: Neil Stalker +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface ScrollToOptions { + /** + * Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'. + */ + axis?: string; + /** + * The OVERALL length of the animation. + */ + duration?: any; + /** + * The easing method for the animation. + */ + easing?: string; + /** + * If true, the margin of the target element will be deducted from the final position. + */ + margin?: boolean; + /** + * Add/deduct from the end position. + * One number for both axes or { top:x, left:y }. + */ + offset?: any; + /** + * Add/deduct the height/width multiplied by 'over'. + * Can be { top:x, left:y } when using both axes. + */ + over? : any; + /** + * If true, and both axis are given. + * The 2nd axis will only be animated after the first one ends. + */ + queue?: boolean; + /** + * Function to be called after the scrolling ends. + */ + onAfter?: () => void; + /** + * If queuing is activated, this function will be called after the first scrolling ends. + */ + onAfterFirst?: () => void; +} + +interface JQuery { + /** + * Scroll the matched elements + */ + scrollTo: { + /** + * Scroll the matched elements + * + * @param target Where to scroll the matched elements. + * @param duration The OVERALL length of the animation + * @param settings Set of settings. + */ + (target: any, duration?: number, settings?: ScrollToOptions): JQuery; + /** + * Scroll the matched elements + * + * @param target Where to scroll the matched elements. + * @param duration The OVERALL length of the animation + * @param onAfter The onAfter callback. + */ + (target: any, duration: number, onAfter?: Function): JQuery; + /** + * Scroll the matched elements + * + * @param target Where to scroll the matched elements. + * @param settings Set of settings. + * @param onAfter The onAfter callback. + */ + (target: any, settings: ScrollToOptions, onAfter?: Function): JQuery; + + }; + +} + +interface JQueryStatic { + /** + * Scroll window + */ + scrollTo: { + /** + * Scroll window + * + * @param target Where to scroll the matched elements. + * @param duration The OVERALL length of the animation + * @param settings Set of settings. + */ + (target: any, duration?: number, settings?: ScrollToOptions): JQuery; + /** + * Scroll window + * + * @param target Where to scroll the matched elements. + * @param duration The OVERALL length of the animation + * @param onAfter The onAfter callback. + */ + (target: any, duration: number, onAfter?: Function): JQuery; + /** + * Scroll window + * + * @param target Where to scroll the matched elements. + * @param settings Set of settings. + * @param onAfter The onAfter callback. + */ + (target: any, settings: ScrollToOptions, onAfter?: Function): JQuery; + + }; + +} diff --git a/jquery.scrollTo/jquery.scrollTo-tests.ts b/jquery.scrollTo/jquery.scrollTo-tests.ts index 009112606f..303ce0cd01 100644 --- a/jquery.scrollTo/jquery.scrollTo-tests.ts +++ b/jquery.scrollTo/jquery.scrollTo-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// $('div').scrollTo(340); diff --git a/jquery.scrollTo/jquery.scrollTo.d.ts b/jquery.scrollTo/jquery.scrollTo.d.ts deleted file mode 100644 index 484d4dbb78..0000000000 --- a/jquery.scrollTo/jquery.scrollTo.d.ts +++ /dev/null @@ -1,116 +0,0 @@ -// Type definitions for jQuery.scrollTo.js 1.4.4 -// Project: https://github.com/flesler/jquery.scrollTo -// Definitions by: Neil Stalker -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface ScrollToOptions { - /** - * Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'. - */ - axis?: string; - /** - * The OVERALL length of the animation. - */ - duration?: any; - /** - * The easing method for the animation. - */ - easing?: string; - /** - * If true, the margin of the target element will be deducted from the final position. - */ - margin?: boolean; - /** - * Add/deduct from the end position. - * One number for both axes or { top:x, left:y }. - */ - offset?: any; - /** - * Add/deduct the height/width multiplied by 'over'. - * Can be { top:x, left:y } when using both axes. - */ - over? : any; - /** - * If true, and both axis are given. - * The 2nd axis will only be animated after the first one ends. - */ - queue?: boolean; - /** - * Function to be called after the scrolling ends. - */ - onAfter?: () => void; - /** - * If queuing is activated, this function will be called after the first scrolling ends. - */ - onAfterFirst?: () => void; -} - -interface JQuery { - /** - * Scroll the matched elements - */ - scrollTo: { - /** - * Scroll the matched elements - * - * @param target Where to scroll the matched elements. - * @param duration The OVERALL length of the animation - * @param settings Set of settings. - */ - (target: any, duration?: number, settings?: ScrollToOptions): JQuery; - /** - * Scroll the matched elements - * - * @param target Where to scroll the matched elements. - * @param duration The OVERALL length of the animation - * @param onAfter The onAfter callback. - */ - (target: any, duration: number, onAfter?: Function): JQuery; - /** - * Scroll the matched elements - * - * @param target Where to scroll the matched elements. - * @param settings Set of settings. - * @param onAfter The onAfter callback. - */ - (target: any, settings: ScrollToOptions, onAfter?: Function): JQuery; - - }; - -} - -interface JQueryStatic { - /** - * Scroll window - */ - scrollTo: { - /** - * Scroll window - * - * @param target Where to scroll the matched elements. - * @param duration The OVERALL length of the animation - * @param settings Set of settings. - */ - (target: any, duration?: number, settings?: ScrollToOptions): JQuery; - /** - * Scroll window - * - * @param target Where to scroll the matched elements. - * @param duration The OVERALL length of the animation - * @param onAfter The onAfter callback. - */ - (target: any, duration: number, onAfter?: Function): JQuery; - /** - * Scroll window - * - * @param target Where to scroll the matched elements. - * @param settings Set of settings. - * @param onAfter The onAfter callback. - */ - (target: any, settings: ScrollToOptions, onAfter?: Function): JQuery; - - }; - -} diff --git a/jquery.scrollTo/tsconfig.json b/jquery.scrollTo/tsconfig.json new file mode 100644 index 0000000000..60aacf69e4 --- /dev/null +++ b/jquery.scrollTo/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.scrollTo-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.simplePagination/index.d.ts b/jquery.simplePagination/index.d.ts new file mode 100644 index 0000000000..c09ea685e3 --- /dev/null +++ b/jquery.simplePagination/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for jQuery simplePagination.js v1.4 +// Project: https://github.com/flaviusmatis/simplePagination.js +// Definitions by: Natan Vivo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface SimplePaginationOptions { + items?: number; + itemsOnPage?: number; + pages?: number; + displayedPages?: number; + edges?: number; + currentPage?: number; + hrefTextPrefix?: string; + hrefTextSuffix?: string; + prevText?: string; + nextText?: string; + cssStyle?: string; + selectOnClick?: boolean; + onPageClick?: (page: number, event: any) => void; + onInit?: () => void; +} + +interface JQuery { + pagination(options?: SimplePaginationOptions): JQuery; + pagination(method: 'selectPage', pageNumber: number): void; + pagination(method: 'prevPage'): void; + pagination(method: 'nextPage'): void; + pagination(method: 'getPagesCount'): number; + pagination(method: 'getCurrentPage'): number; + pagination(method: 'disable'): void; + pagination(method: 'enable'): void; + pagination(method: 'destroy'): void; + pagination(method: 'redraw'): void; + pagination(method: 'updateItems', items: number): void; + pagination(method: string): any; + pagination(method: string, value: any): any; +} diff --git a/jquery.simplePagination/jquery.simplePagination-tests.ts b/jquery.simplePagination/jquery.simplePagination-tests.ts index 728ca03a85..b35a6f42a0 100644 --- a/jquery.simplePagination/jquery.simplePagination-tests.ts +++ b/jquery.simplePagination/jquery.simplePagination-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// var selector = '#elementId'; diff --git a/jquery.simplePagination/jquery.simplePagination.d.ts b/jquery.simplePagination/jquery.simplePagination.d.ts deleted file mode 100644 index 7fc6543575..0000000000 --- a/jquery.simplePagination/jquery.simplePagination.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Type definitions for jQuery simplePagination.js v1.4 -// Project: https://github.com/flaviusmatis/simplePagination.js -// Definitions by: Natan Vivo -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface SimplePaginationOptions { - items?: number; - itemsOnPage?: number; - pages?: number; - displayedPages?: number; - edges?: number; - currentPage?: number; - hrefTextPrefix?: string; - hrefTextSuffix?: string; - prevText?: string; - nextText?: string; - cssStyle?: string; - selectOnClick?: boolean; - onPageClick?: (page: number, event: any) => void; - onInit?: () => void; -} - -interface JQuery { - pagination(options?: SimplePaginationOptions): JQuery; - pagination(method: 'selectPage', pageNumber: number): void; - pagination(method: 'prevPage'): void; - pagination(method: 'nextPage'): void; - pagination(method: 'getPagesCount'): number; - pagination(method: 'getCurrentPage'): number; - pagination(method: 'disable'): void; - pagination(method: 'enable'): void; - pagination(method: 'destroy'): void; - pagination(method: 'redraw'): void; - pagination(method: 'updateItems', items: number): void; - pagination(method: string): any; - pagination(method: string, value: any): any; -} diff --git a/jquery.simplePagination/tsconfig.json b/jquery.simplePagination/tsconfig.json new file mode 100644 index 0000000000..e4b1bc679c --- /dev/null +++ b/jquery.simplePagination/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.simplePagination-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.simplemodal/index.d.ts b/jquery.simplemodal/index.d.ts new file mode 100644 index 0000000000..19ad376bfd --- /dev/null +++ b/jquery.simplemodal/index.d.ts @@ -0,0 +1,118 @@ +// Type definitions for SimpleModal 1.4.4 +// Project: http://www.ericmmartin.com/projects/simplemodal/ +// Definitions by: Friedrich von Never +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace SimpleModal { + interface SimpleModalOptions { + /** The jQuery selector to append the elements to. For ASP.NET, use 'form'. Default: 'body'. */ + appendTo?: string; + + /** Focus in the first visible, enabled element? Default: true. */ + focus?: boolean; + + /** The opacity value for the overlay div, from 0 - 100. Default: 50. */ + opacity?: number; + + /** The DOM element id for the overlay div. Default: 'simplemodal-overlay'. */ + overlayId?: string; + + /** The CSS styling for the overlay div. Default: {}. */ + overlayCss?: Object; + + /** The DOM element id for the container div. Default: 'simplemodal-container'. */ + containerId?: string; + + /** The CSS styling for the container div. Default: {}. */ + containerCss?: Object; + + /** The DOM element id for the data div. Default: 'simplemodal-data'. */ + dataId?: string; + + /** The CSS styling for the data div. Default: {}. */ + dataCss?: Object; + + /** The minimum height for the container. Default: null. */ + minHeight?: number; + + /** The minimum width for the container. Default: null. */ + minWidth?: number; + + /** The maximum height for the container. If not specified, the window height is used. Default: null. */ + maxHeight?: number; + + /** The maximum width for the container. If not specified, the window width is used. Default: null. */ + maxWidth?: number; + + /** Resize the container if it exceeds the browser window dimensions? Default: false. (Changed in 1.4) */ + autoResize?: boolean; + + /** Automatically position the container upon creation and on window resize? Default: true. (Changed in 1.4) */ + autoPosition?: boolean; + + /** Starting z-index value. Default: 1000. */ + zIndex?: number; + + /** If true, closeHTML, escClose and overlayClose will be used if set. If false, none of them will be used. Default: true. */ + close?: boolean; + + /** The HTML for the default close link. SimpleModal will automatically add the closeClass to this element. Default: ''. */ + closeHTML?: string; + + /** The CSS class used to bind to the close event. Default: 'simplemodal-close'. */ + closeClass?: string; + + /** Allow Esc keypress to close the dialog? Default: true. */ + escClose?: boolean; + + /** Allow click on overlay to close the dialog? Default: false. */ + overlayClose?: boolean; + + /** Position of container [top, left]. Can be number of pixels or percentage. Default: null. */ + position?: Array; + + /** Persist the data across modal calls? Only used for existing DOM elements. If true, the data will be maintained across modal calls, if false, the data will be reverted to its original state. Default: true. */ + persist?: boolean; + + /** User will be unable to interact with the page below the modal or tab away from the dialog. If false, the overlay, iframe, and certain events will be disabled allowing the user to interact with the page below the dialog. Default: true. (Added in 1.3.4. Name changed from transient in 1.3.5) */ + modal?: boolean; + + /** The callback function used in place of SimpleModal's open. Default: null. */ + onOpen?: (dialog: SimpleModalDialog) => void; + + /** The callback function used after the modal dialog has opened. Default: null. */ + onShow?: (dialog: SimpleModalDialog) => void; + + /** The callback function used in place of SimpleModal's close. Default: null. */ + onClose?: (dialog: SimpleModalDialog) => void; + } + + /** Sent to callbacks as a parameter. */ + interface SimpleModalDialog { + overlay: JQuery; + container: JQuery; + data: any; + iframe: JQuery; + } + + interface Static { + defaults: SimpleModalOptions; + (element: JQuery, options?: SimpleModalOptions): JQuery; + (html: string, options?: SimpleModalOptions): JQuery; + close(): void; + } + + interface JQueryExtension { + (options?: SimpleModalOptions): JQuery; + } +} + +interface JQueryStatic { + modal: SimpleModal.Static; +} + +interface JQuery { + modal: SimpleModal.JQueryExtension; +} diff --git a/jquery.simplemodal/jquery.simplemodal-tests.ts b/jquery.simplemodal/jquery.simplemodal-tests.ts index fc27d11c73..8e73e057cc 100644 --- a/jquery.simplemodal/jquery.simplemodal-tests.ts +++ b/jquery.simplemodal/jquery.simplemodal-tests.ts @@ -1,7 +1,6 @@ // Tests taken from documentation: http://www.ericmmartin.com/projects/simplemodal/ -/// -/// +/// // Chained call with no options $("#sample").modal(); diff --git a/jquery.simplemodal/jquery.simplemodal.d.ts b/jquery.simplemodal/jquery.simplemodal.d.ts deleted file mode 100644 index 25dfa4aa2a..0000000000 --- a/jquery.simplemodal/jquery.simplemodal.d.ts +++ /dev/null @@ -1,123 +0,0 @@ -// Type definitions for SimpleModal 1.4.4 -// Project: http://www.ericmmartin.com/projects/simplemodal/ -// Definitions by: Friedrich von Never -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace SimpleModal { - interface SimpleModalOptions { - /** The jQuery selector to append the elements to. For ASP.NET, use 'form'. Default: 'body'. */ - appendTo?: string; - - /** Focus in the first visible, enabled element? Default: true. */ - focus?: boolean; - - /** The opacity value for the overlay div, from 0 - 100. Default: 50. */ - opacity?: number; - - /** The DOM element id for the overlay div. Default: 'simplemodal-overlay'. */ - overlayId?: string; - - /** The CSS styling for the overlay div. Default: {}. */ - overlayCss?: Object; - - /** The DOM element id for the container div. Default: 'simplemodal-container'. */ - containerId?: string; - - /** The CSS styling for the container div. Default: {}. */ - containerCss?: Object; - - /** The DOM element id for the data div. Default: 'simplemodal-data'. */ - dataId?: string; - - /** The CSS styling for the data div. Default: {}. */ - dataCss?: Object; - - /** The minimum height for the container. Default: null. */ - minHeight?: number; - - /** The minimum width for the container. Default: null. */ - minWidth?: number; - - /** The maximum height for the container. If not specified, the window height is used. Default: null. */ - maxHeight?: number; - - /** The maximum width for the container. If not specified, the window width is used. Default: null. */ - maxWidth?: number; - - /** Resize the container if it exceeds the browser window dimensions? Default: false. (Changed in 1.4) */ - autoResize?: boolean; - - /** Automatically position the container upon creation and on window resize? Default: true. (Changed in 1.4) */ - autoPosition?: boolean; - - /** Starting z-index value. Default: 1000. */ - zIndex?: number; - - /** If true, closeHTML, escClose and overlayClose will be used if set. If false, none of them will be used. Default: true. */ - close?: boolean; - - /** The HTML for the default close link. SimpleModal will automatically add the closeClass to this element. Default: ''. */ - closeHTML?: string; - - /** The CSS class used to bind to the close event. Default: 'simplemodal-close'. */ - closeClass?: string; - - /** Allow Esc keypress to close the dialog? Default: true. */ - escClose?: boolean; - - /** Allow click on overlay to close the dialog? Default: false. */ - overlayClose?: boolean; - - /** Position of container [top, left]. Can be number of pixels or percentage. Default: null. */ - position?: Array; - - /** Persist the data across modal calls? Only used for existing DOM elements. If true, the data will be maintained across modal calls, if false, the data will be reverted to its original state. Default: true. */ - persist?: boolean; - - /** User will be unable to interact with the page below the modal or tab away from the dialog. If false, the overlay, iframe, and certain events will be disabled allowing the user to interact with the page below the dialog. Default: true. (Added in 1.3.4. Name changed from transient in 1.3.5) */ - modal?: boolean; - - /** The callback function used in place of SimpleModal's open. Default: null. */ - onOpen?: (dialog: SimpleModalDialog) => void; - - /** The callback function used after the modal dialog has opened. Default: null. */ - onShow?: (dialog: SimpleModalDialog) => void; - - /** The callback function used in place of SimpleModal's close. Default: null. */ - onClose?: (dialog: SimpleModalDialog) => void; - } - - /** Sent to callbacks as a parameter. */ - interface SimpleModalDialog { - overlay: JQuery; - container: JQuery; - data: any; - iframe: JQuery; - } - - interface Static { - defaults: SimpleModalOptions; - (element: JQuery, options?: SimpleModalOptions): JQuery; - (html: string, options?: SimpleModalOptions): JQuery; - close(): void; - } - - interface JQueryExtension { - (options?: SimpleModalOptions): JQuery; - } -} - -interface JQueryStatic { - modal: SimpleModal.Static; -} - -interface JQuery { - modal: SimpleModal.JQueryExtension; -} - -/** Ambient wrapper so it can be loaded through require. */ -declare module 'simplemodal' { - export = SimpleModal; -} diff --git a/jquery.simplemodal/tsconfig.json b/jquery.simplemodal/tsconfig.json new file mode 100644 index 0000000000..dbe58c81d5 --- /dev/null +++ b/jquery.simplemodal/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.simplemodal-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.simulate/index.d.ts b/jquery.simulate/index.d.ts new file mode 100644 index 0000000000..65a80a263e --- /dev/null +++ b/jquery.simulate/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for jquery.simulate.js +// Project: https://github.com/jquery/jquery-simulate +// Definitions by: Derek Cicerone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQuery { + + /** + * Simulates an event. + * + * @param type + * the type of event (eg: "mousemove", "keydown", etc...) + * @param options + * the options for the event (these are event-specific) + */ + simulate(type: string, options?: any): void; +} diff --git a/jquery.simulate/jquery.simulate-tests.ts b/jquery.simulate/jquery.simulate-tests.ts index 98de970342..774c471fb6 100644 --- a/jquery.simulate/jquery.simulate-tests.ts +++ b/jquery.simulate/jquery.simulate-tests.ts @@ -1,5 +1,3 @@ -/// - var $element = $("body"); $element.simulate("click"); diff --git a/jquery.simulate/jquery.simulate.d.ts b/jquery.simulate/jquery.simulate.d.ts deleted file mode 100644 index 5aa43a82bb..0000000000 --- a/jquery.simulate/jquery.simulate.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Type definitions for jquery.simulate.js -// Project: https://github.com/jquery/jquery-simulate -// Definitions by: Derek Cicerone -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface JQuery { - - /** - * Simulates an event. - * - * @param type - * the type of event (eg: "mousemove", "keydown", etc...) - * @param options - * the options for the event (these are event-specific) - */ - simulate(type: string, options?: any): void; -} diff --git a/jquery.simulate/tsconfig.json b/jquery.simulate/tsconfig.json new file mode 100644 index 0000000000..48dbb98ab9 --- /dev/null +++ b/jquery.simulate/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.simulate-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.slimScroll/index.d.ts b/jquery.slimScroll/index.d.ts new file mode 100644 index 0000000000..f07ef9636f --- /dev/null +++ b/jquery.slimScroll/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for jQuery.slimScroll v1.3.3 +// Project: https://github.com/rochal/jQuery-slimScroll +// Definitions by: Chintan Shah +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +interface IJQuerySlimScrollOptions { + // width in pixels of the visible scroll area + width? :string; + // height in pixels of the visible scroll area + height? :string; + // width in pixels of the scrollbar and rail + size? :string; + // scrollbar color, accepts any hex/color value + color?:string; + // scrollbar position - left/right + position?:string; + // distance in pixels between the side edge and the scrollbar + distance?:string; + // default scroll position on load - top / bottom / $('selector') + start?:any; + // sets scrollbar opacity + opacity? :number; + // enables always-on mode for the scrollbar + alwaysVisible?: boolean; + // check if we should hide the scrollbar when user is hovering over + disableFadeOut?: boolean; + // sets visibility of the rail + railVisible?: boolean; + // sets rail color + railColor?: string; + // sets rail opacity + railOpacity?:number; + // whether we should use jQuery UI Draggable to enable bar dragging + railDraggable?: boolean; + // defautlt CSS class of the slimscroll rail + railClass?: string; + // defautlt CSS class of the slimscroll bar + barClass?: string; + // defautlt CSS class of the slimscroll wrapper + wrapperClass?: string; + // check if mousewheel should scroll the window if we reach top/bottom + allowPageScroll?: boolean; + // scroll amount applied to each mouse wheel step + wheelStep?: number; + // scroll amount applied when user is using gestures + touchScrollStep?: number; + // sets border radius + borderRadius?: string; + // sets border radius of the rail + railBorderRadius?: string; + // jumps to the specified scroll value + scrollTo?: string; + // increases/decreases current scroll value by specified amount + scrollBy?: string; +} + +interface JQuery { + slimScroll:{ + (): JQuery; + (options:IJQuerySlimScrollOptions): JQuery; + } +} + diff --git a/jquery.slimScroll/jquery.SlimScroll-tests.ts b/jquery.slimScroll/jquery.SlimScroll-tests.ts index deb4f2406d..1a997232fa 100644 --- a/jquery.slimScroll/jquery.SlimScroll-tests.ts +++ b/jquery.slimScroll/jquery.SlimScroll-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// $("div").slimScroll(); diff --git a/jquery.slimScroll/jquery.slimScroll.d.ts b/jquery.slimScroll/jquery.slimScroll.d.ts deleted file mode 100644 index 4d77d28817..0000000000 --- a/jquery.slimScroll/jquery.slimScroll.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -// Type definitions for jQuery.slimScroll v1.3.3 -// Project: https://github.com/rochal/jQuery-slimScroll -// Definitions by: Chintan Shah -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - -interface IJQuerySlimScrollOptions { - // width in pixels of the visible scroll area - width? :string; - // height in pixels of the visible scroll area - height? :string; - // width in pixels of the scrollbar and rail - size? :string; - // scrollbar color, accepts any hex/color value - color?:string; - // scrollbar position - left/right - position?:string; - // distance in pixels between the side edge and the scrollbar - distance?:string; - // default scroll position on load - top / bottom / $('selector') - start?:any; - // sets scrollbar opacity - opacity? :number; - // enables always-on mode for the scrollbar - alwaysVisible?: boolean; - // check if we should hide the scrollbar when user is hovering over - disableFadeOut?: boolean; - // sets visibility of the rail - railVisible?: boolean; - // sets rail color - railColor?: string; - // sets rail opacity - railOpacity?:number; - // whether we should use jQuery UI Draggable to enable bar dragging - railDraggable?: boolean; - // defautlt CSS class of the slimscroll rail - railClass?: string; - // defautlt CSS class of the slimscroll bar - barClass?: string; - // defautlt CSS class of the slimscroll wrapper - wrapperClass?: string; - // check if mousewheel should scroll the window if we reach top/bottom - allowPageScroll?: boolean; - // scroll amount applied to each mouse wheel step - wheelStep?: number; - // scroll amount applied when user is using gestures - touchScrollStep?: number; - // sets border radius - borderRadius?: string; - // sets border radius of the rail - railBorderRadius?: string; - // jumps to the specified scroll value - scrollTo?: string; - // increases/decreases current scroll value by specified amount - scrollBy?: string; -} - -interface JQuery { - slimScroll:{ - (): JQuery; - (options:IJQuerySlimScrollOptions): JQuery; - } -} - diff --git a/jquery.slimScroll/tsconfig.json b/jquery.slimScroll/tsconfig.json new file mode 100644 index 0000000000..05200690d1 --- /dev/null +++ b/jquery.slimScroll/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.slimScroll-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.soap/index.d.ts b/jquery.soap/index.d.ts new file mode 100644 index 0000000000..384b5bc480 --- /dev/null +++ b/jquery.soap/index.d.ts @@ -0,0 +1,83 @@ +// Type definitions for jQuery.SOAP 1.6.7 +// Project: https://github.com/doedje/jquery.soap +// Definitions by: Roland Greim +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ + +/// + +declare namespace JQuerySOAP { + interface SOAPEnvelope { + attributes: Object + bodies: Array + headers: Array + prefix: string + soapConfig: any + typeOf: string + addAttribute(name: String, value: string): void + addAttribute(name: String, value: number): void + addBody(soapObject: SOAPObject): void + addHeader(soapObject: SOAPObject): void + addNamespace(name: String, uri: string): void + toString(): string + send(options: Options): void + } + interface SOAPResponse { + toJSON(): any + toString(): String + toXML(): XMLDocument + } + + interface SOAPObject { + attributes: Object + children: Array + name: string + ns: Object + _parent: SOAPObject + value: any + typeOf: string + addNamespace(name: String, url: string): void + addParameter(name: String, value: string): void + addParameter(name: String, value: number): void + appendChild(soapObject: SOAPObject): SOAPObject + attr(name: string, value: string): Object + attr(name: string, value: number): Object + end(): SOAPObject + find(name: string): SOAPObject + hasChildren(): boolean + newChild(name: string): SOAPObject + parent(): SOAPObject + toString(): string + val(value: string): SOAPObject + val(value: number): SOAPObject + } + interface Options { + appendMethodToURL?: boolean; + async?: boolean; + beforeSend?: (SOAPEnvelope: SOAPEnvelope) => void; + context?: any; + data?: Object; + envAttributes?: any; + elementName?: string; + enableLogging?: boolean; + error?: (SOAPResponse: SOAPResponse) => void; + HTTPHeaders?: Object; + method?: string; + namespaceQualifier?: string; + namespaceURL?: string; + noPrefix?: boolean; + request?: (SOAPEnvelope: SOAPEnvelope) => void; + soap12?: boolean; + SOAPAction?: string; + SOAPHeader?: Object; + statusCode?: Object; + success?: (SOAPResponse: SOAPResponse) => void; + url?: string; + wss?: Object; + } + interface SOAP { + (options?: Options): JQueryXHR; + } +} +interface JQueryStatic { + soap: JQuerySOAP.SOAP; +} diff --git a/jquery.soap/jquery.soap-tests.ts b/jquery.soap/jquery.soap-tests.ts index acef40d8cd..519f1cbae4 100644 --- a/jquery.soap/jquery.soap-tests.ts +++ b/jquery.soap/jquery.soap-tests.ts @@ -1,5 +1,3 @@ -/// - $.soap({ url: 'http://my.server.com/soapservices/', method: 'helloWorld', diff --git a/jquery.soap/jquery.soap.d.ts b/jquery.soap/jquery.soap.d.ts deleted file mode 100644 index 340a5221df..0000000000 --- a/jquery.soap/jquery.soap.d.ts +++ /dev/null @@ -1,83 +0,0 @@ -// Type definitions for jQuery.SOAP 1.6.7 -// Project: https://github.com/doedje/jquery.soap -// Definitions by: Roland Greim -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/ - -/// - -declare namespace JQuerySOAP { - interface SOAPEnvelope { - attributes: Object - bodies: Array - headers: Array - prefix: string - soapConfig: any - typeOf: string - addAttribute(name: String, value: string): void - addAttribute(name: String, value: number): void - addBody(soapObject: SOAPObject): void - addHeader(soapObject: SOAPObject): void - addNamespace(name: String, uri: string): void - toString(): string - send(options: Options): void - } - interface SOAPResponse { - toJSON(): any - toString(): String - toXML(): XMLDocument - } - - interface SOAPObject { - attributes: Object - children: Array - name: string - ns: Object - _parent: SOAPObject - value: any - typeOf: string - addNamespace(name: String, url: string): void - addParameter(name: String, value: string): void - addParameter(name: String, value: number): void - appendChild(soapObject: SOAPObject): SOAPObject - attr(name: string, value: string): Object - attr(name: string, value: number): Object - end(): SOAPObject - find(name: string): SOAPObject - hasChildren(): boolean - newChild(name: string): SOAPObject - parent(): SOAPObject - toString(): string - val(value: string): SOAPObject - val(value: number): SOAPObject - } - interface Options { - appendMethodToURL?: boolean; - async?: boolean; - beforeSend?: (SOAPEnvelope: SOAPEnvelope) => void; - context?: any; - data?: Object; - envAttributes?: any; - elementName?: string; - enableLogging?: boolean; - error?: (SOAPResponse: SOAPResponse) => void; - HTTPHeaders?: Object; - method?: string; - namespaceQualifier?: string; - namespaceURL?: string; - noPrefix?: boolean; - request?: (SOAPEnvelope: SOAPEnvelope) => void; - soap12?: boolean; - SOAPAction?: string; - SOAPHeader?: Object; - statusCode?: Object; - success?: (SOAPResponse: SOAPResponse) => void; - url?: string; - wss?: Object; - } - interface SOAP { - (options?: Options): JQueryXHR; - } -} -interface JQueryStatic { - soap: JQuerySOAP.SOAP; -} diff --git a/jquery.soap/tsconfig.json b/jquery.soap/tsconfig.json new file mode 100644 index 0000000000..b1b0dd411e --- /dev/null +++ b/jquery.soap/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.soap-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.sortElements/index.d.ts b/jquery.sortElements/index.d.ts new file mode 100644 index 0000000000..5fbf62ab8e --- /dev/null +++ b/jquery.sortElements/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for jQuery.sortElements +// Project: http://james.padolsey.com/javascript/sorting-elements-with-jquery/ +// Definitions by: Tim Bureck +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQuery { + sortElements(comparator:Function, getSortable?:Function):JQuery; +} diff --git a/jquery.sortElements/jquery.sortElement.d.ts b/jquery.sortElements/jquery.sortElement.d.ts deleted file mode 100644 index 6a3e6581b7..0000000000 --- a/jquery.sortElements/jquery.sortElement.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Type definitions for jQuery.sortElements -// Project: http://james.padolsey.com/javascript/sorting-elements-with-jquery/ -// Definitions by: Tim Bureck -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface JQuery { - sortElements(comparator:Function, getSortable?:Function):JQuery; -} diff --git a/jquery.sortElements/tsconfig.json b/jquery.sortElements/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/jquery.sortElements/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/jquery.superLink/index.d.ts b/jquery.superLink/index.d.ts new file mode 100644 index 0000000000..3c7bffc074 --- /dev/null +++ b/jquery.superLink/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for jquery.superLink +// Project: http://james.padolsey.com/demos/plugins/jQuery/superLink/superlink.jquery.js +// Definitions by: Blake Niemyjski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQuery { + superLink(link?: string): JQuery; +} \ No newline at end of file diff --git a/jquery.superLink/jquery.superLink.d.ts b/jquery.superLink/jquery.superLink.d.ts deleted file mode 100644 index a70d97d2e8..0000000000 --- a/jquery.superLink/jquery.superLink.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Type definitions for jquery.superLink -// Project: http://james.padolsey.com/demos/plugins/jQuery/superLink/superlink.jquery.js -// Definitions by: Blake Niemyjski -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface JQuery { - superLink(link?: string): JQuery; -} \ No newline at end of file diff --git a/jquery.superLink/tsconfig.json b/jquery.superLink/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/jquery.superLink/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/jquery.tagsmanager/index.d.ts b/jquery.tagsmanager/index.d.ts new file mode 100644 index 0000000000..aa9ff8e74f --- /dev/null +++ b/jquery.tagsmanager/index.d.ts @@ -0,0 +1,72 @@ +// Type definitions for jQuery Tags Manager +// Project: http://welldonethings.com/tags/manager +// Definitions by: Vincent Bortone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface ITagsManagerOptions { + prefilled?: any; + CapitalizeFirstLetter?: boolean; + preventSubmitOnEnter?: boolean; + isClearInputOnEsc?: boolean; + typeahead?: boolean; + typeaheadAjaxSource?: string; + typeaheadAjaxPolling?: boolean; + typeaheadDelegate?: Function; + typeaheadOverrides?: ITypeaheadOverrides; + typeaheadSource?: any; + AjaxPush?: string; //url + delimeters?: number[]; + backspace?: number[]; + maxTags?: number; + blinkBGColor_1?: string; + blinkBGColor_2?: string; + hiddenTagListName?: string; + hiddenTagListId?: string; + deleteTagsOnBackspace?: boolean; + tagsContainer?: HTMLElement; + tagCloseIcon?: string; + tagClass?: string; + validator?: Function; +} + +interface ITypeaheadOverrides { + instanceSelectHandler?: Function; + selectedClass?: string; + select?: Function; +} + +interface ITagsManager { + tagManagerOptions: ITagsManagerOptions; + obj: JQuery; + objName: string; + queuedTag: string; + delimeters: number[]; + backspace: number[]; + tagToManipulate: string; + + initialize(context: JQuery, + options?: ITagsManagerOptions, + tagToManipulate?: string): void; + setupTypeahead(): void; + onTypeaheadAjaxSuccess(data: any, isSetTypeaheadSource: boolean, process?: Function): void; + ajaxPolling(query: string, process: Function): void; + setTypeaheadSource(source: any): void; + trimTag(tag: string): string; + popTag(): void; + empty(): void; + refreshHiddenTagList(): void; + spliceTag(tagId: number, eventData: any): void; + pushTag(tag: string, objToPush: any, isValid: boolean): void; + + setOptions(options: ITagsManagerOptions): void; + setContext(context: JQuery, tagToManipulate?: string): void; + processCommand(context: JQuery, command: string, tagToManipulate?: string): JQuery; + processTags(command?: string, context?: JQuery, tagToManipulate?: string): JQuery; +} + +interface JQuery { + tagsManager(options?: ITagsManagerOptions): JQuery; + tagsManager(command: string, tagToManipulate?: string): JQuery; +} diff --git a/jquery.tagsmanager/jquery.tagsmanager-tests.ts b/jquery.tagsmanager/jquery.tagsmanager-tests.ts index 1e0df62c25..33af6a8b7b 100644 --- a/jquery.tagsmanager/jquery.tagsmanager-tests.ts +++ b/jquery.tagsmanager/jquery.tagsmanager-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + var options: ITagsManagerOptions = { prefilled: ["Pisa", "Rome"], diff --git a/jquery.tagsmanager/jquery.tagsmanager.d.ts b/jquery.tagsmanager/jquery.tagsmanager.d.ts deleted file mode 100644 index 2e98a0231c..0000000000 --- a/jquery.tagsmanager/jquery.tagsmanager.d.ts +++ /dev/null @@ -1,72 +0,0 @@ -// Type definitions for jQuery Tags Manager -// Project: http://welldonethings.com/tags/manager -// Definitions by: Vincent Bortone -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface ITagsManagerOptions { - prefilled?: any; - CapitalizeFirstLetter?: boolean; - preventSubmitOnEnter?: boolean; - isClearInputOnEsc?: boolean; - typeahead?: boolean; - typeaheadAjaxSource?: string; - typeaheadAjaxPolling?: boolean; - typeaheadDelegate?: Function; - typeaheadOverrides?: ITypeaheadOverrides; - typeaheadSource?: any; - AjaxPush?: string; //url - delimeters?: number[]; - backspace?: number[]; - maxTags?: number; - blinkBGColor_1?: string; - blinkBGColor_2?: string; - hiddenTagListName?: string; - hiddenTagListId?: string; - deleteTagsOnBackspace?: boolean; - tagsContainer?: HTMLElement; - tagCloseIcon?: string; - tagClass?: string; - validator?: Function; -} - -interface ITypeaheadOverrides { - instanceSelectHandler?: Function; - selectedClass?: string; - select?: Function; -} - -interface ITagsManager { - tagManagerOptions: ITagsManagerOptions; - obj: JQuery; - objName: string; - queuedTag: string; - delimeters: number[]; - backspace: number[]; - tagToManipulate: string; - - initialize(context: JQuery, - options?: ITagsManagerOptions, - tagToManipulate?: string): void; - setupTypeahead(): void; - onTypeaheadAjaxSuccess(data: any, isSetTypeaheadSource: boolean, process?: Function): void; - ajaxPolling(query: string, process: Function): void; - setTypeaheadSource(source: any): void; - trimTag(tag: string): string; - popTag(): void; - empty(): void; - refreshHiddenTagList(): void; - spliceTag(tagId: number, eventData: any): void; - pushTag(tag: string, objToPush: any, isValid: boolean): void; - - setOptions(options: ITagsManagerOptions): void; - setContext(context: JQuery, tagToManipulate?: string): void; - processCommand(context: JQuery, command: string, tagToManipulate?: string): JQuery; - processTags(command?: string, context?: JQuery, tagToManipulate?: string): JQuery; -} - -interface JQuery { - tagsManager(options?: ITagsManagerOptions): JQuery; - tagsManager(command: string, tagToManipulate?: string): JQuery; -} diff --git a/jquery.tagsmanager/tsconfig.json b/jquery.tagsmanager/tsconfig.json new file mode 100644 index 0000000000..e3f9caaa97 --- /dev/null +++ b/jquery.tagsmanager/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.tagsmanager-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.tile/index.d.ts b/jquery.tile/index.d.ts new file mode 100644 index 0000000000..d8437b0b01 --- /dev/null +++ b/jquery.tile/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for jquery.tile.js 1.1.0 +// Project: https://github.com/urin/jquery.tile.js +// Definitions by: Shunsuke Ohtani +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQuery { + /** + * Align the height of the largest of the elements arranged in the same row. + * if columns is not specified, align the height of the largest of the all elements. + * + * @param columns Number of elements in a row + */ + tile(columns?: number): void; +} diff --git a/jquery.tile/jquery.tile-tests.ts b/jquery.tile/jquery.tile-tests.ts index e4f63a0a7f..e9c4aaa6e5 100644 --- a/jquery.tile/jquery.tile-tests.ts +++ b/jquery.tile/jquery.tile-tests.ts @@ -1,5 +1,3 @@ -/// - $('div').tile(); $('div').tile(4); diff --git a/jquery.tile/jquery.tile.d.ts b/jquery.tile/jquery.tile.d.ts deleted file mode 100644 index fce65eefbc..0000000000 --- a/jquery.tile/jquery.tile.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Type definitions for jquery.tile.js 1.1.0 -// Project: https://github.com/urin/jquery.tile.js -// Definitions by: Shunsuke Ohtani -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface JQuery { - /** - * Align the height of the largest of the elements arranged in the same row. - * if columns is not specified, align the height of the largest of the all elements. - * - * @param columns Number of elements in a row - */ - tile(columns?: number): void; -} diff --git a/jquery.tile/tsconfig.json b/jquery.tile/tsconfig.json new file mode 100644 index 0000000000..c5ce2d30ac --- /dev/null +++ b/jquery.tile/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.tile-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.timeago/index.d.ts b/jquery.timeago/index.d.ts new file mode 100644 index 0000000000..8563792d7a --- /dev/null +++ b/jquery.timeago/index.d.ts @@ -0,0 +1,62 @@ +// Type definitions for jQuery.timeago.js 1.0.2 +// Project: http://timeago.yarp.com/ +// Definitions by: François Guillot +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +interface TimeagoSetings { + refreshMillis?: number; + allowFuture?: boolean; + strings?: { + prefixAgo?: string; + prefixFromNow?: string; + suffixAgo?: string; + suffixFromNow?: string; + + // Those can be string or Function + seconds?: any; + minute?: any; + minutes?: any; + hour?: any; + hours?: any; + day?: any; + days?: any; + month?: any; + months?: any; + year?: any; + years?: any; + + wordSeparator?: string; + numbers?: any[]; + }; +} + +interface TimeagoStatic { + (timestamp: Date): string; + (timestamp: number): string; + (timestamp: string): string; + (timestamp: Element): string; + (timestamp: JQuery): string; + settings: TimeagoSetings; + inWords(distanceMillis: Date): string; + inWords(distanceMillis: number): string; + parse(iso8601: string): Date; + datetime(element: Element): Date; + datetime(element: JQuery): Date; + isTime(element: Element): boolean; + isTime(element: JQuery): boolean; +} + +interface Timeago { + (): JQuery; +} + +interface JQueryStatic { + timeago: TimeagoStatic; +} + +interface JQuery { + timeago: Timeago; +} \ No newline at end of file diff --git a/jquery.timeago/jquery.timeago-tests.ts b/jquery.timeago/jquery.timeago-tests.ts index 8a40389bca..86abc6fe59 100644 --- a/jquery.timeago/jquery.timeago-tests.ts +++ b/jquery.timeago/jquery.timeago-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// // Basic usage diff --git a/jquery.timeago/jquery.timeago-tests.ts.tscparams b/jquery.timeago/jquery.timeago-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/jquery.timeago/jquery.timeago-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/jquery.timeago/jquery.timeago.d.ts b/jquery.timeago/jquery.timeago.d.ts deleted file mode 100644 index 510ad67d0a..0000000000 --- a/jquery.timeago/jquery.timeago.d.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Type definitions for jQuery.timeago.js 1.0.2 -// Project: http://timeago.yarp.com/ -// Definitions by: François Guillot -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -/// - -interface TimeagoSetings { - refreshMillis?: number; - allowFuture?: boolean; - strings?: { - prefixAgo?: string; - prefixFromNow?: string; - suffixAgo?: string; - suffixFromNow?: string; - - // Those can be string or Function - seconds?: any; - minute?: any; - minutes?: any; - hour?: any; - hours?: any; - day?: any; - days?: any; - month?: any; - months?: any; - year?: any; - years?: any; - - wordSeparator?: string; - numbers?: any[]; - }; -} - -interface TimeagoStatic { - (timestamp: Date): string; - (timestamp: number): string; - (timestamp: string): string; - (timestamp: Element): string; - (timestamp: JQuery): string; - settings: TimeagoSetings; - inWords(distanceMillis: Date): string; - inWords(distanceMillis: number): string; - parse(iso8601: string): Date; - datetime(element: Element): Date; - datetime(element: JQuery): Date; - isTime(element: Element): boolean; - isTime(element: JQuery): boolean; -} - -interface Timeago { - (): JQuery; -} - -interface JQueryStatic { - timeago: TimeagoStatic; -} - -interface JQuery { - timeago: Timeago; -} \ No newline at end of file diff --git a/jquery.timeago/tsconfig.json b/jquery.timeago/tsconfig.json new file mode 100644 index 0000000000..8aa475744a --- /dev/null +++ b/jquery.timeago/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.timeago-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.timepicker/index.d.ts b/jquery.timepicker/index.d.ts new file mode 100644 index 0000000000..d6a8d45a3b --- /dev/null +++ b/jquery.timepicker/index.d.ts @@ -0,0 +1,144 @@ +// Type definitions for jQuery UI Timepicker 0.3 +// Project: http://fgelinas.com/code/timepicker/ +// Definitions by: Anwar Javed +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +interface TimePickerHour { + /** first displayed hour */ + starts?: number; + /** last displayed hour */ + ends?: number; +} + +interface TimePickerMinutes { + /** first displayed minute */ + starts?: number; + /** last displayed minute */ + ends?: number; + /** interval of displayed minutes */ + interval?: number; +} + +interface TimePickerOptions { + /** 'focus' for popup on focus, */ + showOn?: string; + + /** + * 'button' element that will trigger the timepicker. + * + * "button" for trigger button, or "both" for either (not yet implemented). + */ + button?: string; + + // Localization + + /** Define the locale text for "Hours" */ + hourText?: string; + + /** Define the locale text for "Minute" */ + minuteText?: string; + + /** Define the locale text for periods. */ + amPmText?: [string, string]; + + /** Name of jQuery animation for popup */ + showAnim?: string; + /** Options for enhanced animations */ + showOptions?: any; + /** Display text following the input box, e.g. showing the format */ + appendText?: string; + + /** Define a callback function executed before the timepicker is shown */ + beforeShow?: () => any; + /** Define a callback function when a hour / minutes is selected */ + onSelect?: (timeText: string, inst: any) => any; + /** Define a callback function when the timepicker is closed */ + onClose?: (timeText: string, inst: any) => any; + + /** The character to use to separate hours and minutes. */ + timeSeparator?: string; + /** The character to use to separate the time from the time period. */ + periodSeparator?: string; + /** Define whether or not to show AM/PM with selected time */ + showPeriod?: boolean; + /** Show the AM/PM labels on the left of the time picker */ + showPeriodLabels?: boolean; + /** Define whether or not to show a leading zero for hours < 10. [true/false] */ + showLeadingZero?: boolean; + /** Define whether or not to show a leading zero for minutes < 10. */ + showMinutesLeadingZero?: boolean; + /** Selector for an alternate field to store selected time into */ + altField?: string; + /** + * Used as default time when input field is empty or for inline timePicker + * (set to 'now' for the current time, '' for no highlighted time) + **/ + defaultTime?: string; + /** + * Position of the dialog relative to the input. + * + * See the position utility for more info : http://jqueryui.com/demos/position/ + */ + myPosition?: string; + /** + * Position of the input element to match + * + * Note : if the position utility is not loaded, the timepicker will attach left top to left bottom + * See the position utility for more info : http://jqueryui.com/demos/position/ + */ + atPosition?: string; + + //NEW: 2011-02-03 + /** callback for enabling / disabling on selectable hours ex : function(hour) { return true; } */ + onHourShow?: () => any; + /** callback for enabling / disabling on time selection ex : function(hour,minute) { return true; } */ + onMinuteShow?: () => any; + + hours?: TimePickerHour; + minutes?: TimePickerMinutes; + + /** number of rows for the input tables, minimum 2, makes more sense if you use multiple of 2 */ + rows?: number; + // 2011-08-05 0.2.4 + /** display the hours section of the dialog */ + showHours?: boolean; + /** display the minute section of the dialog */ + showMinutes?: boolean; + /** optionally parse inputs of whole hours with minutes omitted */ + optionalMinutes?: boolean; + + // buttons + /** shows an OK button to confirm the edit */ + showCloseButton?: boolean; + + /** Text for the confirmation button (ok button).*/ + closeButtonText?: string; + + /** Shows the 'now' button */ + showNowButton?: boolean; + + /** Text for the 'now' button.*/ + nowButtonText?: string; + + /** Shows the deselect time button */ + showDeselectButton?: boolean; + + /** Text for the deselect button */ + deselectButtonText?: string; +} + + +interface JQuery { + timepicker(): JQuery; + timepicker(methodName: 'getTime'): string; + timepicker(methodName: 'getTimeAsDate'): Date; + timepicker(methodName: 'getHour'): number; + timepicker(methodName: 'getMinute'): number; + timepicker(methodName: string): any; + timepicker(methodName: string, methodParameter: any): any; + timepicker(optionLiteral: string, optionName: string): any; + timepicker(options: TimePickerOptions): JQuery; +} diff --git a/jquery.timepicker/jquery.timepicker-tests.ts b/jquery.timepicker/jquery.timepicker-tests.ts index f0e5f49854..cbb14dfe7c 100644 --- a/jquery.timepicker/jquery.timepicker-tests.ts +++ b/jquery.timepicker/jquery.timepicker-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// var beforeShowCallback, onSelectCallback, onCloseCallback, onHourShow, onMinuteShow; $('#timepicker').timepicker({ diff --git a/jquery.timepicker/jquery.timepicker-tests.ts.tscparams b/jquery.timepicker/jquery.timepicker-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/jquery.timepicker/jquery.timepicker-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/jquery.timepicker/jquery.timepicker.d.ts b/jquery.timepicker/jquery.timepicker.d.ts deleted file mode 100644 index c267dedf2c..0000000000 --- a/jquery.timepicker/jquery.timepicker.d.ts +++ /dev/null @@ -1,96 +0,0 @@ -// Type definitions for jQuery UI Timepicker 0.3 -// Project: http://fgelinas.com/code/timepicker/ -// Definitions by: Anwar Javed -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -interface TimePickerHour { - /** first displayed hour */ starts?: number; - /** last displayed hour */ ends?: number; -} - -interface TimePickerMinutes { - /** first displayed minute */ starts?: number; - /** last displayed minute */ ends?: number; - /** interval of displayed minutes */ interval?: number; -} - -interface TimePickerOptions { - /** 'focus' for popup on focus, */ showOn?: string; - - /** * 'button' element that will trigger the timepicker. * * "button" for trigger button, or "both" for either (not yet implemented). */ button?: string; - - // Localization - - /** Define the locale text for "Hours" */ - hourText?: string; - - /** Define the locale text for "Minute" */ - minuteText?: string; - - /** Define the locale text for periods. */ - amPmText?: [string, string]; - - /** Name of jQuery animation for popup */ showAnim?: string; - /** Options for enhanced animations */ showOptions?: any; - /** Display text following the input box, e.g. showing the format */ appendText?: string; - - /** Define a callback function executed before the timepicker is shown */ beforeShow?: () => any; - /** Define a callback function when a hour / minutes is selected */ onSelect?: (timeText: string, inst: any) => any; - /** Define a callback function when the timepicker is closed */ onClose?: (timeText: string, inst: any) => any; - - /** The character to use to separate hours and minutes. */ timeSeparator?: string; - /** The character to use to separate the time from the time period. */ periodSeparator?: string; - /** Define whether or not to show AM/PM with selected time */ showPeriod?: boolean; - /** Show the AM/PM labels on the left of the time picker */ showPeriodLabels?: boolean; - /** Define whether or not to show a leading zero for hours < 10. [true/false] */ showLeadingZero?: boolean; - /** Define whether or not to show a leading zero for minutes < 10. */ showMinutesLeadingZero?: boolean; - /** Selector for an alternate field to store selected time into */ altField?: string; - /** * Used as default time when input field is empty or for inline timePicker * (set to 'now' for the current time, '' for no highlighted time) **/ defaultTime?: string; - /** * Position of the dialog relative to the input. * * See the position utility for more info : http://jqueryui.com/demos/position/ */ myPosition?: string; - /** * Position of the input element to match * * Note : if the position utility is not loaded, the timepicker will attach left top to left bottom * See the position utility for more info : http://jqueryui.com/demos/position/ */ atPosition?: string; - - //NEW: 2011-02-03 - /** callback for enabling / disabling on selectable hours ex : function(hour) { return true; } */ onHourShow?: () => any; - /** callback for enabling / disabling on time selection ex : function(hour,minute) { return true; } */ onMinuteShow?: () => any; - - hours?: TimePickerHour; - minutes?: TimePickerMinutes; - - /** number of rows for the input tables, minimum 2, makes more sense if you use multiple of 2 */ rows?: number; - // 2011-08-05 0.2.4 - /** display the hours section of the dialog */ showHours?: boolean; - /** display the minute section of the dialog */ showMinutes?: boolean; - /** optionally parse inputs of whole hours with minutes omitted */ optionalMinutes?: boolean; - - // buttons - /** shows an OK button to confirm the edit */ showCloseButton?: boolean; - - /** Text for the confirmation button (ok button).*/ - closeButtonText?: string; - - /** Shows the 'now' button */ showNowButton?: boolean; - - /** Text for the 'now' button.*/ - nowButtonText?: string; - - /** Shows the deselect time button */ showDeselectButton?: boolean; - - /** Text for the deselect button */ - deselectButtonText?: string; -} - - -interface JQuery { - timepicker(): JQuery; - timepicker(methodName: 'getTime'): string; - timepicker(methodName: 'getTimeAsDate'): Date; - timepicker(methodName: 'getHour'): number; - timepicker(methodName: 'getMinute'): number; - timepicker(methodName: string): any; - timepicker(methodName: string, methodParameter: any): any; - timepicker(optionLiteral: string, optionName: string): any; - timepicker(options: TimePickerOptions): JQuery; -} diff --git a/jquery.timepicker/tsconfig.json b/jquery.timepicker/tsconfig.json new file mode 100644 index 0000000000..4ea0a00729 --- /dev/null +++ b/jquery.timepicker/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.timepicker-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.timer/index.d.ts b/jquery.timer/index.d.ts new file mode 100644 index 0000000000..e6b26e0b2e --- /dev/null +++ b/jquery.timer/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for jQueryTimer 1.0 +// Project: https://github.com/jchavannes/jquery-timer +// Definitions by: Joshua Strobl +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQueryTimer { + // #region Constructors + (action?: Function, time?: Number, autostart?: Boolean): Object; + set(x: any): Object; + // #endregion + + // #region Actions + once(time: Number): Object; + play(reset?: Boolean): Object; + pause(): Object; + stop(): Object; + toggle(reset?: Boolean): Object; + // #endregion + + // #region Properties + isActive: Boolean; + remaining: Number; + // #endregion + +} + +interface JQuery { + timer: JQueryTimer; +} \ No newline at end of file diff --git a/jquery.timer/jquery.timer-tests.ts b/jquery.timer/jquery.timer-tests.ts index 2e48bbe893..e5d1cdaa3a 100644 --- a/jquery.timer/jquery.timer-tests.ts +++ b/jquery.timer/jquery.timer-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + // Create the timer $("body").timer( diff --git a/jquery.timer/jquery.timer-tests.ts.tscparams b/jquery.timer/jquery.timer-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/jquery.timer/jquery.timer-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/jquery.timer/jquery.timer.d.ts b/jquery.timer/jquery.timer.d.ts deleted file mode 100644 index 6b8c5d6358..0000000000 --- a/jquery.timer/jquery.timer.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Type definitions for jQueryTimer 1.0 -// Project: https://github.com/jchavannes/jquery-timer -// Definitions by: Joshua Strobl -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface JQueryTimer { - // #region Constructors - (action?: Function, time?: Number, autostart?: Boolean): Object; - set(any): Object; - // #endregion - - // #region Actions - once(time: Number): Object; - play(reset?: Boolean): Object; - pause(): Object; - stop(): Object; - toggle(reset?: Boolean): Object; - // #endregion - - // #region Properties - isActive: Boolean; - remaining: Number; - // #endregion - -} - -interface JQuery { - timer: JQueryTimer; -} \ No newline at end of file diff --git a/jquery.timer/jquery.timer.d.ts.tscparams b/jquery.timer/jquery.timer.d.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/jquery.timer/jquery.timer.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/jquery.timer/tsconfig.json b/jquery.timer/tsconfig.json new file mode 100644 index 0000000000..48d3d6e5f4 --- /dev/null +++ b/jquery.timer/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.timer-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.tinycarousel/index.d.ts b/jquery.tinycarousel/index.d.ts new file mode 100644 index 0000000000..10c363f4fa --- /dev/null +++ b/jquery.tinycarousel/index.d.ts @@ -0,0 +1,79 @@ +// Type definitions for jQuery tinycarousel 1.9 +// Project: http://baijs.nl/tinycarousel/ +// Definitions by: Christiaan Rakowski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace JQueryTinyCarousel { + export interface JQueryTinyCarouselOptions { + /** + * Start block of the carousel. (default: 1) + */ + start?: number; + /** + * Vertical or horizontal scroller? 'x' or 'y'. (default: 'x') + */ + axis?: string; + /** + * How many blocks do you want to move at a time? (default: 1) + */ + display?: number; + /** + * If interval is true and rewind is true it will play in reverse if the last slide is reached. (default: false) + */ + rewind?: boolean; + /** + * Show left and right navigation buttons? (default: true) + */ + controls?: boolean; + /** + * Show page number navigation buttons? (default: false) + */ + pager?: boolean; + /** + * Move to the next block on an interval. (default: false) + */ + interval?: boolean; + /** + * Interval time in milliseconds. (default: 3000) + */ + intervaltime?: number; + /** + * Show animation when changing block? (default: true) + */ + animation?: boolean; + /** + * Time of the animation in miliseconds (default: 1000) + */ + duration?: number; + /** + * Function that executes after every move (default: null) + */ + callback? : (element: HTMLElement, index: number) => void; + } +} +interface JQuery { + /** + * Creates a new tinycarousel with the specified, or default, options. + * + * @param options The options + */ + tinycarousel(options?: JQueryTinyCarousel.JQueryTinyCarouselOptions): JQuery; + /** + * Moves the tinycarousel to the specified block. + * + * @param index The index of the block to move to + */ + tinycarousel_move(index: number): void; + + /** + * Starts the interval. + */ + tinycarousel_start(): void; + + /** + * Stops the interval. + */ + tinycarousel_stop(): void; +} diff --git a/jquery.tinycarousel/jquery.tinycarousel-tests.ts b/jquery.tinycarousel/jquery.tinycarousel-tests.ts index 1a4eb79944..b0d32bfe77 100644 --- a/jquery.tinycarousel/jquery.tinycarousel-tests.ts +++ b/jquery.tinycarousel/jquery.tinycarousel-tests.ts @@ -1,4 +1,4 @@ -/// + $('#slider1').tinycarousel(); diff --git a/jquery.tinycarousel/jquery.tinycarousel.d.ts b/jquery.tinycarousel/jquery.tinycarousel.d.ts deleted file mode 100644 index 32ba3da18f..0000000000 --- a/jquery.tinycarousel/jquery.tinycarousel.d.ts +++ /dev/null @@ -1,79 +0,0 @@ -// Type definitions for jQuery tinycarousel 1.9 -// Project: http://baijs.nl/tinycarousel/ -// Definitions by: Christiaan Rakowski -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace JQueryTinyCarousel { - export interface JQueryTinyCarouselOptions { - /** - * Start block of the carousel. (default: 1) - */ - start?: number; - /** - * Vertical or horizontal scroller? 'x' or 'y'. (default: 'x') - */ - axis?: string; - /** - * How many blocks do you want to move at a time? (default: 1) - */ - display?: number; - /** - * If interval is true and rewind is true it will play in reverse if the last slide is reached. (default: false) - */ - rewind?: boolean; - /** - * Show left and right navigation buttons? (default: true) - */ - controls?: boolean; - /** - * Show page number navigation buttons? (default: false) - */ - pager?: boolean; - /** - * Move to the next block on an interval. (default: false) - */ - interval?: boolean; - /** - * Interval time in milliseconds. (default: 3000) - */ - intervaltime?: number; - /** - * Show animation when changing block? (default: true) - */ - animation?: boolean; - /** - * Time of the animation in miliseconds (default: 1000) - */ - duration?: number; - /** - * Function that executes after every move (default: null) - */ - callback? : (element: HTMLElement, index: number) => void; - } -} -interface JQuery { - /** - * Creates a new tinycarousel with the specified, or default, options. - * - * @param options The options - */ - tinycarousel(options?: JQueryTinyCarousel.JQueryTinyCarouselOptions): JQuery; - /** - * Moves the tinycarousel to the specified block. - * - * @param index The index of the block to move to - */ - tinycarousel_move(index: number): void; - - /** - * Starts the interval. - */ - tinycarousel_start(): void; - - /** - * Stops the interval. - */ - tinycarousel_stop(): void; -} diff --git a/jquery.tinycarousel/tsconfig.json b/jquery.tinycarousel/tsconfig.json new file mode 100644 index 0000000000..90edc80a75 --- /dev/null +++ b/jquery.tinycarousel/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.tinycarousel-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.tinyscrollbar/index.d.ts b/jquery.tinyscrollbar/index.d.ts new file mode 100644 index 0000000000..098353d831 --- /dev/null +++ b/jquery.tinyscrollbar/index.d.ts @@ -0,0 +1,53 @@ +// Type definitions for jQuery tinyscrollbar 1.8 +// Project: http://baijs.nl/tinyscrollbar/ +// Definitions by: Christiaan Rakowski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace JQueryTinyScrollbar { + export interface JQueryTinyScrollbarOptions { + /** + * Enable mobile invert style scrolling. (default: false) + */ + invertscroll?: boolean; + /** + * Vertical or horizontal scroller? 'x' or 'y'. (default: 'x') + */ + axis?: string; + /** + * How many pixels must the mouswheel scrolls at a time. (default: 40) + */ + wheel?: number; + /** + * Enable or disable the mousewheel. (default: true) + */ + scroll?: boolean; + /** + * Return scrollwheel event to browser if there is no more content. (default: true) + */ + lockscroll?: boolean; + /** + * Set the size of the scrollbar to auto or a fixed number. (default: 'auto') + */ + size?: any; + /** + * Set the size of the thumb to auto or a fixed number. (default: 'auto') + */ + sizethumb?: any; + } +} +interface JQuery { + /** + * Creates a new tinyscrollbar with the specified, or default, options. + * + * @param options The options + */ + tinyscrollbar(options?: JQueryTinyScrollbar.JQueryTinyScrollbarOptions): JQuery; + /** + * Updates an existing tinyscrollbar with the specified, or default, options. + * + * @param options The options + */ + tinyscrollbar_update(options?: any): JQuery; +} diff --git a/jquery.tinyscrollbar/jquery.tinyscrollbar-tests.ts b/jquery.tinyscrollbar/jquery.tinyscrollbar-tests.ts index d66388cb18..fbf646dbe5 100644 --- a/jquery.tinyscrollbar/jquery.tinyscrollbar-tests.ts +++ b/jquery.tinyscrollbar/jquery.tinyscrollbar-tests.ts @@ -1,4 +1,4 @@ -/// + $('#scrollbar1').tinyscrollbar(); $('#scrollbar2').tinyscrollbar({ axis: 'x' }); diff --git a/jquery.tinyscrollbar/jquery.tinyscrollbar.d.ts b/jquery.tinyscrollbar/jquery.tinyscrollbar.d.ts deleted file mode 100644 index 802741f0be..0000000000 --- a/jquery.tinyscrollbar/jquery.tinyscrollbar.d.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Type definitions for jQuery tinyscrollbar 1.8 -// Project: http://baijs.nl/tinyscrollbar/ -// Definitions by: Christiaan Rakowski -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace JQueryTinyScrollbar { - export interface JQueryTinyScrollbarOptions { - /** - * Enable mobile invert style scrolling. (default: false) - */ - invertscroll?: boolean; - /** - * Vertical or horizontal scroller? 'x' or 'y'. (default: 'x') - */ - axis?: string; - /** - * How many pixels must the mouswheel scrolls at a time. (default: 40) - */ - wheel?: number; - /** - * Enable or disable the mousewheel. (default: true) - */ - scroll?: boolean; - /** - * Return scrollwheel event to browser if there is no more content. (default: true) - */ - lockscroll?: boolean; - /** - * Set the size of the scrollbar to auto or a fixed number. (default: 'auto') - */ - size?: any; - /** - * Set the size of the thumb to auto or a fixed number. (default: 'auto') - */ - sizethumb?: any; - } -} -interface JQuery { - /** - * Creates a new tinyscrollbar with the specified, or default, options. - * - * @param options The options - */ - tinyscrollbar(options?: JQueryTinyScrollbar.JQueryTinyScrollbarOptions): JQuery; - /** - * Updates an existing tinyscrollbar with the specified, or default, options. - * - * @param options The options - */ - tinyscrollbar_update(options?: any): JQuery; -} diff --git a/jquery.tinyscrollbar/tsconfig.json b/jquery.tinyscrollbar/tsconfig.json new file mode 100644 index 0000000000..101d8d1090 --- /dev/null +++ b/jquery.tinyscrollbar/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.tinyscrollbar-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.tipsy/index.d.ts b/jquery.tipsy/index.d.ts new file mode 100644 index 0000000000..678c2a77f0 --- /dev/null +++ b/jquery.tipsy/index.d.ts @@ -0,0 +1,107 @@ +// Type definitions for jQuery.tipsy +// Project: http://onehackoranother.com/projects/jquery/tipsy/ +// Definitions by: Brian Dukes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQuery { + /** + * initialize tipsy plugin + */ + tipsy: JQueryTipsy.Tipsy; +} + +declare namespace JQueryTipsy { + interface Options { + /** + * delay before showing tooltip (ms) + * + * default: 0 + */ + delayIn?: number; + /** + * delay before hiding tooltip (ms) + * + * default: 0 + */ + delayOut?: number; + /** + * fade tooltips in/out? + * + * default: false + */ + fade?: boolean; + /** + * fallback text to use when no tooltip text + * + * default: '' + */ + fallback?: string; + /** + * gravity + * + * default: 'n' + */ + gravity?: any; // string or () => string + /** + * is tooltip content HTML? + * + * default: false + */ + html?: boolean; + /** + * use live event support? + * + * default: false + */ + live?: boolean; + /** + * pixel offset of tooltip from element + * + * default: 0 + */ + offset?: number; + /** + * opacity of tooltip + * + * default: 0.8 + */ + opacity?: number; + /** + * attribute/callback containing tooltip text + * + * default: 'title' + */ + title?: any; // string or () => string + /** + * how tooltip is triggered - hover | focus | manual + * + * default: 'hover' + */ + trigger?: string; + } + + interface Tipsy { + /** + * initialize tipsy plugin + */ + (options?: Options): JQuery; + /** + * determine gravity either to North or South automatically based on the element's location in the viewport + */ + autoNS: () => string; + /** + * determine gravity either to West or East automatically based on the element's location in the viewport + */ + autoWE: () => string; + /** + * determine gravity either to Southwest or Southeast automatically based on the element's location in the viewport + */ + autoSWSE: () => string; + /** + * determine gravity either to Northwest or Northeast automatically based on the element's location in the viewport + */ + autoNWNE: () => string; + } +} diff --git a/jquery.tipsy/jquery.tipsy-tests.ts b/jquery.tipsy/jquery.tipsy-tests.ts index 384e34a217..e307e5d364 100644 --- a/jquery.tipsy/jquery.tipsy-tests.ts +++ b/jquery.tipsy/jquery.tipsy-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// // basic $('#example-1').tipsy(); diff --git a/jquery.tipsy/jquery.tipsy.d.ts b/jquery.tipsy/jquery.tipsy.d.ts deleted file mode 100644 index cbd4d29744..0000000000 --- a/jquery.tipsy/jquery.tipsy.d.ts +++ /dev/null @@ -1,107 +0,0 @@ -// Type definitions for jQuery.tipsy -// Project: http://onehackoranother.com/projects/jquery/tipsy/ -// Definitions by: Brian Dukes -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface JQuery { - /** - * initialize tipsy plugin - */ - tipsy: JQueryTipsy.Tipsy; -} - -declare namespace JQueryTipsy { - interface Options { - /** - * delay before showing tooltip (ms) - * - * default: 0 - */ - delayIn?: number; - /** - * delay before hiding tooltip (ms) - * - * default: 0 - */ - delayOut?: number; - /** - * fade tooltips in/out? - * - * default: false - */ - fade?: boolean; - /** - * fallback text to use when no tooltip text - * - * default: '' - */ - fallback?: string; - /** - * gravity - * - * default: 'n' - */ - gravity?: any; // string or () => string - /** - * is tooltip content HTML? - * - * default: false - */ - html?: boolean; - /** - * use live event support? - * - * default: false - */ - live?: boolean; - /** - * pixel offset of tooltip from element - * - * default: 0 - */ - offset?: number; - /** - * opacity of tooltip - * - * default: 0.8 - */ - opacity?: number; - /** - * attribute/callback containing tooltip text - * - * default: 'title' - */ - title?: any; // string or () => string - /** - * how tooltip is triggered - hover | focus | manual - * - * default: 'hover' - */ - trigger?: string; - } - - interface Tipsy { - /** - * initialize tipsy plugin - */ - (options?: Options): JQuery; - /** - * determine gravity either to North or South automatically based on the element's location in the viewport - */ - autoNS: () => string; - /** - * determine gravity either to West or East automatically based on the element's location in the viewport - */ - autoWE: () => string; - /** - * determine gravity either to Southwest or Southeast automatically based on the element's location in the viewport - */ - autoSWSE: () => string; - /** - * determine gravity either to Northwest or Northeast automatically based on the element's location in the viewport - */ - autoNWNE: () => string; - } -} diff --git a/jquery.tipsy/tsconfig.json b/jquery.tipsy/tsconfig.json new file mode 100644 index 0000000000..b77f1937b9 --- /dev/null +++ b/jquery.tipsy/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.tipsy-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.tooltipster/index.d.ts b/jquery.tooltipster/index.d.ts new file mode 100644 index 0000000000..5dad37aef4 --- /dev/null +++ b/jquery.tooltipster/index.d.ts @@ -0,0 +1,186 @@ +// Type definitions for jQuery Tooltipster 3.0.5 +// Project: https://github.com/iamceege/tooltipster +// Definitions by: Patrick Magee +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQueryTooltipsterOptions { + /** + * Determines how the tooltip will animate in and out. Feel free to modify or create custom transitions in the tooltipster.css file. In IE9 and 8, all animations default to a JavaScript generated, fade animation. Default: 'fade' + * fade, grow, swing, slide, fall + */ + animation?: string; + /** + * Adds the "speech bubble arrow" to the tooltip. Default: true + */ + arrow?: boolean; + /** + * Select a specific color for the "speech bubble arrow". Default: will inherit the tooltip's background color + * hex code / rgb + */ + arrowColor?: any; + /** + * If autoClose is set to false, the tooltip will never close unless you call the 'close' method yourself. Default: true + */ + autoClose?: boolean; + /** + * If set, this will override the content of the tooltip. Default: null + * @type string, jQuery object + */ + content?: any; + /** + * If the content of the tooltip is provided as a string, it is displayed as plain text by default. If this content should actually be interpreted as HTML, set this option to true. Default: false + */ + contentAsHTML?: boolean; + /** + * If you provide a jQuery object to the 'content' option, this sets if it is a clone of this object that should actually be used. Default: true + */ + contentCloning?: boolean; + /** + * Delay how long it takes (in milliseconds) for the tooltip to start animating in. Default: 200 + */ + delay?: number; + /** + * Set a fixed width for the tooltip. The tooltip will always be a consistent width - no matter your content size. Default: 0 (auto width) + */ + fixedWidth?: number; + /** + * Set a max width for the tooltip. If the tooltip ends up being smaller than the set max width, the tooltip's width will be set automatically. Default: 0 (no max width) + */ + maxWidth?: number; + /** + * Create a custom function to be fired only once at instantiation. If the function returns a value, this value will become the content of the tooltip. See the advanced section to learn more. Default: function(origin, content) {} + */ + functionInit?: (origin, content) => any; + /** + * Create a custom function to be fired before the tooltip opens. This function may prevent or hold off the opening. See the advanced section to learn more. Default: function(origin, continueTooltip) { continueTooltip(); } + */ + functionBefore?: (origin, continueTooltip) => void; + /** + * Create a custom function to be fired when the tooltip and its contents have been added to the DOM. Default: function(origin, tooltip) {} + */ + functionReady?: (origin, tooltip) => void; + /** + * Create a custom function to be fired once the tooltip has been closed and removed from the DOM. Default: function(origin) {} + */ + functionAfter?: (origin) => void; + /** + * If using the iconDesktop or iconTouch options, this sets the content for your icon. Default: '(?)' + * @type string, jQuery object + */ + icon?: any; + /** + * If you provide a jQuery object to the 'icon' option, this sets if it is a clone of this object that should actually be used. Default: true + */ + iconCloning?: boolean; + /** + * Generate an icon next to your content that is responsible for activating the tooltip on non-touch devices. Default: false + */ + iconDesktop?: boolean; + /** + * If using the iconDesktop or iconTouch options, this sets the class on the icon (used to style the icon). Default: 'tooltipster-icon' + */ + iconTheme?: string; + /** + * Generate an icon next to your content that is responsible for activating the tooltip on touch devices (tablets, phones, etc). Default: false + */ + iconTouch?: boolean; + /** + * Give users the possibility to interact with the tooltip. Unless autoClose is set to false, the tooltip will still close if the user moves away from or clicks out of the tooltip. Default: false + */ + interactive?: boolean; + /** + * If the tooltip is interactive and activated by a hover event, set the amount of time (milliseconds) allowed for a user to hover off of the tooltip activator (origin) on to the tooltip itself - keeping the tooltip from closing. Default: 350 + */ + interactiveTolerance?: number; + /** + * Offsets the tooltip (in pixels) farther left/right from the origin. Default: 0 + */ + offsetX?: number; + /** + * Offsets the tooltip (in pixels) farther up/down from the origin. Default: 0 + */ + offsetY?: number; + /** + * If true, only one tooltip will be allowed to be active at a time. Non-autoclosing tooltips will not be closed though. Default: false + */ + onlyOne?: boolean; + /** + * Set the position of the tooltip. Default: 'top' + * right, left, top, top-right, top-left, bottom, bottom-right, bottom-left + */ + position?: string; + /** + * Will reposition the tooltip if the origin moves. As this option may have an impact on performance, we suggest you enable it only if you need to. Default: false + */ + positionTracker?: boolean; + /** + * Set the speed of the animation. Default: 350 + */ + speed?: number; + /** + * How long the tooltip should be allowed to live before closing. Default: 0 (disabled) + */ + timer?: number; + /** + * Set the theme used for your tooltip. Default: 'tooltipster-default' + */ + theme?: string; + /** + * If set to false, tooltips will not show on pure-touch devices, unless you open them yourself with the 'show' method. Touch gestures on devices which also have a mouse will still open the tooltips though. Default: true + */ + touchDevices?: boolean; + /** + * Set how tooltips should be activated and closed. See the advanced section to learn how to build custom triggers. Default: 'hover' + * hover, click, custom + */ + trigger?: string; + /** + * If a tooltip is open while its content is updated, play a subtle animation when the content changes. Default: true + */ + updateAnimation?: boolean; +} + +interface JQuery { + /** + * Initiate the Tooltipster plugin + */ + tooltipster(): void; + /** + * Creates a new tooltip with the specified, or default, options. + * @param options The options + * @example + * $('.tooltip').tooltipster({ + * animation: 'fade', + * delay: 200, + * theme: 'tooltipster-default', + * touchDevices: false, + * trigger: 'hover' + * }); + */ + tooltipster(options?: JQueryTooltipsterOptions): JQuery; + /** + * Updates an existing tinyscrollbar with the specified, or default, options. + * @param options The options + * @param callback optional argument callback + * @example + * $(window).keypress(function() { + * $('#example').tooltipster('hide', function() { + * alert('The tooltip is now fully closed'); + * }); + * }); + */ + tooltipster(method: string, callback?: Function): JQuery; + /** + * Call a method trigger with optional paramter + * @example $('#my-special-tooltip').tooltipster('content', 'My new content'); + * @example + * $('#example').tooltipster('show', function() { + * alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content')); + * }); + */ + tooltipster(method: string, param?: string): any; + +} + diff --git a/jquery.tooltipster/jquery.tooltipster-tests.ts b/jquery.tooltipster/jquery.tooltipster-tests.ts index 8a8f29acae..dde6ef1408 100644 --- a/jquery.tooltipster/jquery.tooltipster-tests.ts +++ b/jquery.tooltipster/jquery.tooltipster-tests.ts @@ -1,4 +1,4 @@ -/// + // Type definition tests for jQuery Tooltipster 3.0.5 // Project: https://github.com/iamceege/tooltipster diff --git a/jquery.tooltipster/jquery.tooltipster-tests.ts.tscparams b/jquery.tooltipster/jquery.tooltipster-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/jquery.tooltipster/jquery.tooltipster-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/jquery.tooltipster/jquery.tooltipster.d.ts b/jquery.tooltipster/jquery.tooltipster.d.ts deleted file mode 100644 index a4df0a36e3..0000000000 --- a/jquery.tooltipster/jquery.tooltipster.d.ts +++ /dev/null @@ -1,186 +0,0 @@ -// Type definitions for jQuery Tooltipster 3.0.5 -// Project: https://github.com/iamceege/tooltipster -// Definitions by: Patrick Magee -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface JQueryTooltipsterOptions { - /** - * Determines how the tooltip will animate in and out. Feel free to modify or create custom transitions in the tooltipster.css file. In IE9 and 8, all animations default to a JavaScript generated, fade animation. Default: 'fade' - * fade, grow, swing, slide, fall - */ - animation?: string; - /** - * Adds the "speech bubble arrow" to the tooltip. Default: true - */ - arrow?: boolean; - /** - * Select a specific color for the "speech bubble arrow". Default: will inherit the tooltip's background color - * hex code / rgb - */ - arrowColor?: any; - /** - * If autoClose is set to false, the tooltip will never close unless you call the 'close' method yourself. Default: true - */ - autoClose?: boolean; - /** - * If set, this will override the content of the tooltip. Default: null - * @type string, jQuery object - */ - content?: any; - /** - * If the content of the tooltip is provided as a string, it is displayed as plain text by default. If this content should actually be interpreted as HTML, set this option to true. Default: false - */ - contentAsHTML?: boolean; - /** - * If you provide a jQuery object to the 'content' option, this sets if it is a clone of this object that should actually be used. Default: true - */ - contentCloning?: boolean; - /** - * Delay how long it takes (in milliseconds) for the tooltip to start animating in. Default: 200 - */ - delay?: number; - /** - * Set a fixed width for the tooltip. The tooltip will always be a consistent width - no matter your content size. Default: 0 (auto width) - */ - fixedWidth?: number; - /** - * Set a max width for the tooltip. If the tooltip ends up being smaller than the set max width, the tooltip's width will be set automatically. Default: 0 (no max width) - */ - maxWidth?: number; - /** - * Create a custom function to be fired only once at instantiation. If the function returns a value, this value will become the content of the tooltip. See the advanced section to learn more. Default: function(origin, content) {} - */ - functionInit?: (origin, content) => any; - /** - * Create a custom function to be fired before the tooltip opens. This function may prevent or hold off the opening. See the advanced section to learn more. Default: function(origin, continueTooltip) { continueTooltip(); } - */ - functionBefore?: (origin, continueTooltip) => void; - /** - * Create a custom function to be fired when the tooltip and its contents have been added to the DOM. Default: function(origin, tooltip) {} - */ - functionReady?: (origin, tooltip) => void; - /** - * Create a custom function to be fired once the tooltip has been closed and removed from the DOM. Default: function(origin) {} - */ - functionAfter?: (origin) => void; - /** - * If using the iconDesktop or iconTouch options, this sets the content for your icon. Default: '(?)' - * @type string, jQuery object - */ - icon?: any; - /** - * If you provide a jQuery object to the 'icon' option, this sets if it is a clone of this object that should actually be used. Default: true - */ - iconCloning?: boolean; - /** - * Generate an icon next to your content that is responsible for activating the tooltip on non-touch devices. Default: false - */ - iconDesktop?: boolean; - /** - * If using the iconDesktop or iconTouch options, this sets the class on the icon (used to style the icon). Default: 'tooltipster-icon' - */ - iconTheme?: string; - /** - * Generate an icon next to your content that is responsible for activating the tooltip on touch devices (tablets, phones, etc). Default: false - */ - iconTouch?: boolean; - /** - * Give users the possibility to interact with the tooltip. Unless autoClose is set to false, the tooltip will still close if the user moves away from or clicks out of the tooltip. Default: false - */ - interactive?: boolean; - /** - * If the tooltip is interactive and activated by a hover event, set the amount of time (milliseconds) allowed for a user to hover off of the tooltip activator (origin) on to the tooltip itself - keeping the tooltip from closing. Default: 350 - */ - interactiveTolerance?: number; - /** - * Offsets the tooltip (in pixels) farther left/right from the origin. Default: 0 - */ - offsetX?: number; - /** - * Offsets the tooltip (in pixels) farther up/down from the origin. Default: 0 - */ - offsetY?: number; - /** - * If true, only one tooltip will be allowed to be active at a time. Non-autoclosing tooltips will not be closed though. Default: false - */ - onlyOne?: boolean; - /** - * Set the position of the tooltip. Default: 'top' - * right, left, top, top-right, top-left, bottom, bottom-right, bottom-left - */ - position?: string; - /** - * Will reposition the tooltip if the origin moves. As this option may have an impact on performance, we suggest you enable it only if you need to. Default: false - */ - positionTracker?: boolean; - /** - * Set the speed of the animation. Default: 350 - */ - speed?: number; - /** - * How long the tooltip should be allowed to live before closing. Default: 0 (disabled) - */ - timer?: number; - /** - * Set the theme used for your tooltip. Default: 'tooltipster-default' - */ - theme?: string; - /** - * If set to false, tooltips will not show on pure-touch devices, unless you open them yourself with the 'show' method. Touch gestures on devices which also have a mouse will still open the tooltips though. Default: true - */ - touchDevices?: boolean; - /** - * Set how tooltips should be activated and closed. See the advanced section to learn how to build custom triggers. Default: 'hover' - * hover, click, custom - */ - trigger?: string; - /** - * If a tooltip is open while its content is updated, play a subtle animation when the content changes. Default: true - */ - updateAnimation?: boolean; -} - -interface JQuery { - /** - * Initiate the Tooltipster plugin - */ - tooltipster(): void; - /** - * Creates a new tooltip with the specified, or default, options. - * @param options The options - * @example - * $('.tooltip').tooltipster({ - * animation: 'fade', - * delay: 200, - * theme: 'tooltipster-default', - * touchDevices: false, - * trigger: 'hover' - * }); - */ - tooltipster(options?: JQueryTooltipsterOptions): JQuery; - /** - * Updates an existing tinyscrollbar with the specified, or default, options. - * @param options The options - * @param callback optional argument callback - * @example - * $(window).keypress(function() { - * $('#example').tooltipster('hide', function() { - * alert('The tooltip is now fully closed'); - * }); - * }); - */ - tooltipster(method: string, callback?: Function): JQuery; - /** - * Call a method trigger with optional paramter - * @example $('#my-special-tooltip').tooltipster('content', 'My new content'); - * @example - * $('#example').tooltipster('show', function() { - * alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content')); - * }); - */ - tooltipster(method: string, param?: string): any; - -} - diff --git a/jquery.tooltipster/jquery.tooltipster.d.ts.tscparams b/jquery.tooltipster/jquery.tooltipster.d.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/jquery.tooltipster/jquery.tooltipster.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/jquery.tooltipster/tsconfig.json b/jquery.tooltipster/tsconfig.json new file mode 100644 index 0000000000..5837673c12 --- /dev/null +++ b/jquery.tooltipster/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.tooltipster-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.total-storage/index.d.ts b/jquery.total-storage/index.d.ts new file mode 100644 index 0000000000..5de79c34a6 --- /dev/null +++ b/jquery.total-storage/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for jQueryTotalStorage 1.1.2 +// Project: https://github.com/Upstatement/jquery-total-storage +// Definitions by: Jeremy Brooks +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** +* @desc Set the value of a key to a string +* @example $.totalStorage('the_key', 'the_value'); +* @desc Set the value of a key to a number +* @example $.totalStorage('the_key', 800.2); +* @desc Set the value of a key to a complex Array +* @example var myArray = new Array(); +* myArray.push({name:'Jared', company:'Upstatement', zip:63124}); +* myArray.push({name:'McGruff', company:'Police', zip:60652}; +* $.totalStorage('people', myArray); +* //to return: +* $.totalStorage('people'); +* +*/ + +interface JQueryTotalStorage { + + /** + * @desc Set or get a key's value + * @param key Key to set. + * @param value Value to set for key. If ommited, current value for key is returned. + * @param options Not implemented. + */ + (key: string, value?: any, options?: JQueryTotalStorageOptions): any; + + /** + * @desc Set a key's value + * @param key Key to set. + * @param value Value to set for key. + */ + setItem(key: string, value: any): any; + + /** + * @desc Get a key's value + * @param key Key to get. + */ + getItem(key: string): any; + + /** + * @desc Get all set values + */ + getAll(): any[]; + + /** + * @desc Delete item by key + * @param key Key of item to delete + */ + deleteItem(key: string): boolean; +} + +interface JQueryTotalStorageOptions { + //not implemented... +} + +interface JQueryStatic { + totalStorage: JQueryTotalStorage; +} \ No newline at end of file diff --git a/jquery.total-storage/jquery.total-storage-tests.ts b/jquery.total-storage/jquery.total-storage-tests.ts index 4bbb60b454..0a23dd67cf 100644 --- a/jquery.total-storage/jquery.total-storage-tests.ts +++ b/jquery.total-storage/jquery.total-storage-tests.ts @@ -3,8 +3,7 @@ // Definitions by: Jeremy Brooks // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// //direct call $.totalStorage("test_key1", "test_value"); diff --git a/jquery.total-storage/jquery.total-storage.d.ts b/jquery.total-storage/jquery.total-storage.d.ts deleted file mode 100644 index 6830e4e11a..0000000000 --- a/jquery.total-storage/jquery.total-storage.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -// Type definitions for jQueryTotalStorage 1.1.2 -// Project: https://github.com/Upstatement/jquery-total-storage -// Definitions by: Jeremy Brooks -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -/** -* @desc Set the value of a key to a string -* @example $.totalStorage('the_key', 'the_value'); -* @desc Set the value of a key to a number -* @example $.totalStorage('the_key', 800.2); -* @desc Set the value of a key to a complex Array -* @example var myArray = new Array(); -* myArray.push({name:'Jared', company:'Upstatement', zip:63124}); -* myArray.push({name:'McGruff', company:'Police', zip:60652}; -* $.totalStorage('people', myArray); -* //to return: -* $.totalStorage('people'); -* -*/ - -interface JQueryTotalStorage { - - /** - * @desc Set or get a key's value - * @param key Key to set. - * @param value Value to set for key. If ommited, current value for key is returned. - * @param options Not implemented. - */ - (key: string, value?: any, options?: JQueryTotalStorageOptions): any; - - /** - * @desc Set a key's value - * @param key Key to set. - * @param value Value to set for key. - */ - setItem(key: string, value: any): any; - - /** - * @desc Get a key's value - * @param key Key to get. - */ - getItem(key: string): any; - - /** - * @desc Get all set values - */ - getAll(): any[]; - - /** - * @desc Delete item by key - * @param key Key of item to delete - */ - deleteItem(key: string): boolean; -} - -interface JQueryTotalStorageOptions { - //not implemented... -} - -interface JQueryStatic { - totalStorage: JQueryTotalStorage; -} \ No newline at end of file diff --git a/jquery.total-storage/tsconfig.json b/jquery.total-storage/tsconfig.json new file mode 100644 index 0000000000..4bb8b8a26d --- /dev/null +++ b/jquery.total-storage/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.total-storage-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.transit/index.d.ts b/jquery.transit/index.d.ts new file mode 100644 index 0000000000..f267bbb24f --- /dev/null +++ b/jquery.transit/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for jQuery.transit.js 0.9.9 +// Project: http://ricostacruz.com/jquery.transit/ +// Definitions by: MrBigDog2U +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +// Transit ////////////////////////////////////////////////// + +interface JQueryTransitOptions { + opacity?: number; + duration?: number; + delay?: number; + easing?: string; + complete?: () => void; + scale?: any; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +interface JQuery { + transition(options: JQueryTransitOptions): JQuery; + transition(options: JQueryTransitOptions, duration: number): JQuery; + transition(options: JQueryTransitOptions, easing: string): JQuery; + transition(options: JQueryTransitOptions, duration: number, easing: string): JQuery; + transition(options: JQueryTransitOptions, complete: () => void): JQuery; + transition(options: JQueryTransitOptions, duration: number, easing: string, complete: () => void): JQuery; + + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A value to set for the property. + */ + css(propertyName: string, value: number[]): JQuery; +} diff --git a/jquery.transit/jquery.transit-tests.ts b/jquery.transit/jquery.transit-tests.ts index 6fdb562d7d..2a672ec979 100644 --- a/jquery.transit/jquery.transit-tests.ts +++ b/jquery.transit/jquery.transit-tests.ts @@ -1,6 +1,4 @@ -/// -/// - +/// class TransitOptions implements JQueryTransitOptions { opacity: number; diff --git a/jquery.transit/jquery.transit.d.ts b/jquery.transit/jquery.transit.d.ts deleted file mode 100644 index dddb56d7db..0000000000 --- a/jquery.transit/jquery.transit.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Type definitions for jQuery.transit.js 0.9.9 -// Project: http://ricostacruz.com/jquery.transit/ -// Definitions by: MrBigDog2U -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -// Transit ////////////////////////////////////////////////// - -interface JQueryTransitOptions { - opacity?: number; - duration?: number; - delay?: number; - easing?: string; - complete?: () => void; - scale?: any; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -interface JQuery { - transition(options: JQueryTransitOptions): JQuery; - transition(options: JQueryTransitOptions, duration: number): JQuery; - transition(options: JQueryTransitOptions, easing: string): JQuery; - transition(options: JQueryTransitOptions, duration: number, easing: string): JQuery; - transition(options: JQueryTransitOptions, complete: () => void): JQuery; - transition(options: JQueryTransitOptions, duration: number, easing: string, complete: () => void): JQuery; - - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param propertyName A CSS property name. - * @param value A value to set for the property. - */ - css(propertyName: string, value: number[]): JQuery; -} diff --git a/jquery.transit/tsconfig.json b/jquery.transit/tsconfig.json new file mode 100644 index 0000000000..2b17d118c5 --- /dev/null +++ b/jquery.transit/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.transit-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.ui.datetimepicker/index.d.ts b/jquery.ui.datetimepicker/index.d.ts new file mode 100644 index 0000000000..96ed13e2bc --- /dev/null +++ b/jquery.ui.datetimepicker/index.d.ts @@ -0,0 +1,131 @@ +// Type definitions for jQuery UI DateTimePicker 0.3 +// Project: http://trentrichardson.com/examples/timepicker/ +// Definitions by: dougajmcdonald +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +interface DateTimePickerOptions extends JQueryUI.DatepickerOptions { + + // Control options + showButtonPanel?: boolean; //Default: true - Whether to show the button panel at the bottom.This is generally needed. + timeOnly?: boolean; //Default: false - Hide the datepicker and only provide a time interface. + onSelect?: () => any; //Default: null - Function to be called when a date is chosen or time has changed(parameters: datetimeText, datepickerInstance). + alwaysSetTime?: boolean; //Default: true - Always have a time set internally, even before user has chosen one. + separator?: string; //Default: " " - When formatting the time this string is placed between the formatted date and formatted time. + pickerTimeFormat?: string; //Default: (timeFormat option) - How to format the time displayed within the timepicker. + pickerTimeSuffix?: string; //Default: (timeSuffix option) - String to place after the formatted time within the timepicker. + showTimepicker?: boolean; //Default: true - Whether to show the timepicker within the datepicker. + addSliderAccess?: boolean; //Default: false - Adds the sliderAccess plugin to sliders within timepicker + sliderAccessArgs?: any; //Default: null - Object to pass to sliderAccess when used. + defaultValue?: string; //Default: null - String of the default time value placed in the input on focus when the input is empty. + minDateTime?: Date; //Default: null - Date object of the minimum datetime allowed.Also available as minDate. + maxDateTime?: Date; //Default: null - Date object of the maximum datetime allowed.Also Available as maxDate. + parse?: string; //Default: 'strict' - How to parse the time string. Two methods are provided: 'strict' which must match the timeFormat exactly, and 'loose' which uses javascript's new Date(timeString) to guess the time. You may also pass in a function(timeFormat, timeString, options) to handle the parsing yourself, returning a simple object: + + // Alt field options + altFieldTimeOnly?: boolean; //Default: true - When altField is used from datepicker altField will only receive the formatted time and the original field only receives date. + altSeparator?: string; //Default: (separator option) - String placed between formatted date and formatted time in the altField. + altTimeSuffix?: string; //Default: (timeSuffix option) - String always placed after the formatted time in the altField. + altTimeFormat?: string; //Default: (timeFormat option) - The time format to use with the altField. + + // Localization options + currentText?: string; //Default: "Now", A Localization Setting - Text for the Now button. + closeText?: string; //Default: "Done", A Localization Setting - Text for the Close button. + amNames?: string; //Default: ['AM', 'A'], A Localization Setting - Array of strings to try and parse against to determine AM. + pmNames?: string; //Default: ['PM', 'P'], A Localization Setting - Array of strings to try and parse against to determine PM. + timeFormat?: string; //Default: "HH:mm", A Localization Setting - String of format tokens to be replaced with the time.See Formatting. + timeSuffix?: string; //Default: "", A Localization Setting - String to place after the formatted time. + timeOnlyTitle?: string; //Default: "Choose Time", A Localization Setting - Title of the wigit when using only timepicker. + timeText?: string; //Default: "Time", A Localization Setting - Label used within timepicker for the formatted time. + hourText?: string; //Default: "Hour", A Localization Setting - Label used to identify the hour slider. + minuteText?: string; //Default: "Minute", A Localization Setting - Label used to identify the minute slider. + secondText?: string; //Default: "Second", A Localization Setting - Label used to identify the second slider. + millisecText?: string; //Default: "Millisecond", A Localization Setting - Label used to identify the millisecond slider. + microsecText?: string; //Default: "Microsecond", A Localization Setting - Label used to identify the microsecond slider. + timezoneText?: string; //Default: "Timezone", A Localization Setting - Label used to identify the timezone slider. + isRTL?: boolean; //Default: false, A Localization Setting - Right to Left support. + + // Timefield options + controlType?: string; //Default: 'slider' - Whether to use 'slider' or 'select'.If 'slider' is unavailable through jQueryUI, 'select' will be used.For advanced usage you may pass an object which implements "create", "options", "value" methods to use controls other than sliders or selects.See the _controls property in the source code for more details. + showHour?: boolean; //Default: null - Whether to show the hour control. The default of null will use detection from timeFormat. + showMinute?: boolean; //Default: null - Whether to show the minute control. The default of null will use detection from timeFormat. + showSecond?: boolean; //Default: null - Whether to show the second control. The default of null will use detection from timeFormat. + showMillisec?: boolean; //Default: null - Whether to show the millisecond control. The default of null will use detection from timeFormat. + showMicrosec?: boolean; //Default: null - Whether to show the microsecond control. The default of null will use detection from timeFormat. + showTimezone?: boolean; //Default: null - Whether to show the timezone select. + showTime?: boolean; //Default: true - Whether to show the time selected within the datetimepicker. + stepHour?: number; //Default: 1 - Hours per step the slider makes. + stepMinute?: number; //Default: 1 - Minutes per step the slider makes. + stepSecond?: number; //Default: 1 - Seconds per step the slider makes. + stepMillisec?: number; //Default: 1 - Milliseconds per step the slider makes. + stepMicrosec?: number; //Default: 1 - Microseconds per step the slider makes. + hour?: number; //Default: 0 - Initial hour set. + minute?: number; //Default: 0 - Initial minute set. + second?: number; //Default: 0 - Initial second set. + millisec?: number; //Default: 0 - Initial millisecond set. + microsec?: number; //Default: 0 - Initial microsecond set. Note: Javascript's native Date object does not natively support microseconds. Timepicker adds ability to simply Date.setMicroseconds(m) and Date.getMicroseconds(). Date comparisons will not acknowledge microseconds. Use this only for display purposes. + timezone?: number; //Default: null - Initial timezone set.This is the offset in minutes.If null the browser's local timezone will be used. If you're timezone is "-0400" you would use - 240. For backwards compatibility you may pass "-0400", however the timezone is stored in minutes and more reliable. + hourMin?: number; //Default: 0 - The minimum hour allowed for all dates. + minuteMin?: number; //Default: 0 - The minimum minute allowed for all dates. + secondMin?: number; //Default: 0 - The minimum second allowed for all dates. + millisecMin?: number; //Default: 0 - The minimum millisecond allowed for all dates. + microsecMin?: number; //Default: 0 - The minimum microsecond allowed for all dates. + hourMax?: number; //Default: 23 - The maximum hour allowed for all dates. + minuteMax?: number; //Default: 59 - The maximum minute allowed for all dates. + secondMax?: number; //Default: 59 - The maximum second allowed for all dates. + millisecMax?: number; //Default: 999 - The maximum millisecond allowed for all dates. + microsecMax?: number; //Default: 999 - The maximum microsecond allowed for all dates. + hourGrid?: number; //Default: 0 - When greater than 0 a label grid will be generated under the slider.This number represents the units (in hours) between labels. + minuteGrid?: number; //Default: 0 - When greater than 0 a label grid will be generated under the slider.This number represents the units (in minutes) between labels. + secondGrid?: number; //Default: 0 - When greater than 0 a label grid will be genereated under the slider.This number represents the units (in seconds) between labels. + millisecGrid?: number; //Default: 0 - When greater than 0 a label grid will be genereated under the slider.This number represents the units (in milliseconds) between labels. + microsecGrid?: number; //Default: 0 - When greater than 0 a label grid will be genereated under the slider.This number represents the units (in microseconds) between labels. + + // Timezone options + timezoneList?: Array //Default: [generated timezones] - An array of timezones used to populate the timezone select.Can be an array of values or an array of objects: { label: "EDT", value: -240 }. The value should be the offset number in minutes.So "-0400" which is the format "-hhmm", would equate to - 240 minutes. +} + +interface TimezoneOptions { + label: string; + value: number; +} + +interface Time { + hour?: number; + minute?: number; + second?: number; + millisecond?: number; + timezone?: string; +} + +interface formatTimeOptions { + format: string; + time: Time; + options?: DateTimePickerOptions; +} + +interface parseTimeOptions { + format: string; + time: string; + options?: DateTimePickerOptions; +} + +interface parseDateTimeOptions { + dateFormat: string; + timeFormat: string; + dateTimeString: string; + dateSettings: string; + timeSettings: string; +} + +interface JQuery { + datetimepicker(): JQuery; + datetimepicker(options?: DateTimePickerOptions): JQuery; + datetimepicker(method: string, methodParameter: any): any; + datetimepicker(method: 'formatTime', methodParameter: formatTimeOptions): string; + datetimepicker(method: 'parseTime', methodParameter: parseTimeOptions): Time; + datetimepicker(method: 'parseDateTime', methodParameter: parseDateTimeOptions): Date; +} + diff --git a/jquery.ui.datetimepicker/jquery.ui.datetimepicker-tests.ts b/jquery.ui.datetimepicker/jquery.ui.datetimepicker-tests.ts index 52ae3e2e64..44996637da 100644 --- a/jquery.ui.datetimepicker/jquery.ui.datetimepicker-tests.ts +++ b/jquery.ui.datetimepicker/jquery.ui.datetimepicker-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + // basic no options $('#datetimepicker').datetimepicker({ diff --git a/jquery.ui.datetimepicker/jquery.ui.datetimepicker.d.ts b/jquery.ui.datetimepicker/jquery.ui.datetimepicker.d.ts deleted file mode 100644 index 3cd4891bd7..0000000000 --- a/jquery.ui.datetimepicker/jquery.ui.datetimepicker.d.ts +++ /dev/null @@ -1,131 +0,0 @@ -// Type definitions for jQuery UI DateTimePicker 0.3 -// Project: http://trentrichardson.com/examples/timepicker/ -// Definitions by: dougajmcdonald -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -interface DateTimePickerOptions extends JQueryUI.DatepickerOptions { - - // Control options - showButtonPanel?: boolean; //Default: true - Whether to show the button panel at the bottom.This is generally needed. - timeOnly?: boolean; //Default: false - Hide the datepicker and only provide a time interface. - onSelect?: () => any; //Default: null - Function to be called when a date is chosen or time has changed(parameters: datetimeText, datepickerInstance). - alwaysSetTime?: boolean; //Default: true - Always have a time set internally, even before user has chosen one. - separator?: string; //Default: " " - When formatting the time this string is placed between the formatted date and formatted time. - pickerTimeFormat?: string; //Default: (timeFormat option) - How to format the time displayed within the timepicker. - pickerTimeSuffix?: string; //Default: (timeSuffix option) - String to place after the formatted time within the timepicker. - showTimepicker?: boolean; //Default: true - Whether to show the timepicker within the datepicker. - addSliderAccess?: boolean; //Default: false - Adds the sliderAccess plugin to sliders within timepicker - sliderAccessArgs?: any; //Default: null - Object to pass to sliderAccess when used. - defaultValue?: string; //Default: null - String of the default time value placed in the input on focus when the input is empty. - minDateTime?: Date; //Default: null - Date object of the minimum datetime allowed.Also available as minDate. - maxDateTime?: Date; //Default: null - Date object of the maximum datetime allowed.Also Available as maxDate. - parse?: string; //Default: 'strict' - How to parse the time string. Two methods are provided: 'strict' which must match the timeFormat exactly, and 'loose' which uses javascript's new Date(timeString) to guess the time. You may also pass in a function(timeFormat, timeString, options) to handle the parsing yourself, returning a simple object: - - // Alt field options - altFieldTimeOnly?: boolean; //Default: true - When altField is used from datepicker altField will only receive the formatted time and the original field only receives date. - altSeparator?: string; //Default: (separator option) - String placed between formatted date and formatted time in the altField. - altTimeSuffix?: string; //Default: (timeSuffix option) - String always placed after the formatted time in the altField. - altTimeFormat?: string; //Default: (timeFormat option) - The time format to use with the altField. - - // Localization options - currentText?: string; //Default: "Now", A Localization Setting - Text for the Now button. - closeText?: string; //Default: "Done", A Localization Setting - Text for the Close button. - amNames?: string; //Default: ['AM', 'A'], A Localization Setting - Array of strings to try and parse against to determine AM. - pmNames?: string; //Default: ['PM', 'P'], A Localization Setting - Array of strings to try and parse against to determine PM. - timeFormat?: string; //Default: "HH:mm", A Localization Setting - String of format tokens to be replaced with the time.See Formatting. - timeSuffix?: string; //Default: "", A Localization Setting - String to place after the formatted time. - timeOnlyTitle?: string; //Default: "Choose Time", A Localization Setting - Title of the wigit when using only timepicker. - timeText?: string; //Default: "Time", A Localization Setting - Label used within timepicker for the formatted time. - hourText?: string; //Default: "Hour", A Localization Setting - Label used to identify the hour slider. - minuteText?: string; //Default: "Minute", A Localization Setting - Label used to identify the minute slider. - secondText?: string; //Default: "Second", A Localization Setting - Label used to identify the second slider. - millisecText?: string; //Default: "Millisecond", A Localization Setting - Label used to identify the millisecond slider. - microsecText?: string; //Default: "Microsecond", A Localization Setting - Label used to identify the microsecond slider. - timezoneText?: string; //Default: "Timezone", A Localization Setting - Label used to identify the timezone slider. - isRTL?: boolean; //Default: false, A Localization Setting - Right to Left support. - - // Timefield options - controlType?: string; //Default: 'slider' - Whether to use 'slider' or 'select'.If 'slider' is unavailable through jQueryUI, 'select' will be used.For advanced usage you may pass an object which implements "create", "options", "value" methods to use controls other than sliders or selects.See the _controls property in the source code for more details. - showHour?: boolean; //Default: null - Whether to show the hour control. The default of null will use detection from timeFormat. - showMinute?: boolean; //Default: null - Whether to show the minute control. The default of null will use detection from timeFormat. - showSecond?: boolean; //Default: null - Whether to show the second control. The default of null will use detection from timeFormat. - showMillisec?: boolean; //Default: null - Whether to show the millisecond control. The default of null will use detection from timeFormat. - showMicrosec?: boolean; //Default: null - Whether to show the microsecond control. The default of null will use detection from timeFormat. - showTimezone?: boolean; //Default: null - Whether to show the timezone select. - showTime?: boolean; //Default: true - Whether to show the time selected within the datetimepicker. - stepHour?: number; //Default: 1 - Hours per step the slider makes. - stepMinute?: number; //Default: 1 - Minutes per step the slider makes. - stepSecond?: number; //Default: 1 - Seconds per step the slider makes. - stepMillisec?: number; //Default: 1 - Milliseconds per step the slider makes. - stepMicrosec?: number; //Default: 1 - Microseconds per step the slider makes. - hour?: number; //Default: 0 - Initial hour set. - minute?: number; //Default: 0 - Initial minute set. - second?: number; //Default: 0 - Initial second set. - millisec?: number; //Default: 0 - Initial millisecond set. - microsec?: number; //Default: 0 - Initial microsecond set. Note: Javascript's native Date object does not natively support microseconds. Timepicker adds ability to simply Date.setMicroseconds(m) and Date.getMicroseconds(). Date comparisons will not acknowledge microseconds. Use this only for display purposes. - timezone?: number; //Default: null - Initial timezone set.This is the offset in minutes.If null the browser's local timezone will be used. If you're timezone is "-0400" you would use - 240. For backwards compatibility you may pass "-0400", however the timezone is stored in minutes and more reliable. - hourMin?: number; //Default: 0 - The minimum hour allowed for all dates. - minuteMin?: number; //Default: 0 - The minimum minute allowed for all dates. - secondMin?: number; //Default: 0 - The minimum second allowed for all dates. - millisecMin?: number; //Default: 0 - The minimum millisecond allowed for all dates. - microsecMin?: number; //Default: 0 - The minimum microsecond allowed for all dates. - hourMax?: number; //Default: 23 - The maximum hour allowed for all dates. - minuteMax?: number; //Default: 59 - The maximum minute allowed for all dates. - secondMax?: number; //Default: 59 - The maximum second allowed for all dates. - millisecMax?: number; //Default: 999 - The maximum millisecond allowed for all dates. - microsecMax?: number; //Default: 999 - The maximum microsecond allowed for all dates. - hourGrid?: number; //Default: 0 - When greater than 0 a label grid will be generated under the slider.This number represents the units (in hours) between labels. - minuteGrid?: number; //Default: 0 - When greater than 0 a label grid will be generated under the slider.This number represents the units (in minutes) between labels. - secondGrid?: number; //Default: 0 - When greater than 0 a label grid will be genereated under the slider.This number represents the units (in seconds) between labels. - millisecGrid?: number; //Default: 0 - When greater than 0 a label grid will be genereated under the slider.This number represents the units (in milliseconds) between labels. - microsecGrid?: number; //Default: 0 - When greater than 0 a label grid will be genereated under the slider.This number represents the units (in microseconds) between labels. - - // Timezone options - timezoneList?: Array //Default: [generated timezones] - An array of timezones used to populate the timezone select.Can be an array of values or an array of objects: { label: "EDT", value: -240 }. The value should be the offset number in minutes.So "-0400" which is the format "-hhmm", would equate to - 240 minutes. -} - -interface TimezoneOptions { - label: string; - value: number; -} - -interface Time { - hour?: number; - minute?: number; - second?: number; - millisecond?: number; - timezone?: string; -} - -interface formatTimeOptions { - format: string; - time: Time; - options?: DateTimePickerOptions; -} - -interface parseTimeOptions { - format: string; - time: string; - options?: DateTimePickerOptions; -} - -interface parseDateTimeOptions { - dateFormat: string; - timeFormat: string; - dateTimeString: string; - dateSettings: string; - timeSettings: string; -} - -interface JQuery { - datetimepicker(): JQuery; - datetimepicker(options?: DateTimePickerOptions): JQuery; - datetimepicker(method: string, methodParameter: any): any; - datetimepicker(method: 'formatTime', methodParameter: formatTimeOptions): string; - datetimepicker(method: 'parseTime', methodParameter: parseTimeOptions): Time; - datetimepicker(method: 'parseDateTime', methodParameter: parseDateTimeOptions): Date; -} - diff --git a/jquery.ui.datetimepicker/tsconfig.json b/jquery.ui.datetimepicker/tsconfig.json new file mode 100644 index 0000000000..167600f87d --- /dev/null +++ b/jquery.ui.datetimepicker/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "jquery.ui.datetimepicker-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery.ui.layout/index.d.ts b/jquery.ui.layout/index.d.ts new file mode 100644 index 0000000000..cab45fe24d --- /dev/null +++ b/jquery.ui.layout/index.d.ts @@ -0,0 +1,484 @@ +// Type definitions for jQuery UI Layout Plug-in +// Project: http://layout.jquery-dev.net/ +// Definitions by: Steve Fenton , Douglas Armstrong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace JQueryUILayout { + + interface PaneOptions { + applyDefaultStyles?: boolean; + scrollToBookmarkOnLoad?: boolean; + showOverflowOnHover?: boolean; + closable?: boolean; + resizable?: boolean; + slidable?: boolean; + paneSelector?: string; + contentSelector?: string; + contentIgnoreSelector?: string; + paneClass?: string; + resizerClass?: string; + togglerClass?: string; + buttonClass?: string; + size?: string | number; + minSize?: number; + maxSize?: number; + spacing_open?: number; + spacing_closed?: number; + resizerTip?: string; + resizerCursor?: string; + resizerDragOpacity?: number; + maskIframesOnResize?: boolean | string; + sliderTip?: string; + sliderCursor?: string; + slideTrigger_open?: string; + slideTrigger_close?: string; + togglerTip_open?: string; + togglerTip_closed?: string; + togglerLength_open?: number | string; + togglerLength_closed?: number | string; + hideTogglerOnSlide?: boolean; + togglerAlign_open?: string | number; + togglerAlign_closed?: string | number; + togglerContent_open?: string; + togglerContent_closed?: string; + enableCursorHotkey?: boolean; + customHotkeyModifier?: string; + customHotkey?: string | number; + fxName?: string; + fxSpeed?: string | number; + fxSettings?: JQueryAnimationOptions; + initClosed?: boolean; + initHidden?: boolean; + onshow_start?: string | { (name:string, pane:JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + } + + interface Options extends PaneOptions { + defaults?: PaneOptions; + north?: PaneOptions; + east?: PaneOptions; + south?: PaneOptions; + west?: PaneOptions; + center?: PaneOptions; + + defaults__applyDefaultStyles?: boolean; + defaults__scrollToBookmarkOnLoad?: boolean; + defaults__showOverflowOnHover?: boolean; + defaults__closable?: boolean; + defaults__resizable?: boolean; + defaults__slidable?: boolean; + defaults__paneSelector?: string; + defaults__contentSelector?: string; + defaults__contentIgnoreSelector?: string; + defaults__paneClass?: string; + defaults__resizerClass?: string; + defaults__togglerClass?: string; + defaults__buttonClass?: string; + defaults__size?: string | number; + defaults__minSize?: number; + defaults__maxSize?: number; + defaults__spacing_open?: number; + defaults__spacing_closed?: number; + defaults__resizerTip?: string; + defaults__resizerCursor?: string; + defaults__resizerDragOpacity?: number; + defaults__maskIframesOnResize?: boolean | string; + defaults__sliderTip?: string; + defaults__sliderCursor?: string; + defaults__slideTrigger_open?: string; + defaults__slideTrigger_close?: string; + defaults__togglerTip_open?: string; + defaults__togglerTip_closed?: string; + defaults__togglerLength_open?: number | string; + defaults__togglerLength_closed?: number | string; + defaults__hideTogglerOnSlide?: boolean; + defaults__togglerAlign_open?: string | number; + defaults__togglerAlign_closed?: string | number; + defaults__togglerContent_open?: string; + defaults__togglerContent_closed?: string; + defaults__enableCursorHotkey?: boolean; + defaults__customHotkeyModifier?: string; + defaults__customHotkey?: string | number; + defaults__fxName?: string; + defaults__fxSpeed?: string | number; + defaults__fxSettings?: JQueryAnimationOptions; + defaults__initClosed?: boolean; + defaults__initHidden?: boolean; + defaults__onshow_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + defaults__onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + defaults__onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + defaults__onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + defaults__onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + defaults__onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + defaults__onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + defaults__onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + defaults__onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + defaults__onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + defaults__onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + defaults__onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + defaults__onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + defaults__onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + defaults__onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + + north__applyDefaultStyles?: boolean; + north__scrollToBookmarkOnLoad?: boolean; + north__showOverflowOnHover?: boolean; + north__closable?: boolean; + north__resizable?: boolean; + north__slidable?: boolean; + north__paneSelector?: string; + north__contentSelector?: string; + north__contentIgnoreSelector?: string; + north__paneClass?: string; + north__resizerClass?: string; + north__togglerClass?: string; + north__buttonClass?: string; + north__size?: string | number; + north__minSize?: number; + north__maxSize?: number; + north__spacing_open?: number; + north__spacing_closed?: number; + north__resizerTip?: string; + north__resizerCursor?: string; + north__resizerDragOpacity?: number; + north__maskIframesOnResize?: boolean | string; + north__sliderTip?: string; + north__sliderCursor?: string; + north__slideTrigger_open?: string; + north__slideTrigger_close?: string; + north__togglerTip_open?: string; + north__togglerTip_closed?: string; + north__togglerLength_open?: number | string; + north__togglerLength_closed?: number | string; + north__hideTogglerOnSlide?: boolean; + north__togglerAlign_open?: string | number; + north__togglerAlign_closed?: string | number; + north__togglerContent_open?: string; + north__togglerContent_closed?: string; + north__enableCursorHotkey?: boolean; + north__customHotkeyModifier?: string; + north__customHotkey?: string | number; + north__fxName?: string; + north__fxSpeed?: string | number; + north__fxSettings?: JQueryAnimationOptions; + north__initClosed?: boolean; + north__initHidden?: boolean; + north__onshow_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + north__onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + north__onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + north__onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + north__onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + north__onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + north__onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + north__onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + north__onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + north__onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + north__onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + north__onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + north__onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + north__onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + north__onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + + east__applyDefaultStyles?: boolean; + east__scrollToBookmarkOnLoad?: boolean; + east__showOverflowOnHover?: boolean; + east__closable?: boolean; + east__resizable?: boolean; + east__slidable?: boolean; + east__paneSelector?: string; + east__contentSelector?: string; + east__contentIgnoreSelector?: string; + east__paneClass?: string; + east__resizerClass?: string; + east__togglerClass?: string; + east__buttonClass?: string; + east__size?: string | number; + east__minSize?: number; + east__maxSize?: number; + east__spacing_open?: number; + east__spacing_closed?: number; + east__resizerTip?: string; + east__resizerCursor?: string; + east__resizerDragOpacity?: number; + east__maskIframesOnResize?: boolean | string; + east__sliderTip?: string; + east__sliderCursor?: string; + east__slideTrigger_open?: string; + east__slideTrigger_close?: string; + east__togglerTip_open?: string; + east__togglerTip_closed?: string; + east__togglerLength_open?: number | string; + east__togglerLength_closed?: number | string; + east__hideTogglerOnSlide?: boolean; + east__togglerAlign_open?: string | number; + east__togglerAlign_closed?: string | number; + east__togglerContent_open?: string; + east__togglerContent_closed?: string; + east__enableCursorHotkey?: boolean; + east__customHotkeyModifier?: string; + east__customHotkey?: string | number; + east__fxName?: string; + east__fxSpeed?: string | number; + east__fxSettings?: JQueryAnimationOptions; + east__initClosed?: boolean; + east__initHidden?: boolean; + east__onshow_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + east__onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + east__onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + east__onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + east__onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + east__onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + east__onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + east__onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + east__onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + east__onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + east__onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + east__onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + east__onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + east__onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + east__onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + + south__applyDefaultStyles?: boolean; + south__scrollToBookmarkOnLoad?: boolean; + south__showOverflowOnHover?: boolean; + south__closable?: boolean; + south__resizable?: boolean; + south__slidable?: boolean; + south__paneSelector?: string; + south__contentSelector?: string; + south__contentIgnoreSelector?: string; + south__paneClass?: string; + south__resizerClass?: string; + south__togglerClass?: string; + south__buttonClass?: string; + south__size?: string | number; + south__minSize?: number; + south__maxSize?: number; + south__spacing_open?: number; + south__spacing_closed?: number; + south__resizerTip?: string; + south__resizerCursor?: string; + south__resizerDragOpacity?: number; + south__maskIframesOnResize?: boolean | string; + south__sliderTip?: string; + south__sliderCursor?: string; + south__slideTrigger_open?: string; + south__slideTrigger_close?: string; + south__togglerTip_open?: string; + south__togglerTip_closed?: string; + south__togglerLength_open?: number | string; + south__togglerLength_closed?: number | string; + south__hideTogglerOnSlide?: boolean; + south__togglerAlign_open?: string | number; + south__togglerAlign_closed?: string | number; + south__togglerContent_open?: string; + south__togglerContent_closed?: string; + south__enableCursorHotkey?: boolean; + south__customHotkeyModifier?: string; + south__customHotkey?: string | number; + south__fxName?: string; + south__fxSpeed?: string | number; + south__fxSettings?: JQueryAnimationOptions; + south__initClosed?: boolean; + south__initHidden?: boolean; + south__onshow_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + south__onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + south__onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + south__onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + south__onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + south__onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + south__onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + south__onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + south__onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + south__onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + south__onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + south__onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + south__onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + south__onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + south__onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + + west__applyDefaultStyles?: boolean; + west__scrollToBookmarkOnLoad?: boolean; + west__showOverflowOnHover?: boolean; + west__closable?: boolean; + west__resizable?: boolean; + west__slidable?: boolean; + west__paneSelector?: string; + west__contentSelector?: string; + west__contentIgnoreSelector?: string; + west__paneClass?: string; + west__resizerClass?: string; + west__togglerClass?: string; + west__buttonClass?: string; + west__size?: string | number; + west__minSize?: number; + west__maxSize?: number; + west__spacing_open?: number; + west__spacing_closed?: number; + west__resizerTip?: string; + west__resizerCursor?: string; + west__resizerDragOpacity?: number; + west__maskIframesOnResize?: boolean | string; + west__sliderTip?: string; + west__sliderCursor?: string; + west__slideTrigger_open?: string; + west__slideTrigger_close?: string; + west__togglerTip_open?: string; + west__togglerTip_closed?: string; + west__togglerLength_open?: number | string; + west__togglerLength_closed?: number | string; + west__hideTogglerOnSlide?: boolean; + west__togglerAlign_open?: string | number; + west__togglerAlign_closed?: string | number; + west__togglerContent_open?: string; + west__togglerContent_closed?: string; + west__enableCursorHotkey?: boolean; + west__customHotkeyModifier?: string; + west__customHotkey?: string | number; + west__fxName?: string; + west__fxSpeed?: string | number; + west__fxSettings?: JQueryAnimationOptions; + west__initClosed?: boolean; + west__initHidden?: boolean; + west__onshow_start?: string | { (name:string, pane:JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + west__onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + west__onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + west__onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + west__onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + west__onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + west__onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + west__onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + west__onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + west__onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + west__onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + west__onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + west__onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + west__onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + west__onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + + center__applyDefaultStyles?: boolean; + center__scrollToBookmarkOnLoad?: boolean; + center__showOverflowOnHover?: boolean; + center__closable?: boolean; + center__resizable?: boolean; + center__slidable?: boolean; + center__paneSelector?: string; + center__contentSelector?: string; + center__contentIgnoreSelector?: string; + center__paneClass?: string; + center__resizerClass?: string; + center__togglerClass?: string; + center__buttonClass?: string; + center__size?: string | number; + center__minSize?: number; + center__maxSize?: number; + center__spacing_open?: number; + center__spacing_closed?: number; + center__resizerTip?: string; + center__resizerCursor?: string; + center__resizerDragOpacity?: number; + center__maskIframesOnResize?: boolean | string; + center__sliderTip?: string; + center__sliderCursor?: string; + center__slideTrigger_open?: string; + center__slideTrigger_close?: string; + center__togglerTip_open?: string; + center__togglerTip_closed?: string; + center__togglerLength_open?: number | string; + center__togglerLength_closed?: number | string; + center__hideTogglerOnSlide?: boolean; + center__togglerAlign_open?: string | number; + center__togglerAlign_closed?: string | number; + center__togglerContent_open?: string; + center__togglerContent_closed?: string; + center__enableCursorHotkey?: boolean; + center__customHotkeyModifier?: string; + center__customHotkey?: string | number; + center__fxName?: string; + center__fxSpeed?: string | number; + center__fxSettings?: JQueryAnimationOptions; + center__initClosed?: boolean; + center__initHidden?: boolean; + center__onshow_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + center__onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + center__onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + center__onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + center__onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + center__onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + center__onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + center__onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + center__onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + center__onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + center__onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + center__onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + center__onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; + center__onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + center__onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; + } + + + interface PaneState { + isClosed: boolean; + isSliding: boolean; + isResizing: boolean; + isHidden: boolean; + noRoom: boolean; + size: number; + minSize: number; + maxSize: number; + } + + + interface Layout { + panes: { + north: JQuery | boolean; + east: JQuery | boolean; + south: JQuery | boolean; + west: JQuery | boolean; + }; + options: Options; + state: { + north: PaneState; + east: PaneState; + south: PaneState; + west: PaneState; + } + + toggle(pane: string): JQuery; + open(pane: string): JQuery; + close(pane: string): JQuery; + show(pane: string, openPane?: boolean): JQuery; + hide(pane: string): JQuery; + sizePane(pane: string, sizeInPixels: number): JQuery; + resizeContent(pane: string): JQuery; + resizeAll(): JQuery; + + addToggleBtn(selector: string, pane: string): JQuery; + addCloseBtn(selector: string, pane: string): JQuery; + addOpenBtn(selector: string, pane: string): JQuery; + addPinBtn(selector: string, pane: string): JQuery; + allowOverflow(elemOrPane: HTMLElement | string): JQuery; + resetOverflow(elemOrPane: HTMLElement | string): JQuery; + } +} + + +interface JQuery { + layout(options?: JQueryUILayout.Options): JQueryUILayout.Layout; +} diff --git a/jquery.ui.layout/jquery.ui.layout.d.ts b/jquery.ui.layout/jquery.ui.layout.d.ts deleted file mode 100644 index dd120edd7e..0000000000 --- a/jquery.ui.layout/jquery.ui.layout.d.ts +++ /dev/null @@ -1,484 +0,0 @@ -// Type definitions for jQuery UI Layout Plug-in -// Project: http://layout.jquery-dev.net/ -// Definitions by: Steve Fenton , Douglas Armstrong -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare namespace JQueryUILayout { - - interface PaneOptions { - applyDefaultStyles?: boolean; - scrollToBookmarkOnLoad?: boolean; - showOverflowOnHover?: boolean; - closable?: boolean; - resizable?: boolean; - slidable?: boolean; - paneSelector?: string; - contentSelector?: string; - contentIgnoreSelector?: string; - paneClass?: string; - resizerClass?: string; - togglerClass?: string; - buttonClass?: string; - size?: string | number; - minSize?: number; - maxSize?: number; - spacing_open?: number; - spacing_closed?: number; - resizerTip?: string; - resizerCursor?: string; - resizerDragOpacity?: number; - maskIframesOnResize?: boolean | string; - sliderTip?: string; - sliderCursor?: string; - slideTrigger_open?: string; - slideTrigger_close?: string; - togglerTip_open?: string; - togglerTip_closed?: string; - togglerLength_open?: number | string; - togglerLength_closed?: number | string; - hideTogglerOnSlide?: boolean; - togglerAlign_open?: string | number; - togglerAlign_closed?: string | number; - togglerContent_open?: string; - togglerContent_closed?: string; - enableCursorHotkey?: boolean; - customHotkeyModifier?: string; - customHotkey?: string | number; - fxName?: string; - fxSpeed?: string | number; - fxSettings?: JQueryAnimationOptions; - initClosed?: boolean; - initHidden?: boolean; - onshow_start?: string | { (name:string, pane:JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - } - - interface Options extends PaneOptions { - defaults?: PaneOptions; - north?: PaneOptions; - east?: PaneOptions; - south?: PaneOptions; - west?: PaneOptions; - center?: PaneOptions; - - defaults__applyDefaultStyles?: boolean; - defaults__scrollToBookmarkOnLoad?: boolean; - defaults__showOverflowOnHover?: boolean; - defaults__closable?: boolean; - defaults__resizable?: boolean; - defaults__slidable?: boolean; - defaults__paneSelector?: string; - defaults__contentSelector?: string; - defaults__contentIgnoreSelector?: string; - defaults__paneClass?: string; - defaults__resizerClass?: string; - defaults__togglerClass?: string; - defaults__buttonClass?: string; - defaults__size?: string | number; - defaults__minSize?: number; - defaults__maxSize?: number; - defaults__spacing_open?: number; - defaults__spacing_closed?: number; - defaults__resizerTip?: string; - defaults__resizerCursor?: string; - defaults__resizerDragOpacity?: number; - defaults__maskIframesOnResize?: boolean | string; - defaults__sliderTip?: string; - defaults__sliderCursor?: string; - defaults__slideTrigger_open?: string; - defaults__slideTrigger_close?: string; - defaults__togglerTip_open?: string; - defaults__togglerTip_closed?: string; - defaults__togglerLength_open?: number | string; - defaults__togglerLength_closed?: number | string; - defaults__hideTogglerOnSlide?: boolean; - defaults__togglerAlign_open?: string | number; - defaults__togglerAlign_closed?: string | number; - defaults__togglerContent_open?: string; - defaults__togglerContent_closed?: string; - defaults__enableCursorHotkey?: boolean; - defaults__customHotkeyModifier?: string; - defaults__customHotkey?: string | number; - defaults__fxName?: string; - defaults__fxSpeed?: string | number; - defaults__fxSettings?: JQueryAnimationOptions; - defaults__initClosed?: boolean; - defaults__initHidden?: boolean; - defaults__onshow_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - defaults__onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - defaults__onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - defaults__onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - defaults__onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - defaults__onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - defaults__onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - defaults__onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - defaults__onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - defaults__onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - defaults__onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - defaults__onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - defaults__onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - defaults__onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - defaults__onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - - north__applyDefaultStyles?: boolean; - north__scrollToBookmarkOnLoad?: boolean; - north__showOverflowOnHover?: boolean; - north__closable?: boolean; - north__resizable?: boolean; - north__slidable?: boolean; - north__paneSelector?: string; - north__contentSelector?: string; - north__contentIgnoreSelector?: string; - north__paneClass?: string; - north__resizerClass?: string; - north__togglerClass?: string; - north__buttonClass?: string; - north__size?: string | number; - north__minSize?: number; - north__maxSize?: number; - north__spacing_open?: number; - north__spacing_closed?: number; - north__resizerTip?: string; - north__resizerCursor?: string; - north__resizerDragOpacity?: number; - north__maskIframesOnResize?: boolean | string; - north__sliderTip?: string; - north__sliderCursor?: string; - north__slideTrigger_open?: string; - north__slideTrigger_close?: string; - north__togglerTip_open?: string; - north__togglerTip_closed?: string; - north__togglerLength_open?: number | string; - north__togglerLength_closed?: number | string; - north__hideTogglerOnSlide?: boolean; - north__togglerAlign_open?: string | number; - north__togglerAlign_closed?: string | number; - north__togglerContent_open?: string; - north__togglerContent_closed?: string; - north__enableCursorHotkey?: boolean; - north__customHotkeyModifier?: string; - north__customHotkey?: string | number; - north__fxName?: string; - north__fxSpeed?: string | number; - north__fxSettings?: JQueryAnimationOptions; - north__initClosed?: boolean; - north__initHidden?: boolean; - north__onshow_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - north__onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - north__onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - north__onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - north__onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - north__onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - north__onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - north__onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - north__onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - north__onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - north__onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - north__onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - north__onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - north__onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - north__onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - - east__applyDefaultStyles?: boolean; - east__scrollToBookmarkOnLoad?: boolean; - east__showOverflowOnHover?: boolean; - east__closable?: boolean; - east__resizable?: boolean; - east__slidable?: boolean; - east__paneSelector?: string; - east__contentSelector?: string; - east__contentIgnoreSelector?: string; - east__paneClass?: string; - east__resizerClass?: string; - east__togglerClass?: string; - east__buttonClass?: string; - east__size?: string | number; - east__minSize?: number; - east__maxSize?: number; - east__spacing_open?: number; - east__spacing_closed?: number; - east__resizerTip?: string; - east__resizerCursor?: string; - east__resizerDragOpacity?: number; - east__maskIframesOnResize?: boolean | string; - east__sliderTip?: string; - east__sliderCursor?: string; - east__slideTrigger_open?: string; - east__slideTrigger_close?: string; - east__togglerTip_open?: string; - east__togglerTip_closed?: string; - east__togglerLength_open?: number | string; - east__togglerLength_closed?: number | string; - east__hideTogglerOnSlide?: boolean; - east__togglerAlign_open?: string | number; - east__togglerAlign_closed?: string | number; - east__togglerContent_open?: string; - east__togglerContent_closed?: string; - east__enableCursorHotkey?: boolean; - east__customHotkeyModifier?: string; - east__customHotkey?: string | number; - east__fxName?: string; - east__fxSpeed?: string | number; - east__fxSettings?: JQueryAnimationOptions; - east__initClosed?: boolean; - east__initHidden?: boolean; - east__onshow_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - east__onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - east__onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - east__onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - east__onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - east__onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - east__onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - east__onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - east__onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - east__onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - east__onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - east__onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - east__onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - east__onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - east__onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - - south__applyDefaultStyles?: boolean; - south__scrollToBookmarkOnLoad?: boolean; - south__showOverflowOnHover?: boolean; - south__closable?: boolean; - south__resizable?: boolean; - south__slidable?: boolean; - south__paneSelector?: string; - south__contentSelector?: string; - south__contentIgnoreSelector?: string; - south__paneClass?: string; - south__resizerClass?: string; - south__togglerClass?: string; - south__buttonClass?: string; - south__size?: string | number; - south__minSize?: number; - south__maxSize?: number; - south__spacing_open?: number; - south__spacing_closed?: number; - south__resizerTip?: string; - south__resizerCursor?: string; - south__resizerDragOpacity?: number; - south__maskIframesOnResize?: boolean | string; - south__sliderTip?: string; - south__sliderCursor?: string; - south__slideTrigger_open?: string; - south__slideTrigger_close?: string; - south__togglerTip_open?: string; - south__togglerTip_closed?: string; - south__togglerLength_open?: number | string; - south__togglerLength_closed?: number | string; - south__hideTogglerOnSlide?: boolean; - south__togglerAlign_open?: string | number; - south__togglerAlign_closed?: string | number; - south__togglerContent_open?: string; - south__togglerContent_closed?: string; - south__enableCursorHotkey?: boolean; - south__customHotkeyModifier?: string; - south__customHotkey?: string | number; - south__fxName?: string; - south__fxSpeed?: string | number; - south__fxSettings?: JQueryAnimationOptions; - south__initClosed?: boolean; - south__initHidden?: boolean; - south__onshow_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - south__onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - south__onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - south__onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - south__onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - south__onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - south__onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - south__onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - south__onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - south__onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - south__onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - south__onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - south__onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - south__onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - south__onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - - west__applyDefaultStyles?: boolean; - west__scrollToBookmarkOnLoad?: boolean; - west__showOverflowOnHover?: boolean; - west__closable?: boolean; - west__resizable?: boolean; - west__slidable?: boolean; - west__paneSelector?: string; - west__contentSelector?: string; - west__contentIgnoreSelector?: string; - west__paneClass?: string; - west__resizerClass?: string; - west__togglerClass?: string; - west__buttonClass?: string; - west__size?: string | number; - west__minSize?: number; - west__maxSize?: number; - west__spacing_open?: number; - west__spacing_closed?: number; - west__resizerTip?: string; - west__resizerCursor?: string; - west__resizerDragOpacity?: number; - west__maskIframesOnResize?: boolean | string; - west__sliderTip?: string; - west__sliderCursor?: string; - west__slideTrigger_open?: string; - west__slideTrigger_close?: string; - west__togglerTip_open?: string; - west__togglerTip_closed?: string; - west__togglerLength_open?: number | string; - west__togglerLength_closed?: number | string; - west__hideTogglerOnSlide?: boolean; - west__togglerAlign_open?: string | number; - west__togglerAlign_closed?: string | number; - west__togglerContent_open?: string; - west__togglerContent_closed?: string; - west__enableCursorHotkey?: boolean; - west__customHotkeyModifier?: string; - west__customHotkey?: string | number; - west__fxName?: string; - west__fxSpeed?: string | number; - west__fxSettings?: JQueryAnimationOptions; - west__initClosed?: boolean; - west__initHidden?: boolean; - west__onshow_start?: string | { (name:string, pane:JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - west__onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - west__onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - west__onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - west__onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - west__onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - west__onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - west__onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - west__onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - west__onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - west__onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - west__onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - west__onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - west__onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - west__onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - - center__applyDefaultStyles?: boolean; - center__scrollToBookmarkOnLoad?: boolean; - center__showOverflowOnHover?: boolean; - center__closable?: boolean; - center__resizable?: boolean; - center__slidable?: boolean; - center__paneSelector?: string; - center__contentSelector?: string; - center__contentIgnoreSelector?: string; - center__paneClass?: string; - center__resizerClass?: string; - center__togglerClass?: string; - center__buttonClass?: string; - center__size?: string | number; - center__minSize?: number; - center__maxSize?: number; - center__spacing_open?: number; - center__spacing_closed?: number; - center__resizerTip?: string; - center__resizerCursor?: string; - center__resizerDragOpacity?: number; - center__maskIframesOnResize?: boolean | string; - center__sliderTip?: string; - center__sliderCursor?: string; - center__slideTrigger_open?: string; - center__slideTrigger_close?: string; - center__togglerTip_open?: string; - center__togglerTip_closed?: string; - center__togglerLength_open?: number | string; - center__togglerLength_closed?: number | string; - center__hideTogglerOnSlide?: boolean; - center__togglerAlign_open?: string | number; - center__togglerAlign_closed?: string | number; - center__togglerContent_open?: string; - center__togglerContent_closed?: string; - center__enableCursorHotkey?: boolean; - center__customHotkeyModifier?: string; - center__customHotkey?: string | number; - center__fxName?: string; - center__fxSpeed?: string | number; - center__fxSettings?: JQueryAnimationOptions; - center__initClosed?: boolean; - center__initHidden?: boolean; - center__onshow_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - center__onshow_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - center__onshow?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - center__onhide_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - center__onhide_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - center__onhide?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - center__onopen_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - center__onopen_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - center__onopen?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - center__onclose_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - center__onclose_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - center__onclose?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - center__onresize_start?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): (boolean | void) }; - center__onresize_end?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - center__onresize?: string | { (name: string, pane: JQuery, state: PaneState, options: PaneOptions, layout_name: string): void }; - } - - - interface PaneState { - isClosed: boolean; - isSliding: boolean; - isResizing: boolean; - isHidden: boolean; - noRoom: boolean; - size: number; - minSize: number; - maxSize: number; - } - - - interface Layout { - panes: { - north: JQuery | boolean; - east: JQuery | boolean; - south: JQuery | boolean; - west: JQuery | boolean; - }; - options: Options; - state: { - north: PaneState; - east: PaneState; - south: PaneState; - west: PaneState; - } - - toggle(pane: string): JQuery; - open(pane: string): JQuery; - close(pane: string): JQuery; - show(pane: string, openPane?: boolean): JQuery; - hide(pane: string): JQuery; - sizePane(pane: string, sizeInPixels: number): JQuery; - resizeContent(pane: string): JQuery; - resizeAll(): JQuery; - - addToggleBtn(selector: string, pane: string): JQuery; - addCloseBtn(selector: string, pane: string): JQuery; - addOpenBtn(selector: string, pane: string): JQuery; - addPinBtn(selector: string, pane: string): JQuery; - allowOverflow(elemOrPane: HTMLElement | string): JQuery; - resetOverflow(elemOrPane: HTMLElement | string): JQuery; - } -} - - -interface JQuery { - layout(options?: JQueryUILayout.Options): JQueryUILayout.Layout; -} diff --git a/jquery.ui.layout/tsconfig.json b/jquery.ui.layout/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/jquery.ui.layout/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/jquery.uniform/index.d.ts b/jquery.uniform/index.d.ts new file mode 100644 index 0000000000..b8b44f9b88 --- /dev/null +++ b/jquery.uniform/index.d.ts @@ -0,0 +1,55 @@ +// Type definitions for Uniform.js +// Project: https://github.com/pixelmatrix/uniform +// Definitions by: flyfishMT +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface UniformCoreOptions { + activeClass?: string; + autoHide?: boolean; + buttonClass?: string; + checkboxClass?: string; + checkedClass?: string; + disabledClass?: string; + eventNamespace?: string; + fileButtonClass?: string; + fileButtonHtml?: string; + fileClass?: string; + fileDefaultHtml?: string; + filenameClass?: string; + focusClass?: string; + hoverClass?: string; + idPrefix?: string; + inputAddTypeAsClass?: boolean; + inputClass?: string; + radioClass?: string; + resetDefaultHtml?: string; + resetSelector?: any; + selectAutoWidth?: boolean; + selectClass?: string; + selectMultiClass?: string; + submitDefaultHtml?: string; + textareaClass?: string; + useID?: boolean; + wrapperClass?: string; +} + +interface UniformOptions extends UniformCoreOptions { + [option: string]: any; +} + +interface Uniform { + (options?: UniformOptions): JQuery; + update(elemOrSelector?: any): void; + restore(elemOrSelector?: any): void; + elements: JQuery[]; + defaults: UniformOptions; +} +interface JQueryStatic { + uniform: Uniform; +} + +interface JQuery { + uniform: Uniform; +} diff --git a/jquery.uniform/jquery.uniform-tests.ts b/jquery.uniform/jquery.uniform-tests.ts index 593ebab2b9..758a2c7c21 100644 --- a/jquery.uniform/jquery.uniform-tests.ts +++ b/jquery.uniform/jquery.uniform-tests.ts @@ -1,4 +1,4 @@ -/// + // Style all + * + * @example + * var input = element(by.model('person.name')); + * input.sendKeys('123'); + * expect(input.getAttribute('value')).toBe('Foo123'); + * + * @param {string} model ng-model expression. + */ + model(model: string): webdriver.Locator; + + /** + * Find a button by text. + * + * @view + * + * + * @example + * element(by.buttonText('Save')); + * + * @param {string} searchText + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} + */ + buttonText(searchText: string): webdriver.Locator; + + /** + * Find a button by partial text. + * + * @view + * + * + * @example + * element(by.partialButtonText('Save')); + * + * @param {string} searchText + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} + */ + partialButtonText(searchText: string): webdriver.Locator; + + + /** + * Find elements inside an ng-repeat. + * + * @view + *
+ * {{cat.name}} + * {{cat.age}} + *
+ * + *
+ * {{$index}} + *
+ *
+ *

{{book.name}}

+ *

{{book.blurb}}

+ *
+ * + * @example + * // 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')); + */ + cssContainingText(cssSelector: string, searchText: string): webdriver.Locator; + + /** + * Find an element by ng-options expression. + * + * @alias by.options(optionsDescriptor) + * @view + * + * + * @example + * 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. + */ + options(optionsDescriptor: string): webdriver.Locator; + } + + var By: IProtractorLocatorStrategy; + + interface Protractor extends webdriver.WebDriver { + + /** + * 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; + + /** + * Helper function for finding elements. + * + * @type {function(webdriver.Locator): ElementFinder} + */ + element(locator: webdriver.Locator): ElementFinder; + + /** + * Shorthand function for finding elements by css. + * + * @type {function(string): ElementFinder} + */ + $(selector: string): ElementFinder; + + /** + * Shorthand function for finding arrays of elements by css. + * + * @type {function(string): ElementArrayFinder} + */ + $$(selector: string): ElementArrayFinder; + + /** + * 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; + + /** + * Timeout in milliseconds to wait for pages to load when calling `get`. + * + * @type {number} + */ + getPageTimeout: number; + + /** + * An object that holds custom test parameters. + * + * @type {Object} + */ + params: any; + + /** + * The reset URL to use between page loads. + * + * @type {string} + */ + resetUrl: string; + + /** + * 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; + + /** + * 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. + * + * @example + * browser.addMockModule('modName', function() { + * angular.module('modName', []).value('foo', 'bar'); + * }); + * + * @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, ...varArgs: any[]): void; + addMockModule(name: string, script: Function, ...varArgs: any[]): void; + + /** + * Clear the list of registered mock modules. + */ + clearMockModules(): void; + + /** + * Remove a registered mock module. + * + * @example + * browser.removeMockModule('modName'); + * + * @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 milliseconds 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): webdriver.promise.Promise; + + /** + * 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. + */ + 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 + * + * @example + * 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; + + /** + * 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'). + * + * @example + * element(by.id('foo')).click(); + * browser.pause(); + * // Execution will stop before the next click action. + * element(by.id('bar')).click(); + * + * @param {number=} opt_debugPort Optional port to use for the debugging process + */ + pause(opt_debugPort?: number): void; + } + + // Interface for the global browser object. + interface IBrowser extends Protractor { + /** + * Fork another instance of protractor for use in interactive tests. + * + * @param {boolean} opt_useSameUrl Whether to navigate to current url on creation + * @param {boolean} opt_copyMockModules Whether to apply same mock modules on creation + * @return {Protractor} a protractor instance. + */ + forkNewDriverInstance(opt_useSameUrl?: boolean, opt_copyMockModules?: boolean): Protractor; + + /** + * Get the processed configuration object that is currently being run. This will contain + * the specs and capabilities properties of the current runner instance. + * + * Set by the runner. + * + * @return {webdriver.promise.Promise} A promise which resolves to the capabilities object. + */ + getProcessedConfig(): webdriver.promise.Promise; + } + + /** + * 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; +} + +interface cssSelectorHelper { + (cssLocator: string): protractor.ElementFinder; +} + +interface cssArraySelectorHelper { + (cssLocator: string): protractor.ElementArrayFinder; +} + +declare var browser: protractor.IBrowser; +declare var by: protractor.IProtractorLocatorStrategy; +declare var By: protractor.IProtractorLocatorStrategy; +declare var element: protractor.Element; +declare var $: cssSelectorHelper; +declare var $$: cssArraySelectorHelper; + +declare module 'protractor' { + export = protractor; +} diff --git a/protractor/tsconfig.json b/protractor/tsconfig.json new file mode 100644 index 0000000000..e53e48864f --- /dev/null +++ b/protractor/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "angular-protractor-tests.ts" + ] +} \ No newline at end of file diff --git a/proxyquire/index.d.ts b/proxyquire/index.d.ts new file mode 100644 index 0000000000..c6c38cb85f --- /dev/null +++ b/proxyquire/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for Proxyquire 1.3.0 +// Project: https://github.com/thlorenz/proxyquire +// Definitions by: jt000 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var p: Proxyquire; +export = p; + +interface Proxyquire { + + (request: string, stubs: any): any; + (request: string, stubs: any): T; + + load(request: string, stubs: any): any; + load(request: string, stubs: any): T; + + noCallThru(): Proxyquire; + callThru(): Proxyquire; + + noPreserveCache(): Proxyquire; + preserveCache(): Proxyquire; +} diff --git a/proxyquire/proxyquire-tests.ts b/proxyquire/proxyquire-tests.ts index b1985de58f..f74b0e3853 100644 --- a/proxyquire/proxyquire-tests.ts +++ b/proxyquire/proxyquire-tests.ts @@ -1,4 +1,4 @@ -/// + import proxyquire = require('proxyquire'); diff --git a/proxyquire/proxyquire.d.ts b/proxyquire/proxyquire.d.ts deleted file mode 100644 index 5127592b87..0000000000 --- a/proxyquire/proxyquire.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -// Type definitions for Proxyquire 1.3.0 -// Project: https://github.com/thlorenz/proxyquire -// Definitions by: jt000 -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -interface Proxyquire { - - (request: string, stubs: any): any; - (request: string, stubs: any): T; - - load(request: string, stubs: any): any; - load(request: string, stubs: any): T; - - noCallThru(): Proxyquire; - callThru(): Proxyquire; - - noPreserveCache(): Proxyquire; - preserveCache(): Proxyquire; -} - -declare module 'proxyquire' { - - var p: Proxyquire; - export = p; -} diff --git a/proxyquire/tsconfig.json b/proxyquire/tsconfig.json new file mode 100644 index 0000000000..95822c6b22 --- /dev/null +++ b/proxyquire/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "proxyquire-tests.ts" + ] +} \ No newline at end of file diff --git a/pty.js/index.d.ts b/pty.js/index.d.ts new file mode 100644 index 0000000000..98876953b2 --- /dev/null +++ b/pty.js/index.d.ts @@ -0,0 +1,132 @@ +// Type definitions for pty.js 0.2.7-1 +// Project: https://github.com/chjj/pty.js +// Definitions by: Vadim Macagon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +/** Options that can be used when creating a new pseudo-terminal. */ +interface TerminalOptions { + name?: string; + cols?: number; + rows?: number; + cwd?: string; + env?: any; + uid?: number; + gid?: number; +} + +import stream = require('stream'); +import net = require('net'); + +export declare class Terminal implements stream.Stream { + /** Read-only name of the terminal. */ + name: string; + /** Read-only number of columns in the terminal. */ + cols: number; + /** Read-only number of rows in the terminal. */ + rows: number; + /** + * Read-only identifier of the spawned process associated with the slave end of the + * pseudo-terminal. This will be null if the terminal was created via [[Terminal.open]]. + */ + pid: number; + /** Read-only file descriptor of the master end of the pseudo-terminal. */ + fd: number; + /** Read-only name of the slave end of the pseudo-terminal. */ + pty: string; + /** Read-only filename of the executable associated with the slave end of the pseudo-terminal. */ + file: string; + /** Read-only name of the process associated with the slave end of the pseudo-terminal. */ + process: string; + stdout: Terminal; + /** Note that an exception will be thrown if an attempt is made to access this property. */ + stderr: Terminal; + stdin: Terminal; + socket: net.Socket; + + /** + * Creates a new pseudo-terminal, spawns a child process, and associates it with the slave + * end of the pseudo-terminal. + */ + constructor(file?: string, args?: string[], opt?: TerminalOptions); + + resize(cols?: number, rows?: number): void; + /** + * Sends a signal to the spawned process associated with the slave end of the + * pseudo-terminal (this only works if [[pid]] is not null). + */ + kill(signal?: string): void; + redraw(): void; + + // NodeJS Socket-like interface (wrappers for this.socket) + write(data: any): boolean; + end(data: any): void; + pause(): void; + resume(): void; + setEncoding(encoding: string): void; + /** + * Closes the master end of the pseudo-terminal, and attempts to kill the spawned process + * associated with the slave end of the pseudo-terminal (but only if [[pid]] is not null). + */ + destroy(): void; + + // NodeJS Stream interface + pipe(destination: T, options?: { end?: boolean; }): T; + + // NodeJS EventEmitter interface + + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + // NOTE: this method is not actually defined in pty.js + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; +} + +/** + * Creates a new pseudo-terminal, spawns a child process, and associates it with the slave + * end of the pseudo-terminal. + */ +export declare function createTerminal(file?: string, args?: string[], opt?: TerminalOptions): Terminal; +/** Alias for [[createTerminal]]. */ +export declare function fork(file?: string, args?: string[], opt?: TerminalOptions): Terminal; +/** Alias for [[createTerminal]]. */ +export declare function spawn(file?: string, args?: string[], opt?: TerminalOptions): Terminal; +/** + * Creates a new pseudo-terminal. + * This function is not available on Windows, use [[fork]] there instead. + */ +export declare function open(opt?: { cols?: number; rows?: number }): Terminal; + +// Internal stuff that probably isn't very useful but is exported by pty.js +export declare module native { + /** Unix-only. */ + export function fork( + file: string, args: string[], env: any, cwd: string, cols: number, rows: number, + uid?: number, gid?: number + ): { fd: number; pid: number; pty: string }; + /** Unix-only. */ + export function open( + cols: number, rows: number + ): { master: number; slave: number; pty: string }; + /** Unix-only. */ + export function process(fd: number, tty: string): string; + /** Windows-only. */ + export function open( + dataPipe: string, cols: number, rows: number, debug: boolean + ): { pid: number; pty: number; fd: number }; + /** Windows-only. */ + export function startProcess( + pid: number, file: string, cmdline: string, env: string[], cwd: string + ): void; + /** Windows-only. */ + export function kill(pid: number): void; + export function resize(fd: number, cols: number, rows: number): void; +} diff --git a/pty.js/pty.js-tests.ts b/pty.js/pty.js-tests.ts index cf73af384e..606ecf32a1 100644 --- a/pty.js/pty.js-tests.ts +++ b/pty.js/pty.js-tests.ts @@ -1,4 +1,3 @@ -/// import pty = require('pty.js'); diff --git a/pty.js/pty.js.d.ts b/pty.js/pty.js.d.ts deleted file mode 100644 index 957134e466..0000000000 --- a/pty.js/pty.js.d.ts +++ /dev/null @@ -1,135 +0,0 @@ -// Type definitions for pty.js 0.2.7-1 -// Project: https://github.com/chjj/pty.js -// Definitions by: Vadim Macagon -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'pty.js' { - /** Options that can be used when creating a new pseudo-terminal. */ - interface TerminalOptions { - name?: string; - cols?: number; - rows?: number; - cwd?: string; - env?: any; - uid?: number; - gid?: number; - } - - import stream = require('stream'); - import net = require('net'); - - export class Terminal implements stream.Stream { - /** Read-only name of the terminal. */ - name: string; - /** Read-only number of columns in the terminal. */ - cols: number; - /** Read-only number of rows in the terminal. */ - rows: number; - /** - * Read-only identifier of the spawned process associated with the slave end of the - * pseudo-terminal. This will be null if the terminal was created via [[Terminal.open]]. - */ - pid: number; - /** Read-only file descriptor of the master end of the pseudo-terminal. */ - fd: number; - /** Read-only name of the slave end of the pseudo-terminal. */ - pty: string; - /** Read-only filename of the executable associated with the slave end of the pseudo-terminal. */ - file: string; - /** Read-only name of the process associated with the slave end of the pseudo-terminal. */ - process: string; - stdout: Terminal; - /** Note that an exception will be thrown if an attempt is made to access this property. */ - stderr: Terminal; - stdin: Terminal; - socket: net.Socket; - - /** - * Creates a new pseudo-terminal, spawns a child process, and associates it with the slave - * end of the pseudo-terminal. - */ - constructor(file?: string, args?: string[], opt?: TerminalOptions); - - resize(cols?: number, rows?: number): void; - /** - * Sends a signal to the spawned process associated with the slave end of the - * pseudo-terminal (this only works if [[pid]] is not null). - */ - kill(signal?: string): void; - redraw(): void; - - // NodeJS Socket-like interface (wrappers for this.socket) - - write(data: any): boolean; - end(data: any): void; - pause(): void; - resume(): void; - setEncoding(encoding: string): void; - /** - * Closes the master end of the pseudo-terminal, and attempts to kill the spawned process - * associated with the slave end of the pseudo-terminal (but only if [[pid]] is not null). - */ - destroy(): void; - - // NodeJS Stream interface - - pipe(destination: T, options?: { end?: boolean; }): T; - - // NodeJS EventEmitter interface - - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; - // NOTE: this method is not actually defined in pty.js - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - listenerCount(type: string): number; - } - - /** - * Creates a new pseudo-terminal, spawns a child process, and associates it with the slave - * end of the pseudo-terminal. - */ - export function createTerminal(file?: string, args?: string[], opt?: TerminalOptions): Terminal; - /** Alias for [[createTerminal]]. */ - export function fork(file?: string, args?: string[], opt?: TerminalOptions): Terminal; - /** Alias for [[createTerminal]]. */ - export function spawn(file?: string, args?: string[], opt?: TerminalOptions): Terminal; - /** - * Creates a new pseudo-terminal. - * This function is not available on Windows, use [[fork]] there instead. - */ - export function open(opt?: { cols?: number; rows?: number }): Terminal; - - // Internal stuff that probably isn't very useful but is exported by pty.js - export module native { - /** Unix-only. */ - export function fork( - file: string, args: string[], env: any, cwd: string, cols: number, rows: number, - uid?: number, gid?: number - ): { fd: number; pid: number; pty: string }; - /** Unix-only. */ - export function open( - cols: number, rows: number - ): { master: number; slave: number; pty: string }; - /** Unix-only. */ - export function process(fd: number, tty: string): string; - /** Windows-only. */ - export function open( - dataPipe: string, cols: number, rows: number, debug: boolean - ): { pid: number; pty: number; fd: number }; - /** Windows-only. */ - export function startProcess( - pid: number, file: string, cmdline: string, env: string[], cwd: string - ): void; - /** Windows-only. */ - export function kill(pid: number): void; - export function resize(fd: number, cols: number, rows: number): void; - } -} diff --git a/pty.js/tsconfig.json b/pty.js/tsconfig.json new file mode 100644 index 0000000000..d4aa24863f --- /dev/null +++ b/pty.js/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "pty.js-tests.ts" + ] +} \ No newline at end of file diff --git a/pubsubjs/PubSub-tests.ts b/pubsub-js/PubSub-tests.ts similarity index 98% rename from pubsubjs/PubSub-tests.ts rename to pubsub-js/PubSub-tests.ts index 0a452d08e3..67a23001bb 100644 --- a/pubsubjs/PubSub-tests.ts +++ b/pubsub-js/PubSub-tests.ts @@ -1,4 +1,4 @@ -/// + /// Tests are taken from the PubSubJs Basic Examples https://github.com/mroderick/PubSubJS function test_Subscribe() { diff --git a/pubsubjs/pubsub.d.ts b/pubsub-js/index.d.ts similarity index 100% rename from pubsubjs/pubsub.d.ts rename to pubsub-js/index.d.ts diff --git a/pubsub-js/tsconfig.json b/pubsub-js/tsconfig.json new file mode 100644 index 0000000000..b751488674 --- /dev/null +++ b/pubsub-js/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "PubSub-tests.ts" + ] +} \ No newline at end of file diff --git a/pure-render-decorator/index.d.ts b/pure-render-decorator/index.d.ts new file mode 100644 index 0000000000..7cc6832040 --- /dev/null +++ b/pure-render-decorator/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for pure-render-decorator v0.2.0 +// Project: https://github.com/felixgirault/pure-render-decorator +// Definitions by: Sean Kelley +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare var PureRender: ClassDecorator; +export = PureRender; diff --git a/pure-render-decorator/pure-render-decorator-tests.ts b/pure-render-decorator/pure-render-decorator-tests.ts index e509fe508b..4598d60b41 100644 --- a/pure-render-decorator/pure-render-decorator-tests.ts +++ b/pure-render-decorator/pure-render-decorator-tests.ts @@ -1,5 +1,3 @@ -/// - import * as PureRender from 'pure-render-decorator'; @PureRender diff --git a/pure-render-decorator/pure-render-decorator.d.ts b/pure-render-decorator/pure-render-decorator.d.ts deleted file mode 100644 index d24e842b60..0000000000 --- a/pure-render-decorator/pure-render-decorator.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Type definitions for pure-render-decorator v0.2.0 -// Project: https://github.com/felixgirault/pure-render-decorator -// Definitions by: Sean Kelley -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module 'pure-render-decorator' { - var PureRender: ClassDecorator; - export = PureRender; -} diff --git a/pure-render-decorator/tsconfig.json b/pure-render-decorator/tsconfig.json new file mode 100644 index 0000000000..89a06a5724 --- /dev/null +++ b/pure-render-decorator/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "experimentalDecorators": true, + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "pure-render-decorator-tests.ts" + ] +} \ No newline at end of file diff --git a/purl/index.d.ts b/purl/index.d.ts new file mode 100644 index 0000000000..2849b17a8c --- /dev/null +++ b/purl/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for Purl 2.3.1 +// Project: https://github.com/allmarkedup/purl +// Definitions by: Daniel Ferreira Monteiro Alves +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace purl { + + interface ParameterMap { + [parameterName: string]: string; + } + + export interface Url { + + /** + * The .attr() method is used to return information on various parts of the URL. + */ + attr(option: string): string; + + /** + * The .param() method is used to return the values of querystring parameters. + */ + param(): ParameterMap; + param(parameterName: string): string; + + /** + * The .segment() method is used to return values of individual segments from the URL's path. + * Pass in an integer value to get the value of that segment - note however that the count is not zero-indexed like an array - i.e. .segment(1) returns the first segment, not the second one. + * You can also pass in negative values, in which case it will count back from the end of the path rather than forwards from the start. + */ + segment(position: number): string; + + /** + * Gets a parameter from the fragment segment + */ + fparam(): ParameterMap; + fparam(parameterName: string): string; + + /** + * Gets the fragment segment at the especified position. + */ + fsegment(position: number): string; + } + +} + +/** + * Parse the current page URL + */ +declare function purl(): purl.Url; + +/** + * Pass in a URI as a string and parse that + * + * @param someUrl the url to be parsed + */ +declare function purl(someUrl: string): purl.Url; + +export = purl; +export as namespace purl; diff --git a/purl/purl-jquery.d.ts b/purl/purl-jquery.d.ts index cedbf8042f..64b258d9e0 100644 --- a/purl/purl-jquery.d.ts +++ b/purl/purl-jquery.d.ts @@ -3,8 +3,8 @@ // Definitions by: Daniel Ferreira Monteiro Alves // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// + interface JQueryStatic { diff --git a/purl/purl.d.ts b/purl/purl.d.ts deleted file mode 100644 index 8b4d06fca4..0000000000 --- a/purl/purl.d.ts +++ /dev/null @@ -1,60 +0,0 @@ -// Type definitions for Purl 2.3.1 -// Project: https://github.com/allmarkedup/purl -// Definitions by: Daniel Ferreira Monteiro Alves -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace purl { - - interface ParameterMap { - [parameterName: string]: string; - } - - export interface Url { - - /** - * The .attr() method is used to return information on various parts of the URL. - */ - attr(option: string): string; - - /** - * The .param() method is used to return the values of querystring parameters. - */ - param(): ParameterMap; - param(parameterName: string): string; - - /** - * The .segment() method is used to return values of individual segments from the URL's path. - * Pass in an integer value to get the value of that segment - note however that the count is not zero-indexed like an array - i.e. .segment(1) returns the first segment, not the second one. - * You can also pass in negative values, in which case it will count back from the end of the path rather than forwards from the start. - */ - segment(position: number): string; - - /** - * Gets a parameter from the fragment segment - */ - fparam(): ParameterMap; - fparam(parameterName: string): string; - - /** - * Gets the fragment segment at the especified position. - */ - fsegment(position: number): string; - } - -} - -/** - * Parse the current page URL - */ -declare function purl(): purl.Url; - -/** - * Pass in a URI as a string and parse that - * - * @param someUrl the url to be parsed - */ -declare function purl(someUrl: string): purl.Url; - -declare module "purl" { - export = purl; -} diff --git a/purl/tsconfig.json b/purl/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/purl/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/pusher-js/index.d.ts b/pusher-js/index.d.ts new file mode 100644 index 0000000000..e4ebfee975 --- /dev/null +++ b/pusher-js/index.d.ts @@ -0,0 +1,230 @@ +// Type definitions for pusher-js 3.0.0 +// Project: https://github.com/pusher/pusher-js +// Definitions by: Qubo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + +declare namespace pusher { + interface PusherStatic { + new (apiKey: string, config?: Config): Pusher; + } + + interface Pusher { + subscribe(name: string): Channel; + subscribeAll(): void; + unsubscribe(name: string): void; + channel(name: string): Channel; + allChannels(): Channel[]; + bind(eventName: string, callback: Function): Pusher; + bind_all(callback: Function): Pusher; + disconnect(): void; + key: string; + config: Config; //TODO: add GlobalConfig typings + channels: any; //TODO: Type this + global_emitter: EventsDispatcher; + sessionId: number; + timeline: any; //TODO: Type this + connection: ConnectionManager; + } + + interface Config { + /** + * Forces the connection to use encrypted transports. + */ + encrypted?: boolean; + + /** + * Endpoint on your server that will return the authentication signature needed for private channels. + */ + authEndpoint?: string; + + /** + * Defines how the authentication endpoint, defined using authEndpoint, will be called. + * There are two options available: ajax and jsonp. + */ + authTransport?: string; + + /** + * Allows passing additional data to authorizers. Supports query string params and headers (AJAX only). + * For example, following will pass foo=bar via the query string and baz: boo via headers: + */ + auth?: AuthConfig; + + + /** + * Allows connecting to a different datacenter by setting up correct hostnames and ports for the connection. + */ + cluster?: string; + + + /** + * Disables stats collection, so that connection metrics are not submitted to Pusher’s servers. + */ + disableStats?: boolean; + + /** + * Specifies which transports should be used by Pusher to establish a connection. + * Useful for applications running in controlled, well-behaving environments. + * Available transports: ws, wss, xhr_streaming, xhr_polling, sockjs. + * Additional transports may be added in the future and without adding them to this list, they will be disabled. + */ + enabledTransports?: string[]; + + + /** + * Specified which transports must not be used by Pusher to establish a connection. + * This settings overwrites transports whitelisted via the enabledTransports options. + * Available transports: ws, wss, xhr_streaming, xhr_polling, sockjs. + * Additional transports may be added in the future and without adding them to this list, they will be enabled. + */ + disabledTransports?: string[]; + + /** + * Ignores null origin checks for HTTP fallbacks. Use with care, it should be disabled only if necessary (i.e. PhoneGap). + */ + ignoreNullOrigin?: boolean; + + /** + * After this time (in miliseconds) without any messages received from the server, + * a ping message will be sent to check if the connection is still working. + * Default value is is supplied by the server, low values will result in unnecessary traffic. + */ + activityTimeout?: number; + + /** + * Time before the connection is terminated after sending a ping message. + * Default is 30000 (30s). Low values will cause false disconnections, if latency is high. + */ + pongTimeout?: number; + + wsHost?: string; + wsPort?: number; + wssPort?: number; + httpHost?: string; + httpPort?: number; + httpsPort?: number; + } + + interface AuthConfig { + params?: { [key: string]: any }; + headers?: { [key: string]: any }; + } + + interface GenericEventsDispatcher extends EventsDispatcher { + bind(eventName: string, callback: Function, context?: any): Self; + bind_all(callback: Function): Self; + unbind(eventName?: string, callback?: Function, context?: any): Self; + unbind_all(eventName?: string, callback?: Function): Self; + emit(eventName: string, data?: any): Self; + } + + interface Channel extends GenericEventsDispatcher { + /** Triggers an event */ + trigger(eventName: string, data?: any): boolean; + pusher: Pusher; + name: string; + subscribed: boolean; + /** + * Authenticates the connection as a member of the channel. + * @param {String} socketId + * @param {Function} callback + */ + authorize(socketId: string, callback: (data: any) => void): void; + } + + interface EventsDispatcher { + bind(eventName: string, callback: Function, context?: any): EventsDispatcher; + bind_all(callback: Function): EventsDispatcher; + unbind(eventName?: string, callback?: Function, context?: any): EventsDispatcher; + unbind_all(eventName?: string, callback?: Function): EventsDispatcher; + emit(eventName: string, data?: any): EventsDispatcher; + } + + interface ConnectionManager extends GenericEventsDispatcher { + key: string; + options: any; //TODO: Timeline.js + state: string; + connection: any; //TODO: Type this + encrypted: boolean; + timeline: any; //TODO: Type this + connectionCallbacks: { + message: (message: string) => void; + ping: () => void; + activity: () => void; + error: (error: any) => void; + closed: () => void; + }; + errorCallbacks: { + ssl_only: () => void; + refused: () => void; + backoff: () => void; + retry: () => void; + }; + handshakeCallbacks: { + ssl_only: () => void; + refused: () => void; + backoff: () => void; + retry: () => void; + connected: (handshake: any) => void; //TODO: Type this + }; + /** + * Establishes a connection to Pusher. + * + * Does nothing when connection is already established. See top-level doc + * to find events emitted on connection attempts. + */ + connect(): void; + /** + * Sends raw data. + * @param {String} data + */ + send(data: string): boolean; + /** Sends an event. + * + * @param {String} name + * @param {String} data + * @param {String} [channel] + * @returns {Boolean} whether message was sent or not + */ + send_event(name: string, data: string, channel: string): boolean; + /** Closes the connection. */ + disconnect(): void; + isEncrypted(): boolean; + } + + interface PresenceChannel extends Channel { + members: Members; + } + + interface Members { + /** + * Returns member's info for given id. + * + * Resulting object containts two fields - id and info. + * + * @param {Number} id + * @return {Object} member's info or null + */ + get(id: number): T; + /** + * Calls back for each member in unspecified order. + * + * @param {Function} callback + */ + each(callback: (member: any) => void): void; + members: { [id: number]: UserInfo }; + count: number; + myID: number; + me: UserInfo; + } + + interface UserInfo { + id: number; + info: T; + } +} + +declare var pusher: pusher.PusherStatic; + +export = pusher; diff --git a/pusher-js/pusher-js-tests.ts b/pusher-js/pusher-js-tests.ts index c672ff58e0..b393d6cb75 100644 --- a/pusher-js/pusher-js-tests.ts +++ b/pusher-js/pusher-js-tests.ts @@ -1,4 +1,3 @@ -/// import Pusher = require('pusher-js'); import { PresenceChannel } from "pusher-js"; diff --git a/pusher-js/pusher-js.d.ts b/pusher-js/pusher-js.d.ts deleted file mode 100644 index 0a6dc18d24..0000000000 --- a/pusher-js/pusher-js.d.ts +++ /dev/null @@ -1,231 +0,0 @@ -// Type definitions for pusher-js 3.0.0 -// Project: https://github.com/pusher/pusher-js -// Definitions by: Qubo -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "pusher-js" { - - namespace pusher { - interface PusherStatic { - new(apiKey: string, config?: Config): Pusher; - } - - interface Pusher { - subscribe(name: string): Channel; - subscribeAll(): void; - unsubscribe(name: string): void; - channel(name: string): Channel; - allChannels(): Channel[]; - bind(eventName: string, callback: Function): Pusher; - bind_all(callback: Function): Pusher; - disconnect(): void; - key: string; - config: Config; //TODO: add GlobalConfig typings - channels: any; //TODO: Type this - global_emitter: EventsDispatcher; - sessionId: number; - timeline: any; //TODO: Type this - connection: ConnectionManager; - } - - interface Config { - /** - * Forces the connection to use encrypted transports. - */ - encrypted?: boolean; - - /** - * Endpoint on your server that will return the authentication signature needed for private channels. - */ - authEndpoint?: string; - - /** - * Defines how the authentication endpoint, defined using authEndpoint, will be called. - * There are two options available: ajax and jsonp. - */ - authTransport?: string; - - /** - * Allows passing additional data to authorizers. Supports query string params and headers (AJAX only). - * For example, following will pass foo=bar via the query string and baz: boo via headers: - */ - auth?: AuthConfig; - - - /** - * Allows connecting to a different datacenter by setting up correct hostnames and ports for the connection. - */ - cluster?: string; - - - /** - * Disables stats collection, so that connection metrics are not submitted to Pusher’s servers. - */ - disableStats?: boolean; - - /** - * Specifies which transports should be used by Pusher to establish a connection. - * Useful for applications running in controlled, well-behaving environments. - * Available transports: ws, wss, xhr_streaming, xhr_polling, sockjs. - * Additional transports may be added in the future and without adding them to this list, they will be disabled. - */ - enabledTransports?: string[]; - - - /** - * Specified which transports must not be used by Pusher to establish a connection. - * This settings overwrites transports whitelisted via the enabledTransports options. - * Available transports: ws, wss, xhr_streaming, xhr_polling, sockjs. - * Additional transports may be added in the future and without adding them to this list, they will be enabled. - */ - disabledTransports?: string[]; - - /** - * Ignores null origin checks for HTTP fallbacks. Use with care, it should be disabled only if necessary (i.e. PhoneGap). - */ - ignoreNullOrigin?: boolean; - - /** - * After this time (in miliseconds) without any messages received from the server, - * a ping message will be sent to check if the connection is still working. - * Default value is is supplied by the server, low values will result in unnecessary traffic. - */ - activityTimeout?: number; - - /** - * Time before the connection is terminated after sending a ping message. - * Default is 30000 (30s). Low values will cause false disconnections, if latency is high. - */ - pongTimeout?: number; - - wsHost?: string; - wsPort?: number; - wssPort?: number; - httpHost?: string; - httpPort?: number; - httpsPort?: number; - } - - interface AuthConfig { - params?: { [key: string]: any }; - headers?: { [key: string]: any }; - } - - interface GenericEventsDispatcher extends EventsDispatcher { - bind(eventName: string, callback: Function, context?: any): Self; - bind_all(callback: Function): Self; - unbind(eventName?: string, callback?: Function, context?: any): Self; - unbind_all(eventName?: string, callback?: Function): Self; - emit(eventName: string, data?: any): Self; - } - - interface Channel extends GenericEventsDispatcher { - /** Triggers an event */ - trigger(eventName: string, data?: any): boolean; - pusher: Pusher; - name: string; - subscribed: boolean; - /** - * Authenticates the connection as a member of the channel. - * @param {String} socketId - * @param {Function} callback - */ - authorize(socketId: string, callback: (data: any) => void): void; - } - - interface EventsDispatcher { - bind(eventName: string, callback: Function, context?: any): EventsDispatcher; - bind_all(callback: Function): EventsDispatcher; - unbind(eventName?: string, callback?: Function, context?: any): EventsDispatcher; - unbind_all(eventName?: string, callback?: Function): EventsDispatcher; - emit(eventName: string, data?: any): EventsDispatcher; - } - - interface ConnectionManager extends GenericEventsDispatcher { - key: string; - options: any; //TODO: Timeline.js - state: string; - connection: any; //TODO: Type this - encrypted: boolean; - timeline: any; //TODO: Type this - connectionCallbacks: { - message: (message: string) => void; - ping: () => void; - activity: () => void; - error: (error: any) => void; - closed: () => void; - }; - errorCallbacks: { - ssl_only: () => void; - refused: () => void; - backoff: () => void; - retry: () => void; - }; - handshakeCallbacks: { - ssl_only: () => void; - refused: () => void; - backoff: () => void; - retry: () => void; - connected: (handshake: any) => void; //TODO: Type this - }; - /** - * Establishes a connection to Pusher. - * - * Does nothing when connection is already established. See top-level doc - * to find events emitted on connection attempts. - */ - connect(): void; - /** - * Sends raw data. - * @param {String} data - */ - send(data: string): boolean; - /** Sends an event. - * - * @param {String} name - * @param {String} data - * @param {String} [channel] - * @returns {Boolean} whether message was sent or not - */ - send_event(name: string, data: string, channel: string): boolean; - /** Closes the connection. */ - disconnect(): void; - isEncrypted(): boolean; - } - - interface PresenceChannel extends Channel { - members: Members; - } - - interface Members { - /** - * Returns member's info for given id. - * - * Resulting object containts two fields - id and info. - * - * @param {Number} id - * @return {Object} member's info or null - */ - get(id: number): T; - /** - * Calls back for each member in unspecified order. - * - * @param {Function} callback - */ - each(callback: (member: any) => void): void; - members: { [id: number]: UserInfo }; - count: number; - myID: number; - me: UserInfo; - } - - interface UserInfo { - id: number; - info: T; - } - } - - var pusher: pusher.PusherStatic; - - export = pusher; -} diff --git a/pusher-js/tsconfig.json b/pusher-js/tsconfig.json new file mode 100644 index 0000000000..873e68d745 --- /dev/null +++ b/pusher-js/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "pusher-js-tests.ts" + ] +} \ No newline at end of file diff --git a/q-io/Q-io-tests.ts b/q-io/Q-io-tests.ts index 21b8969884..f0dfe8e01e 100644 --- a/q-io/Q-io-tests.ts +++ b/q-io/Q-io-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + var fs:typeof QioFS = require('q-io/fs'); var http:typeof QioHTTP = require('q-io/http'); diff --git a/q-io/Q-io.d.ts b/q-io/Q-io.d.ts deleted file mode 100644 index 66bffa7577..0000000000 --- a/q-io/Q-io.d.ts +++ /dev/null @@ -1,257 +0,0 @@ -// Type definitions for Q-io -// Project: https://github.com/kriskowal/q-io -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -//TODO add support for q-io/http-apps -//TODO add verified support for q-io/fs-mock -//TODO fix Readers/Writers properly -//TODO find solution for overloaded return types (QioFS.open/QioFS.read) -// for some ideas see https://typescript.codeplex.com/discussions/461587#post1105930 - -declare namespace QioFS { - - //TODO how to define the multiple return types? use any for now? - export function open(path:string, options?:any):Q.Promise; - //export function open(path:string, options?:any):Q.Promise; - //export function open(path:string, options?:any):Q.Promise; - //export function open(path:string, options?:any):Q.Promise; - - //TODO how to define the multiple return types? use any for now? - export function read(path:string, options?:any):Q.Promise; - //export function read(path:string, options?:any):Q.Promise; - //export function read(path:string, options?:any):Q.Promise; - - export function write(path:string, content:Buffer, options?:any):Q.Promise; - export function write(path:string, content:string, options?:any):Q.Promise; - - export function append(path:string, content:Buffer, options?:any):Q.Promise; - export function append(path:string, content:string, options?:any):Q.Promise; - - export function copy(source:string, target:string):Q.Promise; - export function copyTree(source:string, target:string):Q.Promise; - - export function list(path:string):Q.Promise; - export function listTree(path:string, guard?:(path:string, stat:any) => boolean):Q.Promise; - export function listDirectoryTree(path:string):Q.Promise; - - export function makeDirectory(path:string, mode?:string):Q.Promise; - export function makeDirectory(path:string, mode?:number):Q.Promise; - export function makeTree(path:string, mode?:string):Q.Promise; - export function makeTree(path:string, mode?:number):Q.Promise; - - export function remove(path:string):Q.Promise; - export function removeTree(path:string):Q.Promise; - - export function rename(source:string, target:string):Q.Promise; - export function move(source:string, target:string):Q.Promise; - - export function link(source:string, target:any):Q.Promise; - - export function symbolicCopy(source:string, target:string, type:string):Q.Promise; - export function symbolicLink(target:string, link:string, type:string):Q.Promise; - - export function chown(path:string, uid:number, gid:number):Q.Promise; - export function chmod(path:string, mode?:string):Q.Promise; - export function chmod(path:string, mode?:number):Q.Promise; - - export function stat(path:string):Q.Promise; - export function statLink(path:string):Q.Promise; - export function statFd(fd:number):Q.Promise; - - export function exists(path:string):Q.Promise; - - export function isFile(path:string):Q.Promise; - export function isDirectory(path:string):Q.Promise; - export function isSymbolicLink(path:string):Q.Promise; - - export function lastModified(path:string):Q.Promise; - export function lastAccessed(path:string):Q.Promise; - - export function split(path:string):string[]; - export function join(...paths:string[]):string; - export function join(paths:string[]):string; - export function resolve(...path:string[]):string; - export function resolve(paths:string[]):string; - export function normal(...path:string[]):string; - export function normal(paths:string[]):string; - export function absolute(path:string):string; - - export function canonical(path:string):Q.Promise; - export function readLink(path:string):Q.Promise; - - export function contains(parent:string, child:string):boolean; - - export function relative(source:string, target:string):Q.Promise; - - export function relativeFromFile(source:string, target:string):string; - export function relativeFromDirectory(source:string, target:string):string; - - export function isAbsolute(path:string):boolean; - export function isRelative(path:string):boolean; - export function isRoot(path:string):boolean; - - export function root(path:string):string; - export function directory(path:string):string; - export function base(path:string, extension:string):string; - export function extension(path:string):string; - - //this should return a q-io/fs-mock MockFS - export function reroot(path:string):typeof QioFS; - - export function toObject(path:string):{[path:string]:Buffer}; - - //listed but not implemented by Q-io - //export function glob(pattern):Q.Promise; - //export function match(pattern, path:string):Q.Promise; - - //TODO link this to node.js FS module (no lazy clones) - interface Stats { - node:NodeStats; - size:number; - } - interface NodeStats { - isFile():boolean; - isDirectory():boolean; - isBlockDevice():boolean; - isCharacterDevice():boolean; - isSymbolicLink():boolean; - isFIFO():boolean; - isSocket():boolean; - node:NodeStats; - dev:number; - ino:number; - mode:number; - nlink:number; - uid:number; - gid:number; - rdev:number; - size:number; - blksize:number; - blocks:number; - atime:Date; - mtime:Date; - ctime:Date; - } -} - -declare namespace QioHTTP { - export function request(request:Request):Q.Promise; - export function request(url:string):Q.Promise; - - export function read(request:Request):Q.Promise; - export function read(url:string):Q.Promise; - - export function normalizeRequest(request:Request):Request; - export function normalizeRequest(url:string):Request; - export function normalizeResponse(response:Response):Response; - - interface Request { - url:string; - path:string; - scriptName:string; - pathInfo:string; - version:string[]; - method:string; - scheme:string; - - host:string; - port:number; - remoteHost:string; - remotePort:number; - - headers:Headers; - agent:any; - body:any; - node:any; - } - interface Response { - status:number; - headers:Headers; - body:Qio.Reader - onclose:() => void; - node:any; - } - interface Headers { - [name:string]:any; - // [name:string]:any[]; - } - interface Body extends Qio.Stream { - - } - interface Application { - (req:Request):Q.Promise; - } -} - -declare namespace Qio { - interface ForEachCallback { - (chunk:Buffer):Q.Promise; - (chunk:string):Q.Promise; - } - interface ForEach { - forEach(callback:ForEachCallback):Q.Promise; - } - - interface Reader extends ForEach { - read(charset:string):Q.Promise; - read():Q.Promise; - close():void; - node: NodeJS.ReadableStream; - } - interface Writer { - write(content:string):void; - write(content:Buffer):void; - flush():Q.Promise; - close():void; - destroy():void; - node: NodeJS.WritableStream; - } - - interface Stream { - read(charset:string):Q.Promise; - read():Q.Promise; - write(content:string):void; - write(content:Buffer):void; - flush():Q.Promise; - close():void; - destroy():void; - node:any; - } - - interface BufferReader extends QioBufferReader { - - } -} -interface QioBufferReader { - new ():Qio.Reader; - read(stream:Qio.Reader, charset:string):string; - read(stream:Qio.Reader):Buffer; - join(buffers:Buffer[]):Buffer; -} -interface QioBufferWriter { - (writer:Buffer):Qio.Writer; - Writer:Qio.Writer; -} -interface QioBufferStream { - (buffer:Buffer, encoding:string):Qio.Stream -} - -declare module "q-io/http" { -export = QioHTTP; -} -declare module "q-io/fs" { -export = QioFS; -} -declare module "q-io/reader" { -export = QioBufferReader; -} -declare module "q-io/writer" { -export = QioBufferWriter; -} -declare module "q-io/buffer-stream" { -export = QioBufferStream; -} diff --git a/q-io/index.d.ts b/q-io/index.d.ts new file mode 100644 index 0000000000..fa19ef3fd5 --- /dev/null +++ b/q-io/index.d.ts @@ -0,0 +1,257 @@ +// Type definitions for Q-io +// Project: https://github.com/kriskowal/q-io +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +//TODO add support for q-io/http-apps +//TODO add verified support for q-io/fs-mock +//TODO fix Readers/Writers properly +//TODO find solution for overloaded return types (QioFS.open/QioFS.read) +// for some ideas see https://typescript.codeplex.com/discussions/461587#post1105930 + +declare namespace QioFS { + + //TODO how to define the multiple return types? use any for now? + export function open(path:string, options?:any):Q.Promise; + //export function open(path:string, options?:any):Q.Promise; + //export function open(path:string, options?:any):Q.Promise; + //export function open(path:string, options?:any):Q.Promise; + + //TODO how to define the multiple return types? use any for now? + export function read(path:string, options?:any):Q.Promise; + //export function read(path:string, options?:any):Q.Promise; + //export function read(path:string, options?:any):Q.Promise; + + export function write(path:string, content:Buffer, options?:any):Q.Promise; + export function write(path:string, content:string, options?:any):Q.Promise; + + export function append(path:string, content:Buffer, options?:any):Q.Promise; + export function append(path:string, content:string, options?:any):Q.Promise; + + export function copy(source:string, target:string):Q.Promise; + export function copyTree(source:string, target:string):Q.Promise; + + export function list(path:string):Q.Promise; + export function listTree(path:string, guard?:(path:string, stat:any) => boolean):Q.Promise; + export function listDirectoryTree(path:string):Q.Promise; + + export function makeDirectory(path:string, mode?:string):Q.Promise; + export function makeDirectory(path:string, mode?:number):Q.Promise; + export function makeTree(path:string, mode?:string):Q.Promise; + export function makeTree(path:string, mode?:number):Q.Promise; + + export function remove(path:string):Q.Promise; + export function removeTree(path:string):Q.Promise; + + export function rename(source:string, target:string):Q.Promise; + export function move(source:string, target:string):Q.Promise; + + export function link(source:string, target:any):Q.Promise; + + export function symbolicCopy(source:string, target:string, type:string):Q.Promise; + export function symbolicLink(target:string, link:string, type:string):Q.Promise; + + export function chown(path:string, uid:number, gid:number):Q.Promise; + export function chmod(path:string, mode?:string):Q.Promise; + export function chmod(path:string, mode?:number):Q.Promise; + + export function stat(path:string):Q.Promise; + export function statLink(path:string):Q.Promise; + export function statFd(fd:number):Q.Promise; + + export function exists(path:string):Q.Promise; + + export function isFile(path:string):Q.Promise; + export function isDirectory(path:string):Q.Promise; + export function isSymbolicLink(path:string):Q.Promise; + + export function lastModified(path:string):Q.Promise; + export function lastAccessed(path:string):Q.Promise; + + export function split(path:string):string[]; + export function join(...paths:string[]):string; + export function join(paths:string[]):string; + export function resolve(...path:string[]):string; + export function resolve(paths:string[]):string; + export function normal(...path:string[]):string; + export function normal(paths:string[]):string; + export function absolute(path:string):string; + + export function canonical(path:string):Q.Promise; + export function readLink(path:string):Q.Promise; + + export function contains(parent:string, child:string):boolean; + + export function relative(source:string, target:string):Q.Promise; + + export function relativeFromFile(source:string, target:string):string; + export function relativeFromDirectory(source:string, target:string):string; + + export function isAbsolute(path:string):boolean; + export function isRelative(path:string):boolean; + export function isRoot(path:string):boolean; + + export function root(path:string):string; + export function directory(path:string):string; + export function base(path:string, extension:string):string; + export function extension(path:string):string; + + //this should return a q-io/fs-mock MockFS + export function reroot(path:string):typeof QioFS; + + export function toObject(path:string):{[path:string]:Buffer}; + + //listed but not implemented by Q-io + //export function glob(pattern):Q.Promise; + //export function match(pattern, path:string):Q.Promise; + + //TODO link this to node.js FS module (no lazy clones) + interface Stats { + node:NodeStats; + size:number; + } + interface NodeStats { + isFile():boolean; + isDirectory():boolean; + isBlockDevice():boolean; + isCharacterDevice():boolean; + isSymbolicLink():boolean; + isFIFO():boolean; + isSocket():boolean; + node:NodeStats; + dev:number; + ino:number; + mode:number; + nlink:number; + uid:number; + gid:number; + rdev:number; + size:number; + blksize:number; + blocks:number; + atime:Date; + mtime:Date; + ctime:Date; + } +} + +declare namespace QioHTTP { + export function request(request:Request):Q.Promise; + export function request(url:string):Q.Promise; + + export function read(request:Request):Q.Promise; + export function read(url:string):Q.Promise; + + export function normalizeRequest(request:Request):Request; + export function normalizeRequest(url:string):Request; + export function normalizeResponse(response:Response):Response; + + interface Request { + url:string; + path:string; + scriptName:string; + pathInfo:string; + version:string[]; + method:string; + scheme:string; + + host:string; + port:number; + remoteHost:string; + remotePort:number; + + headers:Headers; + agent:any; + body:any; + node:any; + } + interface Response { + status:number; + headers:Headers; + body:Qio.Reader + onclose:() => void; + node:any; + } + interface Headers { + [name:string]:any; + // [name:string]:any[]; + } + interface Body extends Qio.Stream { + + } + interface Application { + (req:Request):Q.Promise; + } +} + +declare namespace Qio { + interface ForEachCallback { + (chunk:Buffer):Q.Promise; + (chunk:string):Q.Promise; + } + interface ForEach { + forEach(callback:ForEachCallback):Q.Promise; + } + + interface Reader extends ForEach { + read(charset:string):Q.Promise; + read():Q.Promise; + close():void; + node: NodeJS.ReadableStream; + } + interface Writer { + write(content:string):void; + write(content:Buffer):void; + flush():Q.Promise; + close():void; + destroy():void; + node: NodeJS.WritableStream; + } + + interface Stream { + read(charset:string):Q.Promise; + read():Q.Promise; + write(content:string):void; + write(content:Buffer):void; + flush():Q.Promise; + close():void; + destroy():void; + node:any; + } + + interface BufferReader extends QioBufferReader { + + } +} +interface QioBufferReader { + new ():Qio.Reader; + read(stream:Qio.Reader, charset:string):string; + read(stream:Qio.Reader):Buffer; + join(buffers:Buffer[]):Buffer; +} +interface QioBufferWriter { + (writer:Buffer):Qio.Writer; + Writer:Qio.Writer; +} +interface QioBufferStream { + (buffer:Buffer, encoding:string):Qio.Stream +} + +declare module "q-io/http" { +export = QioHTTP; +} +declare module "q-io/fs" { +export = QioFS; +} +declare module "q-io/reader" { +export = QioBufferReader; +} +declare module "q-io/writer" { +export = QioBufferWriter; +} +declare module "q-io/buffer-stream" { +export = QioBufferStream; +} diff --git a/q-io/tsconfig.json b/q-io/tsconfig.json new file mode 100644 index 0000000000..47cc97955c --- /dev/null +++ b/q-io/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "q-io-tests.ts" + ] +} \ No newline at end of file diff --git a/q-retry/index.d.ts b/q-retry/index.d.ts new file mode 100644 index 0000000000..851f5fabe3 --- /dev/null +++ b/q-retry/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for q-retry +// Project: https://github.com/vilic/q-retry +// Definitions by: VILIC VANE +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = Q; + +declare namespace Q { + export interface IRetryOptions { + limit?: number; + interval?: number; + maxInterval?: number; + intervalMultiplier?: number; + } + + export function retry(process: () => IPromise, onFail: (reason: any, retries: number) => void, limit: number): Promise; + export function retry(process: () => IPromise, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; + export function retry(process: () => IPromise, limit: number): Promise; + export function retry(process: () => IPromise, options?: IRetryOptions): Promise; + export function retry(process: () => U, onFail: (reason: any, retries: number) => void, limit: number): Promise; + export function retry(process: () => U, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; + export function retry(process: () => U, limit: number): Promise; + export function retry(process: () => U, options?: IRetryOptions): Promise; + + interface Promise { + retry(process: (value: T) => IPromise, onFail: (reason: any, retries: number) => void, limit: number): Promise; + retry(process: (value: T) => IPromise, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; + retry(process: (value: T) => IPromise, limit: number): Promise; + retry(process: (value: T) => IPromise, options?: IRetryOptions): Promise; + retry(process: (value: T) => U, onFail: (reason: any, retries: number) => void, limit: number): Promise; + retry(process: (value: T) => U, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; + retry(process: (value: T) => U, limit: number): Promise; + retry(process: (value: T) => U, options?: IRetryOptions): Promise; + } +} diff --git a/q-retry/q-retry-tests.ts b/q-retry/q-retry-tests.ts index fc33d7ba97..e22ab7ed03 100644 --- a/q-retry/q-retry-tests.ts +++ b/q-retry/q-retry-tests.ts @@ -1,4 +1,4 @@ -/// + import Q = require('q-retry'); diff --git a/q-retry/q-retry.d.ts b/q-retry/q-retry.d.ts deleted file mode 100644 index ada36a59a4..0000000000 --- a/q-retry/q-retry.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Type definitions for q-retry -// Project: https://github.com/vilic/q-retry -// Definitions by: VILIC VANE -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace Q { - export interface IRetryOptions { - limit?: number; - interval?: number; - maxInterval?: number; - intervalMultiplier?: number; - } - - export function retry(process: () => IPromise, onFail: (reason: any, retries: number) => void, limit: number): Promise; - export function retry(process: () => IPromise, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; - export function retry(process: () => IPromise, limit: number): Promise; - export function retry(process: () => IPromise, options?: IRetryOptions): Promise; - export function retry(process: () => U, onFail: (reason: any, retries: number) => void, limit: number): Promise; - export function retry(process: () => U, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; - export function retry(process: () => U, limit: number): Promise; - export function retry(process: () => U, options?: IRetryOptions): Promise; - - interface Promise { - retry(process: (value: T) => IPromise, onFail: (reason: any, retries: number) => void, limit: number): Promise; - retry(process: (value: T) => IPromise, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; - retry(process: (value: T) => IPromise, limit: number): Promise; - retry(process: (value: T) => IPromise, options?: IRetryOptions): Promise; - retry(process: (value: T) => U, onFail: (reason: any, retries: number) => void, limit: number): Promise; - retry(process: (value: T) => U, onFail: (reason: any, retries: number) => void, options?: IRetryOptions): Promise; - retry(process: (value: T) => U, limit: number): Promise; - retry(process: (value: T) => U, options?: IRetryOptions): Promise; - } -} - -declare module "q-retry" { - export = Q; -} diff --git a/q-retry/tsconfig.json b/q-retry/tsconfig.json new file mode 100644 index 0000000000..e68cbe8c18 --- /dev/null +++ b/q-retry/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "q-retry-tests.ts" + ] +} \ No newline at end of file diff --git a/q/Q-tests.ts b/q/Q-tests.ts index ab613f8aa4..efd32d4b98 100644 --- a/q/Q-tests.ts +++ b/q/Q-tests.ts @@ -1,7 +1,7 @@ -/// -/// +/// -import q = require('q'); + +import Q = require('q'); Q(8).then(x => console.log(x.toExponential())); diff --git a/q/Q.d.ts b/q/Q.d.ts deleted file mode 100644 index bd9cdb8ca5..0000000000 --- a/q/Q.d.ts +++ /dev/null @@ -1,336 +0,0 @@ -// Type definitions for Q -// Project: https://github.com/kriskowal/q -// Definitions by: Barrie Nemetchek , Andrew Gaspar , John Reilly -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/** - * If value is a Q promise, returns the promise. - * If value is a promise from another library it is coerced into a Q promise (where possible). - */ -declare function Q(promise: Q.IPromise): Q.Promise; -/** - * If value is not a promise, returns a promise that is fulfilled with value. - */ -declare function Q(value: T): Q.Promise; - -declare namespace Q { - interface IPromise { - then(onFulfill?: (value: T) => U | IPromise, onReject?: (error: any) => U | IPromise): IPromise; - } - - interface Deferred { - promise: Promise; - resolve(value?: T): void; - resolve(value?: IPromise): void; - reject(reason: any): void; - notify(value: any): void; - makeNodeResolver(): (reason: any, value: T) => void; - } - - interface Promise { - /** - * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful for collecting resources regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object. - - * finally returns a promise, which will become resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise returned from callback is finished. - */ - fin(finallyCallback: () => any): Promise; - /** - * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful for collecting resources regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object. - - * finally returns a promise, which will become resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise returned from callback is finished. - */ - finally(finallyCallback: () => any): Promise; - - /** - * The then method from the Promises/A+ specification, with an additional progress handler. - */ - then(onFulfill?: (value: T) => U | IPromise, onReject?: (error: any) => U | IPromise, onProgress?: Function): Promise; - - /** - * Like then, but "spreads" the array into a variadic fulfillment handler. If any of the promises in the array are rejected, instead calls onRejected with the first rejected promise's rejection reason. - * - * This is especially useful in conjunction with all - */ - spread(onFulfill: (...args: any[]) => IPromise | U, onReject?: (reason: any) => IPromise | U): Promise; - - fail(onRejected: (reason: any) => U | IPromise): Promise; - - /** - * A sugar method, equivalent to promise.then(undefined, onRejected). - */ - catch(onRejected: (reason: any) => U | IPromise): Promise; - - /** - * A sugar method, equivalent to promise.then(undefined, undefined, onProgress). - */ - progress(onProgress: (progress: any) => any): Promise; - - /** - * Much like then, but with different behavior around unhandled rejection. If there is an unhandled rejection, either because promise is rejected and no onRejected callback was provided, or because onFulfilled or onRejected threw an error or returned a rejected promise, the resulting rejection reason is thrown as an exception in a future turn of the event loop. - * - * This method should be used to terminate chains of promises that will not be passed elsewhere. Since exceptions thrown in then callbacks are consumed and transformed into rejections, exceptions at the end of the chain are easy to accidentally, silently ignore. By arranging for the exception to be thrown in a future turn of the event loop, so that it won't be caught, it causes an onerror event on the browser window, or an uncaughtException event on Node.js's process object. - * - * Exceptions thrown by done will have long stack traces, if Q.longStackSupport is set to true. If Q.onerror is set, exceptions will be delivered there instead of thrown in a future turn. - * - * The Golden Rule of done vs. then usage is: either return your promise to someone else, or if the chain ends with you, call done to terminate it. - */ - done(onFulfilled?: (value: T) => any, onRejected?: (reason: any) => any, onProgress?: (progress: any) => any): void; - - /** - * If callback is a function, assumes it's a Node.js-style callback, and calls it as either callback(rejectionReason) when/if promise becomes rejected, or as callback(null, fulfillmentValue) when/if promise becomes fulfilled. If callback is not a function, simply returns promise. - */ - nodeify(callback: (reason: any, value: any) => void): Promise; - - /** - * Returns a promise to get the named property of an object. Essentially equivalent to - * - * promise.then(function (o) { - * return o[propertyName]; - * }); - */ - get(propertyName: String): Promise; - set(propertyName: String, value: any): Promise; - delete(propertyName: String): Promise; - /** - * Returns a promise for the result of calling the named method of an object with the given array of arguments. The object itself is this in the function, just like a synchronous method call. Essentially equivalent to - * - * promise.then(function (o) { - * return o[methodName].apply(o, args); - * }); - */ - post(methodName: String, args: any[]): Promise; - /** - * Returns a promise for the result of calling the named method of an object with the given variadic arguments. The object itself is this in the function, just like a synchronous method call. - */ - invoke(methodName: String, ...args: any[]): Promise; - fapply(args: any[]): Promise; - fcall(...args: any[]): Promise; - - /** - * Returns a promise for an array of the property names of an object. Essentially equivalent to - * - * promise.then(function (o) { - * return Object.keys(o); - * }); - */ - keys(): Promise; - - /** - * A sugar method, equivalent to promise.then(function () { return value; }). - */ - thenResolve(value: U): Promise; - /** - * A sugar method, equivalent to promise.then(function () { throw reason; }). - */ - thenReject(reason: any): Promise; - - /** - * Attaches a handler that will observe the value of the promise when it becomes fulfilled, returning a promise for that same value, perhaps deferred but not replaced by the promise returned by the onFulfilled handler. - */ - tap(onFulfilled: (value: T) => any): Promise; - - timeout(ms: number, message?: string): Promise; - /** - * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. - */ - delay(ms: number): Promise; - - /** - * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. - */ - isFulfilled(): boolean; - /** - * Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false. - */ - isRejected(): boolean; - /** - * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. - */ - isPending(): boolean; - - valueOf(): any; - - /** - * Returns a "state snapshot" object, which will be in one of three forms: - * - * - { state: "pending" } - * - { state: "fulfilled", value: } - * - { state: "rejected", reason: } - */ - inspect(): PromiseState; - } - - interface PromiseState { - /** - * "fulfilled", "rejected", "pending" - */ - state: string; - value?: T; - reason?: any; - } - - // If no value provided, returned promise will be of void type - export function when(): Promise; - - // if no fulfill, reject, or progress provided, returned promise will be of same type - export function when(value: T | IPromise): Promise; - - // If a non-promise value is provided, it will not reject or progress - export function when(value: T | IPromise, onFulfilled: (val: T) => U | IPromise, onRejected?: (reason: any) => U | IPromise, onProgress?: (progress: any) => any): Promise; - - /** - * Currently "impossible" (and I use the term loosely) to implement due to TypeScript limitations as it is now. - * See: https://github.com/Microsoft/TypeScript/issues/1784 for discussion on it. - */ - // export function try(method: Function, ...args: any[]): Promise; - - export function fbind(method: (...args: any[]) => T | IPromise, ...args: any[]): (...args: any[]) => Promise; - - export function fcall(method: (...args: any[]) => T, ...args: any[]): Promise; - - export function send(obj: any, functionName: string, ...args: any[]): Promise; - export function invoke(obj: any, functionName: string, ...args: any[]): Promise; - export function mcall(obj: any, functionName: string, ...args: any[]): Promise; - - export function denodeify(nodeFunction: Function, ...args: any[]): (...args: any[]) => Promise; - export function nbind(nodeFunction: Function, thisArg: any, ...args: any[]): (...args: any[]) => Promise; - export function nfbind(nodeFunction: Function, ...args: any[]): (...args: any[]) => Promise; - export function nfcall(nodeFunction: Function, ...args: any[]): Promise; - export function nfapply(nodeFunction: Function, args: any[]): Promise; - - export function ninvoke(nodeModule: any, functionName: string, ...args: any[]): Promise; - export function npost(nodeModule: any, functionName: string, args: any[]): Promise; - export function nsend(nodeModule: any, functionName: string, ...args: any[]): Promise; - export function nmcall(nodeModule: any, functionName: string, ...args: any[]): Promise; - - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IPromise[]): Promise; - - /** - * Returns a promise for the first of an array of promises to become settled. - */ - export function race(promises: IPromise[]): Promise; - - /** - * Returns a promise that is fulfilled with an array of promise state snapshots, but only after all the original promises have settled, i.e. become either fulfilled or rejected. - */ - export function allSettled(promises: IPromise[]): Promise[]>; - - export function allResolved(promises: IPromise[]): Promise[]>; - - /** - * Like then, but "spreads" the array into a variadic fulfillment handler. If any of the promises in the array are rejected, instead calls onRejected with the first rejected promise's rejection reason. - * This is especially useful in conjunction with all. - */ - export function spread(promises: IPromise[], onFulfilled: (...args: T[]) => U | IPromise, onRejected?: (reason: any) => U | IPromise): Promise; - - /** - * Returns a promise that will have the same result as promise, except that if promise is not fulfilled or rejected before ms milliseconds, the returned promise will be rejected with an Error with the given message. If message is not supplied, the message will be "Timed out after " + ms + " ms". - */ - export function timeout(promise: Promise, ms: number, message?: string): Promise; - - /** - * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. - */ - export function delay(promise: Promise, ms: number): Promise; - /** - * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. - */ - export function delay(value: T, ms: number): Promise; - /** - * Returns a promise that will be fulfilled with undefined after at least ms milliseconds have passed. - */ - export function delay(ms: number): Promise ; - /** - * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. - */ - export function isFulfilled(promise: Promise): boolean; - /** - * Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false. - */ - export function isRejected(promise: Promise): boolean; - /** - * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. - */ - export function isPending(promise: Promise): boolean; - - /** - * Returns a "deferred" object with a: - * promise property - * resolve(value) method - * reject(reason) method - * notify(value) method - * makeNodeResolver() method - */ - export function defer(): Deferred; - - /** - * Returns a promise that is rejected with reason. - */ - export function reject(reason?: any): Promise; - - export function Promise(resolver: (resolve: (val: T | IPromise) => void , reject: (reason: any) => void , notify: (progress: any) => void ) => void ): Promise; - - /** - * Creates a new version of func that accepts any combination of promise and non-promise values, converting them to their fulfillment values before calling the original func. The returned version also always returns a promise: if func does a return or throw, then Q.promised(func) will return fulfilled or rejected promise, respectively. - * - * This can be useful for creating functions that accept either promises or non-promise values, and for ensuring that the function always returns a promise even in the face of unintentional thrown exceptions. - */ - export function promised(callback: (...args: any[]) => T): (...args: any[]) => Promise; - - /** - * Returns whether the given value is a Q promise. - */ - export function isPromise(object: any): boolean; - /** - * Returns whether the given value is a promise (i.e. it's an object with a then function). - */ - export function isPromiseAlike(object: any): boolean; - /** - * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. - */ - export function isPending(object: any): boolean; - - /** - * This is an experimental tool for converting a generator function into a deferred function. This has the potential of reducing nested callbacks in engines that support yield. - */ - export function async(generatorFunction: any): (...args: any[]) => Promise; - export function nextTick(callback: Function): void; - - /** - * A settable property that will intercept any uncaught errors that would otherwise be thrown in the next tick of the event loop, usually as a result of done. Can be useful for getting the full stack trace of an error in browsers, which is not usually possible with window.onerror. - */ - export var onerror: (reason: any) => void; - /** - * A settable property that lets you turn on long stack trace support. If turned on, "stack jumps" will be tracked across asynchronous promise operations, so that if an uncaught error is thrown by done or a rejection reason's stack property is inspected in a rejection callback, a long stack trace is produced. - */ - export var longStackSupport: boolean; - - /** - * Calling resolve with a pending promise causes promise to wait on the passed promise, becoming fulfilled with its fulfillment value or rejected with its rejection reason (or staying pending forever, if the passed promise does). - * Calling resolve with a rejected promise causes promise to be rejected with the passed promise's rejection reason. - * Calling resolve with a fulfilled promise causes promise to be fulfilled with the passed promise's fulfillment value. - * Calling resolve with a non-promise value causes promise to be fulfilled with that value. - */ - export function resolve(object: IPromise): Promise; - /** - * Calling resolve with a pending promise causes promise to wait on the passed promise, becoming fulfilled with its fulfillment value or rejected with its rejection reason (or staying pending forever, if the passed promise does). - * Calling resolve with a rejected promise causes promise to be rejected with the passed promise's rejection reason. - * Calling resolve with a fulfilled promise causes promise to be fulfilled with the passed promise's fulfillment value. - * Calling resolve with a non-promise value causes promise to be fulfilled with that value. - */ - export function resolve(object: T): Promise; - - /** - * Resets the global "Q" variable to the value it has before Q was loaded. - * This will either be undefined if there was no version or the version of Q which was already loaded before. - * @returns { The last version of Q. } - */ - export function noConflict(): typeof Q; -} - -declare module "q" { - export = Q; -} diff --git a/q/index.d.ts b/q/index.d.ts new file mode 100644 index 0000000000..f96774b791 --- /dev/null +++ b/q/index.d.ts @@ -0,0 +1,343 @@ +// Type definitions for Q +// Project: https://github.com/kriskowal/q +// Definitions by: Barrie Nemetchek , Andrew Gaspar , John Reilly +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Q; +export as namespace Q; + +/** + * If value is a Q promise, returns the promise. + * If value is a promise from another library it is coerced into a Q promise (where possible). + */ +declare function Q(promise: Q.IPromise): Q.Promise; +/** + * If value is not a promise, returns a promise that is fulfilled with value. + */ +declare function Q(value: T): Q.Promise; + +declare namespace Q { + interface IPromise { + then(onFulfill?: (value: T) => U | IPromise, onReject?: (error: any) => U | IPromise): IPromise; + } + + interface Deferred { + promise: Promise; + resolve(value?: T): void; + resolve(value?: IPromise): void; + reject(reason: any): void; + notify(value: any): void; + makeNodeResolver(): (reason: any, value: T) => void; + } + + interface Promise { + /** + * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful for collecting resources regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object. + + * finally returns a promise, which will become resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise returned from callback is finished. + */ + fin(finallyCallback: () => any): Promise; + /** + * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful for collecting resources regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object. + + * finally returns a promise, which will become resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise returned from callback is finished. + */ + finally(finallyCallback: () => any): Promise; + + /** + * The then method from the Promises/A+ specification, with an additional progress handler. + */ + then(onFulfill?: (value: T) => U | IPromise, onReject?: (error: any) => U | IPromise, onProgress?: Function): Promise; + + /** + * Like then, but "spreads" the array into a variadic fulfillment handler. If any of the promises in the array are rejected, instead calls onRejected with the first rejected promise's rejection reason. + * + * This is especially useful in conjunction with all + */ + spread(onFulfill: (...args: any[]) => IPromise | U, onReject?: (reason: any) => IPromise | U): Promise; + + fail(onRejected: (reason: any) => U | IPromise): Promise; + + /** + * A sugar method, equivalent to promise.then(undefined, onRejected). + */ + catch(onRejected: (reason: any) => U | IPromise): Promise; + + /** + * A sugar method, equivalent to promise.then(undefined, undefined, onProgress). + */ + progress(onProgress: (progress: any) => any): Promise; + + /** + * Much like then, but with different behavior around unhandled rejection. If there is an unhandled rejection, either because promise is rejected and no onRejected callback was provided, or because onFulfilled or onRejected threw an error or returned a rejected promise, the resulting rejection reason is thrown as an exception in a future turn of the event loop. + * + * This method should be used to terminate chains of promises that will not be passed elsewhere. Since exceptions thrown in then callbacks are consumed and transformed into rejections, exceptions at the end of the chain are easy to accidentally, silently ignore. By arranging for the exception to be thrown in a future turn of the event loop, so that it won't be caught, it causes an onerror event on the browser window, or an uncaughtException event on Node.js's process object. + * + * Exceptions thrown by done will have long stack traces, if Q.longStackSupport is set to true. If Q.onerror is set, exceptions will be delivered there instead of thrown in a future turn. + * + * The Golden Rule of done vs. then usage is: either return your promise to someone else, or if the chain ends with you, call done to terminate it. + */ + done(onFulfilled?: (value: T) => any, onRejected?: (reason: any) => any, onProgress?: (progress: any) => any): void; + + /** + * If callback is a function, assumes it's a Node.js-style callback, and calls it as either callback(rejectionReason) when/if promise becomes rejected, or as callback(null, fulfillmentValue) when/if promise becomes fulfilled. If callback is not a function, simply returns promise. + */ + nodeify(callback: (reason: any, value: any) => void): Promise; + + /** + * Returns a promise to get the named property of an object. Essentially equivalent to + * + * promise.then(function (o) { + * return o[propertyName]; + * }); + */ + get(propertyName: String): Promise; + set(propertyName: String, value: any): Promise; + delete(propertyName: String): Promise; + /** + * Returns a promise for the result of calling the named method of an object with the given array of arguments. The object itself is this in the function, just like a synchronous method call. Essentially equivalent to + * + * promise.then(function (o) { + * return o[methodName].apply(o, args); + * }); + */ + post(methodName: String, args: any[]): Promise; + /** + * Returns a promise for the result of calling the named method of an object with the given variadic arguments. The object itself is this in the function, just like a synchronous method call. + */ + invoke(methodName: String, ...args: any[]): Promise; + fapply(args: any[]): Promise; + fcall(...args: any[]): Promise; + + /** + * Returns a promise for an array of the property names of an object. Essentially equivalent to + * + * promise.then(function (o) { + * return Object.keys(o); + * }); + */ + keys(): Promise; + + /** + * A sugar method, equivalent to promise.then(function () { return value; }). + */ + thenResolve(value: U): Promise; + /** + * A sugar method, equivalent to promise.then(function () { throw reason; }). + */ + thenReject(reason: any): Promise; + + /** + * Attaches a handler that will observe the value of the promise when it becomes fulfilled, returning a promise for that same value, perhaps deferred but not replaced by the promise returned by the onFulfilled handler. + */ + tap(onFulfilled: (value: T) => any): Promise; + + timeout(ms: number, message?: string): Promise; + /** + * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. + */ + delay(ms: number): Promise; + + /** + * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. + */ + isFulfilled(): boolean; + /** + * Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false. + */ + isRejected(): boolean; + /** + * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. + */ + isPending(): boolean; + + valueOf(): any; + + /** + * Returns a "state snapshot" object, which will be in one of three forms: + * + * - { state: "pending" } + * - { state: "fulfilled", value: } + * - { state: "rejected", reason: } + */ + inspect(): PromiseState; + } + + interface PromiseState { + /** + * "fulfilled", "rejected", "pending" + */ + state: string; + value?: T; + reason?: any; + } + + // If no value provided, returned promise will be of void type + export function when(): Promise; + + // if no fulfill, reject, or progress provided, returned promise will be of same type + export function when(value: T | IPromise): Promise; + + // If a non-promise value is provided, it will not reject or progress + export function when(value: T | IPromise, onFulfilled: (val: T) => U | IPromise, onRejected?: (reason: any) => U | IPromise, onProgress?: (progress: any) => any): Promise; + + /** + * Currently "impossible" (and I use the term loosely) to implement due to TypeScript limitations as it is now. + * See: https://github.com/Microsoft/TypeScript/issues/1784 for discussion on it. + */ + // export function try(method: Function, ...args: any[]): Promise; + + export function fbind(method: (...args: any[]) => T | IPromise, ...args: any[]): (...args: any[]) => Promise; + + export function fcall(method: (...args: any[]) => T, ...args: any[]): Promise; + + export function send(obj: any, functionName: string, ...args: any[]): Promise; + export function invoke(obj: any, functionName: string, ...args: any[]): Promise; + export function mcall(obj: any, functionName: string, ...args: any[]): Promise; + + export function denodeify(nodeFunction: Function, ...args: any[]): (...args: any[]) => Promise; + export function nbind(nodeFunction: Function, thisArg: any, ...args: any[]): (...args: any[]) => Promise; + export function nfbind(nodeFunction: Function, ...args: any[]): (...args: any[]) => Promise; + export function nfcall(nodeFunction: Function, ...args: any[]): Promise; + export function nfapply(nodeFunction: Function, args: any[]): Promise; + + export function ninvoke(nodeModule: any, functionName: string, ...args: any[]): Promise; + export function npost(nodeModule: any, functionName: string, args: any[]): Promise; + export function nsend(nodeModule: any, functionName: string, ...args: any[]): Promise; + export function nmcall(nodeModule: any, functionName: string, ...args: any[]): Promise; + + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IPromise[]): Promise; + + /** + * Returns a promise for the first of an array of promises to become settled. + */ + export function race(promises: IPromise[]): Promise; + + /** + * Returns a promise that is fulfilled with an array of promise state snapshots, but only after all the original promises have settled, i.e. become either fulfilled or rejected. + */ + export function allSettled(promises: IPromise[]): Promise[]>; + + export function allResolved(promises: IPromise[]): Promise[]>; + + /** + * Like then, but "spreads" the array into a variadic fulfillment handler. If any of the promises in the array are rejected, instead calls onRejected with the first rejected promise's rejection reason. + * This is especially useful in conjunction with all. + */ + export function spread(promises: IPromise[], onFulfilled: (...args: T[]) => U | IPromise, onRejected?: (reason: any) => U | IPromise): Promise; + + /** + * Returns a promise that will have the same result as promise, except that if promise is not fulfilled or rejected before ms milliseconds, the returned promise will be rejected with an Error with the given message. If message is not supplied, the message will be "Timed out after " + ms + " ms". + */ + export function timeout(promise: Promise, ms: number, message?: string): Promise; + + /** + * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. + */ + export function delay(promise: Promise, ms: number): Promise; + /** + * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. + */ + export function delay(value: T, ms: number): Promise; + /** + * Returns a promise that will be fulfilled with undefined after at least ms milliseconds have passed. + */ + export function delay(ms: number): Promise ; + /** + * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. + */ + export function isFulfilled(promise: Promise): boolean; + /** + * Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false. + */ + export function isRejected(promise: Promise): boolean; + /** + * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. + */ + export function isPending(promise: Promise): boolean; + + /** + * Returns a "deferred" object with a: + * promise property + * resolve(value) method + * reject(reason) method + * notify(value) method + * makeNodeResolver() method + */ + export function defer(): Deferred; + + /** + * Returns a promise that is rejected with reason. + */ + export function reject(reason?: any): Promise; + + export function Promise(resolver: (resolve: (val: T | IPromise) => void , reject: (reason: any) => void , notify: (progress: any) => void ) => void ): Promise; + + /** + * Creates a new version of func that accepts any combination of promise and non-promise values, converting them to their fulfillment values before calling the original func. The returned version also always returns a promise: if func does a return or throw, then Q.promised(func) will return fulfilled or rejected promise, respectively. + * + * This can be useful for creating functions that accept either promises or non-promise values, and for ensuring that the function always returns a promise even in the face of unintentional thrown exceptions. + */ + export function promised(callback: (...args: any[]) => T): (...args: any[]) => Promise; + + /** + * Returns whether the given value is a Q promise. + */ + export function isPromise(object: any): boolean; + /** + * Returns whether the given value is a promise (i.e. it's an object with a then function). + */ + export function isPromiseAlike(object: any): boolean; + /** + * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. + */ + export function isPending(object: any): boolean; + /** + * If an object is not a promise, it is as "near" as possible. + * If a promise is rejected, it is as "near" as possible too. + * If it’s a fulfilled promise, the fulfillment value is nearer. + * If it’s a deferred promise and the deferred has been resolved, the + * resolution is "nearer". + */ + export function nearer(promise: Promise): T; + + /** + * This is an experimental tool for converting a generator function into a deferred function. This has the potential of reducing nested callbacks in engines that support yield. + */ + export function async(generatorFunction: any): (...args: any[]) => Promise; + export function nextTick(callback: Function): void; + + /** + * A settable property that will intercept any uncaught errors that would otherwise be thrown in the next tick of the event loop, usually as a result of done. Can be useful for getting the full stack trace of an error in browsers, which is not usually possible with window.onerror. + */ + export var onerror: (reason: any) => void; + /** + * A settable property that lets you turn on long stack trace support. If turned on, "stack jumps" will be tracked across asynchronous promise operations, so that if an uncaught error is thrown by done or a rejection reason's stack property is inspected in a rejection callback, a long stack trace is produced. + */ + export var longStackSupport: boolean; + + /** + * Calling resolve with a pending promise causes promise to wait on the passed promise, becoming fulfilled with its fulfillment value or rejected with its rejection reason (or staying pending forever, if the passed promise does). + * Calling resolve with a rejected promise causes promise to be rejected with the passed promise's rejection reason. + * Calling resolve with a fulfilled promise causes promise to be fulfilled with the passed promise's fulfillment value. + * Calling resolve with a non-promise value causes promise to be fulfilled with that value. + */ + export function resolve(object: IPromise): Promise; + /** + * Calling resolve with a pending promise causes promise to wait on the passed promise, becoming fulfilled with its fulfillment value or rejected with its rejection reason (or staying pending forever, if the passed promise does). + * Calling resolve with a rejected promise causes promise to be rejected with the passed promise's rejection reason. + * Calling resolve with a fulfilled promise causes promise to be fulfilled with the passed promise's fulfillment value. + * Calling resolve with a non-promise value causes promise to be fulfilled with that value. + */ + export function resolve(object: T): Promise; + + /** + * Resets the global "Q" variable to the value it has before Q was loaded. + * This will either be undefined if there was no version or the version of Q which was already loaded before. + * @returns { The last version of Q. } + */ + export function noConflict(): typeof Q; +} diff --git a/q/tsconfig.json b/q/tsconfig.json new file mode 100644 index 0000000000..8abd56d69b --- /dev/null +++ b/q/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "q-tests.ts" + ] +} \ No newline at end of file diff --git a/qajax/index.d.ts b/qajax/index.d.ts new file mode 100644 index 0000000000..31fa32d1f0 --- /dev/null +++ b/qajax/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for Qajax +// Project: https://github.com/gre/qajax +// Definitions by: Boltmade +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +export = Qajax; +export as namespace Qajax; + +declare function Qajax(url : string) : Q.Promise; +declare function Qajax(options : any) : Q.Promise; +declare function Qajax(url : string, options : any) : Q.Promise; + +declare namespace Qajax { + export var defaults : any; + export function filterStatus(validStatus : number) : (xhr : XMLHttpRequest) => Q.Promise; + export function filterStatus(validStatus : (status : number) => boolean) : (xhr : XMLHttpRequest) => Q.Promise; + export function filterSuccess() : Q.Promise; + + export function toJSON(xhr : XMLHttpRequest) : Q.Promise; + + export function getJSON(url : string) : Q.Promise; + + export function serialize(paramsObj : any) : string; +} \ No newline at end of file diff --git a/qajax/qajax-tests.ts b/qajax/qajax-tests.ts index 820dce4554..0307bf4d0c 100644 --- a/qajax/qajax-tests.ts +++ b/qajax/qajax-tests.ts @@ -1,4 +1,4 @@ -/// +import Qajax = require("qajax"); // Based on https://github.com/gre/qajax/blob/master/test/qajax.js diff --git a/qajax/qajax.d.ts b/qajax/qajax.d.ts deleted file mode 100644 index 7b7f9678d9..0000000000 --- a/qajax/qajax.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Type definitions for Qajax -// Project: https://github.com/gre/qajax -// Definitions by: Boltmade -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare function Qajax(url : string) : Q.Promise; -declare function Qajax(options : any) : Q.Promise; -declare function Qajax(url : string, options : any) : Q.Promise; - -declare namespace Qajax { - export var defaults : any; - export function filterStatus(validStatus : number) : (xhr : XMLHttpRequest) => Q.Promise; - export function filterStatus(validStatus : (status : number) => boolean) : (xhr : XMLHttpRequest) => Q.Promise; - export function filterSuccess() : Q.Promise; - - export function toJSON(xhr : XMLHttpRequest) : Q.Promise; - - export function getJSON(url : string) : Q.Promise; - - export function serialize(paramsObj : any) : string; -} - -declare module "qajax" { - export = Qajax; -} diff --git a/qajax/tsconfig.json b/qajax/tsconfig.json new file mode 100644 index 0000000000..6715c8a836 --- /dev/null +++ b/qajax/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "qajax-tests.ts" + ] +} \ No newline at end of file diff --git a/qrcode-generator/index.d.ts b/qrcode-generator/index.d.ts new file mode 100644 index 0000000000..f4517b56d4 --- /dev/null +++ b/qrcode-generator/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for grcode-generator +// Project: https://github.com/kazuhikoarase/qrcode-generator +// Definitions by: Stefan Huber +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function qrcode(type: number, errorCorrectionLevel: string) : QRCode; +export = qrcode; +export as namespace qrcode; + +interface QRCode { + addData(data: string) : void; + make() : void; + + createTableTag(cellSize: number, margin: number) : string; + createSvgTag(cellSize: number, margin: number) : string; + createImageTag(cellSize: number, margin: number) : string; +} diff --git a/qrcode-generator/qrcode-generator-tests.ts b/qrcode-generator/qrcode-generator-tests.ts new file mode 100644 index 0000000000..55a3fe372b --- /dev/null +++ b/qrcode-generator/qrcode-generator-tests.ts @@ -0,0 +1,10 @@ +import qrcode = require('qrcode-generator'); + +let qr = qrcode(4,'M'); + +qr.addData('some arbitrary data'); +qr.make(); + +let imgHtml = qr.createImageTag(5,5); +let svgHtml = qr.createSvgTag(5,5); +let tableHtml = qr.createTableTag(5,5); \ No newline at end of file diff --git a/qrcode-generator/tsconfig.json b/qrcode-generator/tsconfig.json new file mode 100644 index 0000000000..7df378fe8c --- /dev/null +++ b/qrcode-generator/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "qrcode-generator-tests.ts" + ] +} \ No newline at end of file diff --git a/qs/index.d.ts b/qs/index.d.ts new file mode 100644 index 0000000000..41c7b0da6a --- /dev/null +++ b/qs/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for qs +// Project: https://github.com/hapijs/qs +// Definitions by: Roman Korneev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = QueryString; +export as namespace qs; + +declare namespace QueryString { + interface IStringifyOptions { + delimiter?: string; + strictNullHandling?: boolean; + skipNulls?: boolean; + encode?: boolean; + filter?: any; + arrayFormat?: any; + indices?: string; + } + + interface IParseOptions { + delimiter?: string; + depth?: number; + arrayLimit?: number; + parseArrays?: boolean; + allowDots?: boolean; + plainObjects?: boolean; + allowPrototypes?: boolean; + parameterLimit?: number; + strictNullHandling?: boolean; + } + + function stringify(obj: any, options?: IStringifyOptions): string; + function parse(str: string, options?: IParseOptions): any; +} diff --git a/qs/qs-tests.ts b/qs/qs-tests.ts index 04be4f266b..aef2ecd2db 100644 --- a/qs/qs-tests.ts +++ b/qs/qs-tests.ts @@ -1,4 +1,4 @@ -/// + import qs = require('qs'); diff --git a/qs/qs.d.ts b/qs/qs.d.ts deleted file mode 100644 index af18fcdb4d..0000000000 --- a/qs/qs.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Type definitions for qs -// Project: https://github.com/hapijs/qs -// Definitions by: Roman Korneev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace QueryString { - interface IStringifyOptions { - delimiter?: string; - strictNullHandling?: boolean; - skipNulls?: boolean; - encode?: boolean; - filter?: any; - arrayFormat?: any; - indices?: string; - } - - interface IParseOptions { - delimiter?: string; - depth?: number; - arrayLimit?: number; - parseArrays?: boolean; - allowDots?: boolean; - plainObjects?: boolean; - allowPrototypes?: boolean; - parameterLimit?: number; - strictNullHandling?: boolean; - } - - function stringify(obj: any, options?: IStringifyOptions): string; - function parse(str: string, options?: IParseOptions): any; -} - -declare module "qs" { - export = QueryString; -} diff --git a/qs/tsconfig.json b/qs/tsconfig.json new file mode 100644 index 0000000000..72c76a45f4 --- /dev/null +++ b/qs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "qs-tests.ts" + ] +} \ No newline at end of file diff --git a/qtip2/index.d.ts b/qtip2/index.d.ts new file mode 100644 index 0000000000..40e6cd0bf6 --- /dev/null +++ b/qtip2/index.d.ts @@ -0,0 +1,409 @@ +// Type definitions for qtip2 v2.2.1 +// Project: http://qtip2.com/ +// Definitions by: Nathan Pitman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Notes: +// - Type bindings for the QTip2 API and options are included. Bindings for global settings aren't required. +// - Deprecated functionality is not supported. +// - Where possible, things are strongly typed and 'any' is avoided. +// - QTip2 includes a lot of shorthand notation for various expressions. These bindings support it all. + +/// + +declare namespace QTip2 { + type EventApiFunc = (event: Event, api: Api) => void; + + + /** + * Content property + */ + type Title = string | JQuery | EventApiFunc | boolean | JQueryGenericPromise; + type Text = string | JQuery | EventApiFunc | boolean | JQueryGenericPromise; + + interface Content { + title?: Title | { text: Title }; + text?: Text; + attr?: string; + button?: string | JQuery | boolean; + } + + + /** + * Position property + */ + interface PositionAdjust { + x?: number; + y?: number; + mouse?: boolean; + resize?: boolean; + scroll?: boolean; + method?: string; + } + + type Target = JQuery | number[] | string; + + interface Position { + my?: string | boolean; + at?: string | boolean; + target?: Target | boolean; + container?: JQuery | boolean; + viewport?: JQuery | boolean; + effect?: boolean | ((api: Api, pos: any, viewport: any) => void); + adjust?: PositionAdjust; + } + + + /** + * Show property + */ + interface Show { + target?: JQuery | boolean; + event?: string | boolean; + delay?: number; + solo?: JQuery | string | boolean; + ready?: boolean; + effect?: boolean | ((offset: any) => void); + modal?: boolean | Modal; + } + + interface Modal + { + on?: boolean; + blur?: boolean; + escape?: boolean; + stealfocus?: boolean; + effect?: boolean | ((state: any) => void); + } + + + /** + * Hide property + */ + interface Hide { + target?: JQuery | boolean; + event?: string | boolean; + delay?: number; + inactive?: number | boolean; + fixed?: boolean; + leave?: string | boolean; + distance?: number | boolean; + effect?: boolean | ((offset: any) => void); + } + + + /** + * Style property + */ + interface Style { + classes?: string | boolean; + def?: boolean; + widget?: boolean; + width?: string | number | boolean; + height?: string | number | boolean; + tip?: string | boolean | Tip; + } + + interface Tip { + corner?: string | boolean; + mimic?: string | boolean; + border?: number | boolean; + width?: number; + height?: number; + offset?: number; + } + + + /** + * Events property + */ + interface Events { + render?: EventApiFunc; + show?: EventApiFunc; + hide?: EventApiFunc; + toggle?: EventApiFunc; + visible?: EventApiFunc; + hidden?: EventApiFunc; + move?: EventApiFunc; + focus?: EventApiFunc; + blur?: EventApiFunc; + } + + + /** + * Options + */ + interface QTipOptions { + id?: string | boolean; + prerender?: boolean; + overwrite?: boolean; + suppress?: boolean; + metadata?: any; + content?: Text | Content; + position?: string | Position; + style?: string | Style; + show?: string | boolean | JQuery | Show; + hide?: string | JQuery | Hide; + events?: Events; + } + + + /** + * API + */ + interface Api { + get(propertyName: 'id'): string | boolean; + get(propertyName: 'prerender'): boolean; + get(propertyName: 'overwrite'): boolean; + get(propertyName: 'suppress'): boolean; + get(propertyName: 'metadata'): any; + get(propertyName: 'content'): Content; + get(propertyName: 'content.text'): Text; + get(propertyName: 'content.attr'): string; + get(propertyName: 'content.title'): Title; + get(propertyName: 'content.button'): string | JQuery | boolean; + get(propertyName: 'position'): Position; + get(propertyName: 'position.my'): string | boolean; + get(propertyName: 'position.at'): string | boolean; + get(propertyName: 'position.target'): Target | boolean; + get(propertyName: 'position.container'): JQuery | boolean; + get(propertyName: 'position.viewport'): JQuery | boolean; + get(propertyName: 'position.effect'): boolean | ((api: any, pos: any, viewport: any) => void); + get(propertyName: 'position.adjust'): PositionAdjust; + get(propertyName: 'show'): Show; + get(propertyName: 'show.target'): JQuery | boolean; + get(propertyName: 'show.event'): string | boolean; + get(propertyName: 'show.delay'): number; + get(propertyName: 'show.solo'): JQuery | string | boolean; + get(propertyName: 'show.ready'): boolean; + get(propertyName: 'show.effect'): boolean | ((offset: any) => void); + get(propertyName: 'show.modal'): boolean | Modal; + get(propertyName: 'hide'): Hide; + get(propertyName: 'hide.target'): JQuery | boolean; + get(propertyName: 'hide.event'): string | boolean; + get(propertyName: 'hide.delay'): number; + get(propertyName: 'hide.leave'): string | boolean; + get(propertyName: 'hide.distance'): number | boolean; + get(propertyName: 'hide.effect'): boolean | ((offset: any) => void); + get(propertyName: 'style'): Style; + get(propertyName: 'style.classes'): string | boolean; + get(propertyName: 'style.def'): boolean; + get(propertyName: 'style.widget'): boolean; + get(propertyName: 'style.width'): string | number | boolean; + get(propertyName: 'style.height'): string | number | boolean; + get(propertyName: 'style.tip'): string | boolean | Tip; + get(propertyName: 'events'): Events; + get(propertyName: 'events.render'): EventApiFunc; + get(propertyName: 'events.show'): EventApiFunc; + get(propertyName: 'events.hide'): EventApiFunc; + get(propertyName: 'events.toggle'): EventApiFunc; + get(propertyName: 'events.visible'): EventApiFunc; + get(propertyName: 'events.hidden'): EventApiFunc; + get(propertyName: 'events.move'): EventApiFunc; + get(propertyName: 'events.focus'): EventApiFunc; + get(propertyName: 'events.blur'): EventApiFunc; + get(propertyName: string): any; + + set(properties: QTipOptions): Api; + set(propertyName: 'id', value: string | boolean): Api; + set(propertyName: 'prerender', value: boolean): Api; + set(propertyName: 'overwrite', value: boolean): Api; + set(propertyName: 'suppress', value: boolean): Api; + set(propertyName: 'metadata', value: any): Api; + set(propertyName: 'content', value: Text | Content): Api; + set(propertyName: 'content.title', value: Title | { text: Title }): Api; + set(propertyName: 'content.text', value: Text): Api; + set(propertyName: 'content.attr', value: string): Api; + set(propertyName: 'content.button', value: string | JQuery | boolean): Api; + set(propertyName: 'position', value: Position): Api; + set(propertyName: 'position.my', value: string | boolean): Api; + set(propertyName: 'position.at', value: string | boolean): Api; + set(propertyName: 'position.target', value: Target | boolean): Api; + set(propertyName: 'position.container', value: JQuery | boolean): Api; + set(propertyName: 'position.viewport', value: JQuery | boolean): Api; + set(propertyName: 'position.effect', value: boolean | ((api: Api, pos: any, viewport: any) => void) ): Api; + set(propertyName: 'position.adjust', value: PositionAdjust): Api; + set(propertyName: 'show', value: Show): Api; + set(propertyName: 'show.target', value: JQuery | boolean): Api; + set(propertyName: 'show.event', value: string | boolean): Api; + set(propertyName: 'show.delay', value: number): Api; + set(propertyName: 'show.solo', value: JQuery | string | boolean): Api; + set(propertyName: 'show.ready', value: boolean): Api; + set(propertyName: 'show.effect', value: boolean | ((offset: any) => void)): Api; + set(propertyName: 'show.modal', value: boolean | Modal): Api; + set(propertyName: 'hide', value: Hide): Api; + set(propertyName: 'hide.target', value: JQuery | boolean): Api; + set(propertyName: 'hide.event', value: string | boolean): Api; + set(propertyName: 'hide.inactive', value: number | boolean): Api; + set(propertyName: 'hide.fixed', value: boolean): Api; + set(propertyName: 'hide.leave', value: string | boolean): Api; + set(propertyName: 'hide.distance', value: number | boolean): Api; + set(propertyName: 'hide.effect', value: boolean | ((offset: any) => void)): Api + set(propertyName: 'style', value: Style): Api; + set(propertyName: 'style.classes', value: string | boolean): Api; + set(propertyName: 'style.def', value: boolean): Api; + set(propertyName: 'style.widget', value: boolean): Api; + set(propertyName: 'style.width', value: string | number | boolean): Api; + set(propertyName: 'style.height', value: string | number | boolean): Api; + set(propertyName: 'style.tip', value: string | boolean | Tip): Api; + set(propertyName: 'events', value: Events): Api; + set(propertyName: 'events.render', value: EventApiFunc): Api; + set(propertyName: 'events.show', value: EventApiFunc): Api; + set(propertyName: 'events.hide', value: EventApiFunc): Api; + set(propertyName: 'events.toggle', value: EventApiFunc): Api; + set(propertyName: 'events.visible', value: EventApiFunc): Api; + set(propertyName: 'events.hidden', value: EventApiFunc): Api; + set(propertyName: 'events.move', value: EventApiFunc): Api; + set(propertyName: 'events.focus', value: EventApiFunc): Api; + set(propertyName: 'events.blur', value: EventApiFunc): Api; + set(propertyName: string, value: any): Api; + + toggle(state?: boolean, event?: Event): Api; + + show(event?: Event): Api; + + hide(event?: Event): Api; + + disable(state?: boolean): Api; + + enable(): Api; + + reposition(event?: Event, effect?: boolean): Api; + + focus(event?: Event): Api; + + blur(event?: Event): Api; + + destroy(immediate?: boolean): Api; + } +} + + +interface JQuery { + qtip(options?: QTip2.QTipOptions): JQuery; + + qtip(methodName: 'api'): QTip2.Api; + + qtip(methodName: 'option', propertyName: 'id'): string | boolean; + qtip(methodName: 'option', propertyName: 'prerender'): boolean; + qtip(methodName: 'option', propertyName: 'overwrite'): boolean; + qtip(methodName: 'option', propertyName: 'suppress'): boolean; + qtip(methodName: 'option', propertyName: 'metadata'): any; + qtip(methodName: 'option', propertyName: 'content'): QTip2.Content; + qtip(methodName: 'option', propertyName: 'content.text'): QTip2.Text; + qtip(methodName: 'option', propertyName: 'content.attr'): string; + qtip(methodName: 'option', propertyName: 'content.title'): QTip2.Title; + qtip(methodName: 'option', propertyName: 'content.button'): string | JQuery | boolean; + qtip(methodName: 'option', propertyName: 'position'): QTip2.Position; + qtip(methodName: 'option', propertyName: 'position.my'): string | boolean; + qtip(methodName: 'option', propertyName: 'position.at'): string | boolean; + qtip(methodName: 'option', propertyName: 'position.target'): QTip2.Target | boolean; + qtip(methodName: 'option', propertyName: 'position.container'): JQuery | boolean; + qtip(methodName: 'option', propertyName: 'position.viewport'): JQuery | boolean; + qtip(methodName: 'option', propertyName: 'position.effect'): boolean | ((api: QTip2.Api, pos: any, viewport: any) => void); + qtip(methodName: 'option', propertyName: 'position.adjust'): QTip2.PositionAdjust; + qtip(methodName: 'option', propertyName: 'show'): QTip2.Show; + qtip(methodName: 'option', propertyName: 'show.target'): JQuery | boolean; + qtip(methodName: 'option', propertyName: 'show.event'): string | boolean; + qtip(methodName: 'option', propertyName: 'show.delay'): number; + qtip(methodName: 'option', propertyName: 'show.solo'): JQuery | string | boolean; + qtip(methodName: 'option', propertyName: 'show.ready'): boolean; + qtip(methodName: 'option', propertyName: 'show.effect'): boolean | ((offset: any) => void); + qtip(methodName: 'option', propertyName: 'show.modal'): boolean | QTip2.Modal; + qtip(methodName: 'option', propertyName: 'hide'): QTip2.Hide; + qtip(methodName: 'option', propertyName: 'hide.target'): JQuery | boolean; + qtip(methodName: 'option', propertyName: 'hide.event'): string | boolean; + qtip(methodName: 'option', propertyName: 'hide.delay'): number; + qtip(methodName: 'option', propertyName: 'hide.leave'): string | boolean; + qtip(methodName: 'option', propertyName: 'hide.distance'): number | boolean; + qtip(methodName: 'option', propertyName: 'hide.effect'): boolean | ((offset: any) => void); + qtip(methodName: 'option', propertyName: 'style'): QTip2.Style; + qtip(methodName: 'option', propertyName: 'style.classes'): string | boolean; + qtip(methodName: 'option', propertyName: 'style.def'): boolean; + qtip(methodName: 'option', propertyName: 'style.widget'): boolean; + qtip(methodName: 'option', propertyName: 'style.width'): string | number | boolean; + qtip(methodName: 'option', propertyName: 'style.height'): string | number | boolean; + qtip(methodName: 'option', propertyName: 'style.tip'): string | boolean | QTip2.Tip; + qtip(methodName: 'option', propertyName: 'events'): QTip2.Events; + qtip(methodName: 'option', propertyName: 'events.render'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.show'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.hide'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.toggle'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.visible'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.hidden'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.move'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.focus'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.blur'): QTip2.EventApiFunc; + + qtip(methodName: 'option', properties: QTip2.QTipOptions): QTip2.Api; + qtip(methodName: 'option', propertyName: 'id', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'prerender', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'overwrite', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'suppress', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'metadata', value: any): QTip2.Api; + qtip(methodName: 'option', propertyName: 'content', value: QTip2.Text | QTip2.Content): QTip2.Api; + qtip(methodName: 'option', propertyName: 'content.title', value: QTip2.Title | { text: QTip2.Title }): QTip2.Api; + qtip(methodName: 'option', propertyName: 'content.text', value: QTip2.Text): QTip2.Api; + qtip(methodName: 'option', propertyName: 'content.attr', value: string): QTip2.Api; + qtip(methodName: 'option', propertyName: 'content.button', value: string | JQuery | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position', value: QTip2.Position): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.my', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.at', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.target', value: QTip2.Target | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.container', value: JQuery | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.viewport', value: JQuery | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.effect', value: boolean | ((api: QTip2.Api, pos: any, viewport: any) => void) ): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.adjust', value: QTip2.PositionAdjust): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show', value: QTip2.Show): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.target', value: JQuery | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.event', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.delay', value: number): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.solo', value: JQuery | string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.ready', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.effect', value: boolean | ((offset: any) => void)): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.modal', value: boolean | QTip2.Modal): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide', value: QTip2.Hide): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.target', value: JQuery | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.event', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.inactive', value: number | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.fixed', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.leave', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.distance', value: number | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.effect', value: boolean | ((offset: any) => void)): QTip2.Api + qtip(methodName: 'option', propertyName: 'style', value: QTip2.Style): QTip2.Api; + qtip(methodName: 'option', propertyName: 'style.classes', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'style.def', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'style.widget', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'style.width', value: string | number | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'style.height', value: string | number | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'style.tip', value: string | boolean | QTip2.Tip): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events', value: QTip2.Events): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.render', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.show', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.hide', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.toggle', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.visible', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.hidden', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.move', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.focus', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.blur', value: QTip2.EventApiFunc): QTip2.Api; + + qtip(methodName: 'toggle', state?: boolean, event?: Event): JQuery; + + qtip(methodName: 'show', event?: Event): JQuery; + + qtip(methodName: 'hide', event?: Event): JQuery; + + qtip(methodName: 'disable', state?: boolean): JQuery; + + qtip(methodName: 'enable'): JQuery + + qtip(methodName: 'reposition', event?: Event, effect?: boolean): JQuery; + + qtip(methodName: 'focus', event?: Event): JQuery; + + qtip(methodName: 'blur', event?: Event): JQuery; + + qtip(methodName: 'destroy', immediate?: boolean): JQuery; + + qtip(methodName: string, p1?: any, p2?: any, p3?: any): any; +} diff --git a/qtip2/qtip2-tests.ts b/qtip2/qtip2-tests.ts index 9b0f9abcb2..9bea1e3b0c 100644 --- a/qtip2/qtip2-tests.ts +++ b/qtip2/qtip2-tests.ts @@ -1,4 +1,4 @@ -/// + var $a = $('_'); diff --git a/qtip2/qtip2.d.ts b/qtip2/qtip2.d.ts deleted file mode 100644 index f75ac72c21..0000000000 --- a/qtip2/qtip2.d.ts +++ /dev/null @@ -1,409 +0,0 @@ -// Type definitions for qtip2 v2.2.1 -// Project: http://qtip2.com/ -// Definitions by: Nathan Pitman -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Notes: -// - Type bindings for the QTip2 API and options are included. Bindings for global settings aren't required. -// - Deprecated functionality is not supported. -// - Where possible, things are strongly typed and 'any' is avoided. -// - QTip2 includes a lot of shorthand notation for various expressions. These bindings support it all. - -/// - -declare namespace QTip2 { - type EventApiFunc = (event: Event, api: Api) => void; - - - /** - * Content property - */ - type Title = string | JQuery | EventApiFunc | boolean | JQueryGenericPromise; - type Text = string | JQuery | EventApiFunc | boolean | JQueryGenericPromise; - - interface Content { - title?: Title | { text: Title }; - text?: Text; - attr?: string; - button?: string | JQuery | boolean; - } - - - /** - * Position property - */ - interface PositionAdjust { - x?: number; - y?: number; - mouse?: boolean; - resize?: boolean; - scroll?: boolean; - method?: string; - } - - type Target = JQuery | number[] | string; - - interface Position { - my?: string | boolean; - at?: string | boolean; - target?: Target | boolean; - container?: JQuery | boolean; - viewport?: JQuery | boolean; - effect?: boolean | ((api: Api, pos: any, viewport: any) => void); - adjust?: PositionAdjust; - } - - - /** - * Show property - */ - interface Show { - target?: JQuery | boolean; - event?: string | boolean; - delay?: number; - solo?: JQuery | string | boolean; - ready?: boolean; - effect?: boolean | ((offset: any) => void); - modal?: boolean | Modal; - } - - interface Modal - { - on?: boolean; - blur?: boolean; - escape?: boolean; - stealfocus?: boolean; - effect?: boolean | ((state: any) => void); - } - - - /** - * Hide property - */ - interface Hide { - target?: JQuery | boolean; - event?: string | boolean; - delay?: number; - inactive?: number | boolean; - fixed?: boolean; - leave?: string | boolean; - distance?: number | boolean; - effect?: boolean | ((offset: any) => void); - } - - - /** - * Style property - */ - interface Style { - classes?: string | boolean; - def?: boolean; - widget?: boolean; - width?: string | number | boolean; - height?: string | number | boolean; - tip?: string | boolean | Tip; - } - - interface Tip { - corner?: string | boolean; - mimic?: string | boolean; - border?: number | boolean; - width?: number; - height?: number; - offset?: number; - } - - - /** - * Events property - */ - interface Events { - render?: EventApiFunc; - show?: EventApiFunc; - hide?: EventApiFunc; - toggle?: EventApiFunc; - visible?: EventApiFunc; - hidden?: EventApiFunc; - move?: EventApiFunc; - focus?: EventApiFunc; - blur?: EventApiFunc; - } - - - /** - * Options - */ - interface QTipOptions { - id?: string | boolean; - prerender?: boolean; - overwrite?: boolean; - suppress?: boolean; - metadata?: any; - content?: Text | Content; - position?: string | Position; - style?: string | Style; - show?: string | boolean | JQuery | Show; - hide?: string | JQuery | Hide; - events?: Events; - } - - - /** - * API - */ - interface Api { - get(propertyName: 'id'): string | boolean; - get(propertyName: 'prerender'): boolean; - get(propertyName: 'overwrite'): boolean; - get(propertyName: 'suppress'): boolean; - get(propertyName: 'metadata'): any; - get(propertyName: 'content'): Content; - get(propertyName: 'content.text'): Text; - get(propertyName: 'content.attr'): string; - get(propertyName: 'content.title'): Title; - get(propertyName: 'content.button'): string | JQuery | boolean; - get(propertyName: 'position'): Position; - get(propertyName: 'position.my'): string | boolean; - get(propertyName: 'position.at'): string | boolean; - get(propertyName: 'position.target'): Target | boolean; - get(propertyName: 'position.container'): JQuery | boolean; - get(propertyName: 'position.viewport'): JQuery | boolean; - get(propertyName: 'position.effect'): boolean | ((api: any, pos: any, viewport: any) => void); - get(propertyName: 'position.adjust'): PositionAdjust; - get(propertyName: 'show'): Show; - get(propertyName: 'show.target'): JQuery | boolean; - get(propertyName: 'show.event'): string | boolean; - get(propertyName: 'show.delay'): number; - get(propertyName: 'show.solo'): JQuery | string | boolean; - get(propertyName: 'show.ready'): boolean; - get(propertyName: 'show.effect'): boolean | ((offset: any) => void); - get(propertyName: 'show.modal'): boolean | Modal; - get(propertyName: 'hide'): Hide; - get(propertyName: 'hide.target'): JQuery | boolean; - get(propertyName: 'hide.event'): string | boolean; - get(propertyName: 'hide.delay'): number; - get(propertyName: 'hide.leave'): string | boolean; - get(propertyName: 'hide.distance'): number | boolean; - get(propertyName: 'hide.effect'): boolean | ((offset: any) => void); - get(propertyName: 'style'): Style; - get(propertyName: 'style.classes'): string | boolean; - get(propertyName: 'style.def'): boolean; - get(propertyName: 'style.widget'): boolean; - get(propertyName: 'style.width'): string | number | boolean; - get(propertyName: 'style.height'): string | number | boolean; - get(propertyName: 'style.tip'): string | boolean | Tip; - get(propertyName: 'events'): Events; - get(propertyName: 'events.render'): EventApiFunc; - get(propertyName: 'events.show'): EventApiFunc; - get(propertyName: 'events.hide'): EventApiFunc; - get(propertyName: 'events.toggle'): EventApiFunc; - get(propertyName: 'events.visible'): EventApiFunc; - get(propertyName: 'events.hidden'): EventApiFunc; - get(propertyName: 'events.move'): EventApiFunc; - get(propertyName: 'events.focus'): EventApiFunc; - get(propertyName: 'events.blur'): EventApiFunc; - get(propertyName: string): any; - - set(properties: QTipOptions): Api; - set(propertyName: 'id', value: string | boolean): Api; - set(propertyName: 'prerender', value: boolean): Api; - set(propertyName: 'overwrite', value: boolean): Api; - set(propertyName: 'suppress', value: boolean): Api; - set(propertyName: 'metadata', value: any): Api; - set(propertyName: 'content', value: Text | Content): Api; - set(propertyName: 'content.title', value: Title | { text: Title }): Api; - set(propertyName: 'content.text', value: Text): Api; - set(propertyName: 'content.attr', value: string): Api; - set(propertyName: 'content.button', value: string | JQuery | boolean): Api; - set(propertyName: 'position', value: Position): Api; - set(propertyName: 'position.my', value: string | boolean): Api; - set(propertyName: 'position.at', value: string | boolean): Api; - set(propertyName: 'position.target', value: Target | boolean): Api; - set(propertyName: 'position.container', value: JQuery | boolean): Api; - set(propertyName: 'position.viewport', value: JQuery | boolean): Api; - set(propertyName: 'position.effect', value: boolean | ((api: Api, pos: any, viewport: any) => void) ): Api; - set(propertyName: 'position.adjust', value: PositionAdjust): Api; - set(propertyName: 'show', value: Show): Api; - set(propertyName: 'show.target', value: JQuery | boolean): Api; - set(propertyName: 'show.event', value: string | boolean): Api; - set(propertyName: 'show.delay', value: number): Api; - set(propertyName: 'show.solo', value: JQuery | string | boolean): Api; - set(propertyName: 'show.ready', value: boolean): Api; - set(propertyName: 'show.effect', value: boolean | ((offset: any) => void)): Api; - set(propertyName: 'show.modal', value: boolean | Modal): Api; - set(propertyName: 'hide', value: Hide): Api; - set(propertyName: 'hide.target', value: JQuery | boolean): Api; - set(propertyName: 'hide.event', value: string | boolean): Api; - set(propertyName: 'hide.inactive', value: number | boolean): Api; - set(propertyName: 'hide.fixed', value: boolean): Api; - set(propertyName: 'hide.leave', value: string | boolean): Api; - set(propertyName: 'hide.distance', value: number | boolean): Api; - set(propertyName: 'hide.effect', value: boolean | ((offset: any) => void)): Api - set(propertyName: 'style', value: Style): Api; - set(propertyName: 'style.classes', value: string | boolean): Api; - set(propertyName: 'style.def', value: boolean): Api; - set(propertyName: 'style.widget', value: boolean): Api; - set(propertyName: 'style.width', value: string | number | boolean): Api; - set(propertyName: 'style.height', value: string | number | boolean): Api; - set(propertyName: 'style.tip', value: string | boolean | Tip): Api; - set(propertyName: 'events', value: Events): Api; - set(propertyName: 'events.render', value: EventApiFunc): Api; - set(propertyName: 'events.show', value: EventApiFunc): Api; - set(propertyName: 'events.hide', value: EventApiFunc): Api; - set(propertyName: 'events.toggle', value: EventApiFunc): Api; - set(propertyName: 'events.visible', value: EventApiFunc): Api; - set(propertyName: 'events.hidden', value: EventApiFunc): Api; - set(propertyName: 'events.move', value: EventApiFunc): Api; - set(propertyName: 'events.focus', value: EventApiFunc): Api; - set(propertyName: 'events.blur', value: EventApiFunc): Api; - set(propertyName: string, value: any): Api; - - toggle(state?: boolean, event?: Event): Api; - - show(event?: Event): Api; - - hide(event?: Event): Api; - - disable(state?: boolean): Api; - - enable(): Api; - - reposition(event?: Event, effect?: boolean): Api; - - focus(event?: Event): Api; - - blur(event?: Event): Api; - - destroy(immediate?: boolean): Api; - } -} - - -interface JQuery { - qtip(options?: QTip2.QTipOptions): JQuery; - - qtip(methodName: 'api'): QTip2.Api; - - qtip(methodName: 'option', propertyName: 'id'): string | boolean; - qtip(methodName: 'option', propertyName: 'prerender'): boolean; - qtip(methodName: 'option', propertyName: 'overwrite'): boolean; - qtip(methodName: 'option', propertyName: 'suppress'): boolean; - qtip(methodName: 'option', propertyName: 'metadata'): any; - qtip(methodName: 'option', propertyName: 'content'): QTip2.Content; - qtip(methodName: 'option', propertyName: 'content.text'): QTip2.Text; - qtip(methodName: 'option', propertyName: 'content.attr'): string; - qtip(methodName: 'option', propertyName: 'content.title'): QTip2.Title; - qtip(methodName: 'option', propertyName: 'content.button'): string | JQuery | boolean; - qtip(methodName: 'option', propertyName: 'position'): QTip2.Position; - qtip(methodName: 'option', propertyName: 'position.my'): string | boolean; - qtip(methodName: 'option', propertyName: 'position.at'): string | boolean; - qtip(methodName: 'option', propertyName: 'position.target'): QTip2.Target | boolean; - qtip(methodName: 'option', propertyName: 'position.container'): JQuery | boolean; - qtip(methodName: 'option', propertyName: 'position.viewport'): JQuery | boolean; - qtip(methodName: 'option', propertyName: 'position.effect'): boolean | ((api: QTip2.Api, pos: any, viewport: any) => void); - qtip(methodName: 'option', propertyName: 'position.adjust'): QTip2.PositionAdjust; - qtip(methodName: 'option', propertyName: 'show'): QTip2.Show; - qtip(methodName: 'option', propertyName: 'show.target'): JQuery | boolean; - qtip(methodName: 'option', propertyName: 'show.event'): string | boolean; - qtip(methodName: 'option', propertyName: 'show.delay'): number; - qtip(methodName: 'option', propertyName: 'show.solo'): JQuery | string | boolean; - qtip(methodName: 'option', propertyName: 'show.ready'): boolean; - qtip(methodName: 'option', propertyName: 'show.effect'): boolean | ((offset: any) => void); - qtip(methodName: 'option', propertyName: 'show.modal'): boolean | QTip2.Modal; - qtip(methodName: 'option', propertyName: 'hide'): QTip2.Hide; - qtip(methodName: 'option', propertyName: 'hide.target'): JQuery | boolean; - qtip(methodName: 'option', propertyName: 'hide.event'): string | boolean; - qtip(methodName: 'option', propertyName: 'hide.delay'): number; - qtip(methodName: 'option', propertyName: 'hide.leave'): string | boolean; - qtip(methodName: 'option', propertyName: 'hide.distance'): number | boolean; - qtip(methodName: 'option', propertyName: 'hide.effect'): boolean | ((offset: any) => void); - qtip(methodName: 'option', propertyName: 'style'): QTip2.Style; - qtip(methodName: 'option', propertyName: 'style.classes'): string | boolean; - qtip(methodName: 'option', propertyName: 'style.def'): boolean; - qtip(methodName: 'option', propertyName: 'style.widget'): boolean; - qtip(methodName: 'option', propertyName: 'style.width'): string | number | boolean; - qtip(methodName: 'option', propertyName: 'style.height'): string | number | boolean; - qtip(methodName: 'option', propertyName: 'style.tip'): string | boolean | QTip2.Tip; - qtip(methodName: 'option', propertyName: 'events'): QTip2.Events; - qtip(methodName: 'option', propertyName: 'events.render'): QTip2.EventApiFunc; - qtip(methodName: 'option', propertyName: 'events.show'): QTip2.EventApiFunc; - qtip(methodName: 'option', propertyName: 'events.hide'): QTip2.EventApiFunc; - qtip(methodName: 'option', propertyName: 'events.toggle'): QTip2.EventApiFunc; - qtip(methodName: 'option', propertyName: 'events.visible'): QTip2.EventApiFunc; - qtip(methodName: 'option', propertyName: 'events.hidden'): QTip2.EventApiFunc; - qtip(methodName: 'option', propertyName: 'events.move'): QTip2.EventApiFunc; - qtip(methodName: 'option', propertyName: 'events.focus'): QTip2.EventApiFunc; - qtip(methodName: 'option', propertyName: 'events.blur'): QTip2.EventApiFunc; - - qtip(methodName: 'option', properties: QTip2.QTipOptions): QTip2.Api; - qtip(methodName: 'option', propertyName: 'id', value: string | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'prerender', value: boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'overwrite', value: boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'suppress', value: boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'metadata', value: any): QTip2.Api; - qtip(methodName: 'option', propertyName: 'content', value: QTip2.Text | QTip2.Content): QTip2.Api; - qtip(methodName: 'option', propertyName: 'content.title', value: QTip2.Title | { text: QTip2.Title }): QTip2.Api; - qtip(methodName: 'option', propertyName: 'content.text', value: QTip2.Text): QTip2.Api; - qtip(methodName: 'option', propertyName: 'content.attr', value: string): QTip2.Api; - qtip(methodName: 'option', propertyName: 'content.button', value: string | JQuery | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'position', value: QTip2.Position): QTip2.Api; - qtip(methodName: 'option', propertyName: 'position.my', value: string | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'position.at', value: string | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'position.target', value: QTip2.Target | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'position.container', value: JQuery | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'position.viewport', value: JQuery | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'position.effect', value: boolean | ((api: QTip2.Api, pos: any, viewport: any) => void) ): QTip2.Api; - qtip(methodName: 'option', propertyName: 'position.adjust', value: QTip2.PositionAdjust): QTip2.Api; - qtip(methodName: 'option', propertyName: 'show', value: QTip2.Show): QTip2.Api; - qtip(methodName: 'option', propertyName: 'show.target', value: JQuery | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'show.event', value: string | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'show.delay', value: number): QTip2.Api; - qtip(methodName: 'option', propertyName: 'show.solo', value: JQuery | string | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'show.ready', value: boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'show.effect', value: boolean | ((offset: any) => void)): QTip2.Api; - qtip(methodName: 'option', propertyName: 'show.modal', value: boolean | QTip2.Modal): QTip2.Api; - qtip(methodName: 'option', propertyName: 'hide', value: QTip2.Hide): QTip2.Api; - qtip(methodName: 'option', propertyName: 'hide.target', value: JQuery | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'hide.event', value: string | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'hide.inactive', value: number | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'hide.fixed', value: boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'hide.leave', value: string | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'hide.distance', value: number | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'hide.effect', value: boolean | ((offset: any) => void)): QTip2.Api - qtip(methodName: 'option', propertyName: 'style', value: QTip2.Style): QTip2.Api; - qtip(methodName: 'option', propertyName: 'style.classes', value: string | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'style.def', value: boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'style.widget', value: boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'style.width', value: string | number | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'style.height', value: string | number | boolean): QTip2.Api; - qtip(methodName: 'option', propertyName: 'style.tip', value: string | boolean | QTip2.Tip): QTip2.Api; - qtip(methodName: 'option', propertyName: 'events', value: QTip2.Events): QTip2.Api; - qtip(methodName: 'option', propertyName: 'events.render', value: QTip2.EventApiFunc): QTip2.Api; - qtip(methodName: 'option', propertyName: 'events.show', value: QTip2.EventApiFunc): QTip2.Api; - qtip(methodName: 'option', propertyName: 'events.hide', value: QTip2.EventApiFunc): QTip2.Api; - qtip(methodName: 'option', propertyName: 'events.toggle', value: QTip2.EventApiFunc): QTip2.Api; - qtip(methodName: 'option', propertyName: 'events.visible', value: QTip2.EventApiFunc): QTip2.Api; - qtip(methodName: 'option', propertyName: 'events.hidden', value: QTip2.EventApiFunc): QTip2.Api; - qtip(methodName: 'option', propertyName: 'events.move', value: QTip2.EventApiFunc): QTip2.Api; - qtip(methodName: 'option', propertyName: 'events.focus', value: QTip2.EventApiFunc): QTip2.Api; - qtip(methodName: 'option', propertyName: 'events.blur', value: QTip2.EventApiFunc): QTip2.Api; - - qtip(methodName: 'toggle', state?: boolean, event?: Event): JQuery; - - qtip(methodName: 'show', event?: Event): JQuery; - - qtip(methodName: 'hide', event?: Event): JQuery; - - qtip(methodName: 'disable', state?: boolean): JQuery; - - qtip(methodName: 'enable'): JQuery - - qtip(methodName: 'reposition', event?: Event, effect?: boolean): JQuery; - - qtip(methodName: 'focus', event?: Event): JQuery; - - qtip(methodName: 'blur', event?: Event): JQuery; - - qtip(methodName: 'destroy', immediate?: boolean): JQuery; - - qtip(methodName: string, p1?: any, p2?: any, p3?: any): any; -} diff --git a/qtip2/tsconfig.json b/qtip2/tsconfig.json new file mode 100644 index 0000000000..6b4bd06cd3 --- /dev/null +++ b/qtip2/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "qtip2-tests.ts" + ] +} \ No newline at end of file diff --git a/query-string/index.d.ts b/query-string/index.d.ts new file mode 100644 index 0000000000..f2da7fef73 --- /dev/null +++ b/query-string/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for query-string v3.0.0 +// Project: https://github.com/sindresorhus/query-string +// Definitions by: Sam Verschueren +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/** + * Parse a query string into an object. + * Leading ? or # are ignored, so you can pass location.search or location.hash directly. + * @param str + */ +export declare function parse(str: string): any; + +/** + * Stringify an object into a query string, sorting the keys. + * + * @param obj + */ +export declare function stringify(obj: any, options?: { strict: boolean }): string; + +/** + * Extract a query string from a URL that can be passed into .parse(). + * + * @param str + */ +export declare function extract(str: string): string; diff --git a/query-string/query-string-tests.ts b/query-string/query-string-tests.ts index e270786004..b9a6d56075 100644 --- a/query-string/query-string-tests.ts +++ b/query-string/query-string-tests.ts @@ -1,4 +1,3 @@ -/// import qs = require('query-string'); diff --git a/query-string/query-string.d.ts b/query-string/query-string.d.ts deleted file mode 100644 index 807b38935a..0000000000 --- a/query-string/query-string.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Type definitions for query-string v3.0.0 -// Project: https://github.com/sindresorhus/query-string -// Definitions by: Sam Verschueren -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "query-string" { - /** - * Parse a query string into an object. - * Leading ? or # are ignored, so you can pass location.search or location.hash directly. - * @param str - */ - export function parse(str: string): any; - - /** - * Stringify an object into a query string, sorting the keys. - * - * @param obj - */ - export function stringify(obj: any, options?: {strict: boolean}): string; - - /** - * Extract a query string from a URL that can be passed into .parse(). - * - * @param str - */ - export function extract(str: string): string; -} diff --git a/query-string/tsconfig.json b/query-string/tsconfig.json new file mode 100644 index 0000000000..40413cab21 --- /dev/null +++ b/query-string/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "query-string-tests.ts" + ] +} \ No newline at end of file diff --git a/quill/index.d.ts b/quill/index.d.ts new file mode 100644 index 0000000000..95ed5ca2c6 --- /dev/null +++ b/quill/index.d.ts @@ -0,0 +1,119 @@ +// Type definitions for Quill +// Project: http://quilljs.com +// Definitions by: Sumit +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare interface DeltaStatic { + ops?: Array; + retain?: any, + delete?: any, + insert?: any, + attributes?: any +} + +declare interface RangeStatic { + new (): RangeStatic; + start: number; + end: number; +} + +declare interface QuillStatic { + new (selector: string, options?: Object): QuillStatic; + + on(eventName: string, callback: (delta: DeltaStatic, source: string) => void): EventEmitter2; + addModule(id: string, options: any): Object; + + getText(): string; + getText(start: number): string; + getText(start: number, end: number): string; + + getLength(): number; + + getContents(): DeltaStatic; + getContents(start: number): DeltaStatic; + getContents(start: number, end: number): DeltaStatic; + + getHTML(): string; + + insertText(index: number, text: string): void; + insertText(index: number, text: string, name: string, value: string): void; + insertText(index: number, text: string, formats: any): void; + insertText(index: number, text: string, source: string): void; + insertText(index: number, text: string, name: string, value: string, source: string): void; + insertText(index: number, text: string, formats: any, source: string): void; + + deleteText(start: number, end: number): void; + deleteText(start: number, end: number, source: string): void; + + formatText(start: number, end: number): void; + formatText(start: number, end: number, name: string, value: boolean): void; + formatText(start: number, end: number, formats: any): void; + formatText(start: number, end: number, source: string): void; + formatText(start: number, end: number, name: string, value: string, source: string): void; + formatText(start: number, end: number, formats: string, source: string): void; + + + formatLine(start: number, end: number): void; + formatLine(start: number, end: number, name: string, value: boolean): void; + formatLine(start: number, end: number, formats: any): void; + formatLine(start: number, end: number, source: string): void; + formatLine(start: number, end: number, name: string, value: string, source: string): void; + formatLine(start: number, end: number, formats: any, source: string): void; + + + insertEmbed(index: number, type: string, url: string): void; + insertEmbed(index: number, type: string, url: string, source: string): void; + + updateContents(delta: DeltaStatic): void; + + setContents(delta: DeltaStatic): void; + + setHTML(html: string): void; + + setText(text: string): void; + + getSelection(): RangeStatic; + + setSelection(start: number, end: number): void; + setSelection(start: number, end: number, source: string): void; + setSelection(range: RangeStatic): void; + setSelection(range: RangeStatic, source: string): void; + + prepareFormat(format: string, value: boolean): void; + + focus(): void; + + getBounds(index: number): any; + + registerModule(name: string, callback: (quill: QuillStatic, options: any) => {}): any; + + addModule(name: string, options: any): any; + + getModule(name: string): any; + + onModuleLoad(name: string, callback: (input: any) => {}): void; + + addFormat(name: string, config: any): void; + + addContainer(cssClass: string, before?: number): HTMLDivElement; +} + +declare module "Range" +{ + var Range: RangeStatic; + export = Range; +} + +declare var Delta: DeltaStatic; + +declare module "Delta" { + export = Delta; +} + +declare var Quill: QuillStatic; + +declare module "Quill" { + export = Quill; +} diff --git a/quill/quill-tests.ts b/quill/quill-tests.ts index 3a87bd5948..3935149349 100644 --- a/quill/quill-tests.ts +++ b/quill/quill-tests.ts @@ -1,8 +1,3 @@ -/// -/// - -//export var Quill = require("quill"); - function test_quill() { var quillEditor = new Quill('#editor', { diff --git a/quill/quill.d.ts b/quill/quill.d.ts deleted file mode 100644 index 3cef088442..0000000000 --- a/quill/quill.d.ts +++ /dev/null @@ -1,119 +0,0 @@ -// Type definitions for Quill -// Project: http://quilljs.com -// Definitions by: Sumit -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare interface DeltaStatic{ - ops? : Array; - retain?: any, - delete?: any, - insert?: any, - attributes?: any -} - -declare interface RangeStatic{ - new(): RangeStatic; - start: number; - end: number; -} - -declare interface QuillStatic { - new(selector: string, options?: Object):QuillStatic; - - on(eventName: string, callback: (delta: DeltaStatic, source: string) => void): EventEmitter2; - addModule(id: string, options: any) : Object; - - getText(): string; - getText(start: number): string; - getText(start: number, end: number): string; - - getLength(): number; - - getContents(): DeltaStatic; - getContents(start: number): DeltaStatic; - getContents(start: number, end: number): DeltaStatic; - - getHTML(): string; - - insertText(index: number, text: string): void; - insertText(index: number, text: string, name: string, value: string): void; - insertText(index: number, text: string, formats: any): void; - insertText(index: number, text: string, source: string) : void; - insertText(index: number, text: string, name: string, value: string, source: string): void; - insertText(index: number, text: string, formats: any, source: string): void; - - deleteText(start: number, end: number): void; - deleteText(start: number, end: number, source: string): void; - - formatText(start: number, end: number): void; - formatText(start: number, end: number, name: string, value: boolean): void; - formatText(start: number, end: number, formats: any): void; - formatText(start: number, end: number, source: string): void; - formatText(start: number, end: number, name: string, value: string, source: string): void; - formatText(start: number, end: number, formats: string, source: string): void; - - - formatLine(start: number, end: number): void; - formatLine(start: number, end: number, name: string, value: boolean): void; - formatLine(start: number, end: number, formats: any): void; - formatLine(start: number, end: number, source: string): void; - formatLine(start: number, end: number, name: string, value: string, source: string): void; - formatLine(start: number, end: number, formats: any, source: string): void; - - - insertEmbed(index: number, type: string, url: string): void; - insertEmbed(index: number, type: string, url: string, source: string): void; - - updateContents(delta: DeltaStatic): void; - - setContents(delta: DeltaStatic): void; - - setHTML(html: string): void; - - setText(text: string): void; - - getSelection(): RangeStatic; - - setSelection(start: number, end: number): void; - setSelection(start: number, end: number, source: string): void; - setSelection(range: RangeStatic): void; - setSelection(range: RangeStatic, source: string): void; - - prepareFormat(format: string, value: boolean): void; - - focus(): void; - - getBounds(index: number): any; - - registerModule(name: string, callback: (quill: QuillStatic, options: any) => {}): any; - - addModule(name: string, options: any): any; - - getModule(name: string): any; - - onModuleLoad(name: string, callback: (input: any) => {}): void; - - addFormat(name: string, config: any): void; - - addContainer(cssClass: string, before?: number): HTMLDivElement; -} - -declare module "Range" -{ - var Range: RangeStatic; - export = Range; -} - -declare var Delta: DeltaStatic; - -declare module "Delta"{ - export = Delta; -} - -declare var Quill: QuillStatic; - -declare module "Quill" { - export = Quill; -} diff --git a/quill/tsconfig.json b/quill/tsconfig.json new file mode 100644 index 0000000000..8098844c78 --- /dev/null +++ b/quill/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "quill-tests.ts" + ] +} \ No newline at end of file diff --git a/quixote/quixote.d.ts b/quixote/index.d.ts similarity index 100% rename from quixote/quixote.d.ts rename to quixote/index.d.ts diff --git a/quixote/quixote-tests.ts b/quixote/quixote-tests.ts index 0f2d051f24..5ee9905ac0 100644 --- a/quixote/quixote-tests.ts +++ b/quixote/quixote-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + function test_createFrame() { var frame: QFrame; diff --git a/quixote/tsconfig.json b/quixote/tsconfig.json new file mode 100644 index 0000000000..fcec319290 --- /dev/null +++ b/quixote/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "quixote-tests.ts" + ] +} \ No newline at end of file diff --git a/qunit/qunit.d.ts b/qunit/index.d.ts similarity index 100% rename from qunit/qunit.d.ts rename to qunit/index.d.ts diff --git a/qunit/qunit-tests.ts b/qunit/qunit-tests.ts index 20285e8022..23570cb9dd 100644 --- a/qunit/qunit-tests.ts +++ b/qunit/qunit-tests.ts @@ -1,4 +1,4 @@ -/// + QUnit.test("assert.async() test", function (assert) { var done = assert.async(); diff --git a/qunit/qunit-tests.ts.tscparams b/qunit/qunit-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/qunit/qunit-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/qunit/tsconfig.json b/qunit/tsconfig.json new file mode 100644 index 0000000000..2db99e6bbe --- /dev/null +++ b/qunit/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "qunit-tests.ts" + ] +} \ No newline at end of file diff --git a/qwest/qwest.d.ts b/qwest/index.d.ts similarity index 100% rename from qwest/qwest.d.ts rename to qwest/index.d.ts diff --git a/qwest/qwest-tests.ts b/qwest/qwest-tests.ts index 67e2de21b8..a8a22ffcf2 100644 --- a/qwest/qwest-tests.ts +++ b/qwest/qwest-tests.ts @@ -1,4 +1,4 @@ -/// + // Examples taken from https://github.com/pyrsmk/qwest/blob/master/README.md diff --git a/qwest/tsconfig.json b/qwest/tsconfig.json new file mode 100644 index 0000000000..b370724605 --- /dev/null +++ b/qwest/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "qwest-tests.ts" + ] +} \ No newline at end of file diff --git a/rabbit.js/index.d.ts b/rabbit.js/index.d.ts new file mode 100644 index 0000000000..ce745a38d0 --- /dev/null +++ b/rabbit.js/index.d.ts @@ -0,0 +1,107 @@ +// Type definitions for rabbit.js v0.4.2 +// Project: https://github.com/squaremo/rabbit.js +// Definitions by: Wonshik Kim +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import events = require('events'); +import stream = require('stream'); + +export declare function createContext(url?: string): Context; + +export declare class Context extends events.EventEmitter { + public socket(type: string, options?: SocketOptions): T; + public close(callback: Function): any; +} + +export interface SocketOptions { + prefetch?: any; + expiration?: any; + persistent?: any; + topic?: any; + task?: any; +} + +export interface Socket { + connect(destination: string, callback?: Function): any; + setsockopt(opt: string, value: string): any; + close(): any; +} + +export declare class PubSocket extends stream.Writable implements Socket { + constructor(channel: string, opts: SocketOptions); + connect(destination: string, callback?: Function): any; + setsockopt(opt: string, value: string): any; + close(): any; + + publish(topic: string, chunk: string, encoding?: string): any; + publish(topic: string, chunk: Buffer, encoding?: string): any; +} + +export declare class SubSocket extends stream.Readable implements Socket { + constructor(channel: string, opts: SocketOptions); + connect(source: string, callback?: Function): any; + setsockopt(opt: string, value: string): any; + close(): any; +} + +export declare class PushSocket extends stream.Writable implements Socket { + constructor(channel: string, opts: SocketOptions); + connect(destination: string, callback?: Function): any; + setsockopt(opt: string, value: string): any; + close(): any; +} + +export declare class PullSocket extends stream.Readable implements Socket { + constructor(channel: string, opts: SocketOptions); + connect(source: string, callback?: Function): any; + setsockopt(opt: string, value: string): any; + close(): any; +} + +export declare class WorkerSocket extends stream.Readable implements Socket { + constructor(channel: string, opts: SocketOptions); + connect(source: string, callback?: Function): any; + setsockopt(opt: string, value: string): any; + close(): any; + + ack(): any; + requeue(): any; + discard(): any; +} + +export interface RequestMessage { + properties: { correlationId: number }; + content: any; +} + +export declare class ReqSocket extends stream.Duplex implements Socket { + constructor(channel: string, opts: SocketOptions); + connect(destination: string, callback?: Function): any; + setsockopt(opt: string, value: string): any; + close(): any; + + handleReply(msg: RequestMessage): any; +} + +export declare class RepSocket extends stream.Duplex implements Socket { + constructor(channel: string, opts: SocketOptions); + connect(source: string, callback?: Function): any; + setsockopt(opt: string, value: string): any; + close(): any; + + requeue(): any; + discard(): any; +} + +export declare class TaskSocket extends stream.Writable implements Socket { + constructor(channel: string, opts: SocketOptions); + connect(destination: string, callback?: Function): any; + setsockopt(opt: string, value: string): any; + close(): any; + + post(task: string, chunk: string, encoding?: string): any; + post(task: string, chunk: Buffer, encoding?: string): any; +} diff --git a/rabbit.js/rabbit.js-tests.ts b/rabbit.js/rabbit.js-tests.ts index 3e5a4d6d21..c9256f9a3a 100644 --- a/rabbit.js/rabbit.js-tests.ts +++ b/rabbit.js/rabbit.js-tests.ts @@ -1,4 +1,3 @@ -/// import rabbit = require('rabbit.js'); var context = rabbit.createContext(); diff --git a/rabbit.js/rabbit.js.d.ts b/rabbit.js/rabbit.js.d.ts deleted file mode 100644 index 7e09cfe14a..0000000000 --- a/rabbit.js/rabbit.js.d.ts +++ /dev/null @@ -1,108 +0,0 @@ -// Type definitions for rabbit.js v0.4.2 -// Project: https://github.com/squaremo/rabbit.js -// Definitions by: Wonshik Kim -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "rabbit.js" { - import events = require('events'); - import stream = require('stream'); - - export function createContext(url?: string): Context; - - export class Context extends events.EventEmitter { - public socket(type: string, options?: SocketOptions):T; - public close(callback: Function): any; - } - - export interface SocketOptions { - prefetch?: any; - expiration?: any; - persistent?: any; - topic?: any; - task?: any; - } - - export interface Socket { - connect(destination: string, callback?: Function): any; - setsockopt(opt: string, value: string): any; - close(): any; - } - - export class PubSocket extends stream.Writable implements Socket { - constructor(channel: string, opts: SocketOptions); - connect(destination: string, callback?: Function): any; - setsockopt(opt: string, value: string): any; - close(): any; - - publish(topic: string, chunk: string, encoding?: string): any; - publish(topic: string, chunk: Buffer, encoding?: string): any; - } - - export class SubSocket extends stream.Readable implements Socket { - constructor(channel: string, opts: SocketOptions); - connect(source: string, callback?: Function): any; - setsockopt(opt: string, value: string): any; - close(): any; - } - - export class PushSocket extends stream.Writable implements Socket { - constructor(channel: string, opts: SocketOptions); - connect(destination: string, callback?: Function): any; - setsockopt(opt: string, value: string): any; - close(): any; - } - - export class PullSocket extends stream.Readable implements Socket { - constructor(channel: string, opts: SocketOptions); - connect(source: string, callback?: Function): any; - setsockopt(opt: string, value: string): any; - close(): any; - } - - export class WorkerSocket extends stream.Readable implements Socket { - constructor(channel: string, opts: SocketOptions); - connect(source: string, callback?: Function): any; - setsockopt(opt: string, value: string): any; - close(): any; - - ack(): any; - requeue(): any; - discard(): any; - } - - export interface RequestMessage { - properties: { correlationId: number }; - content: any; - } - - export class ReqSocket extends stream.Duplex implements Socket { - constructor(channel: string, opts: SocketOptions); - connect(destination: string, callback?: Function): any; - setsockopt(opt: string, value: string): any; - close(): any; - - handleReply(msg: RequestMessage): any; - } - - export class RepSocket extends stream.Duplex implements Socket { - constructor(channel: string, opts: SocketOptions); - connect(source: string, callback?: Function): any; - setsockopt(opt: string, value: string): any; - close(): any; - - requeue(): any; - discard(): any; - } - - export class TaskSocket extends stream.Writable implements Socket { - constructor(channel: string, opts: SocketOptions); - connect(destination: string, callback?: Function): any; - setsockopt(opt: string, value: string): any; - close(): any; - - post(task: string, chunk: string, encoding?: string): any; - post(task: string, chunk: Buffer, encoding?: string): any; - } -} diff --git a/rabbit.js/tsconfig.json b/rabbit.js/tsconfig.json new file mode 100644 index 0000000000..4c8f03d0ff --- /dev/null +++ b/rabbit.js/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "rabbit.js-tests.ts" + ] +} \ No newline at end of file diff --git a/ractive/ractive.d.ts b/ractive/index.d.ts similarity index 100% rename from ractive/ractive.d.ts rename to ractive/index.d.ts diff --git a/ractive/ractive-tests.ts b/ractive/ractive-tests.ts index df97190c93..5c5eac127b 100644 --- a/ractive/ractive-tests.ts +++ b/ractive/ractive-tests.ts @@ -1,4 +1,4 @@ -/// + function test_transition() { var plugin: Ractive.TransitionPlugin = (t: Ractive.Transition, params: Object) => { diff --git a/ractive/tsconfig.json b/ractive/tsconfig.json new file mode 100644 index 0000000000..58f4abe8fa --- /dev/null +++ b/ractive/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "ractive-tests.ts" + ] +} \ No newline at end of file diff --git a/radium/index.d.ts b/radium/index.d.ts new file mode 100644 index 0000000000..fccdb78f5f --- /dev/null +++ b/radium/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for radium 0.17.1 +// Project: https://github.com/formidablelabs/radium +// Definitions by: Alex Gorbatchev , Philipp Holzer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import React = require('react'); + +interface ReactComponent { + new (p: P): React.Component; +} + +declare var Radium: { + >(comp: T): T; +}; + +export = Radium; diff --git a/radium/radium-tests.tsx b/radium/radium-tests.tsx new file mode 100644 index 0000000000..cc734155d5 --- /dev/null +++ b/radium/radium-tests.tsx @@ -0,0 +1,17 @@ + +/// + +import * as React from "react"; +import * as Radium from 'radium'; + +@Radium +export default class TestComponent extends React.Component { + + render() { + return ( +
+ Test with Radium +
+ ); + } +} diff --git a/radium/tsconfig.json b/radium/tsconfig.json new file mode 100644 index 0000000000..cc416f1eda --- /dev/null +++ b/radium/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "experimentalDecorators": true, + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "radium-tests.tsx" + ] +} \ No newline at end of file diff --git a/radius/index.d.ts b/radius/index.d.ts new file mode 100644 index 0000000000..ccca0e4543 --- /dev/null +++ b/radius/index.d.ts @@ -0,0 +1,105 @@ +// Type definitions for node-radius +// Project: https://github.com/retailnext/node-radius +// Definitions by: Peter Harris +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +/** + * {@link https://github.com/retailnext/node-radius#radiusdecodeargs} for more info. + **/ +export declare function decode(args: DecodeArgsWithSecret): RadiusPacket; + +/** + * {@link https://github.com/retailnext/node-radius#radiusdecode_without_secretargs} for more info. + **/ +export declare function decode_without_secret(args: DecodeArgs): RadiusPacket; + +/** + * {@link https://github.com/retailnext/node-radius#radiusencodeargs} for more info. + **/ +export declare function encode(args: EncodeArgs): Buffer; + +/** + * {@link https://github.com/retailnext/node-radius#radiusencode_responseargs} for more info. + **/ +export declare function encode_response(args: EncodeResponseArgs): Buffer; + +/** + * {@link https://github.com/retailnext/node-radius#radiusverify_responseargs} for more info. + **/ +export declare function verify_response(args: VerifyResponseArgs): boolean; + +/** + * {@link https://github.com/retailnext/node-radius#radiusadd_dictionarypath} for more info. + * + * @param path Can be either a path to a file or a directory. + **/ +export declare function add_dictionary(path: string): void; + +export declare function unload_dictionaries(): void; + + + + + + +/** + * {@link https://github.com/retailnext/node-radius#radiusdecode_without_secretargs} for more info. + **/ +interface DecodeArgs { + packet: Buffer; +} + +/** + * {@link https://github.com/retailnext/node-radius#radiusdecodeargs} for more info. + **/ +interface DecodeArgsWithSecret extends DecodeArgs { + secret: string; +} + +/** + * {@link https://github.com/retailnext/node-radius#radiusencodeargs} for more info. + **/ +interface EncodeArgs { + code: string; + secret: string; + identifier?: number; + /** + * This can be an object: { attribute_name: attribute_value, ... }, + * an array within an array: [ [ attribute_name, attribute_value ], ... ], + * or if you haven't loaded a dictionary for the attributes: [ [ attribute_id, Buffer ], ... ]. + * + * Tag field-attributes can be specified like so: [ [ attribute_name, tag_number, attribute_value ] ... ] + **/ + attributes?: any; + add_message_authenticator?: boolean; +} + +/** + * {@link https://github.com/retailnext/node-radius#radiusencode_responseargs} for more info. + **/ +interface EncodeResponseArgs { + packet: RadiusPacket; + code: string; + secret: string; + attributes?: any; +} + +/** + * {@link https://github.com/retailnext/node-radius#radiusverify_responseargs} for more info. + **/ +interface VerifyResponseArgs { + request: Buffer; + response: Buffer; + secret: string; +} + +interface RadiusPacket { + code: string; + identifier: number; + length: number; + attributes: any; + raw_attributes: Array> +} diff --git a/radius/radius-tests.ts b/radius/radius-tests.ts index 2ce4d2c0d3..c3b50db8ec 100644 --- a/radius/radius-tests.ts +++ b/radius/radius-tests.ts @@ -1,5 +1,5 @@ -/// -/// + +/// import radius = require('radius'); diff --git a/radius/radius.d.ts b/radius/radius.d.ts deleted file mode 100644 index 4e4b41c048..0000000000 --- a/radius/radius.d.ts +++ /dev/null @@ -1,106 +0,0 @@ -// Type definitions for node-radius -// Project: https://github.com/retailnext/node-radius -// Definitions by: Peter Harris -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "radius" { - /** - * {@link https://github.com/retailnext/node-radius#radiusdecodeargs} for more info. - **/ - export function decode(args: DecodeArgsWithSecret): RadiusPacket; - - /** - * {@link https://github.com/retailnext/node-radius#radiusdecode_without_secretargs} for more info. - **/ - export function decode_without_secret(args: DecodeArgs): RadiusPacket; - - /** - * {@link https://github.com/retailnext/node-radius#radiusencodeargs} for more info. - **/ - export function encode(args: EncodeArgs): Buffer; - - /** - * {@link https://github.com/retailnext/node-radius#radiusencode_responseargs} for more info. - **/ - export function encode_response(args: EncodeResponseArgs): Buffer; - - /** - * {@link https://github.com/retailnext/node-radius#radiusverify_responseargs} for more info. - **/ - export function verify_response(args: VerifyResponseArgs):boolean; - - /** - * {@link https://github.com/retailnext/node-radius#radiusadd_dictionarypath} for more info. - * - * @param path Can be either a path to a file or a directory. - **/ - export function add_dictionary(path:string): void; - - export function unload_dictionaries(): void; - - - - - - - /** - * {@link https://github.com/retailnext/node-radius#radiusdecode_without_secretargs} for more info. - **/ - interface DecodeArgs { - packet: Buffer; - } - - /** - * {@link https://github.com/retailnext/node-radius#radiusdecodeargs} for more info. - **/ - interface DecodeArgsWithSecret extends DecodeArgs { - secret: string; - } - - /** - * {@link https://github.com/retailnext/node-radius#radiusencodeargs} for more info. - **/ - interface EncodeArgs { - code: string; - secret: string; - identifier?: number; - /** - * This can be an object: { attribute_name: attribute_value, ... }, - * an array within an array: [ [ attribute_name, attribute_value ], ... ], - * or if you haven't loaded a dictionary for the attributes: [ [ attribute_id, Buffer ], ... ]. - * - * Tag field-attributes can be specified like so: [ [ attribute_name, tag_number, attribute_value ] ... ] - **/ - attributes?: any; - add_message_authenticator?: boolean; - } - - /** - * {@link https://github.com/retailnext/node-radius#radiusencode_responseargs} for more info. - **/ - interface EncodeResponseArgs { - packet: RadiusPacket; - code: string; - secret: string; - attributes?: any; - } - - /** - * {@link https://github.com/retailnext/node-radius#radiusverify_responseargs} for more info. - **/ - interface VerifyResponseArgs { - request: Buffer; - response: Buffer; - secret: string; - } - - interface RadiusPacket { - code: string; - identifier: number; - length: number; - attributes: any; - raw_attributes: Array> - } -} \ No newline at end of file diff --git a/radius/tsconfig.json b/radius/tsconfig.json new file mode 100644 index 0000000000..4c609c67a3 --- /dev/null +++ b/radius/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "radius-tests.ts" + ] +} \ No newline at end of file diff --git a/rails-actioncable/rails-actioncable.d.ts b/rails-actioncable/index.d.ts similarity index 100% rename from rails-actioncable/rails-actioncable.d.ts rename to rails-actioncable/index.d.ts diff --git a/rails-actioncable/rails-actioncable-tests.ts b/rails-actioncable/rails-actioncable-tests.ts index e7a04f338e..a3fd305cc1 100644 --- a/rails-actioncable/rails-actioncable-tests.ts +++ b/rails-actioncable/rails-actioncable-tests.ts @@ -1,4 +1,4 @@ -/// + App = {}; App.cable = ActionCable.createConsumer(); App.cable.subscriptions.create("NetworkChannel", {}); diff --git a/rails-actioncable/tsconfig.json b/rails-actioncable/tsconfig.json new file mode 100644 index 0000000000..9afbd54713 --- /dev/null +++ b/rails-actioncable/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "rails-actioncable-tests.ts" + ] +} \ No newline at end of file diff --git a/random-js/random-js.d.ts b/random-js/index.d.ts similarity index 100% rename from random-js/random-js.d.ts rename to random-js/index.d.ts diff --git a/random-js/random-js-tests.ts b/random-js/random-js-tests.ts index 9ee80883b6..77c698e321 100644 --- a/random-js/random-js-tests.ts +++ b/random-js/random-js-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// // Examples taken from the documentation at https://github.com/ckknight/random-js // create a Mersenne Twister-19937 that is auto-seeded based on time and other random values diff --git a/random-js/tsconfig.json b/random-js/tsconfig.json new file mode 100644 index 0000000000..463bc7c395 --- /dev/null +++ b/random-js/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "random-js-tests.ts" + ] +} \ No newline at end of file diff --git a/random-string/index.d.ts b/random-string/index.d.ts new file mode 100644 index 0000000000..0297e67ce1 --- /dev/null +++ b/random-string/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for random-string +// Project: https://github.com/valiton/node-random-string +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare function randomString(opts?: Object): string; +export = randomString; diff --git a/random-string/random-string-tests.ts b/random-string/random-string-tests.ts index 2b278a4f5e..4a6c3c5f12 100644 --- a/random-string/random-string-tests.ts +++ b/random-string/random-string-tests.ts @@ -1,4 +1,3 @@ -/// import randomString = require('random-string'); diff --git a/random-string/random-string.d.ts b/random-string/random-string.d.ts deleted file mode 100644 index 5fc955adfa..0000000000 --- a/random-string/random-string.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Type definitions for random-string -// Project: https://github.com/valiton/node-random-string -// Definitions by: Sam Saint-Pettersen -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "random-string" { - function randomString(opts?: Object): string; - export = randomString; -} diff --git a/random-string/tsconfig.json b/random-string/tsconfig.json new file mode 100644 index 0000000000..a3b40678a6 --- /dev/null +++ b/random-string/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "random-string-tests.ts" + ] +} \ No newline at end of file diff --git a/rangy/index.d.ts b/rangy/index.d.ts new file mode 100644 index 0000000000..1edb9c3c23 --- /dev/null +++ b/rangy/index.d.ts @@ -0,0 +1,66 @@ +// Type definitions for Rangy +// Project: https://github.com/timdown/rangy +// Definitions by: Rudolph Gottesheim +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface RangyRange extends Range { + setStartAndEnd(startNode:Node, startOffset:number, endNode?:Node, endOffset?:number):any; + setStartAndEnd(startNode:Node, startOffset:number, endOffset:number):any; + canSurroundContents():boolean; + isValid():boolean; + toHtml():string; + compareNode(node:Node):any; + intersectsOrTouchesRange(range:RangyRange):boolean; + intersectsRange(range:RangyRange):boolean; + intersection(range:RangyRange):RangyRange; + union(range:RangyRange):RangyRange; + containsNode(node:Node, partial:boolean):boolean; + containsNodeContents(node:Node):boolean; + containsNodeText(node:Node):boolean; + containsRange(range:RangyRange):boolean; + splitBoundaries():any; + normalizeBoundaries():any; + collapseToPoint(node:Node, offset:number):any; + collapseBefore(node:Node):any; + collapseAfter(node:Node):any; + getNodes(nodeTypes?:any[], filter?:(node:Node) => boolean):Node[]; + getBookmark(containerNode?:Node):{start:number, end:number}; + moveToBookmark(bookmark:Object):any; + getDocument():Document; + inspect():string; + equals(range:RangyRange):boolean; + refresh():any; + select():any; +} + +interface RangySelection extends Selection { + nativeSelection:Selection; + isBackwards():boolean; + refresh(checkForChanges?:boolean):any; + toHtml():string; + getAllRanges():RangyRange[]; + getNativeTextRange():any; + setSingleRange(range:RangyRange):any; + setRanges(ranges:RangyRange[]):any; + getBookmark(containerNode:Node):any; + moveToBookmark(bookmark:Object):any; + saveRanges():Object; + restoreRanges(saved:Object):any; + detach():any; + inspect():string; +} + +interface RangyStatic { + createNativeRange(doc?:Document|Window|HTMLIFrameElement):Range; + createRange(doc?:Document|Window|HTMLIFrameElement):RangyRange; + createRangyRange(doc?:Document|Window|HTMLIFrameElement):RangyRange; + getNativeSelection(win?:Window):Selection; + getSelection():RangySelection; + addInitListener(listener:(rangy:RangyStatic) => void):any; + shim():any; + createMissingNativeApi():any; + initialized:boolean; + supported:boolean; +} + +declare var rangy:RangyStatic; diff --git a/rangy/rangy-tests.ts b/rangy/rangy-tests.ts index b0c6c1cc27..fac44c868c 100644 --- a/rangy/rangy-tests.ts +++ b/rangy/rangy-tests.ts @@ -1,4 +1,4 @@ -/// + declare function assertAny(a:any):any; declare function assertBoolean(b:boolean):any; @@ -6,6 +6,8 @@ declare function assertString(s:string):any; declare function assertRangyRange(r:RangyRange):any; declare function getRangyRange():RangyRange; +type TextRange = any; // ? + function testRangyStatic() { rangy.addInitListener((rangy:RangyStatic) => { }); diff --git a/rangy/rangy.d.ts b/rangy/rangy.d.ts deleted file mode 100644 index 3b385a8b63..0000000000 --- a/rangy/rangy.d.ts +++ /dev/null @@ -1,66 +0,0 @@ -// Type definitions for Rangy -// Project: https://github.com/timdown/rangy -// Definitions by: Rudolph Gottesheim -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -interface RangyRange extends Range { - setStartAndEnd(startNode:Node, startOffset:number, endNode?:Node, endOffset?:number):any; - setStartAndEnd(startNode:Node, startOffset:number, endOffset:number):any; - canSurroundContents():boolean; - isValid():boolean; - toHtml():string; - compareNode(node:Node):any; - intersectsOrTouchesRange(range:RangyRange):boolean; - intersectsRange(range:RangyRange):boolean; - intersection(range:RangyRange):RangyRange; - union(range:RangyRange):RangyRange; - containsNode(node:Node, partial:boolean):boolean; - containsNodeContents(node:Node):boolean; - containsNodeText(node:Node):boolean; - containsRange(range:RangyRange):boolean; - splitBoundaries():any; - normalizeBoundaries():any; - collapseToPoint(node:Node, offset:number):any; - collapseBefore(node:Node):any; - collapseAfter(node:Node):any; - getNodes(nodeTypes?:any[], filter?:(node:Node) => boolean):Node[]; - getBookmark(containerNode?:Node):{start:number, end:number}; - moveToBookmark(bookmark:Object):any; - getDocument():Document; - inspect():string; - equals(range:RangyRange):boolean; - refresh():any; - select():any; -} - -interface RangySelection extends Selection { - nativeSelection:Selection; - isBackwards():boolean; - refresh(checkForChanges?:boolean):any; - toHtml():string; - getAllRanges():RangyRange[]; - getNativeTextRange():TextRange; - setSingleRange(range:RangyRange):any; - setRanges(ranges:RangyRange[]):any; - getBookmark(containerNode:Node):any; - moveToBookmark(bookmark:Object):any; - saveRanges():Object; - restoreRanges(saved:Object):any; - detach():any; - inspect():string; -} - -interface RangyStatic { - createNativeRange(doc?:Document|Window|HTMLIFrameElement):TextRange|Range; - createRange(doc?:Document|Window|HTMLIFrameElement):RangyRange; - createRangyRange(doc?:Document|Window|HTMLIFrameElement):RangyRange; - getNativeSelection(win?:Window):Selection; - getSelection():RangySelection; - addInitListener(listener:(rangy:RangyStatic) => void):any; - shim():any; - createMissingNativeApi():any; - initialized:boolean; - supported:boolean; -} - -declare var rangy:RangyStatic; diff --git a/rangy/tsconfig.json b/rangy/tsconfig.json new file mode 100644 index 0000000000..0f11098f32 --- /dev/null +++ b/rangy/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "rangy-tests.ts" + ] +} \ No newline at end of file diff --git a/raphael/raphael.d.ts b/raphael/index.d.ts similarity index 100% rename from raphael/raphael.d.ts rename to raphael/index.d.ts diff --git a/raphael/raphael-tests.ts b/raphael/raphael-tests.ts index 4fcc7c357e..ea8dd7f742 100644 --- a/raphael/raphael-tests.ts +++ b/raphael/raphael-tests.ts @@ -1,4 +1,4 @@ -/// + var paper = Raphael(10, 50, 320, 200); var circle = paper.circle(50, 40, 10); diff --git a/raphael/raphael-tests.ts.tscparams b/raphael/raphael-tests.ts.tscparams deleted file mode 100644 index 8b13789179..0000000000 --- a/raphael/raphael-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/raphael/tsconfig.json b/raphael/tsconfig.json new file mode 100644 index 0000000000..ff983b9550 --- /dev/null +++ b/raphael/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "raphael-tests.ts" + ] +} \ No newline at end of file diff --git a/rappid/index.d.ts b/rappid/index.d.ts new file mode 100644 index 0000000000..5cbf07b995 --- /dev/null +++ b/rappid/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for Rappid 1.5 +// Project: http://jointjs.com/about-rappid +// Definitions by: Ewout Van Gossum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace joint { + namespace ui { + interface Handle { + name: string; + position: string; + icon: string; + } + + class SelectionView extends Backbone.Model { + paper: joint.dia.Paper; + graph: joint.dia.Graph; + model: Backbone.Collection; + + constructor(opt: { + paper: joint.dia.Paper; + graph: joint.dia.Graph; + model: Backbone.Collection + }); + + createSelectionBox(cellView: joint.dia.CellView): void; + destroySelectionBox(cellView: joint.dia.CellView): void; + startSelecting(evt: any): void; + cancelSelection(): void; + + addHandle(handle: Handle): void; + removeHandle(name: string): void; + changeHandle(name: string, handle: Handle): void; + } + } +} diff --git a/rappid/rappid.d.ts b/rappid/rappid.d.ts deleted file mode 100644 index 2922228759..0000000000 --- a/rappid/rappid.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Type definitions for Rappid 1.5 -// Project: http://jointjs.com/about-rappid -// Definitions by: Ewout Van Gossum -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare namespace joint{ - namespace ui{ - interface Handle { - name : string; - position : string; - icon: string; - } - - class SelectionView extends Backbone.Model { - paper:joint.dia.Paper; - graph:joint.dia.Graph; - model:Backbone.Collection; - - constructor(opt:{ - paper : joint.dia.Paper; - graph : joint.dia.Graph; - model : Backbone.Collection - }); - - createSelectionBox(cellView:joint.dia.CellView) : void; - destroySelectionBox(cellView:joint.dia.CellView) : void; - startSelecting(evt:any) : void; - cancelSelection() : void; - - addHandle(handle:Handle) : void; - removeHandle(name:string) : void; - changeHandle(name:string, handle:Handle) : void; - } - } -} diff --git a/rappid/tsconfig.json b/rappid/tsconfig.json new file mode 100644 index 0000000000..37bc7dfbae --- /dev/null +++ b/rappid/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/ratelimiter/index.d.ts b/ratelimiter/index.d.ts new file mode 100644 index 0000000000..5bf3e33bbb --- /dev/null +++ b/ratelimiter/index.d.ts @@ -0,0 +1,58 @@ +// Type definitions for ratelimiter 2.1.1 +// Project: https://github.com/tj/node-ratelimiter +// Definitions by: Aya Morisawa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +import { RedisClient } from 'redis'; + +interface LimiterOption { + /** + * The identifier to limit against (typically a user id) + */ + id: string; + + /** + * Redis connection instance + */ + db: RedisClient; + + /** + * Max requests within duration + */ + max?: number; + + /** + * Duration of limit in milliseconds + */ + duration?: number; +} + +interface LimiterInfo { + /** + * max value + */ + total: number; + + /** + * Number of calls left in current duration without decreasing current get + */ + remaining: number; + + /** + * Time in milliseconds until the end of current duration + */ + reset: number; +} + +declare class Limiter { + constructor(opts: LimiterOption); + + inspect(): string; + + get(fn: (err: any, info: LimiterInfo) => void): void; +} + +declare namespace Limiter { } + +export = Limiter; diff --git a/ratelimiter/ratelimiter-tests.ts b/ratelimiter/ratelimiter-tests.ts index 7c2f03eec2..4face1baa9 100644 --- a/ratelimiter/ratelimiter-tests.ts +++ b/ratelimiter/ratelimiter-tests.ts @@ -1,11 +1,9 @@ -/// -/// import * as redis from 'redis'; import * as Limiter from 'ratelimiter'; -let id: string; -let db: redis.RedisClient; +declare let id: string; +declare let db: redis.RedisClient; let limit = new Limiter({ id: id, db: db }); const str: string = limit.inspect(); diff --git a/ratelimiter/ratelimiter.d.ts b/ratelimiter/ratelimiter.d.ts deleted file mode 100644 index 4ea3a43fa1..0000000000 --- a/ratelimiter/ratelimiter.d.ts +++ /dev/null @@ -1,61 +0,0 @@ -// Type definitions for ratelimiter 2.1.1 -// Project: https://github.com/tj/node-ratelimiter -// Definitions by: Aya Morisawa -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "ratelimiter" { - import { RedisClient } from 'redis'; - - interface LimiterOption { - /** - * The identifier to limit against (typically a user id) - */ - id: string; - - /** - * Redis connection instance - */ - db: RedisClient; - - /** - * Max requests within duration - */ - max?: number; - - /** - * Duration of limit in milliseconds - */ - duration?: number; - } - - interface LimiterInfo { - /** - * max value - */ - total: number; - - /** - * Number of calls left in current duration without decreasing current get - */ - remaining: number; - - /** - * Time in milliseconds until the end of current duration - */ - reset: number; - } - - class Limiter { - constructor(opts: LimiterOption); - - inspect(): string; - - get(fn: (err: any, info: LimiterInfo) => void): void; - } - - namespace Limiter {} - - export = Limiter; -} diff --git a/ratelimiter/tsconfig.json b/ratelimiter/tsconfig.json new file mode 100644 index 0000000000..3b88bfba3e --- /dev/null +++ b/ratelimiter/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "ratelimiter-tests.ts" + ] +} \ No newline at end of file diff --git a/raty/index.d.ts b/raty/index.d.ts new file mode 100644 index 0000000000..146671e3f9 --- /dev/null +++ b/raty/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for jQuery.raty 2.7.0 +// Project: https://github.com/wbotelhos/raty +// Definitions by: Matt Wheatley +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQuery { + raty(): JQuery; + raty(options: JQueryRatyOptions): JQuery; + raty(method: string, parameter: any): any; + raty(method: 'score'): number; + raty(method: 'score', score: number): void; + raty(method: 'click', star: number): void; + raty(method: 'readonly', on: boolean): void; + raty(method: 'cancel', on: boolean): void; + raty(method: 'reload'): void; + raty(method: 'set', options: JQueryRatyOptions): void; + raty(method: 'destroy'): JQuery; + raty(method: 'move', number: number): void; +} + +interface JQueryRatyOptions { + cancel?: boolean, + cancelClass?: string, + cancelHint?: string, + cancelOff?: string, + cancelOn?: string, + cancelPlace?: string, + click?: (score: number, event: JQueryEventObject) => void, + half?: boolean, + halfShow?: boolean, + hints?: string[], + iconRange?: any[][], + mouseout?: (score: number, event: JQueryEventObject) => void, + mouseover?: (score: number, event: JQueryEventObject) => void, + noRatedMsg?: string, + number?: number, + numberMax?: number, + path?: string, + precision?: boolean, + readOnly?: boolean, + round?: JQueryRatyRoundingOptions, + score?: number, + scoreName?: string, + single?: boolean, + space?: boolean, + starHalf?: string, + starOff?: string, + starOn?: string, + target?: string, + targetFormat?: string, + targetKeep?: boolean, + targetScore?: string, + targetText?: string, + targetType?: string, + starType?: string, +} + +interface JQueryRatyRoundingOptions { + down: number, + full: number, + up: number, +} diff --git a/raty/raty-tests.ts b/raty/raty-tests.ts index 8e5cec93ca..bb2f731038 100644 --- a/raty/raty-tests.ts +++ b/raty/raty-tests.ts @@ -1,5 +1,5 @@ -/// -/// +/// + var $element: JQuery = $('
'); diff --git a/raty/raty.d.ts b/raty/raty.d.ts deleted file mode 100644 index c9999589c1..0000000000 --- a/raty/raty.d.ts +++ /dev/null @@ -1,64 +0,0 @@ -// Type definitions for jQuery.raty 2.7.0 -// Project: https://github.com/wbotelhos/raty -// Definitions by: Matt Wheatley -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -interface JQuery { - raty(): JQuery; - raty(options: JQueryRatyOptions): JQuery; - raty(method: string, parameter: any): any; - raty(method: 'score'): number; - raty(method: 'score', score: number): void; - raty(method: 'click', star: number): void; - raty(method: 'readonly', on: boolean): void; - raty(method: 'cancel', on: boolean): void; - raty(method: 'reload'): void; - raty(method: 'set', options: JQueryRatyOptions): void; - raty(method: 'destroy'): JQuery; - raty(method: 'move', number: number): void; -} - -interface JQueryRatyOptions { - cancel?: boolean, - cancelClass?: string, - cancelHint?: string, - cancelOff?: string, - cancelOn?: string, - cancelPlace?: string, - click?: (score: number, event: JQueryEventObject) => void, - half?: boolean, - halfShow?: boolean, - hints?: string[], - iconRange?: any[][], - mouseout?: (score: number, event: JQueryEventObject) => void, - mouseover?: (score: number, event: JQueryEventObject) => void, - noRatedMsg?: string, - number?: number, - numberMax?: number, - path?: string, - precision?: boolean, - readOnly?: boolean, - round?: JQueryRatyRoundingOptions, - score?: number, - scoreName?: string, - single?: boolean, - space?: boolean, - starHalf?: string, - starOff?: string, - starOn?: string, - target?: string, - targetFormat?: string, - targetKeep?: boolean, - targetScore?: string, - targetText?: string, - targetType?: string, - starType?: string, -} - -interface JQueryRatyRoundingOptions { - down: number, - full: number, - up: number, -} diff --git a/raty/tsconfig.json b/raty/tsconfig.json new file mode 100644 index 0000000000..0332a04a33 --- /dev/null +++ b/raty/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "raty-tests.ts" + ] +} \ No newline at end of file diff --git a/ravenjs/ravenjs.d.ts b/raven-js/index.d.ts similarity index 100% rename from ravenjs/ravenjs.d.ts rename to raven-js/index.d.ts diff --git a/ravenjs/ravenjs-tests.ts b/raven-js/ravenjs-tests.ts similarity index 96% rename from ravenjs/ravenjs-tests.ts rename to raven-js/ravenjs-tests.ts index db0ddd6932..89dbf1f00d 100644 --- a/ravenjs/ravenjs-tests.ts +++ b/raven-js/ravenjs-tests.ts @@ -1,4 +1,4 @@ -/// + import RavenJS from 'raven-js'; diff --git a/raven-js/tsconfig.json b/raven-js/tsconfig.json new file mode 100644 index 0000000000..8a2ae823dd --- /dev/null +++ b/raven-js/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "ravenjs-tests.ts" + ] +} \ No newline at end of file diff --git a/raygun4js/index.d.ts b/raygun4js/index.d.ts new file mode 100644 index 0000000000..b75684474e --- /dev/null +++ b/raygun4js/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for raygun4js 1.18.3 +// Project: https://github.com/MindscapeHQ/raygun4js +// Definitions by: Brian Surowiec +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace raygun { + + // https://github.com/MindscapeHQ/raygun4js/blob/c7d8880045214ab6d403d5cc613c207f696a3cdd/src/raygun.js#L533-539 + interface IStackTrace { + LineNumber: number; + ColumnNumber: number; + ClassName: string; + FileName: string; + MethodName: string; + } + + // https://github.com/MindscapeHQ/raygun4js/blob/c7d8880045214ab6d403d5cc613c207f696a3cdd/src/raygun.js#L598-637 + interface IPayload { + OccurredOn: Date; + Details: { + Error: { + ClassName: string; + Message: string; + StackTrace: IStackTrace[]; + }; + Environment: { + UtcOffset: number; + 'User-Language': string; + 'Document-Mode': number; + 'Browser-Width': number; + 'Browser-Height': number; + 'Screen-Width': number; + 'Screen-Height': number; + 'Color-Depth': number; + Browser: string; + 'Browser-Name': string; + 'Browser-Version': string; + Platform: string; + }; + Client: { + Name: string; + Version: string; + }; + UserCustomData: any; + Tags: string[]; + Request: { + Url: string; + QueryString: string; + Headers: { + 'User-Agent': string; + Referer: string; + Host: string; + }; + }; + Version: string; + }; + } + + // https://github.com/MindscapeHQ/raygun4js/blob/c7d8880045214ab6d403d5cc613c207f696a3cdd/src/raygun.js#L61-82 + interface IRaygunOptions { + allowInsecureSubmissions?: boolean; + ignoreAjaxAbort?: boolean; + ignoreAjaxError?: boolean; + disableAnonymousUserTracking?: boolean; + excludedHostnames?: boolean; + excludedUserAgents?: boolean; + wrapAsynchronousCallbacks?: boolean; + debugMode?: boolean; + ignore3rdPartyErrors?: boolean; + } + + interface RaygunStatic { + noConflict(): RaygunStatic; + constructNewRaygun(): RaygunStatic; + init(apiKey: string, options?: IRaygunOptions, customdata?: any): RaygunStatic; + withCustomData(customdata: any): RaygunStatic; + withTags(tags: string[]): RaygunStatic; + attach(): RaygunStatic; + detach(): RaygunStatic; + send(e: Error, customData?: any, tags?: string[]): RaygunStatic; + setUser(user: string, isAnonymous?: boolean, email?: string, fullName?: string, firstName?: string, uuid?: string): RaygunStatic; + resetAnonymousUser(): void; + setVersion(version: string): RaygunStatic; + saveIfOffline(enableOffline: boolean): RaygunStatic; + filterSensitiveData(filteredKeys: string[]): RaygunStatic; + setFilterScope(scope: string): RaygunStatic; + whitelistCrossOriginDomains(whitelist: string[]): RaygunStatic; + onBeforeSend(callback: (payload: IPayload) => IPayload): RaygunStatic; + } + +} + +declare var Raygun: raygun.RaygunStatic; + +declare module 'raygun4js' { + export = Raygun; +} diff --git a/raygun4js/raygun4js-tests.ts b/raygun4js/raygun4js-tests.ts index 56577765ce..f3c3c9c1ed 100644 --- a/raygun4js/raygun4js-tests.ts +++ b/raygun4js/raygun4js-tests.ts @@ -1,6 +1,4 @@ -/// - -var client: raygun.RaygunStatic = Raygun.noConflict(); +var client: raygun.RaygunStatic = Raygun.noConflict(); var newClient: raygun.RaygunStatic = client.constructNewRaygun(); diff --git a/raygun4js/raygun4js.d.ts b/raygun4js/raygun4js.d.ts deleted file mode 100644 index c1a294bb31..0000000000 --- a/raygun4js/raygun4js.d.ts +++ /dev/null @@ -1,97 +0,0 @@ -// Type definitions for raygun4js 1.18.3 -// Project: https://github.com/MindscapeHQ/raygun4js -// Definitions by: Brian Surowiec -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace raygun { - - // https://github.com/MindscapeHQ/raygun4js/blob/c7d8880045214ab6d403d5cc613c207f696a3cdd/src/raygun.js#L533-539 - interface IStackTrace { - LineNumber: number; - ColumnNumber: number; - ClassName: string; - FileName: string; - MethodName: string; - } - - // https://github.com/MindscapeHQ/raygun4js/blob/c7d8880045214ab6d403d5cc613c207f696a3cdd/src/raygun.js#L598-637 - interface IPayload { - OccurredOn: Date; - Details: { - Error: { - ClassName: string; - Message: string; - StackTrace: IStackTrace[]; - }; - Environment: { - UtcOffset: number; - 'User-Language': string; - 'Document-Mode': number; - 'Browser-Width': number; - 'Browser-Height': number; - 'Screen-Width': number; - 'Screen-Height': number; - 'Color-Depth': number; - Browser: string; - 'Browser-Name': string; - 'Browser-Version': string; - Platform: string; - }; - Client: { - Name: string; - Version: string; - }; - UserCustomData: any; - Tags: string[]; - Request: { - Url: string; - QueryString: string; - Headers: { - 'User-Agent': string; - Referer: string; - Host: string; - }; - }; - Version: string; - }; - } - - // https://github.com/MindscapeHQ/raygun4js/blob/c7d8880045214ab6d403d5cc613c207f696a3cdd/src/raygun.js#L61-82 - interface IRaygunOptions { - allowInsecureSubmissions?: boolean; - ignoreAjaxAbort?: boolean; - ignoreAjaxError?: boolean; - disableAnonymousUserTracking?: boolean; - excludedHostnames?: boolean; - excludedUserAgents?: boolean; - wrapAsynchronousCallbacks?: boolean; - debugMode?: boolean; - ignore3rdPartyErrors?: boolean; - } - - interface RaygunStatic { - noConflict(): RaygunStatic; - constructNewRaygun(): RaygunStatic; - init(apiKey: string, options?: IRaygunOptions, customdata?: any): RaygunStatic; - withCustomData(customdata: any): RaygunStatic; - withTags(tags: string[]): RaygunStatic; - attach(): RaygunStatic; - detach(): RaygunStatic; - send(e: Error, customData?: any, tags?: string[]): RaygunStatic; - setUser(user: string, isAnonymous?: boolean, email?: string, fullName?: string, firstName?: string, uuid?: string): RaygunStatic; - resetAnonymousUser(): void; - setVersion(version: string): RaygunStatic; - saveIfOffline(enableOffline: boolean): RaygunStatic; - filterSensitiveData(filteredKeys: string[]): RaygunStatic; - setFilterScope(scope: string): RaygunStatic; - whitelistCrossOriginDomains(whitelist: string[]): RaygunStatic; - onBeforeSend(callback: (payload: IPayload) => IPayload): RaygunStatic; - } - -} - -declare var Raygun: raygun.RaygunStatic; - -declare module 'Raygun' { - export = Raygun; -} diff --git a/raygun4js/tsconfig.json b/raygun4js/tsconfig.json new file mode 100644 index 0000000000..b14fff0f31 --- /dev/null +++ b/raygun4js/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "raygun4js-tests.ts" + ] +} \ No newline at end of file diff --git a/rc-select/index.d.ts b/rc-select/index.d.ts new file mode 100644 index 0000000000..b3decc23d8 --- /dev/null +++ b/rc-select/index.d.ts @@ -0,0 +1,65 @@ +// Type definitions for React Select v5.9.0 +// Project: https://github.com/react-component/select +// Definitions by: Denis Tirilis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import Select = RcSelect.Select; +import Option = RcSelect.Option; +import OptGroup = RcSelect.OptGroup; + +export default Select; +export { + Option, + OptGroup +}; + +declare namespace RcSelect { + interface SelectProps { + className?: string; + prefixCls?: string; + animation?: string; + transitionName?: string; + choiceTransitionName?: string; + dropdownMatchSelectWidth?: boolean; + dropdownClassName?: string; + dropdownStyle?: { [key: string]: string }; + dropdownMenuStyle?: { [key: string]: string }; + notFoundContent?: string; + showSearch?: boolean; + allowClear?: boolean; + tags?: boolean; + maxTagTextLength?: number; + combobox?: boolean; + multiple?: boolean; + disabled?: boolean; + filterOption?: boolean; + optionFilterProp?: string; + optionLabelProp?: string; + defaultValue?: string | Array; + value?: string | Array; + onChange?: (value: string, label: string) => void; + onSearch?: Function; + onSelect?: (value: string, ontion: Option) => void; + onDeselect?: Function; + defaultLabel?: string | Array; + defaultActiveFirstOption?: boolean; + getPopupContainer?: (trigger: Node) => Node; + } + export class Select extends React.Component { } + interface OptionProps { + className?: string; + disabled?: boolean; + key?: string; + value?: string; + } + export class Option extends React.Component { } + + interface OptGroupProps { + label?: string | React.ReactElement; + key?: string; + value?: string; + } + export class OptGroup extends React.Component { } +} diff --git a/rc-select/rc-select-tests.ts b/rc-select/rc-select-tests.ts index 94cb1541e8..f2ec85ae09 100644 --- a/rc-select/rc-select-tests.ts +++ b/rc-select/rc-select-tests.ts @@ -1,8 +1,8 @@ -/// -/// + +/// import React = require('react'); -import Select = require('rc-select'); +import RcSelect = require('rc-select'); class Component extends React.Component { @@ -19,7 +19,7 @@ class Component extends React.Component { console.log('input changed'); } - private defaultSelectProps: RcSelect.SelectProps = { + private defaultSelectProps = { className: "my-select", prefixCls: "prefix", animation: "slide-up", @@ -44,28 +44,28 @@ class Component extends React.Component { defaultActiveFirstOption: false }; - private defaultOptGroupProps: RcSelect.OptGroupProps = { + private defaultOptGroupProps = { label: "Option group", key: "option-group-0", value: "option-group-0" }; - private defaultOptionProps: RcSelect.OptionProps = { + private defaultOptionProps = { className: "option", disabled: true, key: "option-0", value: "option-0" }; - private createOptions(count: number): React.ReactElement[] { - let options: React.ReactElement[] = []; + private createOptions(count: number) { + let options : any = []; for (let i = 0; i < count; i++) { let props = this.defaultOptionProps; props.key = `option-${i}`; props.value = `option-${i}`; - options.push(React.createElement(Select.Option, props)); + options.push(React.createElement(RcSelect.Option, props)); } return options; @@ -73,11 +73,11 @@ class Component extends React.Component { render() { - let options: React.ReactElement[] = this.createOptions(10); + let options = this.createOptions(10); - let optionGroup: React.ReactElement = React.createElement(Select.OptGroup, this.defaultOptGroupProps, options); + let optionGroup = React.createElement(RcSelect.OptGroup, this.defaultOptGroupProps, options); - let select: React.ReactElement = React.createElement(Select.default, this.defaultSelectProps, optionGroup); + let select = React.createElement(RcSelect.default, this.defaultSelectProps, optionGroup); return select; } diff --git a/rc-select/rc-select.d.ts b/rc-select/rc-select.d.ts deleted file mode 100644 index 8b9ca6978c..0000000000 --- a/rc-select/rc-select.d.ts +++ /dev/null @@ -1,67 +0,0 @@ -// Type definitions for React Select v5.9.0 -// Project: https://github.com/react-component/select -// Definitions by: Denis Tirilis -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace RcSelect { - import React = __React; - interface SelectProps { - className?: string; - prefixCls?: string; - animation?: string; - transitionName?: string; - choiceTransitionName?: string; - dropdownMatchSelectWidth?: boolean; - dropdownClassName?: string; - dropdownStyle?: { [key: string]: string }; - dropdownMenuStyle?: { [key: string]: string }; - notFoundContent?: string; - showSearch?: boolean; - allowClear?: boolean; - tags?: boolean; - maxTagTextLength?: number; - combobox?: boolean; - multiple?: boolean; - disabled?: boolean; - filterOption?: boolean; - optionFilterProp?: string; - optionLabelProp?: string; - defaultValue?: string | Array; - value?: string | Array; - onChange?: (value: string, label: string) => void; - onSearch?: Function; - onSelect?: (value: string, ontion: Option) => void; - onDeselect?: Function; - defaultLabel?: string | Array; - defaultActiveFirstOption?: boolean; - getPopupContainer?: (trigger: Node) => Node; - } - export class Select extends React.Component { } - interface OptionProps { - className?: string; - disabled?: boolean; - key?: string; - value?: string; - } - export class Option extends React.Component { } - - interface OptGroupProps { - label?: string | React.ReactElement; - key?: string; - value?: string; - } - export class OptGroup extends React.Component { } -} -declare module 'rc-select' { - import Select = RcSelect.Select; - import Option = RcSelect.Option; - import OptGroup = RcSelect.OptGroup; - - export default Select; - export { - Option, - OptGroup - }; -} diff --git a/rc-select/tsconfig.json b/rc-select/tsconfig.json new file mode 100644 index 0000000000..e98b9fea45 --- /dev/null +++ b/rc-select/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "rc-select-tests.ts" + ] +} \ No newline at end of file diff --git a/rcloader/index.d.ts b/rcloader/index.d.ts new file mode 100644 index 0000000000..72e3f1f8cc --- /dev/null +++ b/rcloader/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for rcloader +// Project: https://github.com/spalger/rcloader +// Definitions by: Panu Horsmalahti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +interface Options { + [property: string]: any; + lookup?: boolean; +} + +declare class RcLoader { + constructor(configfilename: string, options: string | Options); + for(path: string, callback?: (error: any, fileOpts: any) => void): void; +} + +export = RcLoader; diff --git a/rcloader/rcloader-tests.ts b/rcloader/rcloader-tests.ts index 16ade8c555..f36f61c025 100644 --- a/rcloader/rcloader-tests.ts +++ b/rcloader/rcloader-tests.ts @@ -1,4 +1,3 @@ -/// import RcLoader = require("rcloader"); diff --git a/rcloader/rcloader.d.ts b/rcloader/rcloader.d.ts deleted file mode 100644 index edba798419..0000000000 --- a/rcloader/rcloader.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Type definitions for rcloader -// Project: https://github.com/spalger/rcloader -// Definitions by: Panu Horsmalahti -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare module "rcloader" { - interface Options { - [property: string]: any; - lookup?: boolean; - } - - class RcLoader { - constructor(configfilename: string, options: string | Options); - for(path: string, callback?: (error: any, fileOpts: any) => void): void; - } - - export = RcLoader; -} diff --git a/rcloader/tsconfig.json b/rcloader/tsconfig.json new file mode 100644 index 0000000000..1b5d8e4e1d --- /dev/null +++ b/rcloader/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "rcloader-tests.ts" + ] +} \ No newline at end of file diff --git a/react-addons-create-fragment/index.d.ts b/react-addons-create-fragment/index.d.ts new file mode 100644 index 0000000000..c060e67715 --- /dev/null +++ b/react-addons-create-fragment/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for React v0.14 (react-addons-create-fragment) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign , Microsoft +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as React from 'react'; + +export = createFragment; + +declare function createFragment(object: { [key: string]: React.ReactNode }): React.ReactFragment; diff --git a/react-addons-create-fragment/tsconfig.json b/react-addons-create-fragment/tsconfig.json new file mode 100644 index 0000000000..98c460c2f5 --- /dev/null +++ b/react-addons-create-fragment/tsconfig.json @@ -0,0 +1,16 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/react-addons-css-transition-group/index.d.ts b/react-addons-css-transition-group/index.d.ts new file mode 100644 index 0000000000..ce1f155979 --- /dev/null +++ b/react-addons-css-transition-group/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for React v0.14 (react-addons-css-transition-group) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign , Microsoft +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { ComponentClass } from 'react'; +import { TransitionGroupProps } from 'react-addons-transition-group'; + +declare var CSSTransitionGroup: CSSTransitionGroup; +type CSSTransitionGroup = ComponentClass; +export = CSSTransitionGroup; + +interface CSSTransitionGroupTransitionName { + enter: string; + enterActive?: string; + leave: string; + leaveActive?: string; + appear?: string; + appearActive?: string; +} + +interface CSSTransitionGroupProps extends TransitionGroupProps { + transitionName: string | CSSTransitionGroupTransitionName; + transitionAppear?: boolean; + transitionAppearTimeout?: number; + transitionEnter?: boolean; + transitionEnterTimeout?: number; + transitionLeave?: boolean; + transitionLeaveTimeout?: number; +} diff --git a/react-addons-css-transition-group/tsconfig.json b/react-addons-css-transition-group/tsconfig.json new file mode 100644 index 0000000000..98c460c2f5 --- /dev/null +++ b/react-addons-css-transition-group/tsconfig.json @@ -0,0 +1,16 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/react-addons-linked-state-mixin/index.d.ts b/react-addons-linked-state-mixin/index.d.ts new file mode 100644 index 0000000000..a7ec5ab123 --- /dev/null +++ b/react-addons-linked-state-mixin/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for React v0.14 (react-addons-linked-state-mixin) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign , Microsoft +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Mixin } from 'react'; + +declare var LinkedStateMixin: LinkedStateMixin.LinkedStateMixin; +type LinkedStateMixin = LinkedStateMixin.LinkedStateMixin; +export = LinkedStateMixin; + +declare namespace LinkedStateMixin { + export interface ReactLink { + value: T; + requestChange(newValue: T): void; + } + + export interface LinkedStateMixin extends Mixin { + linkState(key: string): ReactLink; + } +} + +declare module 'react' { + interface HTMLAttributes { + checkedLink?: LinkedStateMixin.ReactLink; + valueLink?: LinkedStateMixin.ReactLink; + } +} diff --git a/react-addons-linked-state-mixin/tsconfig.json b/react-addons-linked-state-mixin/tsconfig.json new file mode 100644 index 0000000000..98c460c2f5 --- /dev/null +++ b/react-addons-linked-state-mixin/tsconfig.json @@ -0,0 +1,16 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/react-addons-perf/index.d.ts b/react-addons-perf/index.d.ts new file mode 100644 index 0000000000..c3499e9a52 --- /dev/null +++ b/react-addons-perf/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for React v0.14 (react-addons-perf) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign , Microsoft +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Perf; + +interface ComponentPerfContext { + current: string; + owner: string; +} + +interface NumericPerfContext { + [key: string]: number; +} + +interface Measurements { + exclusive: NumericPerfContext; + inclusive: NumericPerfContext; + render: NumericPerfContext; + counts: NumericPerfContext; + writes: NumericPerfContext; + displayNames: { + [key: string]: ComponentPerfContext; + }; + totalTime: number; +} + +declare namespace Perf { + export function start(): void; + export function stop(): void; + export function printInclusive(measurements: Measurements[]): void; + export function printExclusive(measurements: Measurements[]): void; + export function printWasted(measurements: Measurements[]): void; + export function printDOM(measurements: Measurements[]): void; + export function getLastMeasurements(): Measurements[]; +} diff --git a/react-addons-perf/tsconfig.json b/react-addons-perf/tsconfig.json new file mode 100644 index 0000000000..98c460c2f5 --- /dev/null +++ b/react-addons-perf/tsconfig.json @@ -0,0 +1,16 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/react-addons-pure-render-mixin/index.d.ts b/react-addons-pure-render-mixin/index.d.ts new file mode 100644 index 0000000000..7e732b583b --- /dev/null +++ b/react-addons-pure-render-mixin/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for React v0.14 (react-addons-pure-render-mixin) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign , Microsoft +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Mixin } from 'react'; + +declare var PureRenderMixin: PureRenderMixin; +export = PureRenderMixin; + +interface PureRenderMixin extends Mixin { } diff --git a/react-addons-pure-render-mixin/tsconfig.json b/react-addons-pure-render-mixin/tsconfig.json new file mode 100644 index 0000000000..98c460c2f5 --- /dev/null +++ b/react-addons-pure-render-mixin/tsconfig.json @@ -0,0 +1,16 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/react-addons-shallow-compare/index.d.ts b/react-addons-shallow-compare/index.d.ts new file mode 100644 index 0000000000..eeb4935176 --- /dev/null +++ b/react-addons-shallow-compare/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for React v0.14 (react-addons-css-transition-group) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign , Microsoft +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Component } from 'react'; + +declare function shallowCompare( + component: Component, + nextProps: P, + nextState: S): boolean; + +export = shallowCompare; diff --git a/react-addons-shallow-compare/tsconfig.json b/react-addons-shallow-compare/tsconfig.json new file mode 100644 index 0000000000..98c460c2f5 --- /dev/null +++ b/react-addons-shallow-compare/tsconfig.json @@ -0,0 +1,16 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/react-addons-test-utils/index.d.ts b/react-addons-test-utils/index.d.ts new file mode 100644 index 0000000000..091c5d5df7 --- /dev/null +++ b/react-addons-test-utils/index.d.ts @@ -0,0 +1,168 @@ +// Type definitions for React v0.14 (react-addons-test-utils) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign , Microsoft +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { AbstractView, Component, ComponentClass, + ReactElement, ReactInstance, ClassType, + DOMElement, SFCElement, CElement, + ReactHTMLElement, DOMAttributes, SFC } from 'react'; + +export = TestUtils; + +declare namespace TestUtils { + export interface OptionalEventProperties { + bubbles?: boolean; + cancelable?: boolean; + currentTarget?: EventTarget; + defaultPrevented?: boolean; + eventPhase?: number; + isTrusted?: boolean; + nativeEvent?: Event; + preventDefault?(): void; + stopPropagation?(): void; + target?: EventTarget; + timeStamp?: Date; + type?: string; + } + + export interface SyntheticEventData extends OptionalEventProperties { + altKey?: boolean; + button?: number; + buttons?: number; + clientX?: number; + clientY?: number; + changedTouches?: TouchList; + charCode?: boolean; + clipboardData?: DataTransfer; + ctrlKey?: boolean; + deltaMode?: number; + deltaX?: number; + deltaY?: number; + deltaZ?: number; + detail?: number; + getModifierState?(key: string): boolean; + key?: string; + keyCode?: number; + locale?: string; + location?: number; + metaKey?: boolean; + pageX?: number; + pageY?: number; + relatedTarget?: EventTarget; + repeat?: boolean; + screenX?: number; + screenY?: number; + shiftKey?: boolean; + targetTouches?: TouchList; + touches?: TouchList; + view?: AbstractView; + which?: number; + } + + export interface EventSimulator { + (element: Element | Component, eventData?: SyntheticEventData): void; + } + + export interface MockedComponentClass { + new(): any; + } + + export interface ShallowRenderer { + getRenderOutput>(): E; + getRenderOutput(): ReactElement; + render(element: ReactElement, context?: any): void; + unmount(): void; + } + + export namespace Simulate { + export var blur: EventSimulator; + export var change: EventSimulator; + export var click: EventSimulator; + export var copy: EventSimulator; + export var cut: EventSimulator; + export var doubleClick: EventSimulator; + export var drag: EventSimulator; + export var dragEnd: EventSimulator; + export var dragEnter: EventSimulator; + export var dragExit: EventSimulator; + export var dragLeave: EventSimulator; + export var dragOver: EventSimulator; + export var dragStart: EventSimulator; + export var drop: EventSimulator; + export var focus: EventSimulator; + export var input: EventSimulator; + export var keyDown: EventSimulator; + export var keyPress: EventSimulator; + export var keyUp: EventSimulator; + export var mouseDown: EventSimulator; + export var mouseEnter: EventSimulator; + export var mouseLeave: EventSimulator; + export var mouseMove: EventSimulator; + export var mouseOut: EventSimulator; + export var mouseOver: EventSimulator; + export var mouseUp: EventSimulator; + export var paste: EventSimulator; + export var scroll: EventSimulator; + export var submit: EventSimulator; + export var touchCancel: EventSimulator; + export var touchEnd: EventSimulator; + export var touchMove: EventSimulator; + export var touchStart: EventSimulator; + export var wheel: EventSimulator; + } + + export function renderIntoDocument( + element: DOMElement): T; + export function renderIntoDocument( + element: SFCElement): void; + export function renderIntoDocument>( + element: CElement): T; + export function renderIntoDocument

( + element: ReactElement

): Component | Element | void; + + export function mockComponent( + mocked: MockedComponentClass, mockTagName?: string): typeof TestUtils; + + export function isElementOfType( + element: ReactElement, type: string): element is ReactHTMLElement; + export function isElementOfType

( + element: ReactElement, type: string): element is DOMElement; + export function isElementOfType

( + element: ReactElement, type: SFC

): element is SFCElement

; + export function isElementOfType, C extends ComponentClass

>( + element: ReactElement, type: ClassType): element is CElement; + + export function isDOMComponent(instance: ReactInstance): instance is Element; + export function isCompositeComponent(instance: ReactInstance): instance is Component; + export function isCompositeComponentWithType, C extends ComponentClass>( + instance: ReactInstance, type: ClassType): T; + + export function findAllInRenderedTree( + root: Component, + fn: (i: ReactInstance) => boolean): ReactInstance[]; + + export function scryRenderedDOMComponentsWithClass( + root: Component, + className: string): Element[]; + export function findRenderedDOMComponentWithClass( + root: Component, + className: string): Element; + + export function scryRenderedDOMComponentsWithTag( + root: Component, + tagName: string): Element[]; + export function findRenderedDOMComponentWithTag( + root: Component, + tagName: string): Element; + + export function scryRenderedComponentsWithType, C extends ComponentClass<{}>>( + root: Component, + type: ClassType): T[]; + + export function findRenderedComponentWithType, C extends ComponentClass<{}>>( + root: Component, + type: ClassType): T; + + export function createRenderer(): ShallowRenderer; +} diff --git a/react-addons-test-utils/tsconfig.json b/react-addons-test-utils/tsconfig.json new file mode 100644 index 0000000000..98c460c2f5 --- /dev/null +++ b/react-addons-test-utils/tsconfig.json @@ -0,0 +1,16 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/react-addons-transition-group/index.d.ts b/react-addons-transition-group/index.d.ts new file mode 100644 index 0000000000..79dcd7cf3f --- /dev/null +++ b/react-addons-transition-group/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for React v0.14 (react-addons-transition-group) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign , Microsoft +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { ReactElement, ComponentClass, ReactType } from 'react'; + +declare namespace ReactCSSTransitionGroup { + export interface TransitionGroupProps { + component?: ReactType; + className?: string; + childFactory?: (child: ReactElement) => ReactElement; + } +} +declare var ReactCSSTransitionGroup : ComponentClass; +export = ReactCSSTransitionGroup; diff --git a/react-addons-transition-group/tsconfig.json b/react-addons-transition-group/tsconfig.json new file mode 100644 index 0000000000..98c460c2f5 --- /dev/null +++ b/react-addons-transition-group/tsconfig.json @@ -0,0 +1,16 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/react-addons-update/index.d.ts b/react-addons-update/index.d.ts new file mode 100644 index 0000000000..bc65dcbfa7 --- /dev/null +++ b/react-addons-update/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for React v0.14 (react-addons-update) +// Project: http://facebook.github.io/react/ +// Definitions by: Asana , AssureSign , Microsoft +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as React from 'react'; + +export = React.__Addons.update; + +declare module 'react' { + interface UpdateSpecCommand { + $set?: any; + $merge?: {}; + $apply?(value: any): any; + } + + interface UpdateSpecPath { + [key: string]: UpdateSpec; + } + + type UpdateSpec = UpdateSpecCommand | UpdateSpecPath; + + interface UpdateArraySpec extends UpdateSpecCommand { + $push?: any[]; + $unshift?: any[]; + $splice?: any[][]; + } + + namespace __Addons { + export function update(value: any[], spec: UpdateArraySpec): any[]; + export function update(value: {}, spec: UpdateSpec): any; + } +} + diff --git a/react-addons-update/tsconfig.json b/react-addons-update/tsconfig.json new file mode 100644 index 0000000000..98c460c2f5 --- /dev/null +++ b/react-addons-update/tsconfig.json @@ -0,0 +1,16 @@ +{ + "files": [ + "index.d.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + } +} \ No newline at end of file diff --git a/react-bootstrap-daterangepicker/index.d.ts b/react-bootstrap-daterangepicker/index.d.ts new file mode 100644 index 0000000000..e7d58f3747 --- /dev/null +++ b/react-bootstrap-daterangepicker/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for react-bootstrap-daterangepicker +// Project: https://github.com/skratchdot/react-bootstrap-daterangepicker +// Definitions by: Ian Ker-Seymer https://github.com/ianks +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace ReactBootstrapDaterangepicker { + export interface EventHandler { (event?: any, picker?: any): any; } + + export interface Props extends DatepickerOptions { + onShow?: EventHandler; + onHide?: EventHandler; + onShowCalendar?: EventHandler; + onHideCalendar?: EventHandler; + onApply?: EventHandler; + onCancel?: EventHandler; + onEvent?: EventHandler; + } + + export class DateRangePicker extends React.Component {} +} + +declare var DateRangePicker: typeof ReactBootstrapDaterangepicker.DateRangePicker; + +declare module "react-bootstrap-daterangepicker" { + export = DateRangePicker; +} diff --git a/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker-tests.tsx b/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker-tests.tsx index a18e430130..b34646031d 100644 --- a/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker-tests.tsx +++ b/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as DateRangePicker from "react-bootstrap-daterangepicker"; import * as React from "react"; diff --git a/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker.d.tsx b/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker.d.tsx deleted file mode 100644 index 723a35aeaa..0000000000 --- a/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker.d.tsx +++ /dev/null @@ -1,29 +0,0 @@ -// Type definitions for react-bootstrap-daterangepicker -// Project: https://github.com/skratchdot/react-bootstrap-daterangepicker -// Definitions by: Ian Ker-Seymer https://github.com/ianks -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare namespace ReactBootstrapDaterangepicker { - export interface EventHandler { (event?: any, picker?: any): any; } - - export interface Props extends DatepickerOptions { - onShow?: EventHandler; - onHide?: EventHandler; - onShowCalendar?: EventHandler; - onHideCalendar?: EventHandler; - onApply?: EventHandler; - onCancel?: EventHandler; - onEvent?: EventHandler; - } - - export class DateRangePicker extends __React.Component {} -} - -declare var DateRangePicker: typeof ReactBootstrapDaterangepicker.DateRangePicker; - -declare module "react-bootstrap-daterangepicker" { - export = DateRangePicker; -} diff --git a/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker.tsx.tscparams b/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker.tsx.tscparams deleted file mode 100644 index 36c3b9323c..0000000000 --- a/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker.tsx.tscparams +++ /dev/null @@ -1 +0,0 @@ ---noImplicitAny --module commonjs --jsx react diff --git a/react-bootstrap-daterangepicker/tsconfig.json b/react-bootstrap-daterangepicker/tsconfig.json new file mode 100644 index 0000000000..616a4a0f62 --- /dev/null +++ b/react-bootstrap-daterangepicker/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "react-bootstrap-daterangepicker-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-bootstrap-table/index.d.ts b/react-bootstrap-table/index.d.ts new file mode 100644 index 0000000000..f2c06f776b --- /dev/null +++ b/react-bootstrap-table/index.d.ts @@ -0,0 +1,114 @@ +// Type definitions for react-bootstrap-table v1.4.6 +// Project: https://github.com/AllenFang/react-bootstrap-table +// Definitions by: Frank Laub +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + + +import { ComponentClass, Props, ReactElement } from 'react'; +import { EventEmitter } from 'events'; + +interface SelectRow { + mode?: string; + bgColor?: string; + selected?: any[]; + onSelect?: Function; + onSelectAll?: Function; + clickToSelect?: boolean; + hideSelectColumn?: boolean; + clickToSelectAndEditCell?: boolean; + showOnlySelected?: boolean; +} + +interface CellEdit { + mode?: string; + blurToSave?: boolean; + afterSaveCell?: Function; +} + +interface Options { + sortName?: string; + sortOrder?: string; + afterTableComplete?: Function; + afterDeleteRow?: Function; + afterInsertRow?: Function; + afterSearch?: Function; + afterColumnFilter?: Function; + onRowClick?: Function; + page?: number; + sizePerPageList?: number[]; + sizePerPage?: number; + paginationSize?: number; + onSortChange?: Function; + onPageChange?: Function; + onSizePerPageList?: Function; + noDataText?: string; + handleConfirmDeleteRow?: Function; +} + +interface FetchInfo { + dataTotalSize?: number; +} + +interface BootstrapTableProps extends Props { + keyField?: string; + height?: string; + maxHeight?: string; + data?: any; + remote?: boolean; + striped?: boolean; + bordered?: boolean; + hover?: boolean; + condensed?: boolean; + pagination?: boolean; + searchPlaceholder?: string; + selectRow?: SelectRow; + cellEdit?: CellEdit; + insertRow?: boolean; + deleteRow?: boolean; + search?: boolean; + columnFilter?: boolean; + trClassName?: any; + options?: Options; + fetchInfo?: FetchInfo; + exportCSV?: boolean; + csvFileName?: string; +} + +interface BootstrapTable extends ComponentClass { } +declare const BootstrapTable: BootstrapTable; + +interface TableHeaderColumnProps extends Props { + dataField?: string; + dataAlign?: string; + dataSort?: boolean; + onSort?: Function; + dataFormat?: Function; + isKey?: boolean; + editable?: any; + hidden?: boolean; + className?: string; + width?: string; + sortFunc?: Function; + columnClassName?: any; + filterFormatted?: boolean; + sort?: string; +} + +interface TableHeaderColumn extends ComponentClass { } +declare const TableHeaderColumn: TableHeaderColumn; + +declare class TableDataSet extends EventEmitter { + constructor(data: any); + setData(data: any): void; + clear(): void; + getData(): any; +} + +export { +BootstrapTable, +TableHeaderColumn, +TableDataSet +} diff --git a/react-bootstrap-table/react-bootstrap-table-tests.tsx b/react-bootstrap-table/react-bootstrap-table-tests.tsx index 9a22bf9df4..2998c92b3c 100644 --- a/react-bootstrap-table/react-bootstrap-table-tests.tsx +++ b/react-bootstrap-table/react-bootstrap-table-tests.tsx @@ -1,5 +1,4 @@ -/// -/// +/// import * as React from 'react'; import { render } from 'react-dom'; diff --git a/react-bootstrap-table/react-bootstrap-table.d.ts b/react-bootstrap-table/react-bootstrap-table.d.ts deleted file mode 100644 index a93b716fbb..0000000000 --- a/react-bootstrap-table/react-bootstrap-table.d.ts +++ /dev/null @@ -1,115 +0,0 @@ -// Type definitions for react-bootstrap-table v1.4.6 -// Project: https://github.com/AllenFang/react-bootstrap-table -// Definitions by: Frank Laub -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare module "react-bootstrap-table" { - import { ComponentClass, Props, ReactElement } from 'react'; - import { EventEmitter } from 'events'; - - interface SelectRow { - mode?: string; - bgColor?: string; - selected?: any[]; - onSelect?: Function; - onSelectAll?: Function; - clickToSelect?: boolean; - hideSelectColumn?: boolean; - clickToSelectAndEditCell?: boolean; - showOnlySelected?: boolean; - } - - interface CellEdit { - mode?: string; - blurToSave?: boolean; - afterSaveCell?: Function; - } - - interface Options { - sortName?: string; - sortOrder?: string; - afterTableComplete?: Function; - afterDeleteRow?: Function; - afterInsertRow?: Function; - afterSearch?: Function; - afterColumnFilter?: Function; - onRowClick?: Function; - page?: number; - sizePerPageList?: number[]; - sizePerPage?: number; - paginationSize?: number; - onSortChange?: Function; - onPageChange?: Function; - onSizePerPageList?: Function; - noDataText?: string; - handleConfirmDeleteRow?: Function; - } - - interface FetchInfo { - dataTotalSize?: number; - } - - interface BootstrapTableProps extends Props { - keyField?: string; - height?: string; - maxHeight?: string; - data?: any; - remote?: boolean; - striped?: boolean; - bordered?: boolean; - hover?: boolean; - condensed?: boolean; - pagination?: boolean; - searchPlaceholder?: string; - selectRow?: SelectRow; - cellEdit?: CellEdit; - insertRow?: boolean; - deleteRow?: boolean; - search?: boolean; - columnFilter?: boolean; - trClassName?: any; - options?: Options; - fetchInfo?: FetchInfo; - exportCSV?: boolean; - csvFileName?: string; - } - - interface BootstrapTable extends ComponentClass { } - const BootstrapTable: BootstrapTable; - - interface TableHeaderColumnProps extends Props { - dataField?: string; - dataAlign?: string; - dataSort?: boolean; - onSort?: Function; - dataFormat?: Function; - isKey?: boolean; - editable?: any; - hidden?: boolean; - className?: string; - width?: string; - sortFunc?: Function; - columnClassName?: any; - filterFormatted?: boolean; - sort?: string; - } - - interface TableHeaderColumn extends ComponentClass { } - const TableHeaderColumn: TableHeaderColumn; - - class TableDataSet extends EventEmitter { - constructor(data: any); - setData(data: any): void; - clear(): void; - getData(): any; - } - - export { - BootstrapTable, - TableHeaderColumn, - TableDataSet - } -} diff --git a/react-bootstrap-table/tsconfig.json b/react-bootstrap-table/tsconfig.json new file mode 100644 index 0000000000..a4fac3ad18 --- /dev/null +++ b/react-bootstrap-table/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "react-bootstrap-table-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-bootstrap/index.d.ts b/react-bootstrap/index.d.ts new file mode 100644 index 0000000000..d98ef3c963 --- /dev/null +++ b/react-bootstrap/index.d.ts @@ -0,0 +1,770 @@ +// Type definitions for react-bootstrap +// Project: https://github.com/react-bootstrap/react-bootstrap +// Definitions by: Walker Burgin , Vincent Siao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "react-bootstrap" { + // Import React + import React = require("react"); + + + //

+ ); + } +}); + +// Dialog tests +React.createClass({ + render: function() { + return ( +
+
+ + + Allow data collection? + +

Allowing us to collect data will let us get you the information you want faster.

+
+ + + + +
+
+ +
+ + + Allow this site to collect usage data to improve your experience? + +

Allowing us to collect data will let us get you the information you want faster.

+
+ + + + +
+
+ +
+ + + Allow data collection? + +

Allowing us to collect data will let us get you the information you want faster.

+
+ + + + +
+
+
+ ); + } +}); + +// Grid tests +React.createClass({ + render: function() { + return ( +
+
+ + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + + + 4 + 4 + 4 + + + 6 + 4 + 2 + + + 6 (8 tablet) + 4 (6 tablet) + 2 (4 phone) + +
+
+ ); + } +}); + +// IconToggle tests +React.createClass({ + render: function() { + return ( +
+ + + +
+ ); + } +}); + +// Layout tests +React.createClass({ + render: function() { + return ( +
+ {/* Uses a transparent header that draws on top of the layout's background */} +
+ +
+ + Link + Link + Link + Link + +
+ + + Link + Link + Link + Link + + + + +
+ + {/* No header, and the drawer stays open on larger screens (fixed drawer). */} +
+ + + + Link + Link + Link + Link + + + + +
+ + {/* Always shows a header, even in smaller screens. */} +
+ +
Area / The Title}> + + Link + Link + Link + Link + +
+ + + Link + Link + Link + Link + + + +
+
+ + {/* The drawer is always open in large screens. The header is always shown, even in small screens. */} +
+ +
+ {}} + label="Search" + expandable + expandableIcon="search" + /> +
+ + + Link + Link + Link + Link + + + +
+
+ + {/* Uses a header that scrolls with the text, rather than staying locked at the top */} +
+ +
+ + Link + Link + Link + Link + +
+ + + Link + Link + Link + Link + + + +
+ + +
+ + {/* Uses a header that contracts as the page scrolls down. */} +
+ +
+ + {}} + label="Search" + expandable + expandableIcon="search" + /> + + + + Link + Link + Link + Link + + +
+ + + Link + Link + Link + Link + + + +
+ + +
+ + {/* Hide the top part of the header when scrolling down */} +
+ +
+ + {}} + label="Search" + expandable + expandableIcon="search" + /> + + + + Link + Link + Link + Link + + +
+ + + Link + Link + Link + Link + + + +
+ + +
+ +
+ +
+ + this.setState({ activeTab: tabId })}> + Tab1 + Tab2 + Tab3 + Tab4 + Tab5 + Tab6 + +
+ + +
Content for the tab: {this.state.activeTab}
+
+
+
+ + {/* Simple header with fixed tabs. */} +
+ +
+ + {}}> + Tab1 + Tab2 + Tab3 + +
+ + +
You can add logic to update the content of this container based on the "activeTab" receive in the `onChange` callback.
+
+
+
+ + + + +
+ ); + } +}); + +// List tests +React.createClass({ + render: function() { + return ( +
+ + Bryan Cranston + Aaron Paul + Bob Odenkirk + + + + + Bryan Cranston + + + Aaron Paul + + + Bob Odenkirk + + + + + + Bryan Cranston + + + + + + Aaron Paul + + + + + + Bob Odenkirk + + + + + + + + + Bryan Cranston + + + + + + Aaron Paul + + + + + + Bob Odenkirk + + + + + + + + + Bryan Cranston + + + + + + Aaron Paul + + + + + + Bob Odenkirk + + + + + + + + + Bryan Cranston + + + + + + Aaron Paul + + + + + + Bob Odenkirk + + + + + +
+ ); + } +}); + +// Menu tests +React.createClass({ + render: function() { + return ( +
+ {/* Lower left */} +
+ + + Some Action + Another Action + Disabled Action + Yet Another Action + +
+ + {/* Lower right */} +
+ + + Some Action + Another Action + Disabled Action + Yet Another Action + +
+ + {/* Top left */} +
+ + + Some Action + Another Action + Disabled Action + Yet Another Action + +
+ + {/* Top right */} +
+ + + Some Action + Another Action + Disabled Action + Yet Another Action + +
+
+ ); + } +}); + +// ProgressBar tests +React.createClass({ + render: function() { + return ( +
+ {/* Simple Progress Bar */} + + + {/* Progress Bar with Indeterminate Progress */} + + + {/* Progress Bar with Buffering */} + +
+ ); + } +}); + +// Radio tests +React.createClass({ + render: function() { + return ( +
+ + Ripple option + Other option + + + + Ripple option + Other option + +
+ ); + } +}); + +// Slider tests +React.createClass({ + render: function() { + return ( +
+ {/* Default slider */} + + + {/* Slider with initial value */} + +
+ ); + } +}); + +// Snackbar tests +React.createClass({ + render: function() { + return ( +
+
+ + Button color changed. +
+ +
+ + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce varius luctus quam. Fusce quis blandit libero. Donec accumsan nunc lectus, vel blandit diam bibendum ac. Integer faucibus, lorem et convallis fermentum, diam dolor imperdiet mi, nec iaculis risus mauris id elit. Vivamus vel eros dapibus, molestie ante ut, vestibulum sem. + +
+
+ ); + } +}); + +// Spinner tests +React.createClass({ + render: function() { + return ( +
+ {/* Simple spinner */} + + + {/* Single color spinner */} + +
+ ); + } +}); + +// Switch tests +React.createClass({ + render: function() { + return ( +
+ Ripple switch + + Switch +
+ ); + } +}); + +// Tab tests +React.createClass({ + render: function() { + return ( +
+
+ this.setState({ activeTab: tabId })} ripple> + Starks + Lannisters + Targaryens + +
+
Content for the tab: {this.state.activeTab}
+
+
+
+ ); + } +}); + +// Textfield tests +React.createClass({ + render: function() { + return ( +
+ {/* Simple textfield */} + {}} + label="Text..." + style={{width: '200px'}} + /> + + {/* Numeric textfield */} + {}} + pattern="-?[0-9]*(\.[0-9]+)?" + error="Input is not a number!" + label="Number..." + style={{width: '200px'}} + /> + + {/* Textfield with floating label */} + {}} + label="Text..." + floatingLabel + style={{width: '200px'}} + /> + + {/* Numeric Textfield with floating label */} + {}} + pattern="-?[0-9]*(\.[0-9]+)?" + error="Input is not a number!" + label="Number..." + floatingLabel + /> +
+ ); + } +}); + +// Tooltip tests +React.createClass({ + render: function() { + return ( +
+ {/* Simple tooltip */} + + + + + {/* Large Tooltip */} + + + + + {/* Rich Tooltip */} + Upload file.zip}> + + + + {/* Multiline Tooltip */} + Share your content
via social media}> + +
+ + {/* Right Tooltip */} + + + + + {/* Left Tooltip */} + + + + + {/* Top Tooltip */} + + + + + {/* Bottom Tooltip */} + + + +
+ ); + } +}); diff --git a/react-mdl/tsconfig.json b/react-mdl/tsconfig.json new file mode 100644 index 0000000000..3187e297d4 --- /dev/null +++ b/react-mdl/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "react-mdl-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-mixin/index.d.ts b/react-mixin/index.d.ts new file mode 100644 index 0000000000..64bcd99869 --- /dev/null +++ b/react-mixin/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for react-mixin 2.0.2 +// Project: https://github.com/brigand/react-mixin +// Definitions by: Qubo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + + +import * as React from 'react'; + +declare namespace reactMixin { + export interface ClassDecorator { + (target: TFunction): TFunction | void; + } + + interface ReactMixin { + decorate(mixin: React.Mixin): ClassDecorator; + onClass(clazz: any, mixin: React.Mixin): React.ComponentClass; + (clazz: any, mixin: React.Mixin): React.ComponentClass; + } +} + +declare var reactMixin: reactMixin.ReactMixin; + +export = reactMixin; diff --git a/react-mixin/react-mixin-tests.tsx b/react-mixin/react-mixin-tests.tsx index 32532b1339..04f6f4b202 100644 --- a/react-mixin/react-mixin-tests.tsx +++ b/react-mixin/react-mixin-tests.tsx @@ -1,5 +1,5 @@ -/// -/// + +/// import reactMixin = require('react-mixin'); import * as React from 'react'; diff --git a/react-mixin/react-mixin.d.ts b/react-mixin/react-mixin.d.ts deleted file mode 100644 index 6285ad02ec..0000000000 --- a/react-mixin/react-mixin.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Type definitions for react-mixin 2.0.2 -// Project: https://github.com/brigand/react-mixin -// Definitions by: Qubo -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "react-mixin" { - import * as React from 'react'; - - namespace reactMixin { - export interface ClassDecorator { - (target: TFunction): TFunction|void; - } - - interface ReactMixin { - decorate(mixin: React.Mixin): ClassDecorator; - onClass(clazz: any, mixin: React.Mixin): React.ComponentClass; - (clazz: any, mixin: React.Mixin): React.ComponentClass; - } - } - - var reactMixin: reactMixin.ReactMixin; - - export = reactMixin; -} - diff --git a/react-mixin/tsconfig.json b/react-mixin/tsconfig.json new file mode 100644 index 0000000000..1770b4f1d2 --- /dev/null +++ b/react-mixin/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "experimentalDecorators": true, + "typesSearchPaths": [ + "../" + ], + "noEmit": true + }, + "files": [ + "index.d.ts", + "react-mixin-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-motion/index.d.ts b/react-motion/index.d.ts new file mode 100644 index 0000000000..93837fc113 --- /dev/null +++ b/react-motion/index.d.ts @@ -0,0 +1,85 @@ +// Type definitions for react-motion +// Project: https://github.com/chenglou/react-motion +// Definitions by: Stepan Mikhaylyuk +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +import { Component } from 'react'; + +// your typical style object given in props. Maps to a number or a spring config +export type Style = { [key: string]: number | OpaqueConfig }; +// the interpolating style object, with the same keys as the above Style object, +// with the values mapped to numbers, naturally +export type PlainStyle = { [key: string]: number }; +// internal velocity object. Similar to PlainStyle, but whose numbers represent +// speed. Might be exposed one day. +export type Velocity = { [key: string]: number }; +interface SpringHelperConfig { + stiffness: number; + damping: number; + /** + * Specifies both the rounding of the interpolated value and the speed (internal). + */ + precision?: number; + // TODO: add onRest. Not public yet +} + +export interface OpaqueConfig { + val: number; + stiffness: number; + damping: number; + precision: number; + // TODO: add onRest. Not public yet +} + +interface MotionProps { + defaultStyle?: any; + style: any; +} + +export declare class Motion extends Component { } + +// === TransitionMotion === +interface TransitionStyle { + key: any; // unique ID to identify component across render animations + data?: any; // optional data you want to carry along the style, e.g. itemText + style: Style; // actual style you're passing +} +interface TransitionPlainStyle { + key: any; + data?: any; + // same as TransitionStyle, passed as argument to style/children function + style: PlainStyle; +} +type InterpolateFunction = (previousInterpolatedStyles?: Array) => Array; +type Styles = Array | InterpolateFunction; +interface TransitionProps { + defaultStyles?: Array; + styles: Styles; + children: (interpolatedStyles: Array) => React.ReactElement; + willEnter?: (styleThatEntered: TransitionStyle) => PlainStyle; + willLeave?: (styleThatLeft: TransitionStyle) => Style; +} +export declare class TransitionMotion extends Component { } + +interface StaggeredMotionProps { + defaultStyles?: Array; + styles: (previousInterpolatedStyles?: Array) => Array