diff --git a/.editorconfig b/.editorconfig index 5ebf4a129c..d3bd86c3ba 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,9 +1,9 @@ root = true [*] +indent_size = 4 trim_trailing_whitespace = true insert_final_newline = true [{*.json,*.yml}] indent_style = space -indent_size = 2 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000000..390df0c3ed --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,3413 @@ +/types/abbrev/ @BendingBender +/types/ably/ @ably +/types/abs/ @AyaMorisawa +/types/absolute/ @AyaMorisawa +/types/acc-wizard/ @cyrilschumacher +/types/accepts/ @bomret +/types/accounting/ @gerich-home @chrisleck +/types/ace/ @Diullei +/types/acl/ @tkQubo +/types/acorn/ @RReverser @e-cloud +/types/actioncable/ @zhu1230 +/types/activex-adodb/ @zspitz +/types/activex-scripting/ @zspitz +/types/activex-wia/ @zspitz +/types/adal/ @mmaitre314 +/types/adm-zip/ @jvilk @abner +/types/adone/ @s0m3on3 @maxveres +/types/aframe/ @devpaul +/types/agenda/ @meirgottlieb +/types/aggregate-error/ @BendingBender +/types/alertify/ @jjeffery +/types/alexa-sdk/ @petebeegle @hoo29 @pascalwhoop @blforce +/types/alexa-voice-service/ @dolanmiu +/types/algebra.js/ @CaselIT +/types/algoliasearch/ @cbaptiste +/types/alt/ @Shearerbeard +/types/amazon-product-api/ @MattiLehtinen +/types/amcharts/ @aleksey-bykov +/types/amplify/ @joeriks +/types/amplify-deferred/ @joeriks @laurentiustamate94 +/types/amplitude-js/ @Asido +/types/amqp/ @seikho +/types/amqp-rpc/ @wokim +/types/amqplib/ @mnahkies @abreits @nfantone +/types/analytics-node/ @fongandrew +/types/angular/ @diegovilar @thorn0 @calebstdenis @leonard-thieu +/types/angular-agility/ @rolandzwaga +/types/angular-animate/ @michelsalib @adidahiya @rasch @codyschaaf +/types/angular-block-ui/ @lassebn @sclassen +/types/angular-bootstrap-calendar/ @Odrin +/types/angular-bootstrap-lightbox/ @rolandzwaga +/types/angular-breadcrumb/ @marctalary +/types/angular-clipboard/ @bradfordwagner +/types/angular-cookie/ @borislavjivkov +/types/angular-cookies/ @diegovilar @aciccarello +/types/angular-deferred-bootstrap/ @Ritzlgrmft +/types/angular-dialog-service/ @wcomartin +/types/angular-dynamic-locale/ @stephenlautier +/types/angular-environment/ @terrawheat +/types/angular-es/ @mbutsykin +/types/angular-feature-flags/ @borislavjivkov +/types/angular-file-saver/ @deenairn +/types/angular-formly/ @scatcher +/types/angular-fullscreen/ @julienpa +/types/angular-gettext/ @AkosLukacs +/types/angular-google-analytics/ @cyrilschumacher @Toxantron +/types/angular-gridster/ @jpmnteiro +/types/angular-growl-v2/ @mkp05 +/types/angular-hotkeys/ @jlz27 @reppners +/types/angular-http-auth/ @vvakame +/types/angular-httpi/ @Kukks +/types/angular-idle/ @mthamil +/types/angular-jwt/ @rerezz +/types/angular-load/ @david-gang +/types/angular-loading-bar/ @stephenlautier +/types/angular-local-storage/ @kenfdev @dona278 +/types/angular-localforage/ @reppners +/types/angular-locker/ @nkovacic +/types/angular-material/ @blbigelow @PeterHajdu @Dona278 @geertjansen +/types/angular-media-queries/ @jpmnteiro +/types/angular-meteor/ @pgrm +/types/angular-mocks/ @diegovilar @daltin +/types/angular-modal/ @paullessing +/types/angular-oauth2/ @anteriovieira +/types/angular-pdfjs-viewer/ @bastienmoulia +/types/angular-permission/ @vmishevski +/types/angular-promise-tracker/ @rufusl +/types/angular-q-spread/ @rafw87 +/types/angular-resource/ @diegovilar @miffels +/types/angular-route/ @park9140 +/types/angular-sanitize/ @diegovilar +/types/angular-scenario/ @RomanoLindano +/types/angular-scroll/ @samherrmann +/types/angular-signalr-hub/ @AdamSantaniello +/types/angular-spinner/ @Biegal +/types/angular-storage/ @mdekrey +/types/angular-strap/ @samherrmann +/types/angular-toastr/ @nkovacic @trodi +/types/angular-toasty/ @muenchdo +/types/angular-tooltips/ @leonard-thieu +/types/angular-touchspin/ @nkovacic +/types/angular-translate/ @michelsalib +/types/angular-ui-bootstrap/ @xt0rted @ry8806 +/types/angular-ui-router/ @michelsalib @matiishyn +/types/angular-ui-scroll/ @marknadig +/types/angular-ui-sortable/ @thgreasi +/types/angular-ui-tree/ @CalvinFernandez +/types/angular-websocket/ @nickveys +/types/angular-wizard/ @mjurisic @rwwilden +/types/angular-xeditable/ @jpmnteiro +/types/angular.throttle/ @reppners +/types/angularfire/ @thSoft +/types/angularlocalstorage/ @horiuchi +/types/angulartics/ @stevenfan +/types/animation-frame/ @qinfchen +/types/animejs/ @A-Babin +/types/annyang/ @hisham @theluk +/types/ansi-styles/ @brynbellomy +/types/ansicolors/ @rogierschouten +/types/any-db/ @rogierschouten +/types/any-db-transaction/ @rogierschouten +/types/anybar/ @khoomeister +/types/anydb-sql-migrations/ @spion +/types/anymatch/ @BendingBender +/types/apex.js/ @y13i +/types/aphrodite/ @asvetliakov +/types/api-error-handler/ @tkrotoff +/types/apigee-access/ @CasperSkydt +/types/app-root-path/ @shantmarouti +/types/appframework/ @kyo-ago +/types/appletvjs/ @brainded +/types/applicationinsights/ @scsouthw +/types/applicationinsights-js/ @kamilszostak +/types/arbiter/ @arash16 +/types/arcgis-js-api/v3/ @Esri +/types/arcgis-js-api/ @Esri +/types/arcgis-rest-api/ @JeffJacobson +/types/arcgis-to-geojson-utils/ @JeffJacobson +/types/archiver/ @dolanmiu @crevil +/types/archy/ @vvakame +/types/are-we-there-yet/ @brianloveswords +/types/argparse/ @arcticwaters +/types/argv/ @hookclaw +/types/array-find-index/ @samverschueren +/types/array-foreach/ @skysteve +/types/array-uniq/ @DanielRosenwasser +/types/arrify/ @wanganjun +/types/artyom.js/ @semagarcia +/types/asana/ @tkqubo +/types/ascii2mathml/ @RagibHasin +/types/asenv/ @remisery +/types/askmethat-rating/ @AlexTeixeira +/types/asn1js/ @microshine +/types/aspnet-identity-pw/ @jt000 +/types/assert-equal-jsx/ @seryl +/types/assert-plus/ @KostyaTretyak +/types/assertion-error/ @Bartvds +/types/assertsharp/ @brunolm +/types/assets-webpack-plugin/ @kryops +/types/async/ @borisyankov @kern0 @Penryn @fenying @pascalmartin +/types/async-lock/ @elisee +/types/async-polling/ @Goldsmith42 +/types/async.nexttick/ @pyrho +/types/asyncblock/ @horiuchi +/types/atmosphere/ @toedter +/types/atom/ @vvakame +/types/atom-keymap/ @enlight +/types/atpl/ @soywiz +/types/audiosprite/ @Perlmint +/types/aurelia-knockout/ @code-chris +/types/auth0/ @wbhob @westy92 @amiram +/types/auth0-angular/ @homesar +/types/auth0-js/v7/ @advancedrei +/types/auth0-js/ @adrianchia @mdurrant +/types/auth0-lock/ @carusology @goldcaddy77 +/types/auth0.widget/ @advancedrei +/types/auto-launch/ @rhysd @unindented +/types/auto-sni/ @janwo +/types/autobahn/ @darkl @valepu +/types/autobind-decorator/ @NoHomey +/types/autolinker/ @leonyu +/types/autoprefixer/ @odnamrataizem +/types/autosize/ @kingdango @keika299 @NeekSandhu +/types/awesomplete/ @webbiesdk @bmdixon @tbekolay +/types/aws-iot-device-sdk/ @niik +/types/aws-lambda/ @skarum @tobyhede @buggy @y13i @wwwy3y3 +/types/aws-serverless-express/ @threesquared @jcaffey @mattmeye +/types/aws4/ @ajcrites +/types/axel/ @ruslan-molodyko +/types/azure/ @AndrewGaspar @antiveeranna @SomaticIT +/types/azure-mobile-services-client/ @dmorosinotto +/types/azure-sb/ @Azure +/types/b_/ @outring +/types/babel-code-frame/ @mohsen1 +/types/babel-core/ @yortus @marvinhagemeister +/types/babel-generator/ @yortus @johnnyestilles +/types/babel-plugin-syntax-jsx/ @marvinhagemeister +/types/babel-template/ @yortus @marvinhagemeister +/types/babel-traverse/ @yortus @marvinhagemeister +/types/babel-types/ @yortus @baxtersa @marvinhagemeister +/types/babelify/ @TeamworkGuy2 @marvinhagemeister +/types/babylon/ @yortus @marvinhagemeister +/types/babyparse/ @cdiddy77 +/types/backbone/ @borisyankov @nvivo +/types/backbone-associations/ @craigbrett17 +/types/backbone-fetch-cache/ @delphinus35 +/types/backbone-relational/ @eirikhm +/types/backbone.layoutmanager/ @hejiang2000 +/types/backbone.localstorage/ @lgrignon +/types/backbone.marionette/ @zhamid @nvivo @sventschui +/types/backbone.paginator/ @Nyamazing +/types/backbone.radio/ @alphaleonis +/types/backgrid/ @jlujan +/types/backlog-js/ @vvatanabe +/types/baconjs/ @alexander-matsievsky @gekkio +/types/bagpipes/ @micmro +/types/barcode/ @pvomhoff +/types/bardjs/ @TepigMC +/types/base-64/ @dolanmiu +/types/base-x/ @chrootsu +/types/base16/ @alechill +/types/base64-js/ @pe8ter +/types/bases/ @harikv +/types/basic-auth/ @moonpyk @vesse +/types/batch-stream/ @drudge +/types/bazinga-translator/ @alexndlm +/types/bcrypt/ @codeanimal @IOAyman +/types/bcryptjs/ @RafaelKr +/types/bem-cn/ @selkinvitaly +/types/better-curry/ @pocesar +/types/better-sqlite3/ @Morfent +/types/bezier-easing/ @ptlis +/types/bezier-js/ @danmarshall +/types/bgiframe/ @sumegizoltan +/types/big.js/ @nycdotnet +/types/bigi/ @mhegazy +/types/bigint/ @Evgenus +/types/bignum/ @Patman64 +/types/bignumber.js/ @LaserUnicorns +/types/bigscreen/ @dduugg +/types/bind-ponyfill/ @skysteve +/types/bingmaps/ @rbrundritt +/types/bintrees/ @CjS77 +/types/bip21/ @stefanhuber +/types/bit-array/ @mudkipme +/types/bitcoinjs-lib/ @mhegazy @dlebrecht @rbuckton +/types/bittorrent-protocol/ @feross @tlaziuk +/types/bitwise-xor/ @rogierschouten +/types/bl/ @Bartvds +/types/blacklist/ @mhegazy +/types/blazy/ @julienpa +/types/blessed/ @brynbellomy +/types/blissfuljs/ @fskorzec +/types/blob-stream/ @erichillah +/types/blob-util/ @WorldMaker +/types/blocks/ @ksmigiel +/types/bloomfilter/ @slawiko +/types/blue-tape/ @sodatea +/types/bluebird/v1/ @Bartvds +/types/bluebird/v2/ @Bartvds @falsandtru +/types/bluebird/ @lhecker +/types/bluebird-global/ @d-ph +/types/bluebird-retry/ @pvomhoff +/types/blueimp-md5/ @rmartone @mkohlmyr +/types/body-parser/ @santialbo @vilic @dreampulse @blendsdk @tlaziuk +/types/bonjour/ @quentin-ol @octo-sniffle +/types/bookshelf/ @arcticwaters @vesse +/types/boom/v3/ @rogatty +/types/boom/ @rogatty @AJamesPhillips @jineshshah36 +/types/bootbox/ @vbortone @konpikwastaken @kanup @icereed @trodi @stannynuytkens +/types/bootpag/ @rdeneau +/types/bootstrap/ @borisyankov +/types/bootstrap-datepicker/ @borisyankov +/types/bootstrap-fileinput/ @CheCoxshall +/types/bootstrap-maxlength/ @danmana +/types/bootstrap-notify/ @niemyjski @mouse0270 @robert-voica +/types/bootstrap-select/ @LKay +/types/bootstrap-slider/ @dbeckwith @leonard-thieu +/types/bootstrap-switch/ @johnmbaughman +/types/bootstrap-table/ @talatbaig +/types/bootstrap-touchspin/ @albinsunnanbo +/types/bootstrap-treeview/ @jbtronics +/types/bootstrap-validator/ @BradyLiles +/types/bootstrap.paginator/ @derikwhittaker +/types/bootstrap.timepicker/ @derikwhittaker +/types/bootstrap.v3.datetimepicker/v3/ @bayitajesi +/types/bootstrap.v3.datetimepicker/ @katonap +/types/bounce.js/ @cherrry +/types/bowser/ @pocesar +/types/box2d/ @jbaldwin +/types/brace-expansion/ @BendingBender +/types/braintree-web/ @chlela +/types/breeze/ @borisyankov +/types/brorand/ @chrootsu +/types/browser-bunyan/ @PaulLockwood @kryops +/types/browser-fingerprint/ @LKay +/types/browser-harness/ @scriby +/types/browser-pack/ @TeamworkGuy2 +/types/browser-report/ @JTOne123 +/types/browser-resolve/ @marionebl +/types/browser-sync/ @joeskeen +/types/browserify/ @AndrewGaspar @jvilk @leonard-thieu +/types/bs58/ @chrootsu +/types/bson/ @horiuchi @CaselIT +/types/bucks/ @zaneli +/types/buffer-compare/ @chrootsu +/types/buffer-equal/ @Bartvds +/types/buffers/ @rhencke +/types/bufferstream/ @Bartvds +/types/bull/v2/ @bgrieder @JProgrammer +/types/bull/ @bgrieder @JProgrammer @marshall007 +/types/bunnymq/ @cyrilschumacher +/types/bunyan/ @amikhalev +/types/bunyan-blackhole/ @olivr70 +/types/bunyan-config/ @cyrilschumacher +/types/bunyan-prettystream/ @jasonswearingen @enlight +/types/bunyan-winston-adapter/ @stevehipwell +/types/busboy/ @jacobbaskin +/types/business-rules-engine/ @rsamec +/types/bwip-js/ @MugeSo +/types/byline/ @reppners +/types/bytebuffer/ @cappellin +/types/bytes/ @danny8002 +/types/c3/ @mcliment @gerinjacob @denyo +/types/cache-manager/ @GausSim +/types/cachefactory/ @vag1830 @danielmassa +/types/cal-heatmap/ @RetroChrisB +/types/callsite/ @newclear +/types/callsites/ @BendingBender +/types/calq/ @eirikhm +/types/camelcase/ @samverschueren +/types/camelcase-keys/ @mhegazy +/types/camo/ @lucasmciruzzi +/types/cannon/ @clark-stevenson +/types/canvas-gauges/ @Mikhus +/types/canvasjs/ @brutalimp +/types/capitalize/ @frederickfogerty +/types/cash/ @akvlko +/types/casperjs/ @jedmao +/types/cassandra-driver/ @Svjard +/types/catbox/ @jasonswearingen @AJamesPhillips +/types/cbor/ @pushplay +/types/ccap/ @taoqf +/types/chai/v2/ @Bartvds @AGBrown +/types/chai/ @jedmao @Bartvds @AGBrown @olivr70 @mwistrand @joshuakgoldberg @shaunluttin +/types/chai-arrays/ @clementprevot +/types/chai-as-promised/ @jt000 @Kuniwak @leonard-thieu +/types/chai-datetime/ @cliffburger +/types/chai-dom/ @mattlewis92 +/types/chai-enzyme/ @asvetliakov +/types/chai-fuzzy/ @Bartvds +/types/chai-http/ @Nemo157 @G1itcher @CaselIT +/types/chai-jquery/ @kazimanzurrashid +/types/chai-json-schema/ @ulrichheiniger +/types/chai-oequal/ @mizunashi-mana +/types/chai-spies/ @kuzn-ilya +/types/chai-string/ @nmalaguti +/types/chai-subset/ @delta62 @AGBrown +/types/chai-xml/ @jedigo +/types/chalk/ @Diullei @Bartvds @nicojs +/types/chance/ @cbowdon +/types/change-emitter/ @iskandersierra +/types/charm/ @Xananax +/types/chart.js/ @anuti @FabienLavocat @KentarouTakeda @larrybahr +/types/chartist/ @mtgibbs @psimonski +/types/chartjs/ @Steve-Fenton @FanaHOVA +/types/chayns/ @HenningKuehl +/types/check-sum/ @BendingBender +/types/checkstyle-formatter/ @mhegazy +/types/checksum/ @rogierschouten +/types/cheerio/ @blittle @wmaurer @umarniz +/types/chokidar/ @reppners @felixfbecker +/types/chosen-js/ @borisyankov @denisname +/types/chroma-js/v0/ @invliD +/types/chroma-js/ @invliD @mpacholec +/types/chrome/ @matthewkimber @otiai10 @couven92 @rreverser @sreimer15 +/types/chunked-dc/ @dbrgn +/types/circular-json/ @jpevarnek +/types/ckeditor/ @ondrejsevcik +/types/clamp-js/ @Hikariii +/types/classnames/ @adidahiya @JKillian @seansfkelley @mradamczyk @marvinhagemeister +/types/cldrjs/ @RamanBut-Husaim @gcastre +/types/clean-css/ @tkrotoff +/types/clean-stack/ @BendingBender +/types/clear-require/ @dan-j +/types/cli/ @kayahr +/types/cli-color/ @ChaosinaCan +/types/cli-table2/ @mgroenhoff +/types/client-sessions/ @netroy +/types/cliff/ @brynbellomy +/types/clipboard/ @impworks +/types/clipboard-js/ @markwongsk +/types/clipboardy/ @BendingBender +/types/clndr/ @jasperjn +/types/closure-compiler/ @mprobst +/types/cloud-env/ @Morfent +/types/cloudflare-apps/ @MartynasZilinskas +/types/co-body/ @geoffreak +/types/co-views/ @devlee @geoffreak +/types/code/ @prashaantt +/types/codemirror/ @mihailik @nrbernard +/types/codependency/ @morphatic +/types/coffeeify/ @tkQubo +/types/coinstring/ @mhegazy +/types/collections/ @scarabedore +/types/color/v0/ @LKay +/types/color/v1/ @LKay +/types/color/ @Airlun +/types/color-convert/ @Airlun +/types/color-name/ @Ailrun +/types/color-string/ @BendingBender @danmarshall +/types/colorbrewer/ @mtraynham +/types/colors/ @Bartvds @staeke +/types/com.darktalker.cordova.screenshot/ @akarienta +/types/combine-source-map/ @TeamworkGuy2 +/types/combined-stream/ @felixge @tlaziuk +/types/combokeys/ @iclanton +/types/cometd/ @derekcicerone +/types/command-line-args/ @CzBuCHi +/types/command-line-commands/ @CzBuCHi +/types/commander/ @alan-agius4 @mdezem @vvakame +/types/commangular/ @hiraash +/types/comment-json/ @Jason3S +/types/common-tags/ @zuzusik +/types/commonmark/ @nicojs @leonard-thieu +/types/compare-version/ @jpevarnek +/types/complex/ @AyaMorisawa +/types/component-emitter/ @psnider +/types/compose-function/ @denis-sokolov +/types/compressible/ @BendingBender +/types/compression/ @santialbo +/types/compression-webpack-plugin/ @dublicator +/types/concat-stream/ @jmarianer +/types/concaveman/ @DenisCarriere +/types/conf/v0/ @SamVerschueren +/types/conf/ @SamVerschueren @BendingBender +/types/confidence/ @jppellerin +/types/config/ @RWander +/types/configstore/ @ArcticLight +/types/confit/ @ethanresnick +/types/connect/ @SomaticIT +/types/connect-ensure-login/ @0x6368656174 +/types/connect-flash/ @AndreasGassmann +/types/connect-history-api-fallback/ @douglasduteil +/types/connect-livereload/ @SomaticIT +/types/connect-modrewrite/ @tinganho +/types/connect-mongo/ @Syati +/types/connect-redis/ @xstoudi @morcerf +/types/connect-slashes/ @samherrmann +/types/connect-timeout/ @cyrilschumacher +/types/console-stamp/ @ericbyers +/types/consolidate/ @soywiz @theosherry @nicolashenry +/types/consul/ @chrootsu +/types/content-disposition/ @bomret +/types/content-type/ @horiuchi @BendingBender +/types/contentful-resolve-response/ @antonkarsten +/types/contextjs/ @kernhanda +/types/continuation-local-storage/ @rath @heycalmdown @aboveyou00 +/types/convert-hrtime/ @BendingBender +/types/convert-source-map/ @AndrewGaspar @mgroenhoff @TeamworkGuy2 +/types/convict/ @Nemo157 @vesse @elyscape +/types/cookie/ @pine613 +/types/cookie-parser/ @santialbo @BendingBender +/types/cookie-session/ @borislavjivkov +/types/cookie-signature/ @lith-light-g +/types/cookie_js/ @slawiko +/types/cookies/ @WangZishi @jkeylu @BendingBender +/types/copy-paste/ @SrTobi +/types/copy-text-to-clipboard/ @BendingBender +/types/copy-webpack-plugin/ @flying-sheep +/types/cordova-ionic/ @hendrikmaus +/types/cordova-plugin-app-version/ @Ritzlgrmft +/types/cordova-plugin-background-mode/ @Lordnoname +/types/cordova-plugin-badge/ @timbru31 +/types/cordova-plugin-ble-central/ @gjunge +/types/cordova-plugin-device-name/ @larrybahr +/types/cordova-plugin-ibeacon/ @Ritzlgrmft +/types/cordova-plugin-insomnia/ @Ritzlgrmft +/types/cordova-plugin-keyboard/ @danmana +/types/cordova-plugin-mapsforge/ @rafw87 +/types/cordova-plugin-ms-adal/ @KaiWalter +/types/cordova-plugin-native-keyboard/ @lobo87 +/types/cordova-plugin-ouralabs/ @Justin-Credible +/types/cordova-plugin-qrscanner/ @bitjson @jab +/types/cordova-plugin-spinner/ @Justin-Credible +/types/cordova-plugin-statusbar/ @Xinkai +/types/cordova-plugin-vibration/ @Minishlink +/types/cordova-plugin-x-socialsharing/ @Ritzlgrmft @larrybahr +/types/cordova-sqlite-storage/ @rafw87 +/types/cordova.plugins.diagnostic/ @dpa99c +/types/cordova_app_version_plugin/ @larrybahr +/types/cordovarduino/ @hendrikmaus +/types/core-decorators/ @tkqubo +/types/core-js/ @rbuckton @mfdeveloper +/types/cote/ @makepost +/types/couchbase/ @maouida +/types/countdown/ @gjuchault +/types/country-list/ @iRoachie +/types/country-select-js/ @humrochagf +/types/cp-file/ @BendingBender +/types/cpy/ @mhegazy @BendingBender +/types/cradle/ @panuhorsmalahti +/types/crc/ @YuJianrong +/types/create-error/ @tkrotoff +/types/createjs/ @evilangelist @gyohk +/types/createjs-lib/ @evilangelist @gyohk +/types/credential/ @phuvo +/types/credit-card-type/ @LKay +/types/cron/ @horiuchi +/types/cropperjs/ @stepancar +/types/croppie/ @connor4312 +/types/crossfilter/ @schmuli @iebaker +/types/crossroads/ @diullei +/types/cryptiles/ @awendland +/types/crypto-js/ @misak113 +/types/cryptojs/ @giabao +/types/cson/ @stpettersens +/types/csprng/ @winksaville +/types/csrf/ @markis +/types/css/ @ilich +/types/css-font-loading-module/ @slikts +/types/css-modules/ @NeekSandhu +/types/cssbeautify/ @rictic +/types/csurf/ @horiuchi +/types/csv-parse/ @davidm77 @obi-jan-kenobi +/types/csv-stringify/ @rogierschouten @arjenvanderende +/types/csvtojson/ @EricByers @wcarson +/types/cucumber/v1/ @abraaoalves @jan-molak @isoung @BendingBender +/types/cucumber/ @abraaoalves @jan-molak @isoung @BendingBender +/types/currency-formatter/ @mhegazy +/types/custom-error-generator/ @thmiceli +/types/cwise/ @taoqf +/types/cwise-compiler/ @taoqf +/types/cwise-parser/ @taoqf +/types/cybozulabs-md5/ @pine613 +/types/cypress/ @ghengeveld @mikewoudenberg +/types/d3/v3/ @gustavderdrache @borisyankov +/types/d3/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-array/ @gustavderdrache @borisyankov @tomwanzek +/types/d3-axis/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-box/ @lk-chen +/types/d3-brush/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-chord/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-collection/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-color/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-contour/ @tomwanzek @Ledragon +/types/d3-dispatch/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-drag/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-dsv/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-ease/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-force/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-format/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-geo/ @Ledragon @tomwanzek @gustavderdrache @borisyankov +/types/d3-hexbin/ @uncovertruth @tomwanzek +/types/d3-hierarchy/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-hsv/ @arrayjam +/types/d3-interpolate/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-path/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-polygon/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-quadtree/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-queue/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-random/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-request/ @Ledragon @gustavderdrache @borisyankov @tomwanzek +/types/d3-sankey/ @tomwanzek @gustavderdrache +/types/d3-scale/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-scale-chromatic/ @Ledragon @gustavderdrache @borisyankov +/types/d3-selection/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-selection-multi/ @gustavderdrache @borisyankov +/types/d3-shape/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-time/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-time-format/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-timer/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-tip/ @brspnnggrt +/types/d3-transition/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-voronoi/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-zoom/ @tomwanzek @gustavderdrache @borisyankov +/types/d3.cloud.layout/ @hansrwindhoff +/types/d3.slider/ @lk-chen +/types/d3kit/ @morphatic +/types/d3pie/ @mc-petry +/types/dagre/ @qinfchen +/types/dagre-d3/ @markwongsk +/types/dargs/ @BendingBender +/types/dat-gui/ @gyohk @sonic3d @rroylance +/types/data-driven/ @mrhen +/types/datadog-metrics/ @pushplay +/types/datatables.net/ @omidkrad @pragmatrix @denisemauldin +/types/datatables.net-buttons/ @SammyG4Free @jimhartford +/types/datatables.net-fixedheader/ @szechyjs +/types/datatables.net-rowreorder/ @baywet +/types/datatables.net-select/ @szechyjs +/types/date.format.js/ @balrob +/types/dateformat/ @aicest +/types/datejs/ @rupertavery +/types/daterangepicker/ @SirMartin @smasala +/types/db-migrate-base/ @nickiannone +/types/db-migrate-pg/ @nickiannone +/types/db.js/ @cgwrench +/types/dc/ @hansrwindhoff @mtraynham +/types/deasync/ @Sicilica +/types/debessmann/ @vkorehov +/types/debounce/ @denis-sokolov +/types/debug/ @swook @galtalmor @zamb3zi +/types/decamelize/ @samverschueren +/types/decay/ @enaeseth +/types/decimal.js/ @musicist288 +/types/decorum/ @dflor003 +/types/dedent/ @douglasduteil +/types/deep-assign/ @souldreamer +/types/deep-diff/ @ZauberNerd +/types/deep-equal/ @remojansen @janslow +/types/deep-extend/ @rhysd +/types/deep-freeze/ @Bartvds @aluanhaddad +/types/deep-freeze-strict/ @mhegazy +/types/deepmerge/ @marvinscharle +/types/defaults/ @IbtihelCHNAB +/types/define-lazy-prop/ @BendingBender +/types/defined/ @BendingBender +/types/deku/ @pocka +/types/del/v2/ @AyaMorisawa +/types/del/ @AyaMorisawa @BendingBender +/types/delaunator/ @DenisCarriere +/types/delay/ @BendingBender +/types/denodeify/ @joaomoreno +/types/deoxxa-content-type/ @pine613 +/types/depd/ @danny8002 +/types/deployjava/ @cyrilschumacher +/types/destroy/ @BendingBender +/types/destroy-on-hwm/ @BendingBender +/types/detect-browser/ @rogierschouten +/types/detect-hover/ @thomastilkema +/types/detect-indent/v0/ @Bartvds +/types/detect-indent/ @Bartvds @BendingBender +/types/detect-it/ @thomastilkema +/types/detect-newline/ @BendingBender +/types/detect-passive-events/ @thomastilkema +/types/detect-pointer/ @thomastilkema +/types/detect-port/ @lith-light-g +/types/detect-touch-events/ @thomastilkema +/types/df-visible/ @Litee +/types/dhtmlxgantt/ @mkozhukh @chriscamicas +/types/dhtmlxscheduler/ @mkozhukh +/types/di-lite/ @dcrusader +/types/diacritics/ @otociulis +/types/diff/ @vvakame +/types/diff2html/ @rtfpessoa +/types/dir-resolve/ @andy-ms +/types/discontinuous-range/ @OiCMudkips +/types/disposable-email-domains/ @geoffreak +/types/doccookies/ @jonegerton +/types/dockerode/ @seikho @nlaplante @isac322 +/types/docopt/ @giggio +/types/doctrine/ @rictic +/types/documentdb/ @NoelAbrahams @brettferdosi @ctstone @yifanwu +/types/documentdb-server/ @lith-light-g +/types/dojo/ @vansimke +/types/dom-inputevent/ @diagramatics +/types/dom4/ @adidahiya @giladgray +/types/domo/ @Steve-Fenton +/types/dompurify/ @bazuzi +/types/domready/ @dotnetnerd +/types/donna/ @vvakame +/types/dookie/ @swanest +/types/dot/ @ZombieHunter +/types/dot-object/ @nkovacic +/types/dot-prop/v2/ @samverschueren +/types/dot-prop/ @samverschueren @BendingBender +/types/dotdotdot/ @milanjaros +/types/dotenv/v2/ @borekb @enaeseth +/types/dotenv/ @jussikinnula @borekb @enaeseth +/types/dotenv-safe/ @krenor +/types/dottie/ @domarmstrong +/types/doublearray/ @mzsm +/types/doubleclick-gpt/ @johngeorgewright +/types/downloadjs/ @cwmoo740 +/types/draft-js/ @dmitryrogozhny @eelco @ghotiphud @schwers @michael-yx-wu @willisplummer +/types/draggabilly/ @jaydubu +/types/dragster/ @zskovacs +/types/dragula/ @pwelter34 @abruzzihraig +/types/dropboxjs/ @Steve-Fenton @xperiments +/types/dropkickjs/ @VorobeY1326 +/types/dropzone/v4/ @nvivo @outring @renuo @Hikariii +/types/dropzone/ @nvivo @outring @renuo @Hikariii @tedbcsgpro +/types/duplexer2/ @Goldsmith42 +/types/duplexer3/ @BendingBender +/types/durandal/ @BlueSpire +/types/dustjs-linkedin/ @mdezem +/types/dw-bxslider-4/ @namerci +/types/dwt/ @yushulx +/types/dymo-label-framework/ @thijskuipers +/types/dynatable/ @francoismassart +/types/each/ @misak113 +/types/easeljs/ @evilangelist +/types/easy-api-request/ @DeadAlready +/types/easy-jsend/ @DeadAlready +/types/easy-session/ @DeadAlready +/types/easy-table/ @nikeee +/types/easy-x-headers/ @DeadAlready +/types/easy-xapi/ @DeadAlready +/types/easy-xapi-supertest/ @DeadAlready +/types/easy-xapi-utils/ @DeadAlready +/types/easystarjs/ @borundin +/types/ebongarde-root/ @Ebongarde +/types/echarts/ @xieisabug @AntiMoron +/types/ecurve/ @mhegazy +/types/egg/ @sheperdwind +/types/egg-mock/ @sheperdwind +/types/egg.js/ @ToastHawaii +/types/ej.web.all/ @syncfusion +/types/ejs-locals/ @jt000 +/types/ejson/ @shantanubhadoria +/types/elasticsearch/ @CasperSkydt @bfsmith @ddunkin @pushplay @mlamp @ahmadferdous +/types/electron-config/ @mrfunkycold @unindented +/types/electron-debug/ @unindented +/types/electron-devtools-installer/ @gamesmaxed +/types/electron-json-storage/ @stpettersens +/types/electron-notifications/ @djpereira +/types/electron-notify/ @djpereira +/types/electron-packager/ @SomaticIT @cortopy +/types/electron-settings/v2/ @leonard-thieu +/types/electron-settings/ @icopp +/types/electron-store/ @unindented +/types/electron-window-state/ @rhysd +/types/element-ready/ @BendingBender +/types/element-resize-event/ @rogierschouten @plgregoire +/types/elm/ @thSoft +/types/email-addresses/ @johngrimsey +/types/email-templates/ @cyrilschumacher @gurisko +/types/email-validator/ @paullessing +/types/ember/v1/ @jedmao +/types/ember/ @jedmao @bttf +/types/emissary/ @vvakame +/types/emojione/ @dbrgn +/types/empower/ @vvakame +/types/emscripten/ @zakki @periklis +/types/engine.io/ @KentarouTakeda +/types/engine.io-client/ @KentarouTakeda +/types/enhanced-resolve/ @e-cloud @onigoetz +/types/ent/ @rogierschouten +/types/entities/ @aliceklipper +/types/env-to-object/ @MugeSo +/types/envify/ @tkQubo +/types/enzyme/ @MarianPalkus @NoHomey @jwbay @huhuanming @MartynasZilinskas @thovden +/types/enzyme-to-json/ @joscha +/types/eonasdan-bootstrap-datetimepicker/ @ToastHawaii +/types/epiceditor/ @borisyankov +/types/epub/ @julien-c +/types/eq.js/ @stephenlautier +/types/errorhandler/ @santialbo +/types/es6-collections/ @rbuckton +/types/es6-error/ @LKay +/types/es6-promise/ @fdecampredon @vvakame +/types/es6-promisify/ @harryshipton +/types/es6-shim/ @rbuckton +/types/es6-weak-map/ @pine +/types/escape-html/ @elisee +/types/escape-latex/ @olsio +/types/escape-string-regexp/ @kruncher +/types/escodegen/ @simondel +/types/eslint-plugin-prettier/ @ikatyang +/types/esprima/ @teppeis @RReverser +/types/esprima-walk/ @tswaters +/types/esri-leaflet/ @strajuser +/types/esri-leaflet-geocoder/ @BendingBender +/types/estraverse/ @sanex3339 +/types/estree/ @RReverser +/types/etag/ @BendingBender +/types/ethjs-signer/ @doppio +/types/eureka-js-client/ @Schnillz +/types/evaporate/ @kookster @chrisrhoden +/types/event-emitter/ @LKay +/types/event-kit/ @enlight +/types/event-loop-lag/ @rogierschouten +/types/event-stream/ @flcdrg +/types/event-to-promise/ @flying-sheep +/types/evernote/ @corps +/types/exceljs/ @rogierschouten @alitaheri +/types/execa/ @douglasduteil @BendingBender +/types/exit/ @Bartvds +/types/exit-hook/ @BendingBender +/types/exorcist/ @TeamworkGuy2 +/types/expect/ @jmreidy @merrywhether +/types/expect.js/ @teppeis +/types/expectations/ @vvakame +/types/expr-eval/ @connor4312 +/types/express/ @borisyankov +/types/express-brute/ @cyrilschumacher +/types/express-brute-memcached/ @cyrilschumacher +/types/express-brute-mongo/ @cyrilschumacher +/types/express-debug/ @federicobond +/types/express-domain-middleware/ @hookclaw +/types/express-enforces-ssl/ @kevinstubbs +/types/express-fileupload/ @Naktibalda +/types/express-flash-2/ @mathsalmi +/types/express-formidable/ @tdolsen +/types/express-graphql/ @isman-usoh @nitintutlani +/types/express-handlebars/ @stpettersens @yhaskell +/types/express-jwt/ @wokim @kacepe @Sl1MBoy +/types/express-less/ @xieyubo +/types/express-minify/ @borislavjivkov +/types/express-mung/ @cyrilschumacher +/types/express-myconnection/ @Cellule +/types/express-mysql-session/ @Akim95 +/types/express-openapi/ @mugeso +/types/express-partials/ @jt000 +/types/express-rate-limit/ @cyrilschumacher +/types/express-route-fs/ @kripod +/types/express-sanitized/ @cjbarth +/types/express-serve-static-core/ @borisyankov @19majkel94 @kacepe +/types/express-session/ @horiuchi +/types/express-unless/ @wokim +/types/extend/ @reppners +/types/extended-listbox/ @code-chris +/types/extjs/ @brian428 +/types/extract-stack/ @BendingBender +/types/extract-text-webpack-plugin/ @flying-sheep @katyo +/types/extract-zip/ @mizunashi-mana +/types/eyes/ @brynbellomy +/types/f1/ @neolwc +/types/fabric/ @oklemencic @joewashear007 @mrand01 +/types/facebook-js-sdk/ @amritk +/types/facebook-pixel/ @noctishsu +/types/faker/v3/ @Kuniwak +/types/faker/ @bensw @basp @Kuniwak +/types/falcor/ @Quramy +/types/falcor-express/ @Quramy +/types/falcor-http-datasource/ @Quramy +/types/falcor-json-graph/ @Quramy +/types/falcor-router/ @Quramy @cdhgee +/types/famous/ @borisvasilenko +/types/fancybox/ @borisyankov +/types/farbtastic/ @EnableSoftware +/types/fast-diff/ @djrenren +/types/fast-levenshtein/ @mizunashi-mana +/types/fast-stats/ @rogierschouten +/types/fastclick/ @shinnn +/types/favico.js/ @drowse314-dev-ymat +/types/fb/ @JoshStrobl +/types/fbemitter/ @kmxz +/types/featherlight/ @xStrom +/types/fecha/ @9y5 +/types/fetch-jsonp/ @tkrotoff +/types/fetch-mock/ @asvetliakov @tamird @merrywhether @chrissinclair +/types/fetch.io/ @newraina +/types/ffi/ @loyd +/types/ffmpeg-static/ @iamstevetran +/types/ffprobe-static/ @iamstevetran +/types/fibers/ @soywiz +/types/figures/ @BendingBender +/types/file-exists/ @BendingBender +/types/file-saver/ @cyrilschumacher @DaIgeb +/types/file-type/ @tcaesvk @BendingBender +/types/filenamify/ @rokt33r +/types/filesize/ @GiedriusGrabauskas +/types/fill-pdf/ @westy92 +/types/finalhandler/ @chrootsu +/types/finch/ @DavidSichau +/types/find-up/ @BendingBender +/types/findup-sync/ @Bartvds @ngbrown +/types/fingerprintjs/ @zaneli +/types/fingerprintjs2/ @curtstate +/types/firebase/ @vbortone @dsebastien @ciekawy +/types/firebase-client/ @fpsscarecrow +/types/firebase-token-generator/ @dotdotcommadot +/types/firebird/ @karak +/types/firefox/ @vvakame +/types/firmata/ @troywweber7 +/types/first-mate/ @enlight +/types/fixed-data-table/ @pepaar @stephenjelfs +/types/flat/ @chrootsu +/types/flatpickr/v2/ @UnwrittenFun +/types/flatpickr/ @UnwrittenFun @rowellx68 @wagich +/types/flexslider/ @diullei +/types/flight/ @jonathanhedren +/types/flightplan/ @borislavjivkov +/types/flipsnap/ @kubosho @gsino @mayuki +/types/flot/ @burlandm @Anticom +/types/flowjs/ @ryan10132 +/types/fluent-ffmpeg/ @tcaesvk @DingWeizhe +/types/flux/ @stkb @GiedriusGrabauskas +/types/flux-standard-action/ @tkqubo +/types/fluxxor/ @mrk21 +/types/fm-websync/ @markusmauch +/types/fontfaceobserver/ @RandScullard +/types/fontoxml/ @rolandzwaga +/types/forever-monitor/ @shuntksh +/types/forge-di/ @adamcarr +/types/form-data/ @soywiz @leonyu @BendingBender +/types/form-serializer/ @flqw +/types/format-unicorn/ @kruncher +/types/formidable/ @Nemo157 +/types/forwarded/ @BendingBender +/types/fossil-delta/ @endel +/types/foundation/ @borisyankov +/types/foundation-sites/ @samvloeberghs +/types/fpsmeter/ @alampros +/types/framebus/ @kbukum +/types/freedom/ @jpevarnek +/types/freeport/ @atd-schubert +/types/fresh/ @BendingBender +/types/frisby/ @johnny4753 +/types/from/ @Bartvds +/types/from2/ @BendingBender +/types/fromjs/ @glenndierckx +/types/fromnow/ @marinewater +/types/fs-ext/ @OguzhanE +/types/fs-extra/ @alan-agius4 @midknight41 @shiftkey +/types/fs-extra-promise/ @midknight41 @jasonswearingen @HiromiShikata +/types/fs-extra-promise-es6/ @midknight41 @jasonswearingen @geoffreak @HiromiShikata +/types/fs-finder/ @misak113 +/types/fs-mock/ @rogierschouten +/types/fs-promise/ @tarruda +/types/fsevents/ @BendingBender +/types/ftdomdelegate/ @dotnetnerd +/types/ftp/ @rogierschouten +/types/ftpd/ @rogierschouten +/types/fullcalendar/v1/ @nestalk @hasellcamargo +/types/fullcalendar/ @nestalk @hasellcamargo @panic175 +/types/fullname/ @kayahr +/types/fuse/ @smrq +/types/fusioncharts/ @rohitkr @shivarajkv +/types/fuzzaldrin/ @mhegazy +/types/fuzzaldrin-plus/ @jeancroy @jkillian +/types/fuzzyset/ @lgrignon +/types/fxn/ @charrondev +/types/gae.channel.api/ @vvakame +/types/gamequery/ @Laubi +/types/gandi-livedns/ @xstoudi +/types/gapi/ @sgtfrankieboy +/types/gapi.analytics/ @gatsbimantico +/types/gapi.auth2/ @flawless2011 +/types/gapi.calendar/ @tkrotoff +/types/gapi.drive/ @baxtersa +/types/gapi.pagespeedonline/ @sgtfrankieboy +/types/gapi.people/ @tkrotoff +/types/gapi.plus/ @tkrotoff +/types/gapi.translate/ @sgtfrankieboy +/types/gapi.urlshortener/ @sgtfrankieboy +/types/gapi.youtube/ @sgtfrankieboy +/types/gapi.youtubeanalytics/ @sgtfrankieboy +/types/gaussian/ @scttcper +/types/generic-functions/ @stpettersens +/types/generic-pool/ @jerray +/types/gently/ @bonnici +/types/geodesy/ @DenisCarriere @HandyG52 +/types/geojson/ @cobster +/types/geojson2osm/ @DenisCarriere +/types/geokdbush/ @DenisCarriere +/types/geolib/ @vvenegasv @dotnetpart +/types/geometry-dom/ @nakakura +/types/geopattern/ @Gaelan +/types/get-node-dimensions/ @vincekovacs +/types/get-stdin/ @DanielRosenwasser +/types/get-stream/ @douglasduteil @BendingBender +/types/getos/ @BendingBender +/types/gettext.js/ @jucrouzet +/types/gijgo/ @atatanasov +/types/giraffe/ @darthapo +/types/git/ @vvakame +/types/git-config/ @stpettersens +/types/git-remote-origin-url/ @janslow +/types/gl-matrix/ @mattijskneppers @tatchx +/types/gldatepicker/ @qcz +/types/glidejs/ @milanjaros +/types/glob/ @vvakame @voy +/types/glob-base/ @alan-agius4 +/types/glob-expand/ @vvakame +/types/glob-stream/ @Bartvds +/types/global-tunnel-ng/ @BendingBender +/types/globalize/ @gcastre @afromogli +/types/globalize-compiler/ @iclanton +/types/globby/ @douglasduteil +/types/globule/ @durad +/types/gm/ @ChaosinaCan +/types/go/ @NorthwoodsSoftware +/types/google-adwords-scripts/ @jafaircl +/types/google-apps-script/ @motemen +/types/google-cloud__storage/ @blove @nbperry +/types/google-earth/ @icholy +/types/google-images/ @dolanmiu +/types/google-libphonenumber/ @leonyu +/types/google-map-react/ @honzabrecka +/types/google-maps/ @DeividasBakanas @GiedriusGrabauskas +/types/google-protobuf/ @marcuslongmuir +/types/google.feeds/ @RodneyJT +/types/google.fonts/ @danmarshall +/types/google.geolocation/ @vbortone +/types/google.picker/ @grapswiz +/types/google.visualization/ @danludwig @gmoore-sjcorg @danmana @mlcheng @IvanBisultanov +/types/googlemaps/ @cgwrench @nertzy @xaolas @mrmcnerd @martincostello +/types/googlemaps.infobubble/ @Dashue +/types/got/ @BendingBender @LinusU +/types/graceful-fs/ @Bartvds +/types/graham_scan/ @hberntsen +/types/graphene-pk11/ @microshine +/types/graphite-udp/ @EricByers +/types/graphql/ @TonyPythoneer @calebmer @intellix @firede @kepennar @freiksenet +/types/graphql-date/ @enaeseth +/types/graphql-relay/ @arvitaly @nitintutlani @Grelinfo +/types/graphql-type-json/ @schfkt +/types/graphviz/ @mhfrantz +/types/gravatar/ @denis-sokolov +/types/greasemonkey/ @kotas +/types/grecaptcha/ @DethAriel +/types/gregorian-calendar/ @cwalv +/types/griddle-react/ @hodavidhara +/types/gridfs-stream/ @liorm +/types/gridstack/ @PascalSenn @ZoolWay @Sl1MBoy +/types/grunt/ @jeffmay @basarat +/types/gsap/ @codebelt @ProbablePrime +/types/gulp/ @GiedriusGrabauskas +/types/gulp-angular-templatecache/ @amanmahajan7 +/types/gulp-babel/ @AyaMorisawa +/types/gulp-batch/ @alvarollmenezes @vizeke +/types/gulp-cache/ @aravindarun +/types/gulp-cached/ @tomc974 +/types/gulp-changed/ @tomc974 +/types/gulp-cheerio/ @tkQubo +/types/gulp-coffeeify/ @tkQubo +/types/gulp-coffeelint/ @tkQubo +/types/gulp-concat/ @k-kagurazaka +/types/gulp-connect/ @andrewiggins +/types/gulp-copy/ @aravindarun +/types/gulp-csso/ @tkrotoff +/types/gulp-debug/ @tkrotoff +/types/gulp-diff/ @ikatyang +/types/gulp-dtsm/ @AyaMorisawa +/types/gulp-espower/ @tkQubo +/types/gulp-file-include/ @DanielRosenwasser +/types/gulp-filter/ @tkrotoff +/types/gulp-flatten/ @k-kagurazaka +/types/gulp-gzip/ @tkQubo +/types/gulp-help/ @tkQubo +/types/gulp-help-doc/ @Mikhus +/types/gulp-html-replace/ @peterjuras +/types/gulp-htmlmin/ @tkrotoff +/types/gulp-if/ @joeskeen +/types/gulp-inject/ @k-kagurazaka +/types/gulp-insert/ @shantmarouti +/types/gulp-install/ @peterjuras +/types/gulp-jade/ @berwyn +/types/gulp-jasmine-browser/ @tkrotoff +/types/gulp-json-editor/ @peterjuras +/types/gulp-jspm/ @peterjuras +/types/gulp-less/ @k-kagurazaka +/types/gulp-load-plugins/ @joeskeen +/types/gulp-minify-css/ @k-kagurazaka +/types/gulp-minify-html/ @tkrotoff +/types/gulp-modernizr/ @remisery +/types/gulp-newer/ @tomc974 +/types/gulp-ng-annotate/ @tkQubo +/types/gulp-nodemon/ @tkQubo +/types/gulp-plumber/ @joeskeen +/types/gulp-protractor/ @tkrotoff +/types/gulp-pug/ @remisery +/types/gulp-remember/ @tomc974 +/types/gulp-rev/ @tkrotoff +/types/gulp-rev-replace/ @tkrotoff +/types/gulp-ruby-sass/ @agnislav +/types/gulp-shell/ @tkqubo +/types/gulp-size/ @tkrotoff @remisery +/types/gulp-sort/ @joeskeen +/types/gulp-strip-debug/ @peterjuras +/types/gulp-svg-sprite/ @tkqubo +/types/gulp-task-listing/ @joeskeen +/types/gulp-tsd/ @k-kagurazaka +/types/gulp-uglify/ @ChristopherHaws @leonard-thieu +/types/gulp-useref/ @tkrotoff +/types/gulp-util/ @jedmao +/types/gulp-watch/ @tkrotoff +/types/gzip-size/ @plantain-00 +/types/h2o2/ @jasonswearingen @AJamesPhillips +/types/halfred/ @dherges +/types/halogen/ @steller +/types/hammerjs/ @milkisevil @codler +/types/handlebars/ @borisyankov +/types/handsontable/ @panesofglass @astegmaier +/types/hapi/v8/ @jasonswearingen +/types/hapi/v12/ @jasonswearingen +/types/hapi/v15/ @jasonswearingen +/types/hapi/ @jasonswearingen @AJamesPhillips +/types/hapi-auth-basic/ @AJamesPhillips +/types/hapi-auth-jwt2/ @warrenseymour +/types/hapi-decorators/ @kenhowardpdx +/types/har-format/ @micmro +/types/hard-rejection/ @BendingBender +/types/harmony-proxy/ @remojansen +/types/has-ansi/ @BendingBender +/types/hash-file/ @HiromiShikata +/types/hash-stream/ @BendingBender +/types/hasha/ @BendgingBender +/types/hasher/ @flyfishMT +/types/hashids/ @pocesar +/types/hashmap/ @outring +/types/haversine/ @screendriver +/types/he/ @sedwards2009 +/types/headroom/ @hakubo +/types/heap/ @ryan10132 +/types/heatmap.js/ @lookuptable +/types/hedron/ @dborysov +/types/hellojs/ @PavelPZ @vuorinem +/types/hellosign-embedded/ @xt0rted +/types/helmet/ @cyrilschumacher @EvanHahn @bluehatbrit +/types/heredatalens/ @denyo +/types/heremaps/ @Josh-ES @denyo +/types/highcharts/ @damianog @baltie @AlbertOzimek @hanssens +/types/highcharts-ng/ @scatcher +/types/highland/ @Bartvds @hgwood @iwllyu +/types/highlight.js/ @nikeee @sourrust +/types/hiredis/ @titan +/types/history/v2/ @sergey-buturlakin @ngbrown +/types/history/v3/ @sergey-buturlakin @ngbrown @LKay +/types/history/ @sergey-buturlakin @ngbrown @rokoroku +/types/history.js/ @borisyankov @gjunge +/types/hjson/ @crunchie84 +/types/hls.js/ @jgainfort +/types/hoek/ @prashaantt +/types/homeworks/ @KennethanCeyer +/types/hooker/ @misak113 +/types/hopscotch/ @pimterry +/types/howler/ @xperiments @tdukart +/types/hpp/ @kryops +/types/html-entities/ @xstoudi +/types/html-minifier/ @tkrotoff +/types/html-pdf/ @westy92 +/types/html-to-text/ @erykwarren +/types/html-webpack-plugin/ @deevus @bumbleblym +/types/html-webpack-template/ @bumbleblym +/types/html2canvas/ @rwhepburn @tan9 +/types/htmlbars-inline-precompile/ @chriskrycho +/types/htmlparser2/ @staticfunction +/types/htmltojsx/ @basarat +/types/http-assert/ @jkeylu +/types/http-aws-es/ @marcogrcr +/types/http-codes/ @mhegazy +/types/http-errors/ @tkrotoff @BendingBender +/types/http-proxy/ @SomaticIT +/types/http-proxy-middleware/ @zebMcCorkle @BendingBender +/types/http-status/ @misak113 +/types/http-status-codes/ @JoshMcCullough +/types/http-string-parser/ @pine613 +/types/httperr/ @yortus +/types/hubot/ @dirk +/types/hubspot-pace/ @borislavjivkov +/types/humane/ @jmvrbanac +/types/humanize-plus/ @DenisCarriere +/types/humanparser/ @MichalPodeszwa +/types/humps/ @nikeee +/types/hyco-ws/ @mrcabellom +/types/hyperscript/ @spacejack @jmfirth +/types/hypertext-application-language/ @maks3w +/types/hystrixjs/ @igorsechyn +/types/i18n/ @SomaticIT @FindQ +/types/i18next/v2/ @mxl @deerawan @GiedriusGrabauskas +/types/i18next/ @mxl @deerawan @GiedriusGrabauskas +/types/i18next-browser-languagedetector/v0/ @cyrilschumacher @GiedriusGrabauskas +/types/i18next-browser-languagedetector/ @cyrilschumacher @GiedriusGrabauskas +/types/i18next-express-middleware/ @cyrilschumacher +/types/i18next-node-fs-backend/ @cyrilschumacher +/types/i18next-sprintf-postprocessor/ @cyrilschumacher +/types/i18next-xhr-backend/ @jamuhl @GiedriusGrabauskas +/types/i2c-bus/ @101100 +/types/iban/ @cyrilschumacher +/types/ibm-mobilefirst/ @nacho4d +/types/ibm_db/ @agov +/types/icepick/ @ngbrown @tobico +/types/icheck/ @qcz +/types/iconv/ @delphinus35 +/types/iconv-lite/ @poelstra +/types/ids/ @3fd +/types/iframe-resizer/ @arminbaljic +/types/ignite-ui/ @IgniteUI +/types/image-size/ @elisee +/types/imagemagick/ @soywiz +/types/imagemagick-native/ @horiuchi +/types/imagemapster/ @delphinus35 +/types/images/ @DingWeizhe +/types/imagesloaded/ @coldacid @apexskier +/types/imap/ @psnider +/types/imap-simple/ @pushplay +/types/imgur-rest-api/ @lukewestby +/types/immutability-helper/ @seansfkelley +/types/impress/ @borisyankov +/types/in-range/ @DanielRosenwasser +/types/incremental-dom/ @basarat @lanthaler @vvakame +/types/indent-string/ @mhegazy +/types/inert/ @nycdotnet @AJamesPhillips +/types/inflected/ @dsci +/types/inflection/ @shiwano +/types/inherits/ @chrootsu +/types/ini/ @marcinporebski +/types/iniparser/ @chrootsu +/types/inline-css/ @philipisapain +/types/inline-style-prefixer/ @ahz @dpetrezselyova +/types/inquirer/ @tkQubo @ppathan +/types/insert-module-globals/ @leonard-thieu +/types/insight/ @vvakame +/types/integer/ @Morfent +/types/interact.js/ @dduugg @adidahiya @thasner +/types/intercomjs/ @spencerwi +/types/internal-ip/ @BendingBender +/types/intl/ @RagibHasin +/types/intl-messageformat/ @mhegazy +/types/intl-tel-input/ @fdnhkj @leonard-thieu +/types/into-stream/ @BendingBender +/types/intro.js/ @anahkiasen +/types/invariant/ @bennett000 +/types/inversify-devtools/ @inversify +/types/ion.rangeslider/v1/ @dduugg +/types/ion.rangeslider/ @sixinli +/types/ionic/ @spencerwi +/types/ioredis/ @chrisleck +/types/ip/ @codeanimal +/types/ip-regex/ @unindented +/types/irc/ @phillips1012 +/types/is/ @cabralRodrigo +/types/is-absolute-url/ @mhegazy +/types/is-alphanumerical/ @vutran +/types/is-archive/ @mhegazy +/types/is-array/ @pine +/types/is-binary-path/ @DanielRosenwasser +/types/is-compressed/ @mhegazy +/types/is-finite/ @mhegazy +/types/is-ip/ @coderslagoon +/types/is-my-json-valid/ @kruncher +/types/is-number/ @harryshipton +/types/is-path-cwd/ @DanielRosenwasser +/types/is-path-in-cwd/ @mhegazy +/types/is-plain-object/ @zengfenfei +/types/is-promise/ @DanielRosenwasser +/types/is-relative-url/ @mhegazy +/types/is-root/ @mhegazy +/types/is-root-path/ @mhegazy +/types/is-stream/ @me +/types/is-svg/ @BendingBender +/types/is-text-path/ @mhegazy +/types/is-url/ @RyotaMurohoshi +/types/is-url-superb/ @kryops +/types/is-windows/ @mizunashi-mana +/types/isbn-utils/ @elhaard +/types/iscroll/ @csrakowski +/types/iso-3166-2/ @sicilica +/types/iso8601-localizer/ @avielfedida +/types/isomorphic-fetch/ @toddlucas +/types/isotope-layout/ @avidenic +/types/istanbul/ @tkrotoff +/types/istanbul-middleware/ @hookclaw +/types/ityped/ @DanielRosenwasser +/types/ix.js/ @Igorbek +/types/jade/ @panuhorsmalahti +/types/jalaali-js/ @alitaheri +/types/japanese-holidays/ @syamatoo +/types/jasmine/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software +/types/jasmine-ajax/ @lgrignon +/types/jasmine-data_driven_tests/ @AnthonyMacKinnon +/types/jasmine-enzyme/ @bolatovumar +/types/jasmine-es6-promise-matchers/ @stephenlautier +/types/jasmine-expect/ @GeneralCss +/types/jasmine-fixture/ @craigbrett17 +/types/jasmine-given/ @shairez +/types/jasmine-jquery/ @gstamac +/types/jasmine-matchers/ @Bartvds +/types/jasmine-node/ @svi3c +/types/jasmine-promise-matchers/ @matthewjh +/types/jasmine_dom_matchers/ @devoto13 +/types/jasminewd2/ @sjelin +/types/java/ @jimlloyd @hrl7 +/types/java-applet/ @cyrilschumacher +/types/javascript-astar/ @ptlis +/types/javascript-bignum/ @sandersn +/types/javascript-obfuscator/ @sanex3339 +/types/javascript-state-machine/ @borisyankov @mdocter @MrBigDog2U @samael65535 @taoqf +/types/jbinary/ @tbureck +/types/jcanvas/ @rogierschouten +/types/jdataview/ @RReverser +/types/jdenticon/ @mtr +/types/jest/v16/ @NoHomey @jwbay +/types/jest/ @NoHomey @jwbay @asvetliakov @alexjoverm @epicallan @ikatyang +/types/jest-matchers/ @joscha +/types/jfs/ @tlaziuk +/types/jimp/ @Jack-Works +/types/jjv/ @Nemo157 +/types/jjve/ @Nemo157 +/types/jmespath/ @pushplay +/types/jodata/ @cgwrench +/types/johnny-five/ @nakakura +/types/joi/v6/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW +/types/joi/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt +/types/joigoose/ @boothwhack +/types/jointjs/ @areel @DavidDurman @DenEwout @CaselIT @ChrisMoran +/types/jpm/ @github-account-because-they-want-it +/types/jqgrid/ @lokeshpeta +/types/jqrangeslider/ @qcz +/types/jquery/v1/ @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @DickvdBrink @King2500 @leonard-thieu +/types/jquery/v2/ @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @DickvdBrink @King2500 @leonard-thieu +/types/jquery/ @leonard-thieu @borisyankov @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @johnnyreilly @DickvdBrink @King2500 +/types/jquery-ajax-chain/ @humana-fragilitas +/types/jquery-alertable/ @stever +/types/jquery-backstretch/ @dkulyk +/types/jquery-cropbox/ @PerKastman +/types/jquery-deparam/ @patsissons +/types/jquery-easy-loading/ @delphinus35 +/types/jquery-editable-select/ @baywet +/types/jquery-fullscreen/ @bgrieder +/types/jquery-galleria/ @rimig +/types/jquery-handsontable/ @intelorca +/types/jquery-jsonrpcclient/ @Ty3uK +/types/jquery-knob/ @iain8 +/types/jquery-mask-plugin/ @avidenic +/types/jquery-match-height/ @kbytesys +/types/jquery-mockjax/ @laszlojakab @vladeck +/types/jquery-mousewheel/ @xt0rted +/types/jquery-param/ @patsissons +/types/jquery-sortable/ @Seltzer +/types/jquery-steps/ @jblank @nickwph +/types/jquery-timeentry/ @marknadig +/types/jquery-toastmessage-plugin/ @joeskeen +/types/jquery-truncate-html/ @abraaoalves +/types/jquery-urlparam/ @stpettersens +/types/jquery-validation-unobtrusive/ @EnableSoftware +/types/jquery.address/ @martinduparc @mardaneus86 +/types/jquery.are-you-sure/ @jonegerton +/types/jquery.autosize/ @kingdango +/types/jquery.bbq/ @sunetos +/types/jquery.bootstrap.wizard/ @niemyjski +/types/jquery.cleditor/ @pushplay +/types/jquery.clientsidelogging/ @diullei +/types/jquery.color/ @derekcicerone +/types/jquery.colorbox/ @gjunge +/types/jquery.colorpicker/ @pushplay +/types/jquery.contextmenu/ @nvivo +/types/jquery.cookie/ @RoyGoode @BenLorantfy +/types/jquery.customselect/ @adamcoulombe +/types/jquery.cycle2/ @dnadolny +/types/jquery.dropotron/ @cyrilschumacher +/types/jquery.dynatree/ @fdecampredon +/types/jquery.elang/ @sumegizoltan +/types/jquery.fancytree/ @alphaleonis @abedi-ir +/types/jquery.finger/ @maxackley +/types/jquery.flagstrap/ @felipedgarcia +/types/jquery.fullscreen/ @piraveen +/types/jquery.gridster/ @jbaldwin +/types/jquery.growl/ @yeganemehr +/types/jquery.highlight-bartaz/ @Pro +/types/jquery.jnotify/ @jamescurran +/types/jquery.joyride/ @vbortone +/types/jquery.jsignature/ @pjmagee +/types/jquery.leanmodal/ @FinelySliced +/types/jquery.livestampjs/ @vbortone +/types/jquery.notify/ @evil-shrike +/types/jquery.notifybar/ @zaneli +/types/jquery.noty/ @kingdango @thelfensdrfer +/types/jquery.payment/ @ejsmith @johnrutherford +/types/jquery.pjax/ @lijunle +/types/jquery.placeholder/ @majorsilence @EnableSoftware +/types/jquery.pnotify/ @DavidSichau @FUNExtreme +/types/jquery.postmessage/ @lijunle +/types/jquery.prettyphoto/ @pgaske +/types/jquery.qrcode/ @danmana +/types/jquery.rateit/ @gjunge +/types/jquery.rowgrid/ @vinayak-garg +/types/jquery.scrollto/ @nestalk +/types/jquery.simplemodal/ @ForNeVeR +/types/jquery.simplepagination/ @nvivo +/types/jquery.simulate/ @derekcicerone +/types/jquery.slimscroll/ @Promact +/types/jquery.soap/ @tigerxy +/types/jquery.sortelements/ @tbureck +/types/jquery.superlink/ @niemyjski +/types/jquery.tagsmanager/ @vbortone +/types/jquery.tile/ @zaneli +/types/jquery.timepicker/ @anwarjaved +/types/jquery.timer/ @JoshStrobl +/types/jquery.tinycarousel/ @csrakowski +/types/jquery.tinyscrollbar/ @csrakowski +/types/jquery.tipsy/ @bdukes +/types/jquery.tools/ @joeskeen +/types/jquery.tooltipster/ @pjmagee @VorobeY1326 @leonard-thieu @janhi +/types/jquery.total-storage/ @JeremyCBrooks +/types/jquery.transit/ @MrBigDog2U +/types/jquery.ui.datetimepicker/ @dougajmcdonald +/types/jquery.ui.layout/ @Steve-Fenton @drarmstr +/types/jquery.uniform/ @flyfishMT +/types/jquery.validation/ @fdecampredon @johnnyreilly @avidenic +/types/jquery.watermark/ @anwarjaved +/types/jquerymobile/ @borisyankov +/types/jqueryui/ @borisyankov @johnnyreilly +/types/js-base64/ @DenisCarriere +/types/js-beautify/ @JoshuaKGoldberg @hansrwindhoff +/types/js-clipper/ @omni360 +/types/js-combinatorics/ @outring +/types/js-cookie/ @theodorejb +/types/js-data/v1/ @reppners +/types/js-data/ @reppners +/types/js-data-angular/ @reppners +/types/js-data-http/ @reppners +/types/js-fixtures/ @kazimanzurrashid +/types/js-git/ @Bartvds +/types/js-md5/ @mwmccarthy +/types/js-quantities/ @wrummler +/types/js-schema/ @marcinporebski @roblabat +/types/js-search/ @guoyunhe +/types/js-to-java/ @skyitachi +/types/js-url/ @pine613 +/types/js-yaml/ @Bartvds @sclausen +/types/js.spec/ @mattbishop +/types/jsbn/ @Evgenus +/types/jscrollpane/ @qcz +/types/jsdeferred/ @minodisk +/types/jsdom/ @leonard-thieu +/types/jsen/ @vladeck +/types/jsend/ @CaselIT +/types/jsesc/ @Bartvds +/types/jsfl/ @soywiz +/types/jsforce/ @dolanmiu @netes +/types/jshamcrest/ @dharkness +/types/jsmockito/ @shiver-me-timbers +/types/jsnox/ @stkb @DovydasNavickas +/types/json-merge-patch/ @senyaarseniy +/types/json-patch/ @vvakame +/types/json-pointer/ @Bartvds +/types/json-rpc-ws/ @npenin +/types/json-schema/ @bcherny +/types/json-socket/ @svi3c +/types/json-stable-stringify/ @mhfrantz +/types/json-stringify-safe/ @BendingBender +/types/json2md/ @MartynasZilinskas +/types/jsoneditor/ @alejo90 +/types/jsoneditoronline/ @vbortone +/types/jsonminify/ @no23reason +/types/jsonnet/ @hookclaw +/types/jsonp/ @surenkov +/types/jsonpath/ @horiuchi @ikatyang +/types/jsonrpc-serializer/ @Akim95 +/types/jsonstream/ @Bartvds +/types/jsonwebtoken/ @SomaticIT @danielheim +/types/jspdf/ @amberjs +/types/jsplumb/ @shearnie +/types/jsrender/ @zakki +/types/jsrp/ @harryshipton +/types/jss/ @Ptival +/types/jssha/ @randombk @SrTobi +/types/jstimezonedetect/ @olamothe +/types/jstorage/ @dflor003 +/types/jstree/ @adaskothebeast +/types/jsts/ @StephaneAlie +/types/jsuite/ @darrenhillconsulting +/types/jsuri/ @coldacid @flqw +/types/jsurl/ @agorshkov23 +/types/jsx-chai/ @nupplaphil +/types/jszip/ @mzeiher +/types/jug/ @yevt +/types/jui/ @easylogic +/types/jui-core/ @easylogic +/types/jui-grid/ @easylogic +/types/jweixin/ @taoqf +/types/jwplayer/ @martinduparc +/types/jwt-client/ @timoteoponce +/types/jwt-decode/ @GiedriusGrabauskas @madsmadsen +/types/jwt-simple/ @kenfdev @GaelMagnan +/types/kafka-node/ @dansitu @bkim54 @sfrooster @amiram +/types/karma/ @tkrotoff +/types/karma-chai/ @JayAndCatchFire +/types/karma-chai-sinon/ @vasek17 +/types/karma-coverage/ @tkrotoff +/types/karma-fixture/ @evictor +/types/karma-jasmine/ @michelsalib +/types/katex/ @mrand01 +/types/kcors/ @Xstoudi @izayoiko +/types/kdbush/ @DenisCarriere +/types/kefir/ @AyaMorisawa +/types/kendo-ui/ @telerik +/types/keyboardjs/ @vbortone @piranha771 +/types/keycloak-js/ @eppsilon +/types/keygrip/ @jkeylu +/types/keymaster/ @nitram509 +/types/keymirror/ @jfahrenkrug +/types/keypress.js/ @rcchen +/types/keysym/ @harryshipton +/types/keytar/ @miniak @shiftkey @juturu +/types/kik-browser/ @joelday +/types/klaw/ @mceachen +/types/klaw-sync/ @shiftkey +/types/knex/ @tkQubo @baronfel +/types/knockback/ @borisyankov +/types/knockout/ @EnableSoftware @BenjaminEckardt +/types/knockout-amd-helpers/ @DavidSichau +/types/knockout-secure-binding/ @pine613 +/types/knockout-transformations/ @johnnyreilly @Nemo157 +/types/knockout.deferred.updates/ @sgaliano +/types/knockout.editables/ @borisyankov +/types/knockout.es5/ @sgaliano +/types/knockout.kogrid/ @huer12 +/types/knockout.mapper/ @BMeyerKC +/types/knockout.mapping/ @borisyankov +/types/knockout.projections/ @johnnyreilly +/types/knockout.punches/ @johnnyreilly +/types/knockout.rx/ @Igorbek +/types/knockout.validation/ @danludwig +/types/knockout.viewmodel/ @oising +/types/knockstrap/ @adaskothebeast +/types/knuddels-userapps-api/ @Knuddels +/types/ko.plus/ @conficient +/types/koa/ @DavidCai1993 @jkeylu +/types/koa-basic-auth/ @Tobias4872 +/types/koa-bodyparser/ @hellopao +/types/koa-cache-control/ @pe8ter +/types/koa-compose/ @jkeylu +/types/koa-compress/ @hellopao +/types/koa-favicon/ @hellopao +/types/koa-generic-session/ @nsimmons +/types/koa-hbs/ @jcbmln @mudkipme +/types/koa-helmet/ @me +/types/koa-json/ @brooklyndev +/types/koa-json-error/ @mudkipme +/types/koa-jwt/ @brunokrebs +/types/koa-logger/ @geoffreak +/types/koa-morgan/ @vesse +/types/koa-mount/ @amirsaber +/types/koa-passport/ @horiuchi +/types/koa-pug/ @Xstoudi +/types/koa-redis/ @nsimmons +/types/koa-route/ @migstopheles +/types/koa-router/ @hellopao @schfkt +/types/koa-send/ @pe8ter +/types/koa-session/ @kerol2r20 +/types/koa-session-minimal/ @longztian +/types/koa-static/ @hellopao +/types/koa-views/ @brooklyndev +/types/koa-websocket/ @me +/types/kolite/ @borisyankov +/types/konami.js/ @mareek +/types/kramed/ @tonicblue +/types/kss/ @giladgray +/types/kue/ @drudge @amiram @pc-jedi +/types/kuromoji/ @mzsm +/types/lab/ @prashaantt +/types/ladda/ @dflor003 @leemicw +/types/lambda-phi/ @elitechance +/types/later/ @jasond-s +/types/latinize/ @GiedriusGrabauskas +/types/launchpad/ @rictic +/types/lazy.js/ @Bartvds +/types/lazypipe/ @tomc974 +/types/ldapjs/ @cvillemure @peterkooijmans +/types/leadfoot/ @theintern +/types/leaflet/v0/ @rgripper +/types/leaflet/ @alejo90 +/types/leaflet-areaselect/ @awallat +/types/leaflet-curve/ @onikiienko +/types/leaflet-draw/ @matt-guest @reblace +/types/leaflet-editable/ @dalie +/types/leaflet-fullscreen/ @DenisCarriere +/types/leaflet-imageoverlay-rotated/ @tkleinke +/types/leaflet-label/ @Nemo157 +/types/leaflet-polylinedecorator/ @soucekv +/types/leaflet-providers/ @BendingBender +/types/leaflet.awesome-markers/v0/ @Odrin @sebek64 +/types/leaflet.awesome-markers/ @sebek64 +/types/leaflet.fullscreen/ @wcomartin +/types/leaflet.gridlayer.googlemutant/ @ernest-rhinozeros +/types/leaflet.locatecontrol/ @DenisCarriere +/types/leaflet.markercluster/ @rimig +/types/leaflet.markercluster.layersupport/ @AsamK +/types/leaflet.pm/ @tkleinke +/types/leapmotionts/ @logotype +/types/left-pad/ @Goldsmith42 +/types/less/ @thasner @pranaygp +/types/less-middleware/ @federicobond +/types/lestate/ @thelambdaparty +/types/level-sublevel/ @basp +/types/leveldown/ @tarruda +/types/levelup/ @blittle @tarruda +/types/leven/ @jmalonzo +/types/levenshtein/ @geoffreak +/types/libpq/ @Lodin +/types/libxmljs/ @fdecampredon +/types/libxslt/ @alejo90 +/types/license-checker/ @rogierschouten +/types/lime-js/ @arthur-xavier +/types/line-by-line/ @etomsen +/types/line-reader/ @stpettersens +/types/linkify-it/ @praxxis +/types/linq4js/ @morrisjdev +/types/lls/ @borislavjivkov +/types/load-json-file/ @SamVerschueren +/types/loader-runner/ @e-cloud +/types/loader-utils/ @Perlmint +/types/lobibox/ @itboy87 +/types/localforage-cordovasqlitedriver/ @thgreasi +/types/localized-countries/ @coderslagoon +/types/locate-path/ @me +/types/lockfile/v0/ @Bartvds +/types/lockfile/ @Bartvds @BendingBender +/types/lockr/ @droritos +/types/locutus/ @hookclaw +/types/lodash/v3/ @bczengel @chrootsu +/types/lodash/ @bczengel @chrootsu @stepancar @ericanderson @aj-r @ailrun +/types/lodash-es/ @stephenlautier +/types/lodash-webpack-plugin/ @bumbleblym +/types/lodash.add/ @bczengel @chrootsu @stepancar +/types/lodash.after/ @bczengel @chrootsu @stepancar +/types/lodash.ary/ @bczengel @chrootsu @stepancar +/types/lodash.assign/ @bczengel @chrootsu @stepancar +/types/lodash.assignin/ @bczengel @chrootsu @stepancar +/types/lodash.assigninwith/ @bczengel @chrootsu @stepancar +/types/lodash.assignwith/ @bczengel @chrootsu @stepancar +/types/lodash.at/ @bczengel @chrootsu @stepancar +/types/lodash.attempt/ @bczengel @chrootsu @stepancar +/types/lodash.before/ @bczengel @chrootsu @stepancar +/types/lodash.bind/ @bczengel @chrootsu @stepancar +/types/lodash.bindall/ @bczengel @chrootsu @stepancar +/types/lodash.bindkey/ @bczengel @chrootsu @stepancar +/types/lodash.camelcase/ @bczengel @chrootsu @stepancar +/types/lodash.capitalize/ @bczengel @chrootsu @stepancar +/types/lodash.castarray/ @bczengel @chrootsu @stepancar +/types/lodash.ceil/ @bczengel @chrootsu @stepancar +/types/lodash.chunk/ @bczengel @chrootsu @stepancar +/types/lodash.clamp/ @bczengel @chrootsu @stepancar +/types/lodash.clone/ @bczengel @chrootsu @stepancar +/types/lodash.clonedeep/ @bczengel @chrootsu @stepancar +/types/lodash.clonedeepwith/ @bczengel @chrootsu @stepancar +/types/lodash.clonewith/ @bczengel @chrootsu @stepancar +/types/lodash.compact/ @bczengel @chrootsu @stepancar +/types/lodash.concat/ @bczengel @chrootsu @stepancar +/types/lodash.constant/ @bczengel @chrootsu @stepancar +/types/lodash.countby/ @bczengel @chrootsu @stepancar +/types/lodash.create/ @bczengel @chrootsu @stepancar +/types/lodash.curry/ @bczengel @chrootsu @stepancar +/types/lodash.curryright/ @bczengel @chrootsu @stepancar +/types/lodash.debounce/ @bczengel @chrootsu @stepancar +/types/lodash.deburr/ @bczengel @chrootsu @stepancar +/types/lodash.defaults/ @bczengel @chrootsu @stepancar +/types/lodash.defaultsdeep/ @bczengel @chrootsu @stepancar +/types/lodash.defer/ @bczengel @chrootsu @stepancar +/types/lodash.delay/ @bczengel @chrootsu @stepancar +/types/lodash.difference/ @bczengel @chrootsu @stepancar +/types/lodash.differenceby/ @bczengel @chrootsu @stepancar +/types/lodash.differencewith/ @bczengel @chrootsu @stepancar +/types/lodash.drop/ @bczengel @chrootsu @stepancar +/types/lodash.dropright/ @bczengel @chrootsu @stepancar +/types/lodash.droprightwhile/ @bczengel @chrootsu @stepancar +/types/lodash.dropwhile/ @bczengel @chrootsu @stepancar +/types/lodash.endswith/ @bczengel @chrootsu @stepancar +/types/lodash.eq/ @bczengel @chrootsu @stepancar +/types/lodash.escape/ @bczengel @chrootsu @stepancar +/types/lodash.escaperegexp/ @bczengel @chrootsu @stepancar +/types/lodash.every/ @bczengel @chrootsu @stepancar +/types/lodash.fill/ @bczengel @chrootsu @stepancar +/types/lodash.filter/ @bczengel @chrootsu @stepancar +/types/lodash.find/ @bczengel @chrootsu @stepancar +/types/lodash.findindex/ @bczengel @chrootsu @stepancar +/types/lodash.findkey/ @bczengel @chrootsu @stepancar +/types/lodash.findlast/ @bczengel @chrootsu @stepancar +/types/lodash.findlastindex/ @bczengel @chrootsu @stepancar +/types/lodash.findlastkey/ @bczengel @chrootsu @stepancar +/types/lodash.first/ @bczengel @chrootsu @stepancar +/types/lodash.flatmap/ @bczengel @chrootsu @stepancar +/types/lodash.flatten/ @bczengel @chrootsu @stepancar +/types/lodash.flattendeep/ @bczengel @chrootsu @stepancar +/types/lodash.flattendepth/ @bczengel @chrootsu @stepancar +/types/lodash.flip/ @bczengel @chrootsu @stepancar +/types/lodash.floor/ @bczengel @chrootsu @stepancar +/types/lodash.flow/ @bczengel @chrootsu @stepancar +/types/lodash.flowright/ @bczengel @chrootsu @stepancar +/types/lodash.foreach/ @bczengel @chrootsu @stepancar +/types/lodash.foreachright/ @bczengel @chrootsu @stepancar +/types/lodash.forin/ @bczengel @chrootsu @stepancar +/types/lodash.forinright/ @bczengel @chrootsu @stepancar +/types/lodash.forown/ @bczengel @chrootsu @stepancar +/types/lodash.forownright/ @bczengel @chrootsu @stepancar +/types/lodash.frompairs/ @bczengel @chrootsu @stepancar +/types/lodash.functions/ @bczengel @chrootsu @stepancar +/types/lodash.functionsin/ @bczengel @chrootsu @stepancar +/types/lodash.get/ @bczengel @chrootsu @stepancar +/types/lodash.groupby/ @bczengel @chrootsu @stepancar +/types/lodash.gt/ @bczengel @chrootsu @stepancar +/types/lodash.gte/ @bczengel @chrootsu @stepancar +/types/lodash.has/ @bczengel @chrootsu @stepancar +/types/lodash.hasin/ @bczengel @chrootsu @stepancar +/types/lodash.head/ @bczengel @chrootsu @stepancar +/types/lodash.identity/ @bczengel @chrootsu @stepancar +/types/lodash.includes/ @bczengel @chrootsu @stepancar +/types/lodash.indexof/ @bczengel @chrootsu @stepancar +/types/lodash.initial/ @bczengel @chrootsu @stepancar +/types/lodash.inrange/ @bczengel @chrootsu @stepancar +/types/lodash.intersection/ @bczengel @chrootsu @stepancar +/types/lodash.intersectionby/ @bczengel @chrootsu @stepancar +/types/lodash.intersectionwith/ @bczengel @chrootsu @stepancar +/types/lodash.invert/ @bczengel @chrootsu @stepancar +/types/lodash.invertby/ @bczengel @chrootsu @stepancar +/types/lodash.invoke/ @bczengel @chrootsu @stepancar +/types/lodash.invokemap/ @bczengel @chrootsu @stepancar +/types/lodash.isarguments/ @bczengel @chrootsu @stepancar +/types/lodash.isarray/ @bczengel @chrootsu @stepancar +/types/lodash.isarraybuffer/ @bczengel @chrootsu @stepancar +/types/lodash.isarraylike/ @bczengel @chrootsu @stepancar +/types/lodash.isarraylikeobject/ @bczengel @chrootsu @stepancar +/types/lodash.isboolean/ @bczengel @chrootsu @stepancar +/types/lodash.isbuffer/ @bczengel @chrootsu @stepancar +/types/lodash.isdate/ @bczengel @chrootsu @stepancar +/types/lodash.iselement/ @bczengel @chrootsu @stepancar +/types/lodash.isempty/ @bczengel @chrootsu @stepancar +/types/lodash.isequal/ @bczengel @chrootsu @stepancar +/types/lodash.isequalwith/ @bczengel @chrootsu @stepancar +/types/lodash.iserror/ @bczengel @chrootsu @stepancar +/types/lodash.isfinite/ @bczengel @chrootsu @stepancar +/types/lodash.isfunction/ @bczengel @chrootsu @stepancar +/types/lodash.isinteger/ @bczengel @chrootsu @stepancar +/types/lodash.islength/ @bczengel @chrootsu @stepancar +/types/lodash.ismap/ @bczengel @chrootsu @stepancar +/types/lodash.ismatch/ @bczengel @chrootsu @stepancar +/types/lodash.ismatchwith/ @bczengel @chrootsu @stepancar +/types/lodash.isnan/ @bczengel @chrootsu @stepancar +/types/lodash.isnative/ @bczengel @chrootsu @stepancar +/types/lodash.isnil/ @bczengel @chrootsu @stepancar +/types/lodash.isnull/ @bczengel @chrootsu @stepancar +/types/lodash.isnumber/ @bczengel @chrootsu @stepancar +/types/lodash.isobject/ @bczengel @chrootsu @stepancar +/types/lodash.isobjectlike/ @bczengel @chrootsu @stepancar +/types/lodash.isplainobject/ @bczengel @chrootsu @stepancar +/types/lodash.isregexp/ @bczengel @chrootsu @stepancar +/types/lodash.issafeinteger/ @bczengel @chrootsu @stepancar +/types/lodash.isset/ @bczengel @chrootsu @stepancar +/types/lodash.isstring/ @bczengel @chrootsu @stepancar +/types/lodash.issymbol/ @bczengel @chrootsu @stepancar +/types/lodash.istypedarray/ @bczengel @chrootsu @stepancar +/types/lodash.isundefined/ @bczengel @chrootsu @stepancar +/types/lodash.isweakmap/ @bczengel @chrootsu @stepancar +/types/lodash.isweakset/ @bczengel @chrootsu @stepancar +/types/lodash.iteratee/ @bczengel @chrootsu @stepancar +/types/lodash.join/ @bczengel @chrootsu @stepancar +/types/lodash.kebabcase/ @bczengel @chrootsu @stepancar +/types/lodash.keyby/ @bczengel @chrootsu @stepancar +/types/lodash.keys/ @bczengel @chrootsu @stepancar +/types/lodash.keysin/ @bczengel @chrootsu @stepancar +/types/lodash.last/ @bczengel @chrootsu @stepancar +/types/lodash.lastindexof/ @bczengel @chrootsu @stepancar +/types/lodash.lowercase/ @bczengel @chrootsu @stepancar +/types/lodash.lowerfirst/ @bczengel @chrootsu @stepancar +/types/lodash.lt/ @bczengel @chrootsu @stepancar +/types/lodash.lte/ @bczengel @chrootsu @stepancar +/types/lodash.mapkeys/ @bczengel @chrootsu @stepancar +/types/lodash.mapvalues/ @bczengel @chrootsu @stepancar +/types/lodash.matches/ @bczengel @chrootsu @stepancar +/types/lodash.matchesproperty/ @bczengel @chrootsu @stepancar +/types/lodash.max/ @bczengel @chrootsu @stepancar +/types/lodash.maxby/ @bczengel @chrootsu @stepancar +/types/lodash.mean/ @bczengel @chrootsu @stepancar +/types/lodash.meanby/ @bczengel @chrootsu @stepancar +/types/lodash.memoize/ @bczengel @chrootsu @stepancar +/types/lodash.merge/ @bczengel @chrootsu @stepancar +/types/lodash.mergewith/ @bczengel @chrootsu @stepancar +/types/lodash.method/ @bczengel @chrootsu @stepancar +/types/lodash.methodof/ @bczengel @chrootsu @stepancar +/types/lodash.min/ @bczengel @chrootsu @stepancar +/types/lodash.minby/ @bczengel @chrootsu @stepancar +/types/lodash.mixin/ @bczengel @chrootsu @stepancar +/types/lodash.negate/ @bczengel @chrootsu @stepancar +/types/lodash.noop/ @bczengel @chrootsu @stepancar +/types/lodash.now/ @bczengel @chrootsu @stepancar +/types/lodash.nth/ @bczengel @chrootsu @stepancar +/types/lodash.ntharg/ @bczengel @chrootsu @stepancar +/types/lodash.omit/ @bczengel @chrootsu @stepancar +/types/lodash.omitby/ @bczengel @chrootsu @stepancar +/types/lodash.once/ @bczengel @chrootsu @stepancar +/types/lodash.orderby/ @bczengel @chrootsu @stepancar +/types/lodash.over/ @bczengel @chrootsu @stepancar +/types/lodash.overargs/ @bczengel @chrootsu @stepancar +/types/lodash.overevery/ @bczengel @chrootsu @stepancar +/types/lodash.oversome/ @bczengel @chrootsu @stepancar +/types/lodash.pad/ @bczengel @chrootsu @stepancar +/types/lodash.padend/ @bczengel @chrootsu @stepancar +/types/lodash.padstart/ @bczengel @chrootsu @stepancar +/types/lodash.parseint/ @bczengel @chrootsu @stepancar +/types/lodash.partial/ @bczengel @chrootsu @stepancar +/types/lodash.partialright/ @bczengel @chrootsu @stepancar +/types/lodash.partition/ @bczengel @chrootsu @stepancar +/types/lodash.pick/ @bczengel @chrootsu @stepancar +/types/lodash.pickby/ @bczengel @chrootsu @stepancar +/types/lodash.property/ @bczengel @chrootsu @stepancar +/types/lodash.propertyof/ @bczengel @chrootsu @stepancar +/types/lodash.pull/ @bczengel @chrootsu @stepancar +/types/lodash.pullall/ @bczengel @chrootsu @stepancar +/types/lodash.pullallby/ @bczengel @chrootsu @stepancar +/types/lodash.pullat/ @bczengel @chrootsu @stepancar +/types/lodash.random/ @bczengel @chrootsu @stepancar +/types/lodash.range/ @bczengel @chrootsu @stepancar +/types/lodash.rangeright/ @bczengel @chrootsu @stepancar +/types/lodash.rearg/ @bczengel @chrootsu @stepancar +/types/lodash.reduce/ @bczengel @chrootsu @stepancar +/types/lodash.reduceright/ @bczengel @chrootsu @stepancar +/types/lodash.reject/ @bczengel @chrootsu @stepancar +/types/lodash.remove/ @bczengel @chrootsu @stepancar +/types/lodash.repeat/ @bczengel @chrootsu @stepancar +/types/lodash.replace/ @bczengel @chrootsu @stepancar +/types/lodash.rest/ @bczengel @chrootsu @stepancar +/types/lodash.result/ @bczengel @chrootsu @stepancar +/types/lodash.reverse/ @bczengel @chrootsu @stepancar +/types/lodash.round/ @bczengel @chrootsu @stepancar +/types/lodash.sample/ @bczengel @chrootsu @stepancar +/types/lodash.samplesize/ @bczengel @chrootsu @stepancar +/types/lodash.set/ @bczengel @chrootsu @stepancar +/types/lodash.setwith/ @bczengel @chrootsu @stepancar +/types/lodash.shuffle/ @bczengel @chrootsu @stepancar +/types/lodash.size/ @bczengel @chrootsu @stepancar +/types/lodash.slice/ @bczengel @chrootsu @stepancar +/types/lodash.snakecase/ @bczengel @chrootsu @stepancar +/types/lodash.some/ @bczengel @chrootsu @stepancar +/types/lodash.sortby/ @bczengel @chrootsu @stepancar +/types/lodash.sortedindex/ @bczengel @chrootsu @stepancar +/types/lodash.sortedindexby/ @bczengel @chrootsu @stepancar +/types/lodash.sortedindexof/ @bczengel @chrootsu @stepancar +/types/lodash.sortedlastindex/ @bczengel @chrootsu @stepancar +/types/lodash.sortedlastindexby/ @bczengel @chrootsu @stepancar +/types/lodash.sortedlastindexof/ @bczengel @chrootsu @stepancar +/types/lodash.sorteduniq/ @bczengel @chrootsu @stepancar +/types/lodash.sorteduniqby/ @bczengel @chrootsu @stepancar +/types/lodash.split/ @bczengel @chrootsu @stepancar +/types/lodash.spread/ @bczengel @chrootsu @stepancar +/types/lodash.startcase/ @bczengel @chrootsu @stepancar +/types/lodash.startswith/ @bczengel @chrootsu @stepancar +/types/lodash.subtract/ @bczengel @chrootsu @stepancar +/types/lodash.sum/ @bczengel @chrootsu @stepancar +/types/lodash.sumby/ @bczengel @chrootsu @stepancar +/types/lodash.tail/ @bczengel @chrootsu @stepancar +/types/lodash.take/ @bczengel @chrootsu @stepancar +/types/lodash.takeright/ @bczengel @chrootsu @stepancar +/types/lodash.takerightwhile/ @bczengel @chrootsu @stepancar +/types/lodash.takewhile/ @bczengel @chrootsu @stepancar +/types/lodash.template/ @bczengel @chrootsu @stepancar +/types/lodash.throttle/ @bczengel @chrootsu @stepancar +/types/lodash.times/ @bczengel @chrootsu @stepancar +/types/lodash.toarray/ @bczengel @chrootsu @stepancar +/types/lodash.tointeger/ @bczengel @chrootsu @stepancar +/types/lodash.tolength/ @bczengel @chrootsu @stepancar +/types/lodash.tolower/ @bczengel @chrootsu @stepancar +/types/lodash.tonumber/ @bczengel @chrootsu @stepancar +/types/lodash.topairs/ @bczengel @chrootsu @stepancar +/types/lodash.topairsin/ @bczengel @chrootsu @stepancar +/types/lodash.topath/ @bczengel @chrootsu @stepancar +/types/lodash.toplainobject/ @bczengel @chrootsu @stepancar +/types/lodash.tosafeinteger/ @bczengel @chrootsu @stepancar +/types/lodash.tostring/ @bczengel @chrootsu @stepancar +/types/lodash.toupper/ @bczengel @chrootsu @stepancar +/types/lodash.transform/ @bczengel @chrootsu @stepancar +/types/lodash.trim/ @bczengel @chrootsu @stepancar +/types/lodash.trimend/ @bczengel @chrootsu @stepancar +/types/lodash.trimstart/ @bczengel @chrootsu @stepancar +/types/lodash.truncate/ @bczengel @chrootsu @stepancar +/types/lodash.unary/ @bczengel @chrootsu @stepancar +/types/lodash.unescape/ @bczengel @chrootsu @stepancar +/types/lodash.union/ @bczengel @chrootsu @stepancar +/types/lodash.unionby/ @bczengel @chrootsu @stepancar +/types/lodash.unionwith/ @bczengel @chrootsu @stepancar +/types/lodash.uniq/ @bczengel @chrootsu @stepancar +/types/lodash.uniqby/ @bczengel @chrootsu @stepancar +/types/lodash.uniqueid/ @bczengel @chrootsu @stepancar +/types/lodash.uniqwith/ @bczengel @chrootsu @stepancar +/types/lodash.unset/ @bczengel @chrootsu @stepancar +/types/lodash.unzip/ @bczengel @chrootsu @stepancar +/types/lodash.unzipwith/ @bczengel @chrootsu @stepancar +/types/lodash.update/ @bczengel @chrootsu @stepancar +/types/lodash.uppercase/ @bczengel @chrootsu @stepancar +/types/lodash.upperfirst/ @bczengel @chrootsu @stepancar +/types/lodash.values/ @bczengel @chrootsu @stepancar +/types/lodash.valuesin/ @bczengel @chrootsu @stepancar +/types/lodash.without/ @bczengel @chrootsu @stepancar +/types/lodash.words/ @bczengel @chrootsu @stepancar +/types/lodash.wrap/ @bczengel @chrootsu @stepancar +/types/lodash.xor/ @bczengel @chrootsu @stepancar +/types/lodash.xorby/ @bczengel @chrootsu @stepancar +/types/lodash.xorwith/ @bczengel @chrootsu @stepancar +/types/lodash.zip/ @bczengel @chrootsu @stepancar +/types/lodash.zipobject/ @bczengel @chrootsu @stepancar +/types/lodash.zipobjectdeep/ @bczengel @chrootsu @stepancar +/types/lodash.zipwith/ @bczengel @chrootsu @stepancar +/types/log-symbols/ @BendingBender +/types/log-update/ @BendingBender +/types/log4javascript/ @Ritzlgrmft +/types/log4js/ @armorik83 +/types/logat/ @krvikash35 +/types/logg/ @blittle +/types/loggly/ @rmartone @geoffreak +/types/loglevel/ @Pro @flqw @szmeti +/types/logrotate-stream/ @rogierschouten +/types/lokijs/ @TeamworkGuy2 +/types/lolex/ @Nemo157 @joshuakgoldberg +/types/long/ @peterkooijmans +/types/loopback/ @kattsushi +/types/loopback-boot/ @kattsushi +/types/lorem-ipsum/ @durad +/types/lory.js/ @kubosho @milkisevil +/types/loud-rejection/ @BendingBender +/types/lovefield/ @freshp86 +/types/lowdb/ @typicode +/types/lowlight/ @NoHomey +/types/lru-cache/ @Bartvds +/types/lscache/ @Chris-Martinezz +/types/ltx/ @PJakcson +/types/luaparse/ @stpettersens +/types/lunr/ @sebastian-lenz +/types/lwip/ @AyaMorisawa +/types/lz-string/ @M0ns1gn0r +/types/magic-number/ @stpettersens +/types/magicsuggest/ @leonardochaia +/types/magnet-uri/ @tlaziuk +/types/mailcheck/ @pocesar +/types/maildev/ @cyrilschumacher @zbarbuto +/types/mailgen/ @vothanhkiet @jordanfarrer +/types/mailparser/ @psnider +/types/main-bower-files/ @k-kagurazaka +/types/make-dir/ @ikatyang @BendingBender +/types/maker.js/ @danmarshall +/types/mandrill-api/ @pocesar +/types/map-obj/ @BendingBender +/types/mapbox/ @anahkiasen +/types/mapbox-gl/ @dobrud +/types/mapbox__shelf-pack/ @Perlmint +/types/mapsjs/ @davismj +/types/mariasql/ @bennett000 +/types/markdown-it/ @rapropos +/types/markdown-it-anchor/ @seryl +/types/markdown-it-container/ @hronex +/types/marked/ @worr @BendingBender +/types/marker-animate-unobtrusive/ @viskin +/types/markerclustererplus/ @enanox +/types/markitup/ @drillbits +/types/maskedinput/ @lokeshpeta +/types/masonry-layout/ @m-a-wilson @warriorrocker +/types/massive/ @swissspidy @clarenceh +/types/match-media-mock/ @asvetliakov +/types/material-design-lite/ @bradzacher +/types/material-ui/ @ngbrown @theigor @alitaheri @herrmanno @DaIgeb @allienna @schlesingermatthias @InsidersByte @artyomsv @dan-j @minodisk +/types/materialize-css/ @eriklieben @leonyu @SinghSukhdeep +/types/math3d/ @laszlojakab +/types/mathjax/ @rolandzwaga +/types/mathjs/ @siavol +/types/matter-js/ @piranha771 +/types/maxmind/ @geoffreak +/types/mcustomscrollbar/ @flurg +/types/md5/ @arcdev1 @jprogrammer +/types/mdns/ @reppners +/types/media-typer/ @BendingBender +/types/medium-editor/ @keika299 +/types/mem/ @SamVerschueren +/types/memcached/ @KentarouTakeda +/types/memoizee/ @juanpicado +/types/memory-cache/ @jedigo +/types/memory-fs/ @e-cloud +/types/memwatch-next/ @cyrilschumacher +/types/meow/ @KnisterPeter +/types/merge-descriptors/ @danny8002 +/types/merge-stream/ @k-kagurazaka +/types/merge2/ @tkrotoff @smac89 +/types/mersenne-twister/ @KentarouTakeda +/types/meshblu/ @fnipo +/types/mess/ @Nemo157 +/types/messenger/ @derekcicerone +/types/meteor/ @barbatus @fullflavedave @orefalo @dagatsoin @birkskyum @ardatan @stefanholzapfel +/types/meteor-accounts-phone/ @DAB0mB +/types/meteor-collection-hooks/ @twastvedt +/types/meteor-jboulhous-dev/ @vangorra +/types/meteor-persistent-session/ @vangorra +/types/meteor-prime8consulting-oauth2/ @vangorra +/types/meteor-publish-composite/ @vangorra +/types/meteor-roles/ @vangorra +/types/method-override/ @santialbo +/types/methods/ @cprecioso +/types/metismenu/ @onokumus @denisname +/types/metric-suffix/ @davidm77 +/types/micro/ @kaoDev +/types/microgears/ @marcusdb +/types/micromatch/ @glen-84 +/types/microrouter/ @mathieudutour +/types/microsoft-ajax/ @pjmagee +/types/microsoft-live-connect/ @jvilk +/types/microsoft-sdk-soap/ @markusmauch +/types/microsoftteams/ @OfficeDev +/types/microtime/ @vincekovacs +/types/milkcocoa/ @odangosan +/types/mime/ @jedigo +/types/mime-db/ @AJamesPhillips +/types/mime-types/ @Perlmint +/types/mimos/ @AJamesPhillips +/types/mina/ @lhk @mattanja @kant2002 +/types/minimatch/ @vvakame @shantmarouti +/types/minimist/ @Bartvds @Necroskillz @kamranayub +/types/minipass/ @BendingBender +/types/mithril/ @spacejack @andraaspar @isiahmeadows +/types/mithril-global/ @spacejack @isiahmeadows +/types/mitm/ @alejo90 +/types/mixpanel/ @hjellek +/types/mixto/ @vvakame +/types/mkdirp/ @Bartvds +/types/mkpath/ @optical +/types/mobile-detect/ @martinmcwhorter +/types/mocha/ @kazimanzurrashid @otiai10 @jt000 @enlight +/types/mocha-phantomjs/ @ErikSchierboom +/types/mock-fs/ @Nemo157 @tkqubo +/types/mock-raf/ @djpereira +/types/mock-require/ @djpereira +/types/mockdate/ @brunolm +/types/mockery/ @jt000 +/types/modernizr/ @borisyankov @theodorejb @leonyu @lucax88x @nhardy +/types/modesl/ @neeschit +/types/moment-business/ @wonbyte +/types/moment-duration-format/ @SwintDC @TwoStone @leonard-thieu +/types/moment-jalaali/ @alitaheri +/types/moment-range/ @Burgov @wilgert @franjuan @MartynasZilinskas +/types/moment-round/ @jacobbaskin +/types/moment-timezone/ @michelsalib +/types/mongodb/ @CaselIT @alanmarcell @kikar +/types/mongoose/ @simonxca @horiuchi @sindrenm @lukasz-zak +/types/mongoose-auto-increment/ @AyaMorisawa +/types/mongoose-deep-populate/ @AyaMorisawa +/types/mongoose-mock/ @jt000 +/types/mongoose-paginate/ @linusbrolin @simonxca +/types/mongoose-promise/ @simonxca +/types/mongoose-seeder/ @Crevil +/types/mongoose-sequence/ @linusbrolin +/types/mongoose-simple-random/ @me +/types/mongoose-unique-validator/ @stevehipwell +/types/monk/ @wzr1337 +/types/moo/ @deltaidea +/types/morgan/ @staticfunction +/types/morris.js/ @mareek @sindilevich +/types/mousetrap/ @qcz +/types/move-concurrently/ @mgroenhoff +/types/moviedb/ @basarat @0x6368656174 +/types/moxios/ @itoasuka +/types/mpromise/ @sgkim126 +/types/mqtt/ @PekkaPLeppanen +/types/mri/ @shiftkey @j-f1 +/types/ms/ @danny8002 +/types/msgpack-lite/ @endel @efokschaner +/types/msgpack5/ @wokim @heycalmdown +/types/msnodesql/ @borisyankov @SomaticIT +/types/msportalfx-test/ @julioct +/types/mssql/ @jaminfarr @buzinas @mrrichar @elhaard @pkeuter +/types/mu2/ @jedigo +/types/multer/ @jt000 @DavidBR-SW @mxl @hyunseob +/types/multer-gridfs-storage/v1/ @devconcept +/types/multer-gridfs-storage/ @devconcept +/types/multer-s3/ @tcaesvk +/types/multi-typeof/ @mhegazy +/types/multimatch/ @stephenlautier +/types/multiparty/ @kenfdev +/types/multiplexjs/ @KamyarNazeri +/types/murmurhash-js/ @cvle +/types/murmurhash3js/ @dlee-nvisia +/types/musicmetadata/ @Xstoudi +/types/mustache/ @markashleybell +/types/mysql/ @wjohnsto @kacepe +/types/mz/ @ThomasHickman +/types/n3/ @phreed +/types/nano/ @timjacobi +/types/nanoajax/ @nathancahill +/types/nanomsg/ @titan +/types/nanoscroller/ @zihark17 +/types/nanp/ @karn +/types/natsort/ @mgroenhoff +/types/natural/ @dmoonfire +/types/natural-sort/ @a-morales +/types/navigation/ @grahammendick +/types/navigation-react/ @grahammendick +/types/navigo/ @aersamkull +/types/nblas/ @erikgerrits +/types/nconf/ @jedigo @jmthibault +/types/ncp/ @bartvds +/types/ndarray/ @pawsong @taoqf +/types/nearley/ @deltaidea +/types/nedb/ @reppners +/types/nedb-logger/ @thisboyiscrazy +/types/needle/v0/ @bigsan +/types/needle/ @bigsan @nikeee +/types/negotiator/ @BendingBender +/types/neo4j/ @cyrilschumacher +/types/nes/ @NoHomey +/types/netmask/ @mhfrantz +/types/nexpect/ @vvakame +/types/next/ @dru89 +/types/next-redux-wrapper/ @stevegeek +/types/ng-command/ @stephenlautier +/types/ng-cordova/ @ksachdeva +/types/ng-dialog/ @stephenlautier +/types/ng-facebook/ @Crevil +/types/ng-file-upload/ @johnnyreilly @thewarpaint +/types/ng-flow/ @ryan10132 +/types/ng-grid/ @smithkl42 @rolandzwaga @kentcooper +/types/ng-i18next/ @cyrilschumacher +/types/ng-notify/ @nzamosenchuk +/types/ng-stomp/ @lpotapczuk +/types/ngbootbox/ @stpettersens +/types/ngeohash/ @erkie +/types/ngkookies/ @martinmcwhorter +/types/ngmap/ @nkovacic +/types/ngprogress/ @martinmcwhorter +/types/ngprogress-lite/ @LukeForder +/types/ngreact/ @velveret +/types/ngstorage/ @kubiq +/types/ngtoaster/ @btesser +/types/ngwysiwyg/ @patrick-mackay +/types/nightmare/ @horiuchi @samyang-au +/types/noble/ @swook @wind-rider @shantanubhadoria @lukel99 @bioball +/types/nock/ @bonnici @horiuchi +/types/nodal/ @charrondev +/types/node/v6/ @WilcoBakker +/types/node/v7/ @parambirs @RobDesideri @tellnes @WilcoBakker @Tyriar +/types/node/ @parambirs @RobDesideri @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @Tyriar @DeividasBakanas +/types/node-7z/ @erkie +/types/node-array-ext/ @Beng89 +/types/node-cache/ @chrootsu @dthunell +/types/node-calendar/ @luzianz +/types/node-cleanup/ @agadar +/types/node-common-errors/ @icopp +/types/node-dir/ @panuhorsmalahti +/types/node-dogstatsd/ @chrisbobo +/types/node-emoji/ @jonestristand +/types/node-feedparser/ @cortopy +/types/node-fetch/ @torstenwerner +/types/node-fibers/ @caryhaynie +/types/node-forge/ @westy92 @flynetworks @a-k-g +/types/node-gcm/ @horiuchi +/types/node-getopt/ @kcauchy +/types/node-hid/ @mhegazy @ert78gb +/types/node-hue-api/ @fjmorel +/types/node-int64/ @x3cion +/types/node-ipc/ @arvitaly +/types/node-jsfl-runner/ @mrand01 +/types/node-json-db/ @kuzn-ilya +/types/node-mysql-wrapper/ @kataras +/types/node-notifier/ @tkQubo +/types/node-pg-migrate/ @bradleyayers +/types/node-polyglot/ @timjk +/types/node-powershell/ @rodrigoff +/types/node-ral/ @ssddi456 +/types/node-rsa/ @alitaheri +/types/node-schedule/ @cyrilschumacher @flowpl +/types/node-slack/ @tkQubo +/types/node-snap7/ @heilingbrunner +/types/node-sprite-generator/ @Perlmint +/types/node-static/ @Morfent +/types/node-statsd/ @alexturek @convoyinc +/types/node-telegram-bot-api/ @ammuench @agadar +/types/node-uuid/ @jeffmay +/types/node-validator/ @kengorab +/types/node-vault/ @YuJianrong +/types/node-waves/ @stephenlautier +/types/node-wit/ @julienduf +/types/node-xmpp-client/ @PJakcson +/types/node-xmpp-core/ @PJakcson +/types/node-zookeeper-client/ @plantain-00 +/types/node_redis/ @borisyankov +/types/nodegit/ @dolanmiu +/types/nodemailer/ @rogierschouten +/types/nodemailer-direct-transport/ @rogierschouten +/types/nodemailer-mailgun-transport/ @otociulis +/types/nodemailer-pickup-transport/ @psnider +/types/nodemailer-ses-transport/ @westy92 +/types/nodemailer-smtp-pool/ @rogierschouten +/types/nodemailer-smtp-transport/ @rogierschouten +/types/nodemailer-stub-transport/ @cyrilschumacher +/types/nodeunit/ @jedigo +/types/noisejs/ @izmhr +/types/nomnom/ @panopticoncentral +/types/nopt/ @jbondc +/types/normalize-url/ @odin3 @BendingBender +/types/notie/ @mateusdemboski +/types/notify/ @hellochar +/types/notify.js/ @bahman616 +/types/notifyjs/ @soundTricker +/types/nouislider/v7/ @acoreyj +/types/nouislider/v8/ @bleuarg +/types/nouislider/ @bleuarg @lagaffe +/types/novnc-core/ @smithkl42 @BendingBender +/types/npm/ @SomaticIT +/types/npm-package-arg/ @mgroenhoff +/types/ns-api/ @Archcry +/types/nslog/ @unindented +/types/nsqjs/ @cezaryrk +/types/number-is-nan/ @mhegazy +/types/number-to-words/ @frederickfogerty +/types/numeral/ @vbortone +/types/numjs/ @taoqf +/types/nunjucks/ @RubenSlabbert +/types/nunjucks-date/ @kruncher +/types/nvd3/ @PjMitchell +/types/nw.gui/ @xperiments +/types/nw.js/ @alirdn +/types/o.js/ @IceOnFire @bradzacher @janhommes +/types/oauth.js/ @nobuoka +/types/oauth2-server/ @vangorra @cirick +/types/oauth2orize/ @wokim @heycalmdown @stevehipwell +/types/obelisk.js/ @bdrupieski +/types/object-assign/ @chbrown +/types/object-diff/ @rogierschouten +/types/object-hash/ @misak113 +/types/object-path/ @pocesar +/types/object-refs/ @3fd +/types/oblo-util/ @Oblosys +/types/oboe/ @optical +/types/observe-js/ @herrmanno +/types/oclazyload/ @rolandzwaga +/types/odata/ @janhommes +/types/ofe/ @Morfent +/types/office-js/ @OfficeDev @LanceEA +/types/offline-js/ @cgwrench +/types/oibackoff/ @geoffreak +/types/oidc-token-manager/ @rosieks +/types/on-finished/ @czechboy0 @BendingBender +/types/on-headers/ @jjeffery @BendingBender +/types/once/ @denis-sokolov @BendingBender +/types/onetime/ @BendingBender +/types/onoff/ @marcel-ernst +/types/open/ @Bartvds +/types/opener/ @tikurahul +/types/openfin/ @chrisbarker +/types/openjscad/ @danmarshall +/types/openlayers/v2/ @bolhovsky +/types/openlayers/v3/ @osechet @matthiasdailey-ccri +/types/openlayers/ @osechet @ganlhi +/types/openstack-wrapper/ @sanjaymadane +/types/opentok/ @westy92 @CatGuardian +/types/opentype.js/ @danmarshall +/types/opn/ @shinnn @SomaticIT +/types/optics-agent/ @crevil +/types/optimist/ @soywiz @chbrown +/types/optimize-css-assets-webpack-plugin/ @odnamrataizem +/types/ora/v0/ @screendriver +/types/ora/ @basarat @screendriver @BendingBender +/types/oracledb/ @Bigous +/types/orchestrator/ @tkQubo @TeamworkGuy2 +/types/orderedmap/ @bradleyayers +/types/orientjs/ @saeedtabrizi +/types/os-homedir/ @mhegazy +/types/os-locale/v1/ @AyaMorisawa @BendingBender +/types/os-locale/ @AyaMorisawa @BendingBender +/types/os-name/ @BendingBender +/types/os-tmpdir/ @mhegazy +/types/osmosis/ @jurajkocan +/types/osmtogeojson/ @tkqubo +/types/owlcarousel/ @dpiatkowski +/types/p-all/ @BendingBender +/types/p-any/ @BendingBender +/types/p-cancelable/ @BendingBender +/types/p-debounce/ @BendingBender +/types/p-defer/ @SamVerschueren +/types/p-do-whilst/ @BendingBender +/types/p-each-series/ @BendingBender +/types/p-event/ @BendingBender +/types/p-every/ @BendingBender +/types/p-lazy/ @BendingBender +/types/p-limit/ @BendingBender +/types/p-locate/ @BendingBender +/types/p-log/ @BendingBender +/types/p-map/ @BendingBender +/types/p-map-series/ @BendingBender +/types/p-one/ @BendingBender +/types/p-props/ @BendingBender +/types/p-queue/ @BendingBender @evanshortiss +/types/p-reduce/ @BendingBender +/types/p-reflect/ @BendingBender +/types/p-retry/ @BendingBender +/types/p-series/ @BendingBender +/types/p-settle/ @natesilva +/types/p-some/ @BendingBender +/types/p-tap/ @BendingBender +/types/p-throttle/ @BendingBender +/types/p-timeout/ @BendingBender +/types/p-try/ @BendingBender +/types/p-wait-for/ @BendingBender +/types/p-whilst/ @BendingBender +/types/p2/ @clark-stevenson +/types/packery/ @piraveen @hanssens +/types/pad/ @mhegazy +/types/paho-mqtt/ @amikhalev +/types/pako/ @cappellin @calebegg +/types/papaparse/ @torpedro @rainshen49 +/types/paper/ @clark-stevenson +/types/paralleljs/ @jbaldwin +/types/parse/ @dpoetzsch @jaeggerr +/types/parse-git-config/ @leonard-thieu +/types/parse-glob/ @glen-84 +/types/parse-link-header/ @zelein +/types/parse-mockdb/ @dpoetzsch +/types/parse-torrent/ @niieani @tlaziuk +/types/parse-torrent-file/ @tlaziuk +/types/parse-unit/ @Jack-Works +/types/parseurl/ @bomret +/types/parsimmon/ @Bartvds @mizunashi-mana @bcherny @bvanreeven @leonard-thieu +/types/passport/ @horiuchi @enaeseth +/types/passport-anonymous/ @0x6368656174 +/types/passport-beam/ @AtlasDev +/types/passport-client-cert/ @warnersean +/types/passport-discord/ @kzay +/types/passport-facebook/ @staticfunction @lucasmacosta +/types/passport-facebook-token/ @rmartone +/types/passport-github/ @yasupeke +/types/passport-github2/ @yasupeke @mthmulders +/types/passport-google-oauth/ @staticfunction +/types/passport-google-oauth2/ @bluehatbrit +/types/passport-http/ @krizalys +/types/passport-http-bearer/ @isman-usoh +/types/passport-jwt/ @mugeso @alsiola +/types/passport-local/ @SomaticIT +/types/passport-local-mongoose/ @linusbrolin +/types/passport-oauth2-client-password/ @akaNightmare +/types/passport-saml/ @cjbarth +/types/passport-steam/ @kzay +/types/passport-strategy/ @liorm +/types/passport-twitter/ @staticfunction +/types/passport-unique-token/ @briman0094 @SomaticIT +/types/password-hash/ @mugeso +/types/password-hash-and-salt/ @alitaheri +/types/path-exists/v1/ @shiwano +/types/path-exists/ @shiwano @BendingBender +/types/path-is-absolute/ @mhegazy +/types/pathfinding/ @BNedry +/types/pathjs/ @lokeshpeta +/types/pathwatcher/ @vvakame +/types/pause/ @BendingBender +/types/payment/ @apare +/types/paypal-cordova-plugin/ @Justin-Credible +/types/paypal-rest-sdk/ @trainerbill +/types/pbf/ @cschwarz +/types/pdfjs-dist/ @jbaldwin +/types/pdfkit/ @erichillah +/types/pdfobject/ @nielsboogaard +/types/pebblekitjs/ @makotokw +/types/peerjs/ @nakakura +/types/pegjs/ @vvakame @SrTobi @siegebell +/types/pem/ @tony19 @DethAriel +/types/perfect-scrollbar/ @aicest @CarbonAtom +/types/persona/ @Nycto +/types/pet-finder-api/ @me +/types/pg-connection-string/ @bradleyayers +/types/pg-pool/ @aleung +/types/pg-query-stream/ @asmarques +/types/pg-types/ @waratuman +/types/pgwmodal/ @pine613 +/types/phantom/ @horiuchi @llRandom +/types/phantomcss/ @abauzac +/types/phantomjs/ @jedhunsaker @keesey +/types/phoenix/ @mciastek +/types/phone/ @DxCx +/types/phone-formatter/ @westy92 +/types/phonegap/ @borisyankov @DickvdBrink +/types/phonegap-facebook-plugin/ @Justin-Credible +/types/phonegap-nfc/ @michaeldesigaud +/types/phonegap-plugin-push/ @fredgalvao @larrybahr +/types/phonon/ @kserin +/types/photonui/ @florentpoujol +/types/photoswipe/ @hellochar +/types/physijs/ @gyohk +/types/pi-spi/ @marcel-ernst +/types/pick-weight/ @rsxdalv +/types/pickadate/ @theodorejb @leonard-thieu +/types/pidusage/ @cyrilschumacher +/types/pify/ @samverschueren +/types/pigpio/ @manerfan +/types/pikaday-time/ @Sayan751 +/types/pinkyswear/ @chances +/types/pino/v3/ @psnider +/types/pino/ @psnider @BendingBender +/types/pinterest-sdk/ @adamburmister +/types/pinyin/ @wanganjun +/types/piwik-tracker/ @lbguilherme +/types/pkijs/ @microshine +/types/platform/ @JakeH +/types/playerframework/ @ricardosabino +/types/pleasejs/ @nakakura +/types/plotly.js/ @chrisgervang @martinduparc @frederikaalund @taoqf +/types/plugapi/ @BNedry +/types/plupload/ @patrickbussmann +/types/pluralize/ @ukyo +/types/png-async/ @kanreisa +/types/podcast/ @nikeee +/types/podium/ @AJamesPhillips +/types/point-in-polygon/ @dyst5422 @kogai +/types/polylabel/ @DenisCarriere +/types/polyline/ @Kern0 +/types/polymer/ @lgrignon @laco0416 +/types/polymer-ts/ @lgrignon +/types/popcorn/ @grapswiz +/types/popper.js/ @joscha @seckardt @marcfallows +/types/portscanner/ @douglasduteil +/types/postal/ @lokeshpeta @myitcv +/types/postmark/ @benbayard +/types/pouch-redux-middleware/ @charrondev +/types/pouchdb/ @AGBrown @geppy @fredgalvao +/types/pouchdb-adapter-fruitdown/ @spaulg @geppy @fredgalvao +/types/pouchdb-adapter-http/ @spaulg @geppy @fredgalvao +/types/pouchdb-adapter-idb/ @spaulg @geppy @fredgalvao +/types/pouchdb-adapter-leveldb/ @spaulg @geppy @fredgalvao +/types/pouchdb-adapter-localstorage/ @spaulg @geppy @fredgalvao +/types/pouchdb-adapter-memory/ @spaulg @geppy @fredgalvao +/types/pouchdb-adapter-node-websql/ @spaulg @geppy @fredgalvao +/types/pouchdb-adapter-websql/ @spaulg @geppy @fredgalvao +/types/pouchdb-browser/ @spaulg @geppy @fredgalvao +/types/pouchdb-core/ @spaulg @trubit @geppy @fredgalvao @TobiasBales +/types/pouchdb-find/ @trubit +/types/pouchdb-http/ @spaulg @geppy @fredgalvao +/types/pouchdb-mapreduce/ @spaulg @geppy @fredgalvao +/types/pouchdb-node/ @spaulg @geppy @fredgalvao +/types/pouchdb-replication/ @trubit +/types/pouchdb-upsert/ @keithdmoore @hotforfeature +/types/power-assert/ @vvakame +/types/power-assert-formatter/ @vvakame +/types/precise/ @codeanimal +/types/precond/ @olsio +/types/preloadjs/ @endel +/types/prelude-ls/ @AyaMorisawa +/types/prettier/ @ikatyang +/types/pretty-bytes/ @plantain-00 +/types/pretty-ms/ @BendingBender +/types/printf/ @AluisioASG +/types/priorityqueuejs/ @geoffreak +/types/prismjs/ @eriklieben @andrewiggins +/types/private-ip/ @coderslagoon +/types/procfs-stats/ @cyrilschumacher +/types/progress/ @sebastian-lenz +/types/progressbar/ @atd-schubert +/types/progressjs/ @zaneli +/types/proj4/ @DenisCarriere +/types/proj4leaflet/ @BendingBender +/types/project-oxford/ @scsouthw +/types/promise-dag/ @OSjoerdWie +/types/promise-pg/ @coldacid +/types/promise-polyfill/ @skysteve +/types/promise-pool/ @vilic +/types/promise.prototype.finally/ @slavik57 @BendingBender +/types/promised-temp/ @rokadias +/types/promisify-node/ @borekb +/types/promisify-supertest/ @aleung +/types/prompt-sync/ @MugeSo +/types/prompt-sync-history/ @MugeSo +/types/promptly/ @danrspencer +/types/prop-types/ @DovydasNavickas +/types/properties-reader/ @Goldsmith42 +/types/prosemirror-collab/ @bradleyayers @davidka +/types/prosemirror-commands/ @bradleyayers @davidka +/types/prosemirror-history/ @bradleyayers @davidka +/types/prosemirror-inputrules/ @bradleyayers @davidka +/types/prosemirror-keymap/ @bradleyayers @davidka +/types/prosemirror-markdown/ @bradleyayers +/types/prosemirror-menu/ @davidka +/types/prosemirror-model/ @bradleyayers @davidka +/types/prosemirror-schema-basic/ @bradleyayers @davidka +/types/prosemirror-schema-list/ @bradleyayers @davidka +/types/prosemirror-state/ @bradleyayers @davidka +/types/prosemirror-transform/ @bradleyayers @davidka +/types/prosemirror-view/ @bradleyayers @davidka +/types/protobufjs/ @panuhorsmalahti +/types/protractor-browser-logs/ @rokadias +/types/protractor-helpers/ @johncant +/types/protractor-http-mock/ @Crevil +/types/proxy-addr/ @BendingBender +/types/proxyquire/ @jt000 +/types/pty.js/ @enlight +/types/public-ip/ @BendingBender +/types/pubsub-js/ @borisyankov +/types/pug/ @TonyPythoneer @19majkel94 +/types/pulltorefreshjs/ @DanielRosenwasser +/types/pump/ @tlaziuk +/types/pure-render-decorator/ @seansfkelley +/types/purl/ @danfma +/types/pusher-js/ @tkqubo +/types/pvutils/ @microshine +/types/python-shell/ @dolanmiu +/types/q/v0/ @bnemetchek @johnnyreilly +/types/q/ @bnemetchek @AndrewGaspar @johnnyreilly @mboudreau +/types/q-io/ @Bartvds +/types/q-retry/ @vilic +/types/qhistory/ @Kovensky +/types/qlik/ @RubenSlabbert @AginicX +/types/qlik-engineapi/ @konne +/types/qlik-visualizationextensions/ @konne +/types/qr-image/ @taoqf +/types/qrcode-generator/ @stefanhuber +/types/qrcode.react/ @mleko +/types/qs/ @RWander @leonyu @tehbelinda @zyml @artursvonda +/types/qtip2/ @Seltzer @leonard-thieu +/types/query-string/ @SamVerschueren @tkrotoff @huhuanming +/types/quick-lru/ @BendingBender +/types/quill/ @sumitkm @guillaume-ro-fr +/types/quixote/ @greybax +/types/qunit/v1/ @diullei +/types/qunit/ @waratuman +/types/quoted-printable/ @pushplay +/types/qwest/ @lindsayevans +/types/r-script/ @NaridaL +/types/rabbit.js/ @wokim +/types/radium/ @alexgorbatchev @nupplaphil @asvetliakov @mihe +/types/radius/ @codeanimal +/types/ramda/ @donnut @mdekrey @LiamGoodacre @mrdziuban @sbking @afharo @teves-castro @1M0reBug @hojberg +/types/random-js/ @pistacchio +/types/random-seed/ @endel +/types/random-string/ @stpettersens +/types/randomcolor/ @feitzi @BradyLiles +/types/range-parser/ @tlaziuk +/types/rangyinputs/ @ersimont +/types/raphael/ @CheCoxshall +/types/rappid/ @DenEwout +/types/ratelimiter/ @AyaMorisawa +/types/raty/ @terrawheat +/types/raven/ @scttcper @1999 +/types/raygun4js/ @xt0rted @BenjaminHarding +/types/rc/ @DanielRosenwasser +/types/rc-select/ @DenisTirilis +/types/rc-slider/ @mantasmarcinkus @mattoni +/types/rc-tree/ @johnnyreilly +/types/rcloader/ @panuhorsmalahti +/types/react/v15/ @bbenezech @pzavolinsky @digiguru @ericanderson @morcerf @tkrotoff @DovydasNavickas @onigoetz +/types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @morcerf @tkrotoff @DovydasNavickas @onigoetz @richseviora +/types/react-app/ @prakarshpandey +/types/react-autosuggest/ @nicolas-schmitt @pjo256 @robessog @tbayne +/types/react-body-classname/ @mhegazy +/types/react-bootstrap/ @walkerburgin @vsiao @danilojrr @Batbold-Gansukh @octatone @chengsieuly @katbusch +/types/react-bootstrap-date-picker/ @LKay @ssi-hu-antal-bodnar +/types/react-bootstrap-daterangepicker/ @ianks +/types/react-bootstrap-table/ @flaub @alelode +/types/react-breadcrumbs/ @KostyaEsmukov +/types/react-burger-menu/ @radziksh +/types/react-calendar-timeline/ @radziksh +/types/react-chartjs-2/ @apare @FabienLavocat +/types/react-codemirror/ @velveret @rudi-c +/types/react-color/ @LKay @markspolakovs @mntdn +/types/react-copy-to-clipboard/ @mabels +/types/react-cropper/ @stepancar +/types/react-css-modules/ @KostyaEsmukov @skirsdeda +/types/react-css-transition-replace/ @LKay +/types/react-custom-scrollbars/v3/ @David-LeBlanc-git +/types/react-custom-scrollbars/ @David-LeBlanc-git @kittimiyo +/types/react-data-grid/v1/ @SupernaviX +/types/react-data-grid/ @SupernaviX @KieranPeat @martinnov92 +/types/react-datagrid/ @stephenjelfs +/types/react-datepicker/ @radziksh @andrewBalekha @smrq @Rogach +/types/react-daterange-picker/ @uncovertruth @MartynasZilinskas +/types/react-dates/ @Artur-A +/types/react-daum-postcode/ @Sa-ryong +/types/react-dnd-html5-backend/ @oizie +/types/react-document-title/ @cleverguy25 +/types/react-dom/ @MartynasZilinskas +/types/react-dropzone/v2/ @matdube @LynxEyes @goblindegook @benbayard +/types/react-dropzone/ @matdube @LynxEyes @goblindegook @benbayard @LKay +/types/react-easy-chart/ @danzel +/types/react-event-listener/ @asvetliakov +/types/react-fa/ @flaub @patsissons @LKay +/types/react-facebook-login/ @apare @jankarres +/types/react-faux-dom/ @alitaheri @cleverguy25 +/types/react-file-input/ @dmitryrogozhny +/types/react-file-reader-input/ @dmitryrogozhny @alitaheri +/types/react-flatpickr/ @begincalendar +/types/react-flex/ @pushplay +/types/react-flexr/ @pushplay +/types/react-flip-move/ @jmhain +/types/react-fontawesome/ @timurrustamov @dublicator @vincaslt @gavingregory +/types/react-ga/ @telshin +/types/react-geosuggest/ @brmenchl +/types/react-gravatar/ @invliD +/types/react-grid-layout/ @abirkholz @alitaheri @ZheyangSong +/types/react-hamburger-menu/ @grzesie2k +/types/react-helmet/v4/ @evanbb @isman-usoh +/types/react-helmet/ @evanbb @isman-usoh @lith-light-g @sammkj @yuit +/types/react-highlight-words/ @mhegazy +/types/react-highlighter/ @oizie +/types/react-holder/ @isman-usoh +/types/react-hot-loader/ @jacekjagiello +/types/react-i18next/v1/ @KostyaEsmukov +/types/react-i18next/ @GiedriusGrabauskas +/types/react-icon-base/ @apare @LKay +/types/react-icons/ @apare +/types/react-imageloader/ @stephenjelfs +/types/react-infinite/ @rhysd +/types/react-infinite-scroller/ @Lapanti @psrebniak +/types/react-input-calendar/ @stepancar +/types/react-input-mask/ @apare +/types/react-intl/v1/ @bgrieder +/types/react-intl/ @bgrieder @cdroulers @gyzerok @tillwolff @LKay @bhouser @kristerkari +/types/react-intl-redux/ @LKay +/types/react-is-deprecated/ @seansfkelley +/types/react-joyride/ @DanielRosenwasser @bendxn +/types/react-json-pretty/ @LKay +/types/react-json-tree/ @gnestor +/types/react-jsonschema-form/ @iamdanfox @sirreal +/types/react-lazyload/ @m0a +/types/react-leaflet/ @danzel @davschne @yuit +/types/react-list/ @buptyyf +/types/react-loadable/ @Kovensky @odensc +/types/react-loader/ @artfuldev +/types/react-maskedinput/ @LKay @lavoaster @CarlosBonetti +/types/react-mdl/ @bradzacher +/types/react-measure/ @asvetliakov @marcfallows +/types/react-mixin/ @tkqubo +/types/react-modal/ @radziksh @drewnoakes @homburg @ttamminen @hallowatcher +/types/react-monaco-editor/ @jnetterf +/types/react-motion/ @stepancar @asvetliakov +/types/react-motion-slider/ @asvetliakov +/types/react-native/ @alloy @gyzerok @huhuanming @iRoachie @timwangdev @kamal +/types/react-native-collapsible/ @iRoachie +/types/react-native-communications/ @huhuanming +/types/react-native-datepicker/ @jacobbaskin +/types/react-native-drawer/ @jnbt +/types/react-native-drawer-layout/ @jmfirth +/types/react-native-elements/ @iRoachie +/types/react-native-fbsdk/ @ifiokjr +/types/react-native-fetch-blob/ @MNBuyskih +/types/react-native-fs/ @pocesar +/types/react-native-goby/ @MessageDream +/types/react-native-google-analytics-bridge/ @huhuanming @nbperry +/types/react-native-keep-awake/ @huhuanming +/types/react-native-material-design-searchbar/ @iRoachie +/types/react-native-material-ui/ @iRoachie +/types/react-native-modalbox/ @iRoachie +/types/react-native-orientation/ @MoLow +/types/react-native-scrollable-tab-view/ @CaiHuan +/types/react-native-sensor-manager/ @SahinVardar +/types/react-native-snap-carousel/ @jnbt +/types/react-native-sortable-list/ @sivolobov +/types/react-native-svg-uri/ @iRoachie +/types/react-native-swiper/ @CaiHuan @huhuanming @mhcgrq +/types/react-native-touch-id/ @huhuanming +/types/react-native-vector-icons/ @iRoachie @timwangdev +/types/react-native-video/ @huhuanming +/types/react-navigation/ @huhuanming @mhcgrq @fangpenlin @abrahambotros @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev +/types/react-notification-system/ @GiedriusGrabauskas @DeividasBakanas @LKay @sztobar +/types/react-notification-system-redux/ @LKay +/types/react-onclickoutside/v5/ @LKay +/types/react-onclickoutside/ @LKay +/types/react-overlays/ @aaronbeall @vitosamson +/types/react-paginate/ @deevus @wouterhardeman @pegel03 @archy-bold +/types/react-pointable/ @istefo +/types/react-portal/ @shuntksh +/types/react-props-decorators/ @tkqubo +/types/react-recaptcha/ @mhegazy +/types/react-redux/ @tkqubo @seansfkelley @thasner @kenzierocks @clayne11 @tansongyang +/types/react-redux-i18n/ @clementdevos +/types/react-redux-toastr/ @Smiche @artyomsv @kulmajaba +/types/react-relay/ @graphcool +/types/react-responsive/ @asvetliakov +/types/react-router/v2/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov +/types/react-router/v3/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas +/types/react-router/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @tkrotoff @huy-nguyen @grmiade @DaIgeb @egorshulga +/types/react-router-bootstrap/ @vlesierse @LKay @olmobrutall +/types/react-router-config/ @lith-light-g +/types/react-router-dom/ @tkrotoff @huy-nguyen +/types/react-router-native/ @ezintz +/types/react-router-redux/v3/ @isman-usoh @noah79 @rosendi +/types/react-router-redux/v4/ @isman-usoh @noah79 @rosendi @LKay @DovydasNavickas +/types/react-router-redux/ @huy-nguyen @8398a7 +/types/react-scroll/ @sudoplz @GiedriusGrabauskas +/types/react-scrollbar/ @stephenjelfs +/types/react-select/ @Hesquibet @giladgray @iebaker @skirsdeda @vujevits @devrelm @MartynasZilinskas +/types/react-side-effect/ @remojansen +/types/react-sidebar/ @jeroenvervaeke +/types/react-slick/ @andrewBalekha @GiedriusGrabauskas +/types/react-smooth-scrollbar/ @asvetliakov +/types/react-sortable-hoc/ @NoHomey @charlesrey +/types/react-sortable-tree/ @wouterhardeman +/types/react-spinkit/v1/ @tkqubo @mleko @pelotom +/types/react-spinkit/ @tkqubo @mleko @pelotom @zzanol +/types/react-split-pane/ @rcchen +/types/react-sticky/ @curtisw0 +/types/react-svg-pan-zoom/ @huy-nguyen +/types/react-swf/ @stepancar +/types/react-swipe/ @DeividasBakanas +/types/react-swipeable/ @GiedriusGrabauskas @mctep +/types/react-swipeable-views/ @mxl @DeividasBakanas +/types/react-syntax-highlighter/ @NoHomey +/types/react-tabs/ @danez +/types/react-tag-input/ @Ogglas @jankarres +/types/react-tagcloud/ @wassname +/types/react-tap-event-plugin/ @mxl +/types/react-test-renderer/ @arvitaly @lochbrunner @lochbrunner @johnnyreilly +/types/react-tether/ @ryprice +/types/react-textarea-autosize/ @asvetliakov @zry656565 +/types/react-toggle/v2/ @LKay +/types/react-toggle/ @LKay +/types/react-tooltip/ @DeividasBakanas +/types/react-touch/ @grzesie2k +/types/react-transition-group/v1/ @LKay +/types/react-transition-group/ @LKay +/types/react-user-tour/ @ccancellieri +/types/react-virtual-keyboard/ @bsurai +/types/react-virtualized/ @kaoDev @guntherjh @wasd171 +/types/react-virtualized-select/ @seansfkelley +/types/react-weui/ @tairan +/types/react-widgets/ @rogierschouten @sanyatuning @frodehansen2 +/types/reactable/ @spielc +/types/reactcss/ @chrisgervang @LKay +/types/reactstrap/ @alihammad @mfal @danilobjr +/types/read/ @timjk +/types/read-package-tree/ @mgroenhoff +/types/readdir-stream/ @Bartvds +/types/readline-sync/ @jonestristand +/types/realm/ @Akim95 +/types/reapop/ @Barrokgl +/types/recaptcha/ @brentj73 +/types/recase/ @18steps +/types/recharts/ @mthmulders @rapmue +/types/recompose/ @iskandersierra @mrapogee @clayne11 +/types/reconnectingwebsocket/ @nguarracino +/types/recursive-readdir/ @elisee +/types/redis/ @soywiz @CodeAnimal @MugeSo +/types/redis-mock/ @BendingBender +/types/redis-rate-limiter/ @westy92 +/types/redis-scripto/ @westy92 +/types/redlock/v2/ @chrootsu +/types/redlock/ @chrootsu @BendingBender +/types/reduce-reducers/ @huy-nguyen +/types/redux-action/ @newraina +/types/redux-action-utils/ @tkqubo +/types/redux-actions/ @jaysoo @alexgorbatchev +/types/redux-auth-wrapper/v1/ @LKay +/types/redux-auth-wrapper/ @LKay +/types/redux-batched-subscribe/ @mDibyo +/types/redux-bootstrap/ @remojansen +/types/redux-debounced/ @seansfkelley +/types/redux-devtools/ @mc-petry +/types/redux-devtools-dock-monitor/ @mc-petry +/types/redux-devtools-log-monitor/ @mc-petry +/types/redux-doghouse/ @BendingBender +/types/redux-first-router/ @Valbrand @viggyfresh +/types/redux-form/v4/ @aikoven +/types/redux-form/v6/ @carsonf @aikoven @LKay @bancek +/types/redux-form/ @carsonf @aikoven @LKay @bancek +/types/redux-immutable/ @oizie @sebald @gavingregory +/types/redux-immutable-state-invariant/ @remojansen @highflying +/types/redux-infinite-scroll/ @silkyfray +/types/redux-localstorage/ @LKay +/types/redux-localstorage-debounce/ @LKay +/types/redux-localstorage-filter/ @LKay +/types/redux-logger/ @arusakov +/types/redux-mock-store/ @MarianPalkus +/types/redux-optimistic-ui/ @asvetliakov +/types/redux-pack/ @tansongyang +/types/redux-persist-transform-encrypt/ @LKay +/types/redux-persist-transform-filter/ @LKay +/types/redux-promise/ @molekilla @xStrom +/types/redux-promise-middleware/ @ianks +/types/redux-recycle/ @LKay +/types/redux-router/ @stepancar +/types/redux-storage/ @asvetliakov +/types/redux-ui/ @andyshuxin +/types/ref/ @loyd +/types/ref-array/ @loyd +/types/ref-struct/ @loyd +/types/ref-union/ @loyd +/types/reflect-metadata/ @rbuckton +/types/reflux/ @mauricedb +/types/relateurl/ @tkrotoff +/types/relaxed-json/ @18steps +/types/remote-redux-devtools/ @ColinEberhardt @unindented +/types/remove-markdown/ @RagibHasin +/types/replace-ext/ @DeividasBakanas +/types/request/ @soywiz @bonnici @Bartvds @joeskeen @ccurrens +/types/request-ip/ @mrhen +/types/request-promise/ @cglantschnig @joeskeen @AyaMorisawa +/types/request-promise-native/ @gustavohenke +/types/requestretry/ @EricByers +/types/require-directory/ @Igmat +/types/require-from-string/ @ikatyang +/types/requirejs/ @jbaldwin +/types/requirejs-domready/ @lefb766 +/types/resemblejs/ @pimterry +/types/resolve/ @marionebl +/types/resolve-from/ @unional +/types/response-time/ @urossmolnik @TonyPythoneer +/types/rest/ @Nemo157 +/types/restangular/ @borisyankov +/types/restful.js/ @tkqubo +/types/restify/v4/ @blittle @stevehipwell +/types/restify/ @blittle @stevehipwell +/types/restify-cors-middleware/ @dthunell +/types/restify-errors/ @stevehipwell +/types/restify-plugins/ @KostyaTretyak +/types/restler/ @cyrilschumacher +/types/resumablejs/ @DanielMcAssey +/types/rethinkdb/ @alexgorbatchev +/types/retry/ @krenor +/types/rev-hash/ @ikatyang +/types/revalidate/ @alex3165 +/types/revalidator/ @brewsoftware +/types/reveal/ @robertop87 @Nava2 +/types/rewire/ @borislavjivkov @CaselIT +/types/rfc2047/ @mugifly +/types/rheostat/ @SashaBayan @kourge +/types/rickshaw/ @niemyjski +/types/rimraf/ @soywiz @e-cloud @bash +/types/riot/ @Stubb0rn +/types/riot-api-nodejs/ @zafixlrp +/types/riot-games-api/ @xstoudi +/types/riotcontrol/ @chrootsu +/types/riotjs/ @vvakame +/types/rison/ @impworks +/types/rivets/ @TrevorDev +/types/rollup/ @flying-sheep +/types/ronomon__crypto-async/ @BendingBender +/types/rosie/ @abner +/types/roslib/ @Pro @skycoop +/types/rot-js/ @atiaxi +/types/route-parser/ @ianks @bobbuehler +/types/router5/ @sandersky +/types/routie/ @Adilson +/types/royalslider/ @csrakowski +/types/rpio/ @DominikPalo +/types/rrc/ @DeividasBakanas +/types/rrule/ @waratuman +/types/rsmq/ @MugeSo +/types/rsmq-worker/ @MugeSo +/types/rss/ @secondwtq +/types/rsvp/ @Taytay @mkohlmyr @theroncross @chriskrycho +/types/rsync/ @philippstucki +/types/rtree/ @oefirouz +/types/run-sequence/ @k-kagurazaka +/types/rvo2/ @erikvullings +/types/rx/ @Igorbek +/types/rx-angular/ @mickdelaney +/types/rx-core/ @Igorbek @mizunashi-mana +/types/rx-core-binding/ @Igorbek +/types/rx-dom/ @oliverw +/types/rx-jquery/ @Igorbek +/types/rx-lite/ @Igorbek +/types/rx-lite-aggregates/ @Igorbek +/types/rx-lite-async/ @zoetrope @Igorbek +/types/rx-lite-backpressure/ @Igorbek +/types/rx-lite-coincidence/ @Igorbek +/types/rx-lite-experimental/ @Igorbek +/types/rx-lite-joinpatterns/ @Igorbek +/types/rx-lite-testing/ @Igorbek +/types/rx-lite-time/ @Igorbek +/types/rx-lite-virtualtime/ @Igorbek +/types/rx.wamp/ @darkl +/types/s3-upload-stream/ @geoffreak +/types/safari-extension/ @luukd +/types/safari-extension-content/ @luukd +/types/safe-json-stringify/ @ericbyers +/types/safe-regex/ @mhegazy +/types/sails.io.js/ @arvitaly +/types/saml2-js/ @horiuchi +/types/saml20/ @HackerUndKoch +/types/samlp/ @horiuchi +/types/sammy/ @borisyankov @oising +/types/sandboxed-module/ @svi3c +/types/sane/ @BendingBender +/types/sanitize-filename/ @Nemo157 +/types/sanitize-html/ @rogierschouten @afshin +/types/sap__xsenv/ @mad-mike +/types/sass-graph/ @marvinhagemeister +/types/sat/ @omni360 +/types/satnav/ @DotNetNerd +/types/saywhen/ @SeanSobey +/types/scalike/ @ryoppy +/types/screenfull/ @icholy @lionelb @joelshepherd +/types/screeps-profiler/ @ramblurr +/types/scriptjs/ @ssttevee +/types/scroll-into-view/ @zivni +/types/scroller/ @borisyankov +/types/scrollreveal/ @Davidblkx +/types/scrolltofixed/ @bmdixon +/types/scrypt-async/ @xStrom +/types/seamless/ @danmana +/types/seamless-immutable/ @alex3165 @xsburg @geirsagberg +/types/seedrandom/ @kernhanda +/types/segment-analytics/ @fongandrew +/types/select2/ @borisyankov +/types/selectize/ @adidahiya @naBausch +/types/selenium-webdriver/v2/ @BillArmstrong @Kuniwak @cnishina +/types/selenium-webdriver/ @BillArmstrong @Kuniwak @cnishina @SupernaviX @bendxn +/types/semantic-ui/ @leonard-thieu +/types/semantic-ui-accordion/ @leonard-thieu +/types/semantic-ui-api/ @leonard-thieu +/types/semantic-ui-checkbox/ @leonard-thieu +/types/semantic-ui-dimmer/ @leonard-thieu +/types/semantic-ui-dropdown/ @leonard-thieu +/types/semantic-ui-embed/ @leonard-thieu +/types/semantic-ui-form/ @leonard-thieu +/types/semantic-ui-modal/ @leonard-thieu +/types/semantic-ui-nag/ @leonard-thieu +/types/semantic-ui-popup/ @leonard-thieu +/types/semantic-ui-progress/ @leonard-thieu +/types/semantic-ui-rating/ @leonard-thieu +/types/semantic-ui-search/ @leonard-thieu +/types/semantic-ui-shape/ @leonard-thieu +/types/semantic-ui-sidebar/ @leonard-thieu +/types/semantic-ui-site/ @leonard-thieu +/types/semantic-ui-sticky/ @leonard-thieu +/types/semantic-ui-tab/ @leonard-thieu +/types/semantic-ui-transition/ @leonard-thieu +/types/semantic-ui-visibility/ @leonard-thieu +/types/semaphore/ @mhfrantz +/types/semver/ @Bartvds @BendingBender @LucianBuzzo +/types/semver-diff/ @chrismbarr +/types/sencha_touch/ @brian428 +/types/send/ @MikeJerred +/types/seneca/ @psnider +/types/sequelize/v3/ @samuelneff @codeanimal @drinchev @morpheusxaut @torhal +/types/sequelize/ @samuelneff @codeanimal @drinchev @babolivier @kukoo1 @morpheusxaut +/types/sequelize-fixtures/ @cschwarz +/types/sequester/ @Strate +/types/serialize-javascript/ @lith-light-g +/types/serialport/ @codefoster +/types/serve-favicon/ @urossmolnik +/types/serve-index/ @tkrotoff +/types/serve-static/ @urossmolnik +/types/session-file-store/ @blendsdk +/types/set-cookie-parser/ @nickp10 +/types/sha1/ @arcdev1 +/types/shallowequal/ @seansfkelley +/types/shapefile/ @DenisCarriere +/types/sharedworker/ @nakakura +/types/sharepoint/ @baywet +/types/sharp/ @lith-light-g +/types/sharp-timer/ @afractal +/types/sheetify/ @toddself +/types/shell-quote/ @jason0x43 +/types/shelljs/ @nikeee @voy +/types/shipit/ @cyrilschumacher +/types/shipit-utils/ @cyrilschumacher +/types/shopify-buy/ @openminder +/types/shortid/ @stpettersens @despairblue +/types/shot/ @AJamesPhillips +/types/should/ @varju +/types/should-promised/ @devoto13 +/types/showdown/ @cbowdon @tan9 +/types/siema/ @Irmiz +/types/siesta/ @bquarmby +/types/sigmajs/ @qinfchen +/types/signalr/ @borisyankov @keesey @GiedriusGrabauskas +/types/signals/ @diullei +/types/signature_pad/ @AbubakerB +/types/simple-assign/ @NoHomey +/types/simple-cw-node/ @vvakame +/types/simple-mock/ @leonyu +/types/simple-oauth2/ @mad-mike +/types/simple-peer/ @tlaziuk +/types/simple-url-cache/ @a-lucas +/types/simple-xml/ @notVitaliy +/types/simplebar/v1/ @gregonnet @leonard-thieu +/types/simplebar/ @leonard-thieu +/types/simplemde/ @Scalesoft +/types/simplesmtp/ @rogierschouten +/types/simplestorage.js/ @axelcostaspena @mxl +/types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j +/types/sinon-as-promised/ @igrayson +/types/sinon-chai/ @kazimanzurrashid @jedmao +/types/sinon-chrome/ @pimterry +/types/sinon-express-mock/ @jpchip @tlaziuk +/types/sinon-mongoose/ @stevehipwell +/types/sinon-stub-promise/ @vintem +/types/sinon-test/ @mummybot +/types/sip.js/ @decyrus +/types/sipml/ @chookies +/types/sitemap2/ @shundy +/types/sizzle/ @leonard-thieu +/types/sjcl/ @Evgenus +/types/ski/ @AyaMorisawa +/types/skyway/ @nakakura +/types/slack-node/ @geoffreak +/types/slack-winston/ @BlueHatbRit +/types/slackify-html/ @hypexr +/types/slate-irc/ @elisee +/types/sleep/ @rajarz +/types/slickgrid/ @jbaldwin +/types/slideout/ @ToastHawaii +/types/slimerjs/ @alexwall +/types/slocket/ @BendingBender +/types/slug/ @mhegazy +/types/smart-fox-server/ @ChanceM +/types/smooth-scrollbar/ @asvetliakov +/types/smoothie/ @mikehhawley +/types/smoothscroll-polyfill/ @kryops +/types/smtp-server/ @markisme +/types/smtpapi/ @a-morales +/types/snapsvg/ @lhk @mattanja @kant2002 +/types/snazzy-info-window/ @milosd92 +/types/snekfetch/ @DarkerTV +/types/snoowrap/ @vitosamson +/types/soap/ @aleung @cagefox +/types/socket.io/ @progre @divillysausages @florentpoujol @KentarouTakeda +/types/socket.io-client/ @progre @divillysausages @florentpoujol +/types/socket.io-redis/ @nupplaphil +/types/socket.io.users/ @kataras +/types/socketio-wildcard/ @BendingBender +/types/socketty/ @Nax +/types/sockjs/ @pmccloghrylaing +/types/sockjs-client/ @vladev @arusakov @BendingBender +/types/solution-center-communicator/ @dami-gg +/types/sortablejs/ @Maw-Fox +/types/source-list-map/ @e-cloud +/types/source-map/ @MortenHoustonLudvigsen @rbuckton +/types/source-map-support/ @Bartvds @jason0x43 +/types/space-pen/ @vvakame +/types/spark-md5/ @bastienmoulia +/types/sparkly/ @BendingBender +/types/sparkpost/v1/ @geoffreak +/types/sparkpost/ @geoffreak @bondz +/types/spatialite/ @atd-schubert +/types/spdy/ @tony19 +/types/speakeasy/ @legendecas @mrOlorin +/types/speakingurl/ @Goldsmith42 +/types/spectacle/ @zmaybury +/types/spectrum/ @M-Zuber +/types/spin.js/ @borisyankov @theodorejb +/types/split/ @marcinporebski +/types/split2/ @mugeso +/types/spotify-api/ @skovmand +/types/sprintf/ @soywiz +/types/sql.js/ @Hozuki +/types/sqlite3/ @nmalaguti @dpyro +/types/sqlstring/ @marvinhagemeister +/types/squirejs/ @bradleyayers +/types/srp/ @Patman64 +/types/ss-utils/ @mythz +/types/ssh2/ @tkQubo @rbuckton +/types/ssh2-sftp-client/ @igrayson +/types/ssh2-streams/ @rbuckton +/types/sshpk/ @mabels +/types/stack-mapper/ @rogierschouten +/types/stack-trace/ @exceptionless +/types/stack-utils/ @BendingBender +/types/stacktrace-js/ @exceptionless @pilagod +/types/stale-lru-cache/ @cxcorp +/types/stampit/ @koresar +/types/stamplay-js-sdk/ @ridermansb +/types/stat-mode/ @BendingBender +/types/stats.js/ @gregolai @hberntsen +/types/statsd-client/ @peterkooijmans +/types/status-bar/ @vvakame +/types/statuses/ @tkrotoff @BendingBender +/types/steam/ @kant2002 +/types/steed/ @Paul-Isache +/types/stompjs/ @jimic +/types/storejs/ @vbortone +/types/storybook__addon-actions/ @joscha +/types/storybook__addon-knobs/ @joscha @martynaskadisa +/types/storybook__addon-links/ @joscha +/types/storybook__addon-notes/ @joscha +/types/storybook__addon-options/ @joscha +/types/storybook__react/ @joscha +/types/stream-buffers/ @Jason3S +/types/stream-meter/ @mugeso +/types/stream-series/ @k-kagurazaka +/types/stream-to-array/v0/ @Bartvds +/types/stream-to-array/ @Bartvds @BendingBender +/types/streaming-json-stringify/ @BendingBender +/types/streamjs/ @erosb +/types/strftime/ @cyrilschumacher +/types/string/ @basp +/types/string-hash/ @ethanrubio +/types/string-similarity/ @ragtime +/types/string-template/ @TonyPythoneer +/types/string_score/ @marcinporebski +/types/stringify-object/ @khoomeister +/types/strip-ansi/ @mhegazy +/types/strip-bom/ @mhegazy +/types/strip-json-comments/ @dmoonfire +/types/stripe-checkout/ @cgwrench +/types/stripe-node/ @wjohnsto @codeanimal +/types/stripe-v2/ @ejsmith @amritk @adamcmiel @jleider @galuszkak +/types/stripe-v3/ @ejsmith @amritk @adamcmiel @jleider @galuszkak +/types/striptags/ @ccitro +/types/strong-cluster-control/ @shuntksh +/types/strophe/ @DavidKDeutsch +/types/stylelint/ @alan-agius4 +/types/stylus/ @SomaticIT +/types/subsume/ @BendingBender +/types/succinct/ @EnableSoftware +/types/sudo-block/ @BendingBender +/types/suitescript/ @darrenhillconsulting +/types/sumo-logger/ @forabi +/types/superagent/ @NicoZelaya @mxl @paplorinc +/types/superagent-no-cache/ @mxl +/types/superagent-prefix/ @mxl +/types/supercluster/ @DenisCarriere +/types/supertest/ @varju +/types/supertest-as-promised/ @tkrotoff +/types/supports-color/ @mgroenhoff +/types/survey-knockout/ @andrewtelnov +/types/svg-injector/ @poke +/types/svg-pan-zoom/v2/ @Promact +/types/svg-pan-zoom/ @Yimiprod +/types/svg-sprite/ @tkqubo +/types/svg2png/ @hansrwindhoff +/types/svg4everybody/ @BendingBender +/types/svgjs.draggable/ @LiFeleSs +/types/svgjs.resize/ @jkevingutierrez +/types/swag/ @shiwano +/types/swagger-express-middleware/ @alexandreroba +/types/swagger-express-mw/ @micmro +/types/swagger-hapi/ @micmro +/types/swagger-jsdoc/ @drGrove +/types/swagger-node-runner/ @micmro +/types/swagger-parser/ @Tobias4872 @EricHenry +/types/swagger-restify-mw/ @micmro +/types/swagger-sails-hook/ @micmro +/types/swagger-schema-official/ @mohsen1 @bsouthga @nimerritt +/types/swagger-tools/ @bricka +/types/swaggerize-express/ @mugeso @nickmorton +/types/sweetalert/ @ToastHawaii +/types/swfobject/ @rou +/types/swiftclick/ @Laurence-C +/types/swig/ @CodeAnimal @soywiz +/types/swig-email-templates/ @mrhen +/types/swipe/ @kant2002 +/types/swiper/ @sgaliano @lucax88x +/types/swipeview/ @borisyankov +/types/switchery/ @bgrieder @claylaut +/types/swiz/ @jedigo +/types/sylvester/ @StephaneAlie +/types/synaptic/ @ToastHawaii @austincummings +/types/systeminformation/ @PixelcrabAT +/types/systemjs/ @ludohenin @NathanWalker @GiedriusGrabauskas +/types/table/ @evanshortiss +/types/tabtab/ @vojtechhabarta +/types/tapable/ @e-cloud +/types/tape/ @Bartvds @sodatea @DennisSchwartz +/types/tar/ @SomaticIT +/types/tedious/ @rogierschouten @cjthompson +/types/tedious-connection-pool/ @sandorfr +/types/telebot/ @mariotsi +/types/temp/ @DanielRosenwasser +/types/temp-write/ @BendingBender +/types/tempfile/ @SamVerschueren @BendingBender +/types/tempy/ @douglasduteil +/types/terminal-menu/ @aravindarun +/types/testingbot-api/ @timbru31 +/types/tether/ @adidahiya +/types/tether-drop/ @adidahiya +/types/tether-shepherd/ @mtgibbs +/types/text-buffer/ @vvakame +/types/text-encoding/ @pine613 +/types/three/ @gyohk @florentpoujol @SereznoKot @omni360 @ivoisbelongtous @piranha771 @qszhusightp @nakakura @s093294 @Pro @efokschaner +/types/thrift/ @kamek-pf +/types/throng/ @cyrilschumacher +/types/throttle/ @BendingBender +/types/through/ @AndrewGaspar +/types/through2/v0/ @Bartvds @jedmao +/types/through2/ @Bartvds @jedmao @valotas @TeamworkGuy2 +/types/through2-map/ @LucasHill +/types/tile-reduce/ @DenisCarriere +/types/tilebelt/ @DenisCarriere +/types/time-span/ @BendingBender @mdvorscak +/types/timelinejs/ @rolandzwaga +/types/timelinejs3/ @MikeMatusz +/types/timer-machine/ @dolanmiu +/types/timezone-js/ @bonnici +/types/timezonecomplete/ @rogierschouten +/types/tinder/ @pingec +/types/tinycolor2/ @M-Zuber @geertjansen @nvh +/types/tinycopy/ @vvatanabe +/types/tinymce/ @martinduparc @ipoul +/types/titanium/ @cyounkins +/types/title/ @fa7ad +/types/tldjs/ @geoffreak +/types/tmp/ @optical @Perlmint +/types/to-markdown/ @SuperPaintman +/types/to-title-case-gouch/ @stpettersens +/types/toastr/ @borisyankov +/types/tooltipster/ @stephenlautier +/types/topojson/ @ricardo-mello @chenzhutian +/types/torrent-stream/ @xstoudi +/types/touch/ @mizunashi-mana @BendingBender +/types/touch-events/ @kevinb7 +/types/tough-cookie/ @leonard-thieu +/types/traceback/ @misak113 +/types/tracking/ @pimterry +/types/transducers-js/ @colinkahn @dphilipson +/types/transducers.js/ @dphilipson +/types/traverse/ @newclear +/types/traverson/ @marcinporebski +/types/trayballoon/ @korve +/types/trim/ @skysteve +/types/trunk8/ @niemyjski +/types/tspromise/ @soywiz +/types/tunnel/ @BendingBender +/types/turf/v2/ @gcroteau +/types/turf/ @gcroteau @DenisCarriere +/types/tus-js-client/ @kevhiggins +/types/tv4/ @Bartvds @psnider +/types/tween.js/ @Amos47 @sunetos @jzarnikov +/types/tweenjs/ @evilangelist +/types/tweezer.js/ @praxxis +/types/twig/ @soywiz @enko +/types/twilio/ @nickiannone @ashleybrener +/types/twit/ @Volox +/types/twitter/ @chitoku-k +/types/twix/ @j3ko +/types/type-check/ @hansrwindhoff +/types/type-detect/ @Bartvds +/types/type-is/ @BendingBender +/types/type-name/ @armorik83 +/types/typeahead/ @igochkov @gjunge +/types/typedarray-pool/ @pawsong +/types/typescript-deferred/ @DirtyHairy +/types/tz-format/ @samverschueren +/types/ua-parser-js/ @superduper @legendecas @MeLlamoPablo +/types/uglify-js/ @tkrotoff +/types/uglifycss/ @blendsdk +/types/ui-grid/ @btesser @joeskeen +/types/ui-router-extras/ @mputters @marcel-k @LaserUnicorns +/types/ui-select/ @nkovacic +/types/uid-safe/ @geoffreak +/types/uikit/ @giovannicandido @s0x +/types/uk.co.workingedge.phonegap.plugin.launchnavigator/ @dpa99c +/types/umbraco/ @DeCareSystemsIreland +/types/umd/ @TeamworkGuy2 +/types/umzug/ @drinchev +/types/underscore/ @borisyankov @jbaldwin @ccurrens +/types/underscore-ko/ @MagicMau +/types/underscore.string/ @rygine +/types/undertaker/ @tkqubo @GiedriusGrabauskas +/types/undertaker-registry/ @GiedriusGrabauskas +/types/uniq/ @hansrwindhoff +/types/uniqid/ @me +/types/unique-hash-stream/ @BendingBender +/types/unique-random/ @Kuniwak +/types/unity-webapi/ @jmvrbanac +/types/universal-analytics/ @Bartvds @DarkerTV +/types/universal-router/ @jtmthf +/types/unorm/ @chbrown +/types/untildify/ @BendingBender +/types/unused-filename/ @BendingBender +/types/update-notifier/ @vvakame @nchen63 +/types/uppercamelcase/ @plantain-00 +/types/urbanairship-cordova/ @Justin-Credible +/types/uri-templates/ @Bartvds +/types/urijs/ @RodneyJT @xt0rted +/types/uritemplate/ @teyc +/types/url-assembler/ @wolfgang42 +/types/url-join/ @rogierschouten @devrelm +/types/url-regex/ @unindented +/types/url-template/ @marcinporebski +/types/urlrouter/ @soywiz +/types/urlsafe-base64/ @tkrotoff +/types/usage/ @pvomhoff +/types/usb/ @underscorebrody +/types/user-home/ @mhegazy +/types/useragent/ @geoffreak +/types/username/ @kayahr +/types/utf8/ @zelein +/types/util-deprecate/ @BendingBender +/types/util.promisify/ @adamvoss +/types/utils-merge/ @chrootsu +/types/uuid/ @iamolivinius @felipeochoa @cjbarth +/types/uuid-1345/ @mugeso +/types/uuid-js/ @mhegazy +/types/uuid-validate/ @HiromiShikata +/types/uuidjs/ @staxmanade +/types/uws/ @plantain-00 +/types/valdr/ @ilbertz +/types/valdr-message/ @ilbertz +/types/valerie/ @conficient +/types/valid-url/ @stevehipwell +/types/validate.js/ @HillTravis +/types/validator/ @tgfjt @chrootsu @IOAyman @louy @kacepe +/types/validatorjs/ @LKay +/types/vanilla-tilt/ @BrunnerLivio +/types/vary/ @BendingBender +/types/vast-client/ @jgainfort +/types/vec3/ @xstoudi +/types/vectorious/ @erikgerrits +/types/vega/ @pelotom +/types/velocity-animate/ @smrq +/types/verror/ @svi3c @max4t +/types/vertx3-eventbus-client/ @oddeirik +/types/vex-js/ @gdcohan +/types/vexflow/ @rquiring @sebastianhaas @bohoffi +/types/victory/ @asvetliakov @snerks @Havret +/types/video.js/ @vbortone +/types/viewability-helper/ @lironzluf +/types/viewerjs/ @lrh3321 +/types/viewporter/ @borisyankov +/types/vimeo/ @DazWilkin +/types/vimeo__player/ @denisyilmaz +/types/vinyl/v0/ @jedmao +/types/vinyl/ @vvakame @jedmao @thorn0 +/types/vinyl-buffer/ @tkQubo +/types/vinyl-fs/ @vvakame @remisery +/types/vinyl-paths/ @tkQubo +/types/virtual-dom/ @chbrown +/types/virtual-keyboard/ @bsurai +/types/vis/ @MichaelBitard @macleodbroad-wf @adripanico @seveves @kaktus40 @mmaitre314 +/types/vision/ @jasonswearingen @AJamesPhillips +/types/vitalsigns/ @cyrilschumacher +/types/vivus/ @DanielRosenwasser @lekhmanrus +/types/vkbeautify/ @sch3lp +/types/voca/ @pine +/types/voronoi-diagram/ @michaelneu +/types/vortex-web-client/ @Pro +/types/voximplant-websdk/ @aylarov +/types/vue-i18n/ @aicest +/types/vue-resource/ @kaorun343 +/types/w2ui/ @Ptival +/types/wake_on_lan/ @SrTobi +/types/wallabyjs/ @andrewconnell +/types/wallpaper/ @BendingBender +/types/wampy/ @KSDaemon +/types/warning/ @cvle +/types/watch/ @soywiz @Perlmint +/types/watchify/ @TeamworkGuy2 +/types/watchpack/ @e-cloud +/types/waterline/ @arvitaly +/types/watson-developer-cloud/ @waldo000000 +/types/waypoints/ @dominikbulaj @Koloto +/types/weapp-api/ @vargeek +/types/web-animations-js/ @kritollm +/types/web-bluetooth/ @urish +/types/webappsec-credential-management/ @iainmcgin +/types/webassembly-js-api/ @periklis +/types/webcl/ @NCARalph +/types/webcomponents.js/ @adidahiya +/types/webcrypto/ @iislucas +/types/webdriverio/ @nmalaguti @timbru31 @fsmedberg-tc @tanvirislam06 +/types/webfontloader/ @doskallemaskin +/types/webgl-ext/ @zenmumbler +/types/webgl2/ @nkemnitz +/types/webgme/ @phreed +/types/webix/ @mkozhukh +/types/webmidi/ @lostfictions +/types/webpack/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 +/types/webpack-bundle-analyzer/ @kryops +/types/webpack-chain/ @eirikurn @psachs21 +/types/webpack-dev-middleware/ @bumbleblym +/types/webpack-dev-server/ @maestroh @daveparslow +/types/webpack-dotenv-plugin/ @kryops +/types/webpack-env/ @use-strict +/types/webpack-fail-plugin/ @deevus +/types/webpack-hot-middleware/ @bumbleblym +/types/webpack-merge/ @deevus +/types/webpack-notifier/ @bumbleblym +/types/webpack-sources/ @e-cloud @chriseppstein +/types/webpack-stream/ @iclanton @bumbleblym +/types/webpack-validator/ @deevus +/types/webrtc/ @nakakura +/types/websocket/ @loyd @flynetworks +/types/webspeechapi/ @saschanaz +/types/websql/ @TeamworkGuy2 +/types/webtorrent/ @niieani @tlaziuk +/types/webvr-api/ @lostfictions +/types/week/ @sindrenm +/types/weighted/ @ccitro +/types/weixin-app/ @taoqf +/types/wellknown/ @yairtawil +/types/whatwg-streams/ @saschanaz +/types/when/ @derekcicerone @Nemo157 +/types/which/ @vvakame +/types/wicg-mediasession/ @jucrouzet +/types/wiiu/ @mzsm +/types/window-or-global/ @vvakame +/types/window-size/ @pmkary +/types/windows-1251/ @RomanGolovanov +/types/windows-service/ @rogierschouten +/types/winjs/v1/ @adamhewitt627 @craigktreasure @xirzec +/types/winjs/v2/ @adamhewitt627 @craigktreasure @xirzec +/types/winjs/ @adamhewitt627 @craigktreasure @xirzec +/types/winreg/ @RX14 @BobBuehler +/types/winrt-uwp/ @saschanaz @taylor224 +/types/winston/ @bonnici @codeanimal @DABH +/types/winston-dynamodb/ @nickiannone +/types/wiring-pi/ @NoHomey +/types/wnumb/ @acoreyj +/types/wolfy87-eventemitter/ @ryiwamoto +/types/wonder-commonlib/ @yyc-git +/types/wonder-frp/ @yyc-git +/types/wonder.js/ @yyc-git +/types/wordcloud/ @joeskeen +/types/words-to-numbers/ @James-Frowen +/types/wrap-ansi/ @kayahr +/types/wreck/ @marcinporebski +/types/wrench/ @soywiz +/types/write-file-atomic/ @BendingBender +/types/write-json-file/ @DenisCarriere +/types/ws/ @loyd @elithrar +/types/wu/ @phiresky +/types/wx-js-sdk-dt/ @agasbzj +/types/x-editable/ @sirkirby +/types/xadesjs/ @microshine +/types/xdate/ @yamada28go +/types/xdg-basedir/ @tlaziuk +/types/xlsx/ @themauveavenger +/types/xml/ @YuJianrong +/types/xml-parser/ @mhfrantz +/types/xml2js/ @michelsalib @jasonrm @ccurrens @edwardhinkle +/types/xml2json/ @dolanmiu +/types/xmlbuilder/ @wallymathieu +/types/xmldoc/ @Xstoudi @ajsheehan +/types/xmldom/ @tkqubo +/types/xmlpoke/ @garthk +/types/xmltojson/ @traviscrowe +/types/xmpp__jid/ @PJakcson +/types/xregexp/ @Bartvds @jfahrenkrug @sigo +/types/xrm/v7/ @daryllabar +/types/xrm/ @6ix4our @mattngan @markusmauch @daryllabar @clownwilleatme +/types/xsd-schema-validator/ @Goldsmith42 +/types/xsockets/ @pushplay +/types/xterm/ @blink1073 @LucianBuzzo +/types/yallist/ @BendingBender +/types/yandex-money-sdk/ @chrootsu +/types/yargs/ @poelstra @mizunashi-mana @pushplay @jeffkenney +/types/yayson/ @Codesleuth +/types/ydn-db/ @yathit @gabrielmaldi +/types/yeoman-generator/ @armorik83 @janslow +/types/yeoman-test/ @ikatyang +/types/yfiles/ @yGuy +/types/yog-bigpipe/ @ssddi456 +/types/yog-log/ @ssddi456 +/types/yog2-kernel/ @ssddi456 +/types/yosay/ @armorik83 +/types/youtube/ @DazWilkin @JoshuaKGoldberg @eliotfallon213 +/types/yui/ @giabao +/types/z-schema/ @pgonzal +/types/zen-observable/ @aicest +/types/zepto/ @jbaldwin +/types/zeroclipboard/v1/ @ejsmith @niemyjski @balassy @leonyu +/types/zeroclipboard/ @ejsmith @niemyjski @balassy @leonyu +/types/zeromq/ @davemckeown @erikma +/types/zetapush-js/ @ghoullier +/types/zip.js/ @lgrignon +/types/zmq/ @davemckeown +/types/zui/ @yuanxu +/types/zynga-scroller/ @haskellcamargo diff --git a/README.md b/README.md index 9f3c4fe78f..29d174ef77 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.png?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) +# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) [![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) @@ -96,7 +96,7 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in // Steve // John ``` -* `npm install -g typescript@2.0` and run `tsc`. +* If there is a `tslint.json`, run `npm run lint package-name`. Otherwise, run `tsc` in the package directory. When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors. If it doesn't, you can do so yourself in the comment associated with the PR. @@ -133,6 +133,7 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D * First, follow advice from the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html). * Formatting: Either use all tabs, or always use 4 spaces. +* `function sum(nums: number[]): number`: Use `ReadonlyArray` if a function does not write to its parameters. * `interface Foo { new(): Foo; }`: This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); }`. * `const Class: { new(): IClass; }`: @@ -177,6 +178,18 @@ If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. (To indicate that a lint rule truly does not apply, use `// tslint:disable rule-name` or better, `//tslint:disable-next-line rule-name`.) +To assert that an expression is of a given type, use `$ExpectType`. To assert that an expression causes a compile error, use `$ExpectError`. + +```js +// $ExpectType void +f(1); + +// $ExpectError +f("one"); +``` + +For more details, see [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme. + Test by running `npm run lint package-name` where `package-name` is the name of your package. This script uses [dtslint](https://github.com/Microsoft/dtslint). @@ -264,6 +277,17 @@ Also, `/// ` will not work with path mapping, so depende Types for a scoped package `@foo/bar` should go in `types/foo__bar`. Note the double underscore. +When `dts-gen` is used to scaffold a scoped package, the `paths` property has to be manually adapted in the generated +`tsconfig.json` to correctly reference the scoped package: + +```json +{ + "paths":{ + "@foo/bar": ["foo__bar"] + } +} +``` + #### The file history in GitHub looks incomplete. diff --git a/notNeededPackages.json b/notNeededPackages.json index 50d71d2165..c7a7168ff0 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -1,11 +1,35 @@ { "packages": [ + { + "libraryName": "3d-bin-packing", + "typingsPackageName": "3d-bin-packing", + "sourceRepoURL": "https://github.com/betterwaysystems/packer", + "asOfVersion": "1.1.3" + }, + { + "libraryName": "ag-grid", + "typingsPackageName": "ag-grid", + "sourceRepoURL": "https://github.com/ceolter/ag-grid", + "asOfVersion": "3.2.0" + }, { "libraryName": "ajv", "typingsPackageName": "ajv", "sourceRepoURL": "https://github.com/epoberezkin/ajv", "asOfVersion": "1.0.0" }, + { + "libraryName": "angular-ui-router-default", + "typingsPackageName": "angular-ui-router-default", + "sourceRepoURL": "https://github.com/nonplus/angular-ui-router-default", + "asOfVersion": "0.0.5" + }, + { + "libraryName": "angular-ui-router-uib-modal", + "typingsPackageName": "angular-ui-router-uib-modal", + "sourceRepoURL": "https://github.com/nonplus/angular-ui-router-uib-modal", + "asOfVersion": "0.0.11" + }, { "libraryName": "antd", "typingsPackageName": "antd", @@ -18,6 +42,12 @@ "sourceRepoURL": "https://github.com/doxout/anydb-sql", "asOfVersion": "0.6.46" }, + { + "libraryName": "apn", + "typingsPackageName": "apn", + "sourceRepoURL": "https://github.com/node-apn/node-apn", + "asOfVersion": "2.1.2" + }, { "libraryName": "Argon2", "typingsPackageName": "argon2", @@ -54,6 +84,12 @@ "sourceRepoURL": "http://www.babylonjs.com/", "asOfVersion": "2.4.1" }, + { + "libraryName": "base64url", + "typingsPackageName": "base64url", + "sourceRepoURL": "https://github.com/brianloveswords/base64url", + "asOfVersion": "2.0.0" + }, { "libraryName": "BigInteger.js", "typingsPackageName": "big-integer", @@ -246,6 +282,12 @@ "sourceRepoURL": "https://github.com/blakeembrey/is-upper-case", "asOfVersion": "1.1.2" }, + { + "libraryName": "jpush-react-native", + "typingsPackageName": "jpush-react-native", + "sourceRepoURL": "https://github.com/jpush/jpush-react-native", + "asOfVersion": "2.0.0" + }, { "libraryName": "jquery.ajaxfile", "typingsPackageName": "jquery.ajaxfile", @@ -294,6 +336,12 @@ "sourceRepoURL": "https://github.com/localForage/localForage", "asOfVersion": "0.0.34" }, + { + "libraryName": "lodash-decorators", + "typingsPackageName": "lodash-decorators", + "sourceRepoURL": "https://github.com/steelsojka/lodash-decorators", + "asOfVersion": "4.0.0" + }, { "libraryName": "lower-case", "typingsPackageName": "lower-case", @@ -438,6 +486,12 @@ "sourceRepoURL": "https://github.com/getsentry/raven-js", "asOfVersion": "3.10.0" }, + { + "libraryName": "raw-body", + "typingsPackageName": "raw-body", + "sourceRepoURL": "https://github.com/stream-utils/raw-body", + "asOfVersion": "2.3.0" + }, { "libraryName": "react-day-picker", "typingsPackageName": "react-day-picker", @@ -504,6 +558,24 @@ "sourceRepoURL": "https://github.com/tildeio/route-recognizer", "asOfVersion": "0.3.0" }, + { + "libraryName": "samchon", + "typingsPackageName": "samchon", + "sourceRepoURL": "https://github.com/samchon/framework", + "asOfVersion": "2.0.22" + }, + { + "libraryName": "samchon-framework", + "typingsPackageName": "samchon-framework", + "sourceRepoURL": "https://github.com/samchon/framework", + "asOfVersion": "2.0.21" + }, + { + "libraryName": "samchon-library", + "typingsPackageName": "samchon-library", + "sourceRepoURL": "https://github.com/samchon/framework", + "asOfVersion": "0.1.0" + }, { "libraryName": "node-scanf", "typingsPackageName": "scanf", @@ -588,6 +660,12 @@ "sourceRepoURL": "https://github.com/cbowdon/TsMonad", "asOfVersion": "0.5.0" }, + { + "libraryName": "tstl", + "typingsPackageName": "tstl", + "sourceRepoURL": "https://github.com/samchon/tstl", + "asOfVersion": "1.5.7" + }, { "libraryName": "TypeScript", "typingsPackageName": "typescript", diff --git a/package.json b/package.json index c2fef9b679..b12e3fe2eb 100644 --- a/package.json +++ b/package.json @@ -17,11 +17,14 @@ "scripts": { "compile-scripts": "tsc -p scripts", "not-needed": "node scripts/not-needed.js", - "test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed --nProcesses 8", + "test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed", "lint": "dtslint types" }, "devDependencies": { - "dtslint": "Microsoft/dtslint#production", + "dtslint": "github:Microsoft/dtslint#production", "types-publisher": "Microsoft/types-publisher#production" + }, + "dependencies": { + "@egjs/axes": "^2.0.0" } } diff --git a/scripts/generate-tsconfigs.ts b/scripts/generate-tsconfigs.ts index b72144bf40..0115067e34 100644 --- a/scripts/generate-tsconfigs.ts +++ b/scripts/generate-tsconfigs.ts @@ -5,10 +5,6 @@ import * as fs from 'fs'; import * as path from 'path'; -function repeat(s: string, count: number) { - return Array(count + 1).join(s); -} - const home = path.join(__dirname, '..'); for (const dirName of fs.readdirSync(home)) { diff --git a/scripts/material-ui/README.md b/scripts/material-ui/README.md new file mode 100644 index 0000000000..8fe5206a81 --- /dev/null +++ b/scripts/material-ui/README.md @@ -0,0 +1,15 @@ +# Generator for material-ui + +## Usage + +```sh +node scripts/material-ui/generate.js +``` + +### GitHub API Limitation + +The error `GitHub response: 401 Unauthorized` is due to [Rate Limiting | GitHub API v3 \| GitHub Developer Guide](https://developer.github.com/v3/#rate-limiting). In order to avoid this, it is necessary to publish [Personal access token](https://github.com/settings/tokens) and specify it as an environment variable. + +```sh +GITHUB_ACCESS_TOKEN=XXXXX node scripts/material-ui/generate.js +``` diff --git a/scripts/material-ui/generate.js b/scripts/material-ui/generate.js new file mode 100644 index 0000000000..06e6983a44 --- /dev/null +++ b/scripts/material-ui/generate.js @@ -0,0 +1,147 @@ +const {get} = require('https') +const {readdir, readFile, writeFile} = require('fs') +const {join, extname, basename, dirname, relative} = require('path') + +const token = process.env.GITHUB_ACCESS_TOKEN || '' + +const toMixedCase = (name) => { + let dist = name[0].toUpperCase() + for (let i = 1; i < name.length; i++) { + const c = name[i] + if (c !== '-') { + dist += c + continue + } + i++ + dist += name[i].toUpperCase() + } + return dist +} + +const github = (path) => new Promise((resolve, reject) => { + get({ + headers: {'user-agent': 'DefinitelyTyped/material-ui/generate'}, + host: 'api.github.com', + path, + }, (res) => { + if ((res.statusCode / 100 >> 0) != 2) { + reject(`GitHub response: ${res.statusCode} ${res.statusMessage}`) + return + } + let data = ''; + res + .on('data', (chunk) => data += chunk) + .on('end', () => resolve(JSON.parse(data))) + }).on('error', reject) +}) + +const categories = () => github(`/repos/callemall/material-ui/contents/src/svg-icons?ref=master&access_token=${token}`) + +const contents = (path) => github(`/repos/callemall/material-ui/contents/${path}?ref=master&access_token=${token}`) + +const collator = new Intl.Collator() + +const resolvePath = (filename) => join(__dirname, '../../types/material-ui', filename) + +const readText = (filename) => new Promise((resolve, reject) => { + readFile(resolvePath(filename), 'utf8', (err, data) => { + if (err != null) { + reject(err) + return + } + resolve(data) + }) +}) + +const writeText = (filename, text) => new Promise((resolve, reject) => { + writeFile(resolvePath(filename), text, 'utf8', (err) => { + if (err != null) { + reject(err) + return + } + resolve() + }) +}) + +const inject = (content) => { + content.category = this.name + return content +} + +const rMark = /(\/{2} \{{3})[\s\S]*?(\/{2} \}{3})/g + +categories() + .then((cats) => Promise.all(Array.prototype.map.call(cats, (cat) => contents(cat.path) + .then((cons) => Array.prototype.map.call(cons, (con) => { + con.category = cat.name + return con + })) + ))) + .then((contentsList) => Array.prototype.concat.apply([], contentsList) + .map((content) => { + const {path} = content + const name = basename(path, extname(path)) + content.id = join(relative('src', dirname(path)), name) + content.className = toMixedCase(content.category) + toMixedCase(name) + return content + }) + .sort((a, b) => collator.compare(a.id, b.id)) + .reduce((prev, content) => { + const {dts, test} = prev + dts.individuals.push(`declare module 'material-ui/${content.id}' { + export import ${content.className} = __MaterialUI.SvgIcon; + export default ${content.className}; +}`) + dts.summarizeds.push(` export import ${content.className} = __MaterialUI.SvgIcon; // require('material-ui/${content.id}');`) + + test.individuals.push(`import _${content.className} from 'material-ui/${content.id}';`) + test.summarizeds.push(` ${content.className},`) + return prev + }, { + dts: {individuals: [], summarizeds: []}, + test: {individuals: [], summarizeds: []}, + }) +) + .then(({dts, test}) => { + return Promise.all([ + (() => { + const {individuals, summarizeds} = dts + const file = 'index.d.ts' + let index = 0 + return readText(file) + .then((script) => writeText(file, script.replace(rMark, (_, p1, p2) => { + let text = '' + switch (index) { + case 0: + text = individuals.join('\n\n') + break + case 1: + text = summarizeds.join('\n') + break + } + index++ + return p1 + '\n' + text + '\n' + p2 + }))) + })(), + (() => { + const {individuals, summarizeds} = test + const file = join('material-ui-tests.tsx') + let index = 0 + return readText(file) + .then((script) => writeText(file, script.replace(rMark, (_, p1, p2) => { + let text = '' + switch (index) { + case 0: + text = individuals.join('\n') + break + case 1: + text = summarizeds.join('\n') + break + } + index++ + return p1 + '\n' + text + '\n' + p2 + }))) + })(), + ]) + }) + .catch((err) => console.error(err)) diff --git a/types/3d-bin-packing/3d-bin-packing-tests.ts b/types/3d-bin-packing/3d-bin-packing-tests.ts deleted file mode 100644 index 8e394e46bb..0000000000 --- a/types/3d-bin-packing/3d-bin-packing-tests.ts +++ /dev/null @@ -1,50 +0,0 @@ -import packer = require("3d-bin-packing"); -import samchon = require("samchon"); - -function main(): void -{ - /////////////////////////// - // CONSTRUCT OBJECTS - /////////////////////////// - let wrapperArray: bws.packer.WrapperArray = new packer.WrapperArray(); - let instanceArray: bws.packer.InstanceArray = new packer.InstanceArray(); - - // Wrappers - wrapperArray.push - ( - new packer.Wrapper("Large", 1000, 40, 40, 15, 0), - new packer.Wrapper("Medium", 700, 20, 20, 10, 0), - new packer.Wrapper("Small", 500, 15, 15, 8, 0) - ); - - /////// - // Each Instance is repeated #15 - /////// - instanceArray.insert(instanceArray.end(), 15, new packer.Product("Eraser", 1, 2, 5)); - instanceArray.insert(instanceArray.end(), 15, new packer.Product("Book", 15, 30, 3)); - instanceArray.insert(instanceArray.end(), 15, new packer.Product("Drink", 3, 3, 10)); - instanceArray.insert(instanceArray.end(), 15, new packer.Product("Umbrella", 5, 5, 20)); - - // Wrappers also can be packed into another Wrapper. - instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Notebook-Box", 2000, 30, 40, 4, 2)); - instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Tablet-Box", 2500, 20, 28, 2, 0)); - - /////////////////////////// - // BEGINS PACKING - /////////////////////////// - // CONSTRUCT PACKER - let my_packer: bws.packer.Packer = new packer.Packer(wrapperArray, instanceArray); - - /////// - // PACK (OPTIMIZE) - let result: bws.packer.WrapperArray = my_packer.optimize(); - /////// - - /////////////////////////// - // TRACE PACKING RESULT - /////////////////////////// - let xml: samchon.library.XML = result.toXML(); - console.log(xml.toString()); -} - -main(); \ No newline at end of file diff --git a/types/3d-bin-packing/index.d.ts b/types/3d-bin-packing/index.d.ts deleted file mode 100644 index 8165ea513e..0000000000 --- a/types/3d-bin-packing/index.d.ts +++ /dev/null @@ -1,1383 +0,0 @@ -// Type definitions for 3d-bin-packing v1.1.2 -// Project: https://github.com/betterwaysystems/packer -// Definitions by: Jeongho Nam -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "3d-bin-packing" -{ - export = bws.packer; -} - -/// -/// -declare namespace bws.packer { - export import library = samchon.library; - export import protocol = samchon.protocol; - function _Test(): void; -} -declare namespace boxologic { - /** - *

An abstract instance of boxologic.

- * - *

{@link st_Instance} represents a physical, tangible instance of 3-dimension.

- * - * @author Jeongho Nam - */ - abstract class Instance { - /** - * Width of the tangible instance, length on the X-axis in 3D. - */ - width: number; - /** - * Height of the tangible instance, length on the Y-axis in 3D. - */ - height: number; - /** - * Length of the tangible instance, length on the Z-axis in 3D. - */ - length: number; - /** - * Width considering layout placement. - */ - layout_width: number; - /** - * Height considering layout placement. - */ - layout_height: number; - /** - * Length considering layout placement. - */ - layout_length: number; - /** - * Volume, Width x Height x Length. - */ - volume: number; - /** - * Construct from size members. - * - * @param width Width, length on the X-axis in 3D. - * @param height Height, length on the Y-axis in 3D. - * @param length Length, length on the Z-axis in 3D. - */ - constructor(width: number, height: number, length: number); - } -} -declare namespace boxologic { - /** - * A box, trying to pack into a {@link Pallet}. - * - * @author Bill Knechtel,
- * Migrated and Refactored by Jeongho Nam - */ - class Box extends Instance { - /** - * Coordinate-X of the box placement in a {@link Pallet}. - */ - cox: number; - /** - * Coordinate-Y of the box placement in a {@link Pallet}. - */ - coy: number; - /** - * Coordinate-Z of the box placement in a {@link Pallet}. - */ - coz: number; - /** - * Whether the {@link Box} is packed into a {@link Pallet}. - */ - is_packed: boolean; - overlapped_boxes: std.HashSet; - /** - * Construct from an instance. - * - * @param instance An instance adapts with. - */ - constructor(instance: bws.packer.Instance); - hit_test(obj: Box): boolean; - private hit_test_single(obj); - private hit_test_point(x, y, z); - } -} -/** - *

A set of programs that calculate the best fit for boxes on a pallet migrated from language C.

- * - *
    - *
  • Original Boxologic: https://github.com/exad/boxologic
  • - *
- * - * @author Bill Knechtel,
- * Migrated and Refactored by Jeongho Nam - */ -declare namespace boxologic { - /** - *

A facade class of boxologic.

- * - *

The Boxologic class dudcts the best solution of packing boxes to a pallet.

- * - *
    - *
  • Reference: https://github.com/exad/boxologic
  • - *
- * - * @author Bill Knechtel,
- * Migrated and Refactored by Jeongho Nam - */ - class Boxologic { - /** - * A Wrapper to pack instances. - */ - private wrapper; - /** - * Instances trying to put into the wrapper. - */ - private instanceArray; - /** - * Instances failed to pack by overloading. - */ - private leftInstances; - /** - * A pallet containing {@link Box boxes}. - * - * @see Wrapper - */ - private pallet; - /** - * Boxes, trying to pack into the {@link pallet}. - */ - private box_array; - /** - * Sum of all boxes' volume. - */ - private total_box_volume; - /** - *

All different lengths of {@link box_array all box} dimensions along with evaluation values.

- * - *

In other word, the layer_map stores those entries; each {@link Boxbox}'s length on each - * axis as a key (width, height or length) and evaluation value as a value. The evaluation - * value means sum of minimum gaps between the key and other {@link Box boxes}' width, height and length - *

- * - * - FOR i := 0 to box_array.size() - WHILE key IN width, length and height in box_array[i] - BEGIN - value := 0 - FOR j to box_array.size() - value += min - ( - abs(key - box_array[j].width), - abs(key - box_array[j].height), - abs(key - box_array[j].length) - ) - layer_map.insert({key, value}); - END - * - * - *
    - *
  • key: A dimension value
  • - *
  • value: Evaluation weight value for the corresponding key.
  • - *
- */ - private layer_map; - /** - * {@link List} of {@link Scrapped} instances, edges of layers under construction. - * - * @see Scrapped - * @see scrap_min_z - */ - private scrap_list; - /** - * The topology {@link Scrapped}, the edge of the current layer under construction. - * - * @see Scrapped - * @see scrap_list - */ - private scrap_min_z; - /** - * Index of the current {@link box}. - */ - private cboxi; - /** - * Candidate {@link Box.layout_width layout_width} of the {@link cboxi current box}. - */ - private cbox_layout_width; - /** - * Candidate {@link Box.layout_height layout_height} of the {@link cboxi current box}. - */ - private cbox_layout_height; - /** - * Candidate {@link Box.layout_length layout_length} of the {@link cboxi current box}. - */ - private cbox_layout_length; - /** - * Current layer's key on iteration. - */ - private layer_thickness; - /** - * Previous layer's key had iterated. - */ - private pre_layer; - /** - * Key of the unevened layer in the current packing layer. - */ - private layer_in_layer; - /** - * Little Z, gotten from {@link Scrapped.cumz cumz} in {@link min_scrap_z} - */ - private lilz; - /** - * Remained (unfilled) {@link Pallet.layout_height layout_height} of the {@link pallet}. - */ - private remain_layout_height; - /** - * Remained (unfilled) {@link Pallet.layout_length layout_length} of the {@link pallet}. - */ - private remain_layout_length; - /** - * Packed (filled) {@link Pallet.layout_height layout_height} of the {@link pallet}. - */ - private packed_layout_height; - /** - * Packed {@link Pallet.vo1lume volume} of the {@lnk pallet}. - */ - private packed_volume; - private boxi; - private bboxi; - private boxx; - private boxy; - private boxz; - private bboxx; - private bboxy; - private bboxz; - private bfx; - private bfy; - private bfz; - private bbfx; - private bbfy; - private bbfz; - /** - *

Whether the packing is on progress.

- * - *

The {@link packing} is a flag variable for terminating iterations in - * {@link iterate_orientations iterate_orientations()}, who deducts the best packing solution.

- */ - private packing; - /** - * Whether packing a layer is done. - */ - private layer_done; - /** - * Whether the current packing layer is evened. - */ - private evened; - /** - * Whether the best solution is deducted. - */ - private packing_best; - /** - * Whether the utilization degree of pallet space is 100%. - */ - private hundred_percent; - /** - * The best orientation of the pallet, which can deduct the {@link best_solution_volume}. - */ - private best_orientation; - /** - * The best layer, which can deduct the {@link best_solution_volume}. - */ - private best_layer; - /** - * The best volume, fit the best utilization degree of the pallet space. - */ - private best_solution_volume; - /** - * Construct from a wrapper and instances. - * - * @param wrapper A Wrapper to pack instances. - * @param instanceArray Instances trying to put into the wrapper. - */ - constructor(wrapper: bws.packer.Wrapper, instanceArray: bws.packer.InstanceArray); - /** - *

Encode data

- * - *

Encodes {@link bws.packer Packer}'s data to be suitable for the - * {@link boxologic Boxologic}'s parametric data.

- */ - private encode(); - /** - *

Decode data

- * - *

Decodes the Boxologic's optimization result data to be suitable for the Packer's own.

- */ - private decode(); - private inspect_validity(); - /** - *

Pack instances to the {@link wrapper}.

- * - *

The {@link Boxologic.pack} is an adaptor method between {@link bws.packer Packer} and - * {@link boxologic}. It encodes data from {@link bws.packer Packer}, deducts the best packing - * solution decodes the optimization result and returns it.

- * - *

The optimization result is returned as a {@link Pair} like below:

- *
    - *
  • first: The {@link wrapper} with packed instances.
  • - *
  • second: {@link leftInstances Left instances failed to pack} by overloading.
  • - *
- * - * @return A pair of {@link wrapper} with packed instances and - * {@link leftInstances instances failed to pack} by overloading. - */ - pack(): std.Pair; - /** - *

Execute iterations by calling proper functions.

- * - *

Iterations are done and parameters of the best solution are found.

- */ - private iterate_orientations(); - /** - * Iterate a layer. - * - * @param thickness Thickness of the iterating layer. - */ - private iterate_layer(thickness); - /** - *

Construct layers.

- * - *

Creates all possible layer heights by giving a weight value to each of them.

- */ - private construct_layers(); - /** - *

Packs the boxes found and arranges all variables and records properly.

- * - *

Update the linked list and the Boxlist[] array as a box is packed.

- */ - private pack_layer(); - /** - * Find the most proper layer height by looking at the unpacked boxes and - * the remaining empty space available. - */ - private find_layer(thickness); - /** - *

Determine the gap with the samllest z value in the current layer.

- * - *

Find the most proper boxes by looking at all six possible orientations, - * empty space given, adjacent boxes, and pallet limits.

- * - * @param hmx Maximum available x-dimension of the current gap to be filled. - * @param hy Current layer thickness value. - * @param hmy Current layer thickness value. - * @param hz Z-dimension of the current gap to be filled. - * @param hmz Maximum available z-dimension to the current gap to be filled. - */ - private find_box(hmx, hy, hmy, hz, hmz); - /** - *

Analyzes each unpacked {@link Box box} to find the best fitting one to the empty space.

- * - *

Used by {@link find_box find_box()} to analyze box dimensions.

- * - * @param x index of a {@link Box box} in the {@link box_array}. - * - * @param hmx Maximum available x-dimension of the current gap to be filled. - * @param hy Current layer thickness value. - * @param hmy Current layer thickness value. - * @param hz Z-dimension of the current gap to be filled. - * @param hmz Maximum available z-dimension to the current gap to be filled. - * - * @param dim1 X-dimension of the orientation of the box being examined. - * @param dim2 Y-dimension of the orientation of the box being examined. - * @param dim3 Z-dimension of the orientation of the box being examined. - */ - private analyze_box(index, hmx, hy, hmy, hz, hmz, dim1, dim2, dim3); - /** - * After finding each box, the candidate boxes and the condition of the layer are examined. - */ - private check_found(); - /** - * After packing of each box, 100% packing condition is checked. - */ - private volume_check(); - /** - *

Find the first to be packed gap in the layer edge.

- * - *

Determine the gap with the {@link scrap_min_z smallest z} value in the current layer.

- */ - private find_smallest_z(); - /** - *

Determine {@link box_arrray boxes}.

- * - *

Using the parameters found, packs the best solution found and reports.

- */ - private report_results(); - /** - *

Determine a {@link Box}.

- * - *

Transforms the found co-ordinate system to the one entered by the user and write them to the - * report.

- */ - private write_box_file(); - } -} -declare namespace boxologic { - /** - * A pallet containing boxes. - * - * @author Bill Knechtel,
- * Migrated and Refactored by Jeongho Nam - */ - class Pallet extends Instance { - /** - * Construct from a wrapper. - * - * @param wrapper A wrapper wrapping instances. - */ - constructor(wrapper: bws.packer.Wrapper); - /** - * Set placement orientation. - */ - set_orientation(orientation: number): void; - } -} -declare namespace boxologic { - /** - *

Cumulated lengths of current layer.

- * - *

{@link Scrapped} represents an edge of the current layer under construction.

- * - * @author Bill Knechtel,
- * Migrated and Refactored by Jeongho Nam - */ - class Scrap { - /** - * Cumulated length on the X-axis in 3D. - */ - cumx: number; - /** - * Cumulated length on the Z-axis in 3D. - */ - cumz: number; - /** - * Default Constructor. - */ - constructor(); - /** - * Initialization Constructor. - * - * @param cumx Cumulated length on the x-axis. - * @param cumz Cumulated length on the z-axis. - */ - constructor(cumx: number, cumz: number); - } -} -declare namespace bws.packer { - /** - * Bridge of {@link Packer} for {@link InstanceForm repeated instances}. - * - * @author Jeongho Nam - */ - class PackerForm extends protocol.Entity { - /** - * Form of Instances to pack. - */ - private instanceFormArray; - /** - * Type of Wrappers to be used. - */ - private wrapperArray; - /** - * Default Constructor. - */ - constructor(); - /** - * Initializer Constructor. - * - * @param instanceFormArray Form of Instances to pack. - * @param wrapperArray Type of Wrappers to be used. - */ - constructor(instanceFormArray: InstanceFormArray, wrapperArray: WrapperArray); - construct(xml: library.XML): void; - optimize(): WrapperArray; - getInstanceFormArray(): InstanceFormArray; - getWrapperArray(): WrapperArray; - TAG(): string; - toXML(): library.XML; - toPacker(): Packer; - } - /** - * An array of {@link InstanceForm} objects. - * - * @author Jeongho Nam - */ - class InstanceFormArray extends protocol.EntityArrayCollection { - /** - * Default Constructor. - */ - constructor(); - createChild(xml: library.XML): InstanceForm; - TAG(): string; - CHILD_TAG(): string; - /** - * Convert {@link InstanceForm} objects to {@link InstanceArray}. - * - * @return An array of instance containing repeated instances in {@link InstanceForm} objects. - */ - toInstanceArray(): InstanceArray; - } - /** - *

A repeated Instance.

- * - *

InstanceForm is an utility class for repeated {@link Instance}. It is designed for shrinking - * volume of network message I/O by storing {@link count repeated count}.

- * - * @author Jeongho Nam - */ - class InstanceForm extends protocol.Entity { - /** - * A duplicated Instance. - */ - private instance; - /** - * Repeated count of the {@link instance}. - */ - private count; - /** - * Default Constructor. - */ - constructor(instance?: Instance, count?: number); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - private createInstance(xml); - key(): any; - getInstance(): Instance; - getCount(): number; - setCount(val: number): void; - $name: string; - $width: string; - $height: string; - $length: string; - $count: string; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - /** - *

Repeated {@link instance} to {@link InstanceArray}. - * - * @details - *

Contains the {@link instance repeated instance} to an {@link InstanceArray} to make - * {@link instance} to participate in the packing process. The returned {@link InstanceArray} will be - * registered on {@link Packer.instanceArray}. - * - * @return An array of instance containing repeated {@link instance}. - */ - toInstanceArray(): InstanceArray; - } -} -declare namespace bws.packer { - class WrapperArray extends protocol.EntityArrayCollection { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - createChild(xml: library.XML): Wrapper; - /** - * Get (calculate) price. - */ - getPrice(): number; - /** - * Get (calculate) utilization rate. - */ - getUtilization(): number; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - CHILD_TAG(): string; - } -} -declare namespace bws.packer { - class GAWrapperArray extends WrapperArray { - protected instanceArray: InstanceArray; - protected result: std.HashMap; - private price; - /** - * @brief Validity of this sequence list. - */ - private valid; - /** - * Construct from instances. - * - * @param instanceArray Instances to be wrapped. - */ - constructor(instanceArray: InstanceArray); - /** - * @brief Copy Constructor. - */ - constructor(genes: GAWrapperArray); - private constructResult(); - /** - * @brief Get optimization result. - * - * @return result map. - */ - getResult(): std.HashMap; - less(obj: GAWrapperArray): boolean; - } -} -declare namespace bws.packer { - /** - * An interface of physical 3D-instances. - * - * @author Jeongho Nam - */ - interface Instance extends protocol.IEntity { - /** - * Get name. - */ - getName(): string; - /** - * Get width, length on the X-axis in 3D. - */ - getWidth(): number; - /** - * Get height, length on the Y-axis in 3D. - */ - getHeight(): number; - /** - * Get length, length on the Z-axis in 3D. - */ - getLength(): number; - /** - * Get (calculate) volume. - * - * @return width x height x length - */ - getVolume(): number; - /** - * Set name. - */ - setName(val: string): void; - /** - * Set width, length on the X-axis in 3D. - */ - setWidth(val: number): void; - /** - * Set height, length on the Y-axis in 3D. - */ - setHeight(val: number): void; - /** - * Set length, length on the Z-axis in 3D. - */ - setLength(val: number): void; - /** - *

A type, identifier of derived class.

- * - *

Derived types

- *
    - *
  • {@link Product product}
  • - *
  • {@link Wrapper wrapper}
  • - *
      - */ - TYPE(): string; - } -} -declare namespace bws.packer { - /** - * An array of Instance objects. - * - * @author Jeongho Nam - */ - class InstanceArray extends protocol.EntityArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - createChild(xml: library.XML): Instance; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - CHILD_TAG(): string; - } -} -declare namespace bws.packer { - /** - * @brief Packer, a solver of 3d bin packing with multiple wrappers. - * - * @details - *

      Packer is a facade class supporting packing operations in user side. You can solve a packing problem - * by constructing Packer class with {@link WrapperArray wrappers} and {@link InstanceArray instances} to - * pack and executing {@link optimize Packer.optimize()} method.

      - * - *

      In background side, deducting packing solution, those algorithms are used.

      - * - * - * @author Jeongho Nam - */ - class Packer extends protocol.Entity { - /** - * Candidate wrappers who can contain instances. - */ - protected wrapperArray: WrapperArray; - /** - * Instances trying to pack into the wrapper. - */ - protected instanceArray: InstanceArray; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from members. - * - * @param wrapperArray Candidate wrappers who can contain instances. - * @param instanceArray Instances to be packed into some wrappers. - */ - constructor(wrapperArray: WrapperArray, instanceArray: InstanceArray); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * Get wrapperArray. - */ - getWrapperArray(): WrapperArray; - /** - * Get instanceArray. - */ - getInstanceArray(): InstanceArray; - /** - *

      Deduct - * - */ - optimize(): WrapperArray; - /** - * @brief Initialize sequence list (gene_array). - * - * @details - *

      Deducts initial sequence list by such assumption:

      - * - *
        - *
      • Cost of larger wrapper is less than smaller one, within framework of price per volume unit.
      • - *
          - *
        • Wrapper Larger: (price: $1,000, volume: 100cm^3 -> price per volume unit: $10 / cm^3)
        • - *
        • Wrapper Smaller: (price: $700, volume: 50cm^3 -> price per volume unit: $14 / cm^3)
        • - *
        • Larger's cost is less than Smaller, within framework of price per volume unit
        • - *
        - *
      - * - *

      Method {@link initGenes initGenes()} constructs {@link WrapperGroup WrapperGroups} corresponding - * with the {@link wrapperArray} and allocates {@link instanceArray instances} to a {@link WrapperGroup}, - * has the smallest cost between containbles.

      - * - *

      After executing packing solution by {@link WrapperGroup.optimize WrapperGroup.optimize()}, trying to - * {@link repack re-pack} each {@link WrapperGroup} to another type of {@link Wrapper}, deducts the best - * solution between them. It's the initial sequence list of genetic algorithm.

      - * - * @return Initial sequence list. - */ - protected initGenes(): GAWrapperArray; - /** - * Try to repack each wrappers to another type. - * - * @param $wrappers Wrappers to repack. - * @return Re-packed wrappers. - */ - protected repack($wrappers: WrapperArray): WrapperArray; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace bws.packer { - /** - * A product. - * - * @author Jeongho Nam - */ - class Product extends protocol.Entity implements Instance { - /** - *

      Name, key of the Product.

      - * - *

      The name must be unique because a name identifies a {@link Product}.

      - */ - protected name: string; - /** - * Width of the Product, length on the X-axis in 3D. - */ - protected width: number; - /** - * Height of the Product, length on the Y-axis in 3D. - */ - protected height: number; - /** - * Length of the Product, length on the Z-axis in 3D. - */ - protected length: number; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from members. - * - * @param name Name, identifier of the Product. - * @param width Width, length on the X-axis in 3D. - * @param height Height, length on the Y-axis in 3D. - * @param length Length, length on the Z-axis in 3D. - */ - constructor(name: string, width: number, height: number, length: number); - /** - * Key of a Product is its name. - */ - key(): any; - /** - * @inheritdoc - */ - getName(): string; - /** - * @inheritdoc - */ - getWidth(): number; - /** - * @inheritdoc - */ - getHeight(): number; - /** - * @inheritdoc - */ - getLength(): number; - /** - * @inheritdoc - */ - getVolume(): number; - /** - * @inheritdoc - */ - setName(val: string): void; - /** - * @inheritdoc - */ - setWidth(val: number): void; - /** - * @inheritdoc - */ - setHeight(val: number): void; - /** - * @inheritdoc - */ - setLength(val: number): void; - /** - * @inheritdoc - */ - TYPE(): string; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace bws.packer { - /** - *

      Wrap represents an act wrap(ping).

      - * - *

      {@link Wrap} is a class represents an act wrapping an {@link Instance} to an {@link Wrapper}. - * To represent the relationship, Wrap uses Bridge and Capsular patterns to links and intermediates - * relationship between Wrapper and Instance.

      - * - *

      Wrap also helps packing optimization and 3d-visualization with its own members - * {@link orientation} and position variables {@link x}, {@link y} and {@link z}.

      - * - * @author Jeongho Nam - */ - class Wrap extends protocol.Entity { - /** - * A wrapper wrapping the {@link instance}. - */ - protected wrapper: Wrapper; - /** - * An instance wrapped into the {@link wrapper}. - */ - protected instance: Instance; - /** - * Coordinate-X of the instance placement in the wrapper. - */ - protected x: number; - /** - * Coordinate-Y of the instance placement in the wrapper. - */ - protected y: number; - /** - * Coordinate-Z of the instance placement in the wrapper. - */ - protected z: number; - /** - * Placement orientation of wrapped {@link instance}. - */ - protected orientation: number; - /** - * Construct from a Wrapper. - * - * @param wrapper A wrapper who will contain an instance. - */ - constructor(wrapper: Wrapper); - /** - * Construct from a Wrapper and Instance with its position and default orientation 1. - * - * @param wrapper A wrapper who contains the instance. - * @param instance An instance contained into the wrapper. - * @param x Coordinate-X of the {@link instance} placement in the {@link wrapper}. - * @param y Coordinate-Y of the {@link instance} placement in the {@link wrapper}. - * @param z Coordinate-Z of the {@link instance} placement in the {@link wrapper}. - */ - constructor(wrapper: Wrapper, instance: Instance, x: number, y: number, z: number); - /** - * Construct from a Wrapper and Instance with its position and orientation. - * - * @param wrapper A wrapper who contains the instance. - * @param instance An instance contained into the wrapper. - * @param x Coordinate-X of the {@link instance} placement in the {@link wrapper}. - * @param y Coordinate-Y of the {@link instance} placement in the {@link wrapper}. - * @param z Coordinate-Z of the {@link instance} placement in the {@link wrapper}. - * @param orientation Placement orientation of wrapped {@link instance}. - */ - constructor(wrapper: Wrapper, instance: Instance, x: number, y: number, z: number, orientation: number); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * Factory method of wrapped Instance. - * - * @param type Type of contained Instance's type. - */ - protected createInstance(type: string): Instance; - /** - * Set orientation. - * - * @param orientation Orientation code (1 to 6). - */ - setOrientation(orientation: number): void; - /** - * Set position. - * - * @param x Coordinate-X of the instance placement in the wrapper. - * @param y Coordinate-Y of the instance placement in the wrapper. - * @param z Coordinate-Z of the instance placement in the wrapper. - */ - setPosition(x: number, y: number, z: number): void; - /** - * @brief Estimate orientation by given size. - * - * @param width Width by placement. - * @param height Height by placement. - * @param length Length by placement. - */ - estimateOrientation(width: number, height: number, length: number): void; - /** - * @brief Orientation change is occured in level of the packer. - * - * @details orientation Packer's new orientation. - */ - changeWrapperOrientation(orientation: number): void; - /** - * Get wrapper. - */ - getWrapper(): Wrapper; - /** - * Get instance. - */ - getInstance(): Instance; - /** - * Get x. - */ - getX(): number; - /** - * Get y. - */ - getY(): number; - /** - * Get z. - */ - getZ(): number; - /** - * Get orientation. - */ - getOrientation(): number; - /** - * Get width. - */ - getLayoutWidth(): number; - /** - * Get height. - */ - getLayoutHeight(): number; - /** - * Get length. - */ - getLength(): number; - /** - * Get volume. - */ - getVolume(): number; - readonly $instanceName: string; - readonly $layoutScale: string; - readonly $position: string; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace bws.packer { - /** - * A wrapper wrapping instances. - * - * @author Jeongho Nam - */ - class Wrapper extends protocol.EntityDeque implements Instance { - /** - *

      Name, key of the Wrapper.

      - * - *

      The name represents a type of Wrapper and identifies the Wrapper.

      - */ - protected name: string; - /** - * Price, cost of using an Wrapper. - */ - protected price: number; - /** - * Width of the Wrapper, length on the X-axis in 3D. - */ - protected width: number; - /** - * Height of the Wrapper, length on the Y-axis in 3D. - */ - protected height: number; - /** - * Length of the Wrapper, length on the Z-axis in 3D. - */ - protected length: number; - /** - *

      Thickness, margin of a Wrapper causes shrinkness of containable volume.

      - * - *

      The thickness reduces each dimension's containable size (dimension - 2*thickness), - * so finally, it reduces total containable volume (-8 * thickness^3).

      - */ - protected thickness: number; - /** - * Default Constructor. - */ - constructor(); - /** - * Copy Constructor. - */ - constructor(wrapper: Wrapper); - /** - * Construct from members. - * - * @param name Name, identifier of a Wrapper. - * @param price Price, issued cost for a type of the Wrapper. - * @param width Width, dimensional length on the X-axis in 3D. - * @param height Height, dimensional length on the Y-axis in 3D. - * @param length Length, dimensional length on the Z-axis in 3D. - * @param thickness A thickness causes shrinkness on containable volume. - */ - constructor(name: string, price: number, width: number, height: number, length: number, thickness: number); - /** - * @inheritdoc - */ - createChild(xml: library.XML): Wrap; - /** - * Key of a Wrapper is its name. - */ - key(): any; - /** - * Get name. - */ - getName(): string; - /** - * Get price. - */ - getPrice(): number; - /** - * Get width, length on X-axis in 3D. - */ - getWidth(): number; - /** - * Get height, length on Y-axis in 3D. - */ - getHeight(): number; - /** - * Get length, length on Z-axis in 3D. - */ - getLength(): number; - /** - * Get thickness. - */ - getThickness(): number; - /** - *

      Get (calculate) containable width, length on the X-axis in 3D.

      - * - *

      Calculates containable width considering the {@link thickness}.

      - * - * @return width - (2 x thickness) - */ - getContainableWidth(): number; - /** - *

      Get (calculate) containable height, length on the Y-axis in 3D.

      - * - *

      Calculates containable height considering the {@link thickness}.

      - * - * @return height - (2 x thickness) - */ - getContainableHeight(): number; - /** - *

      Get (calculate) containable length, length on the Z-axis in 3D.

      - * - *

      Calculates containable length considering the {@link thickness}.

      - * - * @return length - (2 x thickness) - */ - getContainableLength(): number; - /** - *

      Get (calculate) volume.

      - * - *

      Notice

      - *

      If {@link thickness} of the Wrapper is not 0, the volume does not mean containable volume. - * In that case, use {@link containableVolume} instead.

      - * - * @return width x height x length - */ - getVolume(): number; - /** - *

      Get (calculate) containable volume.

      - * - *

      Calculates containable volume considering the {@link thickness}.

      - * - * @return volume - {(2 x thickness) ^ 3} - */ - getContainableVolume(): number; - /** - * Get utilization ratio of containable volume. - * - * @return utilization ratio. - */ - getUtilization(): number; - equals(obj: Wrapper): boolean; - /** - *

      Wrapper is enough greater?

      - * - *

      Test whether the Wrapper is enough greater than an Instance to contain.

      - * - * @param instance An Instance to test. - * @return Enough greater or not. - */ - containable(instance: Instance): boolean; - /** - * @inheritdoc - */ - setName(val: string): void; - /** - * Set price. - */ - setPrice(val: number): void; - /** - * @inheritdoc - */ - setWidth(val: number): void; - /** - * @inheritdoc - */ - setHeight(val: number): void; - /** - * @inheritdoc - */ - setLength(val: number): void; - /** - * Set thickness. - */ - setThickness(val: number): void; - $name: string; - $price: string; - $width: string; - $height: string; - $length: string; - $thickness: string; - readonly $scale: string; - readonly $spaceUtilization: string; - /** - * @inheritdoc - */ - TYPE(): string; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace bws.packer { - /** - * A group of {@link Wrapper Wrappers} with same type. - * - * @author Jeongho Nam - */ - class WrapperGroup extends WrapperArray { - /** - *

      A sample, standard of the WrapperGroup.

      - * - *

      The sample represents what type of Wrappers are grouped into the WrapperGroup.

      - */ - protected sample: Wrapper; - /** - * Allocated instances. - */ - protected allocatedInstanceArray: InstanceArray; - /** - * Default Constructor. - */ - constructor(); - /** - * Copy Constructor. - */ - constructor(wrapperGroup: WrapperGroup); - /** - * Construct from a sample. - * - * @param sample A sample, standard of the WrapperGroup. - */ - constructor(sample: Wrapper); - /** - * Construct from members of the {@link sample}. - * - * @param name Name, identifier of the sample. - * @param price Price, issued cost for a type of the sample. - * @param width Width, dimensional length on the X-axis in 3D, of the sample. - * @param height Height, dimensional length on the Y-axis in 3D, of the sample. - * @param length Length, dimensional length on the Z-axis in 3D, of the sample. - * @param thickness A thickness, causes shrinkness on containable volume, of the sample. - */ - constructor(name: string, price: number, width: number, height: number, length: number, thickness: number); - /** - * Key of a WrapperGroup is dependent on its sample. - */ - key(): any; - /** - * Get sample. - */ - getSample(): Wrapper; - /** - * Get allocated instances. - */ - getAllocatedInstanceArray(): InstanceArray; - /** - * Get (calculate) price. - * - * @return (Price of the sample) x (numbers of children Wrappers) - */ - getPrice(): number; - /** - * @inheritdoc - */ - getUtilization(): number; - /** - *

      Allocate instance(s) to the WrapperGroup.

      - * - *

      Inspect the instance is enough small to be wrapped into an empty wrapper. If the instance - * is enough small, registers the instance (or repeated instances) to the {@link reserveds} and - * returns true. If the instance is too large to be capsuled, returns false.

      - * - *

      Note

      - *

      The word the instance is enough small to be wrapped into the empty wrapper means - * the instance can be contained into an empty, a new wrapper contaning nothing literally.

      - * - *

      In the method allocate(), it doesn't consider how many instances are wrapped into ordinary - * wrapper and how much volumes are consumed.

      - * - * @param instance An Instance to allocate. - * @param n Repeating number of the instance. - * - * @return Whether the instance is enough small to be wrapped into a (new) wrapper - * of same type with the sample. - */ - allocate(instance: Instance, n?: number): boolean; - /** - *

      Run optimization in level of the group.

      - * - *

      The optimization routine begins by creating a {@link Wrapper} like the {@link sample}. Then - * try to pack {@link allocatedInstanceArray allocated instances} to the {@link Wrapper} as a lot as - * possible. If there're some {@link Wrappers} can't be packed by overloading, then create a new - * {@link Wrapper} again and try to pack {@link allocatedInstanceArray instances} again, too.

      - * - *

      Repeats those steps until all {@link alloctedInstanceArray instances} are {@link Wrap packed} - * so that there's not any {@link Instance instance} left.

      - * - *

      Warning

      - *

      When call this {@link optimize optimize()} method, ordinary children {@link Wrapper} objects - * in the {@link WrapperGroup} will be substituted with the newly optimized {@link Wrapper} objects.

      - */ - optimize(): void; - /** - *

      Wrap allocated instances into a new {@link Wrapper}.

      - * - *

      {@link Wrap Wraps} instances to a new Wrapper which is copied from the sample.

      - *

      After the wrapping is done, the new {@link Wrapper} is registered to the {@link WrapperGroup} - * as a child and instances failed to wrap by overloading is returned.

      - * - * @param instanceArray instances to {@link Wrap wrap} into a new {@link Wrapper}. - * - * @return Instances failed to {@link Wrap wrap} by overloading. - * @see boxologic - */ - private pack(instanceArray); - /** - * @inheritdoc - */ - TAG(): string; - } -} diff --git a/types/3d-bin-packing/tsconfig.json b/types/3d-bin-packing/tsconfig.json deleted file mode 100644 index 18e4645ac9..0000000000 --- a/types/3d-bin-packing/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "3d-bin-packing-tests.ts" - ] -} \ No newline at end of file diff --git a/types/abbrev/abbrev-tests.ts b/types/abbrev/abbrev-tests.ts new file mode 100644 index 0000000000..b4f892e9e3 --- /dev/null +++ b/types/abbrev/abbrev-tests.ts @@ -0,0 +1,13 @@ +import abbrev = require('abbrev'); + +let abbrs: { [abbreviation: string]: string; }; +abbrs = abbrev(); +abbrs = abbrev('foo', 'fool', 'folding', 'flop'); +abbrs = abbrev(['foo', 'fool', 'folding', 'flop']); + +abbrev.monkeyPatch(); + +abbrs = [].abbrev(); +const roArr: ReadonlyArray = []; +abbrs = roArr.abbrev(); +abbrs = ({}).abbrev(); diff --git a/types/abbrev/index.d.ts b/types/abbrev/index.d.ts new file mode 100644 index 0000000000..0d55334d3f --- /dev/null +++ b/types/abbrev/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for abbrev 1.1 +// Project: https://github.com/isaacs/abbrev-js#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = abbrev; + +declare function abbrev(words: string[]): {[abbreviation: string]: string}; +declare function abbrev(...words: string[]): {[abbreviation: string]: string}; + +declare namespace abbrev { + function monkeyPatch(): void; +} + +declare global { + interface Array { + abbrev(): {[abbreviation: string]: string}; + } + + interface ReadonlyArray { + abbrev(): {[abbreviation: string]: string}; + } + + interface Object { + abbrev(): {[abbreviation: string]: string}; + } +} diff --git a/types/abbrev/tsconfig.json b/types/abbrev/tsconfig.json new file mode 100644 index 0000000000..95c20ed32a --- /dev/null +++ b/types/abbrev/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "abbrev-tests.ts" + ] +} diff --git a/types/raw-body/tslint.json b/types/abbrev/tslint.json similarity index 100% rename from types/raw-body/tslint.json rename to types/abbrev/tslint.json diff --git a/types/ably/index.d.ts b/types/ably/index.d.ts index 7bfc2338b6..3a150257ba 100644 --- a/types/ably/index.d.ts +++ b/types/ably/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Ably Realtime and Rest client library 0.9 // Project: https://www.ably.io/ -// Definitions by: Ably +// Definitions by: Ably // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export namespace ablyLib { @@ -287,7 +287,7 @@ export namespace ablyLib { } // Common Listeners - type paginatedResultCallback = (error: ErrorInfo, results: PaginatedResult ) => void; + type paginatedResultCallback = (error: ErrorInfo, results: PaginatedResult) => void; type standardCallback = (error: ErrorInfo, results: any) => void; type messageCallback = (message: T) => void; type errorCallback = (error: ErrorInfo) => void; @@ -410,7 +410,7 @@ export namespace ablyLib { state: ConnectionState; close: () => void; connect: () => void; - ping: (callback?: (error: ErrorInfo, responseTime: number ) => void ) => void; + ping: (callback?: (error: ErrorInfo, responseTime: number) => void) => void; } class Stats { diff --git a/types/accounting/index.d.ts b/types/accounting/index.d.ts index 9a990a6519..8a9feca611 100644 --- a/types/accounting/index.d.ts +++ b/types/accounting/index.d.ts @@ -1,7 +1,7 @@ // Type definitions for accounting.js 0.4 // Project: http://openexchangerates.github.io/accounting.js/ -// Definitions by: Sergey Gerasimov -// Christopher Eck +// Definitions by: Sergey Gerasimov +// Christopher Eck // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace accounting { diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index 58bf1c2bd8..456727756c 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -1041,6 +1041,12 @@ declare namespace AceAjax { addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any): void; addEventListener(ev: string, callback: Function): void; + off(ev: string, callback: Function): void; + + removeListener(ev: string, callback: Function): void; + + removeEventListener(ev: string, callback: Function): void; + inMultiSelectMode: boolean; selectMoreLines(n: number): void; @@ -2166,8 +2172,16 @@ declare namespace AceAjax { **/ export interface Selection { + on(ev: string, callback: Function): void; + addEventListener(ev: string, callback: Function): void; + off(ev: string, callback: Function): void; + + removeListener(ev: string, callback: Function): void; + + removeEventListener(ev: string, callback: Function): void; + moveCursorWordLeft(): void; moveCursorWordRight(): void; diff --git a/types/activex-adodb/activex-adodb-tests.ts b/types/activex-adodb/activex-adodb-tests.ts index cadb01c15e..22680d963c 100644 --- a/types/activex-adodb/activex-adodb-tests.ts +++ b/types/activex-adodb/activex-adodb-tests.ts @@ -14,9 +14,7 @@ let obj5 = new ActiveXObject('ADODB.Stream'); let pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx'; let conn = new ActiveXObject('ADODB.Connection'); conn.Provider = 'Microsoft.ACE.OLEDB.12.0'; -conn.ConnectionString = - 'Data Source="' + pathToExcelFile + '";' + - 'Extended Properties="Excel 12.0;HDR=Yes"'; +conn.ConnectionString = `Data Source="${pathToExcelFile}";Extended Properties="Excel 12.0;HDR=Yes"`; conn.Open(); // create a Command to access the data diff --git a/types/activex-scripting/activex-scripting-tests.ts b/types/activex-scripting/activex-scripting-tests.ts index cc14a421ff..2297548b81 100644 --- a/types/activex-scripting/activex-scripting-tests.ts +++ b/types/activex-scripting/activex-scripting-tests.ts @@ -1,7 +1,7 @@ // source -- https://msdn.microsoft.com/en-us/library/ebkhfaaz.aspx // Generates a string describing the drive type of a given Drive object. -let showDriveType = (drive: Scripting.Drive) => { +function showDriveType(drive: Scripting.Drive) { switch (drive.DriveType) { case Scripting.DriveTypeConst.Removable: return 'Removeable'; @@ -16,15 +16,15 @@ let showDriveType = (drive: Scripting.Drive) => { default: return 'Unknown'; } -}; +} // Generates a string describing the attributes of a file or folder. -let showFileAttributes = (file: Scripting.File) => { - let attr = file.Attributes; +function showFileAttributes(file: Scripting.File) { + const attr = file.Attributes; if (attr === 0) { return 'Normal'; } - let attributeStrings: string[] = []; + const attributeStrings: string[] = []; if (attr & Scripting.FileAttribute.Directory) { attributeStrings.push('Directory'); } if (attr & Scripting.FileAttribute.ReadOnly) { attributeStrings.push('Read-only'); } if (attr & Scripting.FileAttribute.Hidden) { attributeStrings.push('Hidden'); } @@ -34,22 +34,22 @@ let showFileAttributes = (file: Scripting.File) => { if (attr & Scripting.FileAttribute.Alias) { attributeStrings.push('Alias'); } if (attr & Scripting.FileAttribute.Compressed) { attributeStrings.push('Compressed'); } return attributeStrings.join(','); -}; +} // source --https://msdn.microsoft.com/en-us/library/ts2t8ybh(v=vs.84).aspx -let showFreeSpace = (drvPath: string) => { - let fso = new ActiveXObject('Scripting.FileSystemObject'); - let d = fso.GetDrive(fso.GetDriveName(drvPath)); - let s = 'Drive ' + drvPath + ' - '; +function showFreeSpace(drvPath: string) { + const fso = new ActiveXObject('Scripting.FileSystemObject'); + const d = fso.GetDrive(fso.GetDriveName(drvPath)); + let s = `Drive ${drvPath} - `; s += d.VolumeName + '
      '; - s += 'Free Space: ' + d.FreeSpace / 1024 + ' Kbytes'; + s += `Free Space: ${d.FreeSpace / 1024} Kbytes`; return (s); -}; +} // source -- https://msdn.microsoft.com/en-us/library/kaf6yaft(v=vs.84).aspx -let getALine = (filespec: string) => { - let fso = new ActiveXObject('Scripting.FileSystemObject'); - let file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false); +function getALine(filespec: string) { + const fso = new ActiveXObject('Scripting.FileSystemObject'); + const file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false); let s = ''; while (!file.AtEndOfLine) { @@ -57,4 +57,4 @@ let getALine = (filespec: string) => { } file.Close(); return (s); -}; +} diff --git a/types/activex-wia/activex-wia-tests.ts b/types/activex-wia/activex-wia-tests.ts index 8384291f5d..d8046ef319 100644 --- a/types/activex-wia/activex-wia-tests.ts +++ b/types/activex-wia/activex-wia-tests.ts @@ -7,7 +7,7 @@ let img = commonDialog.ShowAcquireImage(); // when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these: let jpegFormatID = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}'; if (img.FormatID !== jpegFormatID) { - let ip = new ActiveXObject('WIA.ImageProcess'); + const ip = new ActiveXObject('WIA.ImageProcess'); ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID); ip.Filters.Item(1).Properties.Item('FormatID').Value = jpegFormatID; img = ip.Apply(img); @@ -24,8 +24,8 @@ if (img.FormatID !== jpegFormatID) { let dev = commonDialog.ShowSelectDevice(); if (dev.Type === WIA.WiaDeviceType.CameraDeviceType) { // when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these: - let commandID = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}'; - let itm = dev.ExecuteCommand(commandID); + const commandID = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}'; + const itm = dev.ExecuteCommand(commandID); // with this: // let itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture); @@ -36,15 +36,15 @@ dev = commonDialog.ShowSelectDevice(); let e = new Enumerator(dev.Properties); // no foreach over ActiveX collections e.moveFirst(); while (!e.atEnd()) { - let p = e.item(); - let s = p.Name + ' (' + p.PropertyID + ') = '; + const p = e.item(); + let s = `${p.Name} (${p.PropertyID}) = `; if (p.IsVector) { s += '[vector of data]'; } else { s += p.Value; if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType) { if (p.Value !== p.SubTypeDefault) { - s += ' (Default = ' + p.SubTypeDefault + ')'; + s += ` (Default = ${p.SubTypeDefault})`; } } } @@ -60,7 +60,7 @@ while (!e.atEnd()) { } else { s += ' [valid values include: '; } - let count = p.SubTypeValues.Count; + const count = p.SubTypeValues.Count; for (let i = 1; i <= count; i++) { s += p.SubTypeValues.Item(i); if (i < count) { @@ -70,7 +70,7 @@ while (!e.atEnd()) { s += ']'; break; case WIA.WiaSubType.RangeSubType: - s += ' [valid values in the range from ' + p.SubTypeMin + ' to ' + p.SubTypeMax + ' in increments of ' + p.SubTypeStep + ']'; + s += ` [valid values in the range from ${p.SubTypeMin} to ${p.SubTypeMax} in increments of ${p.SubTypeStep}]`; break; } } diff --git a/types/adal/index.d.ts b/types/adal/index.d.ts index 2150716b17..43655efbbb 100644 --- a/types/adal/index.d.ts +++ b/types/adal/index.d.ts @@ -31,6 +31,8 @@ declare namespace adal { resource?: string; extraQueryParameter?: string; navigateToLoginRequestUrl?: boolean; + logOutUri?: string; + isAngular?: boolean; } interface User { diff --git a/types/adone/adone-tests.ts b/types/adone/adone-tests.ts new file mode 100644 index 0000000000..861660ee89 --- /dev/null +++ b/types/adone/adone-tests.ts @@ -0,0 +1,3 @@ +// Actual tests inside ./test/ + +const a: string = adone.ok; diff --git a/types/adone/adone.d.ts b/types/adone/adone.d.ts new file mode 100644 index 0000000000..a4f102752c --- /dev/null +++ b/types/adone/adone.d.ts @@ -0,0 +1,85 @@ +/// + +declare const _null: symbol; +export { _null as null }; +export function noop(): void; +export function identity(x: T): T; +export function truly(): true; +export function falsely(): false; +export const ok: "OK"; +export const bad: "BAD"; +export const exts: [".js", ".tjs", ".ajs"]; +export function log(...args: any[]): void; +export function fatal(...args: any[]): void; +export function error(...args: any[]): void; +export function warn(...args: any[]): void; +export function info(...args: any[]): void; +export function debug(...args: any[]): void; +export function trace(...args: any[]): void; +export function o(...props: any[]): object; +export const Date: typeof global.Date; +export const hrtime: typeof global.process.hrtime; +export const setTimeout: typeof global.setTimeout; +export const setInterval: typeof global.setInterval; +export const setImmediate: typeof global.setImmediate; +export const clearTimeout: typeof global.clearTimeout; +export const clearInterval: typeof global.clearInterval; +export const clearImmediate: typeof global.clearImmediate; +interface LazifyOptions { + configurable: boolean; +} +export function lazify(modules: object, obj?: object, require?: (path: string) => any, options?: LazifyOptions): object; +interface Tag { + set(Class: object, tag: string): void; + has(obj: object, tag: string): boolean; + define(tag: string, predicate?: string): void; + SUBSYSTEM: symbol; + APPLICATION: symbol; + TRANSFORM: symbol; + CORE_STREAM: symbol; + LOGGER: symbol; + LONG: symbol; + BIGNUMBER: symbol; + EXBUFFER: symbol; + EXDATE: symbol; + CONFIGURATION: symbol; + GENESIS_NETRON: symbol; + GENESIS_PEER: symbol; + NETRON: symbol; + NETRON_PEER: symbol; + NETRON_ADAPTER: symbol; + NETRON_DEFINITION: symbol; + NETRON_DEFINITIONS: symbol; + NETRON_REFERENCE: symbol; + NETRON_INTERFACE: symbol; + NETRON_STUB: symbol; + NETRON_REMOTESTUB: symbol; + NETRON_STREAM: symbol; + FAST_STREAM: symbol; + FAST_FS_STREAM: symbol; + FAST_FS_MAP_STREAM: symbol; +} +export const tag: Tag; +export function run(App: object, ignoreArgs?: boolean): Promise; +export function bind(libName: string): object; +export function getAssetAbsolutePath(relPath: string): string; +export function loadAsset(relPath: string): string | Buffer; +export function require(path: string): object; +export const package: object; + +import * as std from "./glosses/std"; +export { std }; + +export * from "./glosses/common"; +export * from "./glosses/math"; +export * from "./glosses/utils"; +export * from "./glosses/assertion"; +export * from "./glosses/promise"; +export * from "./glosses/shani"; + +import "./glosses/shani-global"; + +export const assert: adone.assertion.I.AssertFunction; +export const expect: adone.assertion.I.ExpectFunction; + +export as namespace adone; diff --git a/types/adone/glosses/assertion.d.ts b/types/adone/glosses/assertion.d.ts new file mode 100644 index 0000000000..4e8bfc593a --- /dev/null +++ b/types/adone/glosses/assertion.d.ts @@ -0,0 +1,1074 @@ +import adone from "adone"; + +/** + * assertion functions + */ +export namespace assertion { + namespace I { + interface assertion { + AssertionError: AssertionError; + config: Config; + use: UseFunction; + loadMockInterface: LoadInterfaceFunction; + loadExpectInterface: LoadInterfaceFunction; + loadAssertInterface: LoadInterfaceFunction; + assert: AssertFunction; + expect: ExpectFunction; + } + + interface Config { + /** + * Include stack in Assertion error message + */ + includeStack: boolean; + /** + * Include `showDiff` flag in the thrown errors + */ + showDiff: boolean; + /** + * Length threshold for actual and expected values in assertion errors + */ + truncateThreshold: number; + /** + * use Proxy to throw an error when a non-existent property is read + */ + useProxy: boolean; + /** + * properties that should be ignored instead of throwing an error if they do not exist on the assertion + */ + proxyExcludedKeys: string[]; + } + + type PossibleTypes = adone.util.I.PossibleTypes | "array"; + + type UseFunction = (fn: () => void) => assertion; + + type LoadInterfaceFunction = () => assertion; + + interface AssertFunction { + /** + * Asserts that value is truthy + */ + (value: any, message?: string): void; + /** + * Throws an AssertionError, like node.js + */ + fail(actual?: any, expected?: any, message?: string, operator?: any): void; + /** + * Asserts that value is truthy + */ + isOk(value: any, message?: string): void; + /** + * Asserts that value is truthy + */ + ok(value: any, message?: string): void; + /** + * Asserts that value is falsy + */ + isNotOk(value: any, message?: string): void; + /** + * Asserts that value is falsy + */ + notOk(value: any, message?: string): void; + /** + * Asserts non-strict equality + */ + equal(actual: any, expected: any, message?: string): void; + /** + * Asserts non-strict inequality + */ + notEqual(actual: any, expected: any, message?: string): void; + /** + * Asserts strict equality + */ + strictEqual(actual: any, expected: any, message?: string): void; + /** + * Asserts strict inequality + */ + notStrictEqual(actual: any, expected: any, message?: string): void; + /** + * Asserts that actual is deeply equal to expected + */ + deepEqual(actual: any, expected: any, message?: string): void; + /** + * Asserts that actual is deeply equal to expected + */ + deepStrictEqual(actual: any, expected: any, message?: string): void; + /** + * Asserts that actual and expected have the same length and the same members (===) + */ + equalArrays(actual: any[], expected: any[], message?: string): void; + /** + * Asserts that actual is not deeply equal to expected + */ + notDeepEqual(actual: any, expected: any, message?: string): void; + /** + * Asserts that value > above + */ + isAbove(value: any, above: any, message?: string): void; + /** + * Asserts that value >= atLeast + */ + isAtLeast(value: any, atLeast: any, message?: string): void; + /** + * Asserts that value < below + */ + isBelow(value: any, below: any, message?: string): void; + /** + * Asserts that value <= atMost + */ + isAtMost(value: any, atMost: any, message?: string): void; + /** + * Asserts that value is true + */ + isTrue(value: any, message?: string): void; + /** + * Asserts that value is not true + */ + isNotTrue(value: any, message?: string): void; + /** + * Asserts that value is false + */ + isFalse(value: any, message?: string): void; + /** + * Asserts that value is not false + */ + isNotFalse(value: any, message?: string): void; + /** + * Asserts that value is null + */ + isNull(value: any, message?: string): void; + /** + * Asserts that valus is not null + */ + isNotNull(value: any, message?: string): void; + /** + * Asserts that value is NaN + */ + isNaN(value: any, message?: string): void; + /** + * Asserts that value is not NaN + */ + isNotNaN(value: any, message?: string): void; + /** + * Asserts that value is neither null nor undefined + */ + exists(value: any, message?: string): void; + /** + * Asserts that value is either null or undefined + */ + notExists(value: any, message?: string): void; + /** + * Asserts that value is undefined + */ + isUndefined(value: any, message?: string): void; + /** + * Asserts that value is not undefined + */ + isDefined(value: any, message?: string): void; + /** + * Asserts that value is a function + */ + isFunction(value: any, message?: string): void; + /** + * Asserts that value is not a function + */ + isNotFunction(value: any, message?: string): void; + /** + * Asserts that value is an object of type Object + */ + isObject(value: any, message?: string): void; + /** + * Asserts that value is not an object of type Object + */ + isNotObject(value: any, message?: string): void; + /** + * Asserts that value is an array + */ + isArray(value: any, message?: string): void; + /** + * Asserts that value is not an array + */ + isNotArray(value: any, message?: string): void; + /** + * Asserts that value is a string + */ + isString(value: any, message?: string): void; + /** + * Asserts that value is not a string + */ + isNotString(value: any, message?: string): void; + /** + * Asserts that value is a number + */ + isNumber(value: any, message?: string): void; + /** + * Asserts that value is not a number + */ + isNotNumber(value: any, message?: string): void; + /** + * Asserts that value is a finite number + */ + isFinite(value: any, message?: string): void; + /** + * Asserts that value is a boolean + */ + isBoolean(value: any, message?: string): void; + /** + * Asserts that value is not a boolean + */ + isNotBoolean(value: any, message?: string): void; + /** + * Asserts that value's type is `type` + */ + typeOf(value: any, type: I.PossibleTypes, message?: string): void; + typeOf(value: any, type: string, message?: string): void; + /** + * Assert that value's type is not `type` + */ + notTypeOf(value: any, type: I.PossibleTypes, message?: string): void; + notTypeOf(value: any, type: string, message?: string): void; + /** + * Asserts that value is an instance of constructor + */ + instanceOf(value: any, constructor: object, message?: string): void; + /** + * Asserts that value is not an instance of constructor + */ + notInstanceOf(value: any, constructor: object, message?: string): void; + /** + * Asserts that expected includes inc + */ + include(expected: T[], inc: T, message?: string): void; + include(expected: string, inc: string, message?: string): void; + /** + * Asserts that expected does not include inc + */ + notInclude(expected: T[], inc: T, message?: string): void; + notInclude(expected: string, inc: string, message?: string): void; + /** + * Asserts that expected includes inc + */ + deepInclude(expected: T[], inc: T, message?: string): void; + deepInclude(expected: string, inc: string, message?: string): void; + /** + * Asserts that expected does not include inc + */ + notDeepInclude(expected: T[], inc: T, message?: string): void; + notDeepInclude(expected: string, inc: string, message?: string): void; + /** + * Asserts that expected includes inc + */ + nestedInclude(expected: object, inc: object, message?: string): void; + /** + * Asserts that expected does not include inc + */ + notNestedInclude(expected: object, inc: object, message?: string): void; + /** + * Assert that expected includes inc + */ + deepNestedInclude(expected: object, inc: object, message?: string): void; + /** + * Assert that expected includes inc + */ + notDeepNestedInclude(expected: object, inc: object, message?: string): void; + /** + * Assert that expected includes inc + */ + ownInclude(expected: object, inc: object, message?: string): void; + /** + * Assert that expected does not include inc + */ + notOwnInclude(expected: object, inc: object, message?: string): void; + /** + * Assert that expected includes inc + */ + deepOwnInclude(expected: object, inc: object, message?: string): void; + /** + * Assert that expected does not include inc + */ + notDeepOwnInclude(expected: object, inc: object, message?: string): void; + /** + * Asserts that expected matches the regular expression regExp + */ + match(expected: any, regExp: RegExp, message?: string): void; + /** + * Asserts that expected does not match the regular expression regExp + */ + notMatch(expected: any, regExp: RegExp, message?: string): void; + /** + * Asserts that object has a property named `property` + */ + property(object: object, property: string, message?: string): void; + /** + * Asserts that object does not have a property named `property` + */ + notProperty(object: object, property: string, message?: string): void; + /** + * Asserts that object has a property named `property` with value `value` (===) + */ + propertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object does not have a property named `property` with value `value` (===) + */ + notPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object has a property named `property` with a value `value` + */ + deepPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object does not have a property named `property` with value `value` + */ + notDeepPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object has an owned property named `property` + */ + ownProperty(object: object, property: string, message?: string): void; + /** + * Asserts that object does not have an owned property named `property` + */ + notOwnProperty(object: object, property: string, message?: string): void; + /** + * Asserts that object has an owned property named `property` with value `value`(===) + */ + ownPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object does not have an owned property named `property` with value `value`(===) + */ + notOwnPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object has an owned property named `property` with value `value` + */ + deepOwnPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object does not have an owned property named `property` with value `value`(===) + */ + notDeepOwnPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object has a property named `property` + */ + nestedProperty(object: object, property: string, message?: string): void; + /** + * Asserts that object does not have a property named `property` + */ + notNestedProperty(object: object, property: string, message?: string): void; + /** + * Asserts that object has a property named `property` with value `value`(===) + */ + nestedPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object does not have a property named `property` with value `value`(===) + */ + notNestedPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object has a property named `property` with value `value` + */ + deepNestedPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object does not have a property named `property` with value `value` + */ + notDeepNestedPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that expected has a length property with value `length` + */ + lengthOf(expected: any, length: number, message?: string): void; + /** + * Asserts that object has at least one key from `keys` + */ + hasAnyKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object has all and only all of the keys provided + */ + hasAllKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object has all the keys provided but maybe more + */ + containsAllKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object does not have any provided key + */ + doesNotHaveAnyKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object does not have all the keys provided + */ + doesNotHaveAllKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object has at least one of the keys provided + */ + hasAnyDeepKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object has all and only all of the keys provided + */ + hasAllDeepKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object has all the keys provided but maybe more + */ + containsAllDeepKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object does not have any provided key + */ + doesNotHaveAnyDeepKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object does not have all the keys provided + */ + doesNotHaveAllDeepKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that a function or an async functions throws an error + */ + throws(fn: () => void, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): any; + throws(fn: () => Promise, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): Promise; + /** + * Asserts that a function or an async functions throws an error + */ + throw(fn: () => void, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): any; + throw(fn: () => Promise, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): Promise; + /** + * Asserts that a function or an async function does not throw an error + */ + doesNotThrow(fn: () => Promise, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): Promise; + doesNotThrow(fn: () => void, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): any; + /** + * Compares two values using operator + */ + operator(value: any, operator: string, val2: any, message?: string): void; + /** + * Asserts that actual is expected +/- delta + */ + closeTo(actual: number, expected: number, delta: number, message?: string): void; + /** + * Asserts that actual is expect +/- delta + */ + approximately(actual: number, expected: number, delta: number, message?: string): void; + /** + * Asserts that arrays have the same members in any order (===) + */ + sameMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays do not have the same members in any order (===) + */ + notSameMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays have the same members in any order + */ + sameDeepMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays do not have the same members in any order + */ + notSameDeepMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays have the same members in the same order (===) + */ + sameOrderedMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays do not have the same members in the same order (===) + */ + notSameOrderedMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays have the same members in the same order + */ + sameDeepOrderedMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays do not have the same members in the same order + */ + notSameDeepOrderedMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that subset is included in superset in any order (===) + */ + includeMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is not included in superset in any order (===) + */ + notIncludeMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is included in superset in any order + */ + includeDeepMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is not included in superset in any order + */ + notIncludeDeepMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is included in superset in the same order (===) + */ + includeOrderedMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is not included in superset in the same order (===) + */ + notIncludeOrderedMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is included in superset in the same order + */ + includeDeepOrderedMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is not included in superset in the same order + */ + notIncludeDeepOrderedMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that list includes inList + */ + oneOf(inList: any, list: any[], message?: string): void; + /** + * Asserts that a function changes the value of a property + */ + changes(fn: () => void, object: object, property: string, message?: string): void; + /** + * Asserts that a function changes the value of a property by delta + */ + changesBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Asserts that a function does not changes the value of a property + */ + doesNotChange(fn: () => void, object: object, property: string, message?: string): void; + /** + * Asserts that a function does not change the value of a property or of a function’s return value by delta + */ + changesButNotBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Asserts that a function increases a numeric object property + */ + increases(fn: () => void, object: object, property: string, message?: string): void; + /** + * Asserts that a function increases a numeric object property or a function’s return value by delta + */ + increasesBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Asserts that a function does not increase a numeric object property + */ + doesNotIncrease(fn: () => void, object: object, property: string, message?: string): void; + /** + * Asserts that a function does not increase a numeric object property or function’s return value by delta + */ + increasesButNotBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Asserts that a function decreases the value of a property + */ + decreases(fn: () => void, object: object, property: string, message?: string): void; + /** + * Asserts that a function decreases the value of a property by delta + */ + decreasesBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Asserts that a function does not decrease the value of a property + */ + doesNotDecrease(fn: () => void, object: object, property: string, message?: string): void; + /** + * Asserts that a function does not decrease the value of a property or a function's return value by delta + */ + doesNotDecreaseBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Asserts that a function does not decreases a numeric object property or a function’s return value by delta + */ + decreasesButNotBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Throws an error if value is truthy + */ + ifError(value: any): void; + /** + * Asserts that object is extensible + */ + isExtensible(object: object, message?: string): void; + /** + * Asserts that object is extensible + */ + extensible(object: object, message?: string): void; + /** + * Asserts that object is not extensible + */ + isNotExtensible(object: object, message?: string): void; + /** + * Asserts that object is not extensible + */ + notExtensible(object: object, message?: string): void; + /** + * Asserts that object is sealed + */ + isSealed(object: object, message?: string): void; + /** + * Asserts that object is sealed + */ + sealed(object: object, message?: string): void; + /** + * Asserts that object is not sealed + */ + isNotSealed(object: object, message?: string): void; + /** + * Asserts that object is not sealed + */ + notSealed(object: object, message?: string): void; + /** + * Asserts that object is frozen + */ + isFrozen(object: object, message?: string): void; + /** + * Asserts that object is frozen + */ + frozen(object: object, message?: string): void; + /** + * Asserts that object is not frozen + */ + isNotFrozen(object: object, message?: string): void; + /** + * Asserts that object is not frozen + */ + notFrozen(object: object, message?: string): void; + /** + * Asserts that value is empty + */ + isEmpty(value: any, message?: string): void; + /** + * Asserts that value is empty + */ + empty(value: any, message?: string): void; + /** + * Asserts that value is not empty + */ + isNotEmpty(value: any, message?: string): void; + /** + * Asserts that value is not empty + */ + notEmpty(value: any, message?: string): void; + } + + interface ExpectFunction { + (value: adone.shani.util.I.Spy, message?: string): MockAssertions; + (value: any, message?: string): Assertion; + fail(actual: any, expected: any, message?: string, operator?: any): void; + } + + interface LanguageChains { + to: this; + be: this; + been: this; + is: this; + that: this; + which: this; + and: this; + has: this; + have: this; + with: this; + at: this; + of: this; + same: this; + but: this; + does: this; + } + + interface Assertion extends LanguageChains { + /** + * Negates all following assertion in the chain + */ + not: this; + /** + * Causes following assertions to use deep equality + */ + deep: this; + /** + * Enables dot- and bracket-notation in following property and include assertions + */ + nested: this; + /** + * Causes following property and incude assertions to ignore inherited properties + */ + own: this; + /** + * Causes following members assertions to require that members be in the same order + */ + ordered: this; + /** + * Causes following keys assertions to only require that the target have at least one of the given keys + */ + any: this; + /** + * Causes following keys assertions to require that the target have all of the given keys + */ + all: this; + /** + * Asserts that the target's type is `type` + */ + a(type: I.PossibleTypes, message?: string): this; + a(type: string, message?: string): this; + /** + * Asserts that the target's type is `type` + */ + an(type: I.PossibleTypes, message?: string): this; + an(type: string, message?: string): this; + /** + * Asserts that the target includes the given value + */ + include(value: any, message?: string): this; + /** + * Asserts that the target includes the given value + */ + includes(value: any, message?: string): this; + /** + * Asserts that the target contains the given value + */ + contain(value: any, message?: string): this; + /** + * Asserts that the target contains the given value + */ + contains(value: any, message?: string): this; + /** + * Asserts that the target is non-strictly equal to true + */ + ok: this; + /** + * Asserts that the target is true + */ + true: this; + /** + * Asserts that the target is false + */ + false: this; + /** + * Asserts that the target is null + */ + null: this; + /** + * Asserts that the target is undefined + */ + undefined: this; + /** + * Asserts that the target is NaN + */ + NaN: this; + /** + * Asserts that the target is neither null nor undefined + */ + exist: this; + /** + * Asserts that the target is empty + */ + empty: this; + /** + * Asserts that the target is an arguments object + */ + arguments: this; + /** + * Asserts that the target is an arguments object + */ + Arguments: this; + /** + * Asserts that the target is strictly equal to value(===) + */ + equal(value: any, message?: string): this; + /** + * Asserts that the target is strictly equal to value(===) + */ + equals(value: any, message?: string): this; + /** + * Asserts that the target is strictly equal to value(===) + */ + eq(value: any, message?: string): this; + /** + * Asserts that the target is deeply equal to object + */ + eql(object: any, message?: string): this; + /** + * Asserts that the target is deeply equal to object + */ + eqls(object: any, message?: string): this; + /** + * Asserts that the target has the same length length and elements as array in the same order + */ + eqlArray(array: any[], message?: string): this; + /** + * Asserts that target > n + */ + above(n: number, message?: string): this; + /** + * Asserts that target > n + */ + gt(n: number, message?: string): this; + /** + * Asserts that target > n + */ + greaterThan(n: number, message?: string): this; + /** + * Asserts that target >= n + */ + least(n: number, message?: string): this; + /** + * Asserts that target >= n + */ + gte(n: number, message?: string): this; + /** + * Asserts that target < n + */ + below(n: number, message?: string): this; + /** + * Asserts that target < n + */ + lt(n: number, message?: string): this; + /** + * Asserts that target < n + */ + lessThan(n: number, message?: string): this; + /** + * Asserts that target <= n + */ + most(n: number, message?: string): this; + /** + * Asserts that target <= n + */ + lte(n: number, message?: string): this; + /** + * Asserts that start <= target <= end + */ + within(start: number, end: number, message?: string): this; + /** + * Asserts that the target is an instance of constructor + */ + instanceof(constructor: object, message?: string): this; + /** + * Asserts that the target is an instance of constructor + */ + instanceOf(constructor: object, message?: string): this; + /** + * Asserts that the target has a property name `name` with value `value` + */ + property(name: string, value?: any, message?: string): this; + /** + * Asserts that the target has its own property name `name` with value `value` + */ + ownProperty(name: string, value?: any, message?: string): this; + /** + * Asserts that the target has its own property name `name` with value `value` + */ + haveOwnProperty(name: string, value?: any, message?: string): this; + /** + * Asserts that the target has its own property descriptor with name `name` and value `value` + */ + ownPropertyDescriptor(name: string, descriptor?: object, message?: string): this; + /** + * Asserts that the target has its own property descriptor with name `name` and value `value` + */ + haveOwnPropertyDescriptor(name: string, descriptor?: object, message?: string): this; + /** + * Asserts that the target's property length equal to n + */ + length(n: number, message?: string): this; + /** + * Asserts that the target's property length equal to n + */ + lengthOf(n: number, message?: string): this; + /** + * Asserts that the target matches the regular expression regExp + */ + match(regExp: RegExp, message?: string): this; + /** + * Asserts that the target matches the regular expression regExp + */ + matches(regExp: RegExp, message?: string): this; + /** + * Asserts that the target contains str as a substring + */ + string(str: string, message?: string): this; + /** + * Assert that the target has the given keys + */ + key(key: string | string[] | object): this; + key(...keys: string[]): this; + /** + * Assert that the target has the given keys + */ + keys(key: string | string[] | object): this; + keys(...keys: string[]): this; + /** + * Assert that the target throws an error + */ + throw(errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): this; + /** + * Assert that the target throws an error + */ + throws(errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): this; + /** + * Assert that the target throws an error + */ + Throw(errorLike?: Error, errMsgMatcher?: string | RegExp): this; + /** + * Assert that the target has a method with name `method`. For functions checks the prototype + */ + respondTo(method: string, message?: string): this; + /** + * Assert that the target has a method with name `method`. For functions checks the prototype + */ + respondsTo(method: string, message?: string): this; + /** + * Makes respondsTo behave like the target is not a function + */ + itself: this; + /** + * Asserts that matches returns a truthy value with the target as the first argument + */ + satisfy(matcher: () => boolean, message?: string): this; + /** + * Asserts that matches returns a truthy value with the target as the first argument + */ + satisfies(matcher: () => boolean, message?: string): this; + /** + * Asserts that the target is expected +/- delta + */ + closeTo(expected: number, delta: number, message?: string): this; + /** + * Asserts that the target is expected +/- delta + */ + approximately(expected: number, delta: number, message?: string): this; + /** + * Asserts that the target array has the same members as the given + */ + members(set: any[], message?: string): this; + /** + * Asserts that the target is the member of list + */ + oneOf(list: any[], message?: string): this; + /** + * Asserts that fn returns a different value after the target's invokation than before + */ + change(fn: () => any, message?: string): this; + /** + * Asserts that the target's invokation changes subject's property + */ + change(subject: object, property: string, message?: string): this; + /** + * Asserts that fn returns a different value after the target's invokation than before + */ + changes(fn: () => any, message?: string): this; + /** + * Asserts that the target's invokation changes subject's property + */ + changes(subject: object, property: string, message?: string): this; + /** + * Asserts that fn returns a greater number after the target's invokation than before + */ + increase(fn: () => number, message?: string): this; + /** + * Asserts that the target's invokation increases subject's property + */ + increase(subject: object, property?: string, message?: string): this; + /** + * Asserts that fn returns a greater number after the target's invokation than before + */ + increases(fn: () => number, message?: string): this; + /** + * Asserts that the target's invokation increases subject's property + */ + increases(subject: object, property?: string, message?: string): this; + /** + * Asserts that fn returns a lesser number after the target's invokation than before + */ + decrease(fn: () => number, message?: string): this; + /** + * Asserts that the target's invokation decreases subject's property + */ + decrease(subject: object, property?: string, message?: string): this; + /** + * Asserts that fn returns a lesser number after the target's invokation than before + */ + decreases(fn: () => number, message?: string): this; + /** + * Asserts that the target's invokation decreases subject's property + */ + decreases(subject: object, property?: string, message?: string): this; + /** + * Asserts that the value was decreased/increased by delta + */ + by(delta: number, message?: string): this; + /** + * Asserts that the target is extensible + */ + extensible: this; + /** + * Asserts that the target is sealed + */ + sealed: this; + /** + * Asserts that the target is frozen + */ + frozen: this; + /** + * Asserts that the target is a finite number + */ + finite: this; + } + + interface MockAssertions extends Assertion { + /** + * Asserts that the spy has been called + */ + called: this; + /** + * Asserts that the spy has been called n times + */ + callCount(n: number): this; + /** + * Asserts that the spy has been called once + */ + calledOnce: this; + /** + * Asserts that the spy has been called twice + */ + calledTwice: this; + /** + * Asserts that the spy has been been called with `new` + */ + calledThrice: this; + /** + * Asserts that the spy has been called before anotherSpy + */ + calledBefore(anotherSpy: adone.shani.util.I.Spy): this; + /** + * Asserts that the spy has been called after anotherSpy + */ + calledAfter(anotherSpy: adone.shani.util.I.Spy): this; + /** + * Asserts that the spy has been called immediately before anotherSpy + */ + calledImmediatelyBefore(anotherSpy: adone.shani.util.I.Spy): this; + /** + * Asserts that the spy has been called immediately after anotherSpy + */ + calledImmediatelyAfter(anotherSpy: adone.shani.util.I.Spy): this; + /** + * Asserts that the spy has been called with context as this value + */ + calledOn(context: object): this; + /** + * Asserts that the spy has been called with the given arguments + */ + calledWith(...args: any[]): this; + /** + * Asserts that the spy has been called exactly with the given arguments + */ + calledWithExactly(...args: any[]): this; + /** + * Asserts that the spy has been called with matching arguments + */ + calledWithMatch(...args: any[]): this; + /** + * Asserts that the spy returned value + */ + returned(value: any): this; + /** + * Asserts that the spy threw error + */ + thrown(error: any): this; + /** + * Asserts that the spy threw error + */ + threw(error: any): this; + } + } + + class AssertionError extends adone.x.Exception { + constructor(message?: string, props?: object, ssf?: object) + } + + const config: I.Config; + const use: I.UseFunction; + const loadMockInterface: I.LoadInterfaceFunction; + const loadExpectInterface: I.LoadInterfaceFunction; + const loadAssertInterface: I.LoadInterfaceFunction; + const assert: I.AssertFunction; + const expect: I.ExpectFunction; +} diff --git a/types/adone/glosses/common.d.ts b/types/adone/glosses/common.d.ts new file mode 100644 index 0000000000..57025ea054 --- /dev/null +++ b/types/adone/glosses/common.d.ts @@ -0,0 +1,465 @@ +/** + * predicates + */ +export namespace is { + function _null(obj: any): boolean; + export { _null as null }; + export function undefined(obj: any): boolean; + export function exist(obj: any): boolean; + export function nil(obj: any): boolean; + export function number(obj: any): boolean; + export function numeral(obj: any): boolean; + export function infinite(obj: any): boolean; + export function odd(obj: any): boolean; + export function even(obj: any): boolean; + export function float(obj: any): boolean; + export function negativeZero(obj: any): boolean; + export function string(obj: any): boolean; + export function emptyString(obj: any): boolean; + export function substring(substring: string, string: string, offset?: number): boolean; + export function prefix(prefix: string, string: string): boolean; + export function suffix(suffix: string, string: string): boolean; + export function boolean(obj: any): boolean; + export function json(obj: any): boolean; + export function object(obj: any): boolean; + export function plainObject(obj: any): boolean; + function _class(obj: any): boolean; + export { _class as class }; + export function emptyObject(obj: any): boolean; + export function propertyOwned(obj: any, field: string): boolean; + export function propertyDefined(obj: any, field: string): boolean; + export function conforms(obj: object, schema: object, strict?: boolean): boolean; + export function arrayLikeObject(obj: any): boolean; + export function inArray(value: T, array: any[], offset?: number, comparator?: (a: T, b: T) => boolean): boolean; + export function sameType(value: any, other: any): boolean; + export function primitive(obj: any): boolean; + export function equalArrays(left: any[], right: any[]): boolean; + export function deepEqual(left: any, right: any): boolean; + export function shallowEqual(left: any, right: any): boolean; + export function stream(obj: any): boolean; + export function writableStream(obj: any): boolean; + export function readableStream(obj: any): boolean; + export function duplexStream(obj: any): boolean; + export function transformStream(obj: any): boolean; + export function utf8(obj: Buffer): boolean; + export function win32PathAbsolute(path: string): boolean; + export function posixPathAbsolute(path: string): boolean; + export function pathAbsolute(path: string): boolean; + export function glob(str: string): boolean; + export function dotfile(str: string): boolean; + function _function(obj: any): boolean; + export { _function as function }; + export function asyncFunction(obj: any): boolean; + export function promise(obj: any): boolean; + export function validDate(str: string): boolean; + export function buffer(obj: any): boolean; + export function callback(obj: any): boolean; + export function generator(obj: any): boolean; + export function nan(obj: any): boolean; + export function finite(obj: any): boolean; + export function integer(obj: any): boolean; + export function safeInteger(obj: any): boolean; + export function array(obj: any): boolean; + export function uint8Array(obj: any): boolean; + export function configuration(obj: any): boolean; + export function long(obj: any): boolean; + export function bigNumber(obj: any): boolean; + export function exbuffer(obj: any): boolean; + export function exdate(obj: any): boolean; + export function transform(obj: any): boolean; + export function subsystem(obj: any): boolean; + export function application(obj: any): boolean; + export function logger(obj: any): boolean; + export function coreStream(obj: any): boolean; + export function fastStream(obj: any): boolean; + export function fastFSStream(obj: any): boolean; + export function fastFSMapStream(obj: any): boolean; + export function genesisNetron(obj: any): boolean; + export function genesisPeer(obj: any): boolean; + export function netronAdapter(obj: any): boolean; + export function netron(obj: any): boolean; + export function netronPeer(obj: any): boolean; + export function netronDefinition(obj: any): boolean; + export function netronDefinitions(obj: any): boolean; + export function netronReference(obj: any): boolean; + export function netronInterface(obj: any): boolean; + export function netronContext(obj: any): boolean; + export function netronIMethod(netronInterface: object, name: string): boolean; + export function netronIProperty(netronInterface: any, name: string): boolean; + export function netronStub(obj: any): boolean; + export function netronRemoteStub(obj: any): boolean; + export function netronStream(obj: any): boolean; + export function iterable(obj: any): boolean; + export const windows: boolean; + export const linux: boolean; + export const freebsd: boolean; + export const darwin: boolean; + export const sunos: boolean; + export function uppercase(str: string): boolean; + export function lowercase(str: string): boolean; + export function digits(str: string): boolean; + export function identifier(str: string): boolean; + export function binaryExtension(str: string): boolean; + export function binaryPath(str: string): boolean; + export function ip4(str: string): boolean; + export function ip6(str: string): boolean; + export function arrayBuffer(obj: any): boolean; + export function arrayBufferView(obj: any): boolean; + export function date(obj: any): boolean; + export function error(obj: any): boolean; + export function map(obj: any): boolean; + export function regexp(obj: any): boolean; + export function set(obj: any): boolean; + export function symbol(obj: any): boolean; + export function validUTF8(obj: any): boolean; +} + +export namespace x { + class Exception extends Error { + constructor(message?: string | Error, captureStackTrace?: boolean); + } + class Runtime extends Exception { } + class IncompleteBufferError extends Exception { } + class NotImplemented extends Exception { } + class IllegalState extends Exception { } + class NotValid extends Exception { } + class Unknown extends Exception { } + class NotExists extends Exception { } + class Exists extends Exception { } + class Empty extends Exception { } + class InvalidAccess extends Exception { } + class NotSupported extends Exception { } + class InvalidArgument extends Exception { } + class InvalidNumberOfArguments extends Exception { } + class NotFound extends Exception { } + class Timeout extends Exception { } + class Incorrect extends Exception { } + class NotAllowed extends Exception { } + class LimitExceeded extends Exception { } + class Encoding extends Exception { } + class Network extends Exception { } + class Bind extends Exception { } + class Connect extends Exception { } + class Database extends Exception { } + class DatabaseInitialization extends Exception { } + class DatabaseOpen extends Exception { } + class DatabaseRead extends Exception { } + class DatabaseWrite extends Exception { } + class NetronIllegalState extends Exception { } + class NetronPeerDisconnected extends Exception { } + class NetronTimeout extends Exception { } +} + +export class EventEmitter { + static listenerCount(emitter: EventEmitter, event: string | symbol): number; + static defaultMaxListeners: number; + + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Array<(...args: any[]) => any>; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): Array; + listenerCount(type: string | symbol): number; +} + +export class AsyncEmitter extends EventEmitter { + constructor(concurrency?: number); + + setConcurrency(max?: number): this; + + emitParallel(event: string, ...args: any[]): Promise; + + emitSerial(event: string, ...args: any[]): Promise; + + emitReduce(event: string, ...args: any[]): Promise; + + emitReduceRight(event: string, ...args: any[]): Promise; + + subscribe(event: string, listener: (...args: any[]) => void, once?: boolean): () => void; +} + +declare namespace I { + type Long = adone.math.Long; + + type Longable = adone.math.I.Longable; + + namespace ExBuffer { + interface Varint32 { + value: number; + length: number; + } + + interface Varint64 { + value: Long; + length: number; + } + + interface String { + string: string; + length: number; + } + + type Wrappable = string | ExBuffer | Buffer | Uint8Array | ArrayBuffer; + + type METRICS = "b" | "c"; + } +} + +export class ExBuffer { + constructor(capacity?: number, noAssert?: boolean); + + readBitSet(offset?: number): number[]; + + read(length: number, offset?: number): ExBuffer; + + readInt8(offset?: number): number; + + readUInt8(offset?: number): number; + + readInt16LE(offset?: number): number; + + readUInt16LE(offset?: number): number; + + readInt16BE(offset?: number): number; + + readUInt16BE(offset?: number): number; + + readInt32LE(offset?: number): number; + + readUInt32LE(offset?: number): number; + + readInt32BE(offset?: number): number; + + readUInt32BE(offset?: number): number; + + readInt64LE(offset?: number): adone.math.Long; + + readUInt64LE(offset?: number): adone.math.Long; + + readInt64BE(offset?: number): adone.math.Long; + + readUInt64BE(offset?: number): adone.math.Long; + + readFloatLE(offset?: number): number; + + readFloatBE(offset?: number): number; + + readDoubleLE(offset?: number): number; + + readDoubleBE(offset?: number): number; + + write(source: I.ExBuffer.Wrappable, offset?: number, length?: number, encoding?: string): this; + + writeBitSet(value: number[]): this; + + writeBitSet(value: number[], offset: number): number; + + writeInt8(value: number, offset?: number): this; + + writeUInt8(value: number, offset?: number): this; + + writeInt16LE(value: number, offset?: number): this; + + writeInt16BE(value: number, offset?: number): this; + + writeUInt16LE(value: number, offset?: number): this; + + writeUInt16BE(value: number, offset?: number): this; + + writeInt32LE(value: number, offset?: number): this; + + writeInt32BE(value: number, offset?: number): this; + + writeUInt32LE(value: number, offset?: number): this; + + writeUInt32BE(value: number, offset?: number): this; + + writeInt64LE(value: I.Longable, offset?: number): this; + + writeInt64BE(value: I.Longable, offset?: number): this; + + writeUInt64LE(value: I.Longable, offset?: number): this; + + writeUInt64BE(value: I.Longable, offset?: number): this; + + writeFloatLE(value: number, offset?: number): this; + + writeFloatBE(value: number, offset?: number): this; + + writeDoubleLE(value: number, offset?: number): this; + + writeDoubleBE(value: number, offset?: number): this; + + writeVarint32(value: number): this; + + writeVarint32(value: number, offset: number): number; + + writeVarint32ZigZag(value: number): this; + + writeVarint32ZigZag(value: number, offset: number): number; + + readVarint32(): number; + + readVarint32(offset: number): I.ExBuffer.Varint32; + + readVarint32ZigZag(): number; + + readVarint32ZigZag(offset: number): I.ExBuffer.Varint32; + + writeVarint64(value: I.Longable): this; + + writeVarint64(value: I.Longable, offset: number): number; + + writeVarint64ZigZag(value: I.Longable): this; + + writeVarint64ZigZag(value: I.Longable, offset: number): number; + + readVarint64(): I.Long; + + readVarint64(offset: number): I.ExBuffer.Varint64; + + readVarint64ZigZag(): adone.math.Long; + + readVarint64ZigZag(offset: number): I.ExBuffer.Varint64; + + writeCString(str: string): this; + + writeCString(str: string, offset: number): number; + + readCString(): string; + + readCString(offset: number): I.ExBuffer.String; + + writeString(str: string): this; + + writeString(str: string, offset: number): number; + + readString(length: number, metrics?: I.ExBuffer.METRICS): string; + + readString(length: number, metrics: I.ExBuffer.METRICS, offset: number): I.ExBuffer.String; + + readString(length: number, offset: number): I.ExBuffer.String; + + writeVString(str: string): this; + + writeVString(str: string, offset: number): number; + + readVString(): string; + + readVString(offset: number): I.ExBuffer.String; + + appendTo(target: ExBuffer, offset?: number): this; + + assert(assert?: boolean): this; + + capacity(): number; + + clear(): this; + + compact(begin?: number, end?: number): this; + + copy(begin?: number, end?: number): ExBuffer; + + copyTo(target: ExBuffer, targetOffset?: number, souceOffset?: number, sourceLimit?: number): this | ExBuffer; + + ensureCapacity(capacity: number): this; + + fill(value: string | number, begin?: number, end?: number): this; + + flip(): this; + + mark(offset?: number): this; + + prepend(source: I.ExBuffer.Wrappable, encoding?: string, offset?: number): this; + + prepend(source: I.ExBuffer.Wrappable, offset: number): this; + + prependTo(target: ExBuffer, offset?: number): this; + + remaining(): number; + + reset(): this; + + resize(capacity: number): this; + + reverse(begin?: number, end?: number): this; + + skip(length: number): this; + + slice(begin?: number, end?: number): ExBuffer; + + toBuffer(forceCopy?: boolean, begin?: number, end?: number): Buffer; + + toArrayBuffer(): ArrayBuffer; + + toString(encoding?: string, begin?: number, end?: number): string; + + toBase64(begin?: number, end?: number): string; + + toBinary(begin?: number, end?: number): string; + + toDebug(columns?: boolean): string; + + toHex(begin?: number, end?: number): string; + + toUTF8(begin?: number, end?: number): string; + + static accessor(): typeof Buffer; + + static allocate(capacity?: number, noAssert?: boolean): ExBuffer; + + static concat(buffers: I.ExBuffer.Wrappable[], encoding?: string, noAssert?: boolean): ExBuffer; + + static type(): typeof Buffer; + + static wrap(buffer: I.ExBuffer.Wrappable, encoding?: string, noAssert?: boolean): ExBuffer; + + static calculateVarint32(value: number): number; + + static zigZagEncode32(n: number): number; + + static zigZagDecode32(n: number): number; + + static calculateVarint64(value: number | string): number; + + static zigZagEncode64(value: number | string | I.Long): I.Long; + + static zigZagDecode64(value: number | string | I.Long): I.Long; + + static calculateUTF8Chars(str: string): number; + + static calculateString(str: string): number; + + static fromBase64(str: string): ExBuffer; + + static btoa(str: string): string; + + static atob(b64: string): string; + + static fromBinary(str: string): ExBuffer; + + static fromDebug(str: string, noAssert?: boolean): ExBuffer; + + static fromHex(str: string, noAssert?: boolean): ExBuffer; + + static fromUTF8(str: string, noAssert?: boolean): ExBuffer; + + static DEFAULT_CAPACITY: number; + + static DEFAULT_NOASSERT: boolean; + + static MAX_VARINT32_BYTES: number; + + static MAX_VARINT64_BYTES: number; + + static METRICS_CHARS: string; + + static METRICS_BYTES: string; +} diff --git a/types/adone/glosses/math.d.ts b/types/adone/glosses/math.d.ts new file mode 100644 index 0000000000..076bdd105f --- /dev/null +++ b/types/adone/glosses/math.d.ts @@ -0,0 +1,118 @@ +/** + * math related things + */ +export namespace math { + namespace I { + interface LowHighBits { + low: number; + high: number; + } + type Longable = math.Long | number | string | LowHighBits; + } + + export class Long { + constructor(low?: number, high?: number, unsigned?: boolean); + + toInt(): number; + + toNumber(): number; + + toString(radix?: number): string; + + getHighBits(): number; + + getHighBitsUnsigned(): number; + + getLowBits(): number; + + getLowBitsUnsigned(): number; + + getNumBitsAbs(): number; + + isZero(): boolean; + + isNegative(): boolean; + + isPositive(): boolean; + + isOdd(): boolean; + + isEven(): boolean; + + equals(other: I.Longable): boolean; + + lessThan(other: I.Longable): boolean; + + lessThanOrEqual(other: I.Longable): boolean; + + greaterThan(other: I.Longable): boolean; + + greaterThanOrEqual(other: I.Longable): boolean; + + compare(other: I.Longable): number; + + negate(): Long; + + add(addend: I.Longable): Long; + + sub(subtrahend: I.Longable): Long; + + mul(multiplier: I.Longable): Long; + + div(divisor: I.Longable): Long; + + mod(divisor: I.Longable): Long; + + not(): Long; + + and(other: I.Longable): Long; + + or(other: I.Longable): Long; + + xor(other: I.Longable): Long; + + shl(numBits: number | Long): Long; + + shr(numBits: number | Long): Long; + + shru(numBits: number | Long): Long; + + toSigned(): Long; + + toUnsigned(): Long; + + toBytes(le?: boolean): number[]; + + toBytesLE(): number[]; + + toBytesBE(): number[]; + + static fromInt(value: number, unsigned?: boolean): Long; + + static fromNumber(value?: number, unsigned?: boolean): Long; + + static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long; + + static fromString(str: string, unsigned?: boolean, radix?: number): Long; + + static fromString(str: string, radix?: number): Long; + + static fromValue(val: I.Longable): Long; + + static MIN_VALUE: Long; + + static MAX_VALUE: Long; + + static MAX_UNSIGNED_VALUE: Long; + + static ZERO: Long; + + static UZERO: Long; + + static ONE: Long; + + static UONE: Long; + + static NEG_ONE: Long; + } +} diff --git a/types/adone/glosses/promise.d.ts b/types/adone/glosses/promise.d.ts new file mode 100644 index 0000000000..a5267c69a3 --- /dev/null +++ b/types/adone/glosses/promise.d.ts @@ -0,0 +1,114 @@ +/** + * promise helpers + */ +export namespace promise { + namespace I { + interface Deferred { + /** + * Resolves the promise + */ + resolve(value?: T): void; + + /** + * Rejects the promise + */ + reject(value?: any): void; + + promise: Promise; + } + } + + /** + * Creates a promise and returns an interface to control the state + */ + export function defer(): I.Deferred; + + /** + * Creates a promise that will be resolved after given milliseconds + * + * @param ms delay in milliseconds + * @param value resolving value + */ + export function delay(ms: number, value?: T): Promise; + + /** + * Creates a promise that will be rejected after given milliseconds if the given promise is not fulfilled + * + * @param ms timeout in milliseconds + */ + export function timeout(promise: Promise, ms: number): Promise; + + /** + * Converts a promise to node.js style callback + */ + export function nodeify(promise: Promise, callback: (err?: any, value?: T) => void): Promise; + + namespace I { + interface PromisifyOptions { + /** + * Context to bind to new function + */ + context?: object; + } + } + + /** + * Converts a callback function to a promise-based function + */ + export function promisify(fn: (callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): () => Promise; + export function promisify(fn: (a: T, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T) => Promise; + export function promisify(fn: (a: T, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T) => Promise; + export function promisify(fn: (a: T1, b: T2, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2) => Promise; + export function promisify(fn: (a: T1, b: T2, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2) => Promise; + export function promisify(fn: (a: T1, b: T2, c: T3, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2, c: T3) => Promise; + export function promisify(fn: (a: T1, b: T2, c: T3, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2, c: T3) => Promise; + export function promisify( + fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any, result?: R) => void) => void, + options?: I.PromisifyOptions + ): (a: T1, b: T2, c: T3, d: T4) => Promise; + export function promisify( + fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any) => void) => void, + options?: I.PromisifyOptions + ): (a: T1, b: T2, c: T3, d: T4) => Promise; + export function promisify( + fn: (a: T1, b: T2, c: T3, d: T4, e: T5, callback: (err?: any, result?: R) => void) => void, + options?: I.PromisifyOptions + ): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise; + export function promisify( + fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any) => void) => void, + options?: I.PromisifyOptions + ): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise; + export function promisify(fn: (...args: any[]) => void, options?: I.PromisifyOptions): (...args: any[]) => Promise; + + namespace I { + interface PromisifyAllOptions { + /** + * Suffix to use for keys + */ + suffix?: string; + + /** + * Function to filter keys + */ + + filter?(key: string): boolean; + /** + * Context to bind to new functions + */ + context?: object; + } + } + + /** + * Promisifies entire object + */ + export function promisifyAll(source: object, options?: I.PromisifyAllOptions): object; + + /** + * Executes a function after promise fulfillment + * + * @returns the original promise + */ + function _finally(promise: Promise, onFinally?: (...args: any[]) => void): Promise; + export { _finally as finally }; +} diff --git a/types/adone/glosses/shani-global.d.ts b/types/adone/glosses/shani-global.d.ts new file mode 100644 index 0000000000..8cb7bf1827 --- /dev/null +++ b/types/adone/glosses/shani-global.d.ts @@ -0,0 +1,79 @@ +/** + * Defines a tests block + */ +declare const describe: adone.shani.I.DescribeFunction; + +/** + * Defines a tests block + */ +declare const context: adone.shani.I.DescribeFunction; + +/** + * Defines a test + */ +declare const it: adone.shani.I.TestFunction; + +/** + * Defines a test + */ +declare const specify: adone.shani.I.TestFunction; + +/** + * Defines a hook that will be called only once before the block's tests + */ +declare const before: adone.shani.I.HookFunction; + +/** + * Defines a hook that will be called only once after the block's tests + */ +declare const after: adone.shani.I.HookFunction; + +/** + * Defines a hook that will be called before each test + */ +declare const beforeEach: adone.shani.I.HookFunction; + +/** + * Defines a hook that will be called after each test + */ +declare const afterEach: adone.shani.I.HookFunction; + +/** + * assertion functions + */ +declare const assert: adone.assertion.I.AssertFunction; + +/** + * bdd-style assertion functons + */ +declare const expect: adone.assertion.I.ExpectFunction; + +/** + * tools for installing controllable timer functions + */ +declare const fakeClock: adone.util.I.fakeClock.FakeClock; + +/** + * defines a spy function + */ +declare const spy: typeof adone.shani.util.spy; + +/** + * defines a stub function + */ +declare const stub: typeof adone.shani.util.stub; + +/** + * defines a mock function + */ +declare const mock: typeof adone.shani.util.mock; + +/** + * defines a matcher for spies/stubs/mocks + */ +declare const match: typeof adone.shani.util.match; + +/** + * assertion tool for http server responses + */ +declare const request: typeof adone.shani.util.request; diff --git a/types/adone/glosses/shani.d.ts b/types/adone/glosses/shani.d.ts new file mode 100644 index 0000000000..788267c693 --- /dev/null +++ b/types/adone/glosses/shani.d.ts @@ -0,0 +1,1655 @@ +/** + * testing framework + */ +export namespace shani { + namespace I { + interface EngineOptions { + /** + * Default timeout for tests and block + */ + defaultTimeout?: number; + + /** + * Default timeout for hooks + */ + defaultHookTimeout?: number; + + /** + * Options that transplirer uses when loads tests from files + */ + transpilerOptions?: object; // TODO: possible options to adone.js.compiler + + /** + * Forca calling gc function after each processed file + */ + callGc?: boolean; + } + + interface DescribeOptions { + /** + * Specify that this block must be skipped + */ + skip?: boolean | (() => void); + + /** + * Specify the timeout for this block + */ + timeout?: number | (() => void); + } + + interface DescribeRuntimeContext { + /** + * Skip this block + */ + skip(): void; + + /** + * Specify timeout for this block + */ + timeout(ms: number): void; + + [key: string]: any; + } + + type DescribeCallback = (this: DescribeRuntimeContext) => void; + + interface DescribeFunction { + (description: string, callback: DescribeCallback): void; + (description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, description: string, callback: DescribeCallback): void; + (a: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, i: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, i: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, i: string, j: string, description: string, callback: DescribeCallback): void; + ( + a: string, b: string, c: string, + d: string, e: string, f: string, + g: string, h: string, i: string, + j: string, description: string, options: DescribeOptions, + callback: DescribeCallback + ): void; + (a: string, ...args: Array): void; + + /** + * Mark this block as inclusive + */ + only: DescribeFunction; + + /** + * Mark this block as exclusive + */ + skip: DescribeFunction; + } + + interface TestOptions { + /** + * Specify that this test must be skipped + */ + skip?: boolean | (() => void); + + /** + * Specify timeout for this test + */ + timeout?: number | (() => void); + + /** + * Add before hook for this test + */ + before?: HookCallback | [string, HookCallback]; + + /** + * Add after hook for this test + */ + after?: HookCallback | [string, HookCallback]; + } + + interface TestRuntimeContext { + /** + * Skip this test + */ + skip(): void; + + /** + * Specify timeout for this test + */ + timeout(ms: number): void; + + [key: string]: any; + } + + type TestCallback = (this: TestRuntimeContext, done: (err?: any) => void) => void; + + interface TestFunction { + (description: string, callback: TestCallback): void; + (description: string, options: TestOptions, callback: TestCallback): void; + /** + * Mark this test as inclusive + */ + only: TestFunction; + + /** + * Mark this test as exclusive + */ + skip: TestFunction; + } + + interface HookRuntimeContext { + /** + * Specify timeout for this hook + */ + timeout(ms: number): void; + + [key: string]: any; + } + + type HookCallback = (this: HookRuntimeContext, done: (err?: any) => void) => void; + + interface HookFunction { + (callback: HookCallback): void; + (description: string, callback: HookCallback): void; + } + + type StartHookEvent = "start before hook" | "start after hook" + | "start before each hook" | "start after each hook" + | "start before test hook" | "start after test hook"; + + type EndHookEvent = "end before hook" | "end after hook" + | "end before each hook" | "end after each hook" + | "end before test hook" | "end after test hook"; + + interface Emitter extends adone.EventEmitter { + on(event: "enter block", listener: (event: { block: Block }) => void): this; + on(event: "exit block", listener: (event: { block: Block }) => void): this; + on(event: "start test", listener: (event: { block: Block, test: Test }) => void): this; + on(event: "end test", listener: (event: { block: Block, test: Test, meta: ExecutionResult }) => void): this; + on(event: "skip test", listener: (event: { block: Block, test: Test, runtime: boolean }) => void): this; + on(event: StartHookEvent, listener: (event: { block: Block, test: Test, hook: Hook }) => void): this; + on(event: EndHookEvent, listener: (event: { block: Block, test: Test, hook: Hook, meta: ExecutionResult }) => void): this; + on(event: "error", listener: (err: any) => void): this; + on(event: "done", listener: () => void): this; + + /** + * Stops testing + */ + stop(): void; + } + + interface ExecutionResult { + /** + * Resulting error + */ + err: any; + + /** + * Elapsed time in milliseconds + */ + elapsed: number; + } + + class Hook { + desctiption: string; + + constructor(description: string, callback: HookCallback, runtimeContext: object); + + /** + * Check if this hook has been run + */ + fired(): boolean; + + /** + * Check if this hook failed + */ + failed(): boolean; + + /** + * The cause of the fail + */ + cause(): any; + + /** + * Returns the timeout of the hook + */ + timeout(): number; + + /** + * Seta a timeout for this hook + */ + timeout(ms: number): this; + + /** + * Executes the hook + */ + run(): Promise; + } + + class Test { + description: string; + + constructor(description: string, callback: TestCallback, block: Block, runtimeContext: object, options: TestOptions); + + /** + * Handles params from options + */ + prepare(): Promise; + + /** + * Checks if this test is exclusive (has skip flag) + */ + isExclusive(): boolean; + + /** + * Checks if this test is exclusive (has only flag) + */ + isInclusive(): boolean; + + /** + * Skips this test + */ + skip(): this; + + /** + * Marks this test as inclusive + */ + only(): this; + + /** + * Returns the timeout of the test + */ + timeout(): number | null; + + /** + * Sets a timeout for this test + */ + timeout(ms: number): this; + + /** + * Returns a string of names from the root to this test + */ + chain(): string; + + /** + * Executes the test + */ + run(): Promise; + } + + class Block { + name: string; + hooks: { + before: Hook[]; + beforeEach: Hook[]; + afterEach: Hook[]; + after: Hook[]; + }; + children: Array; + + constructor(name: string, parent: Block, options: DescribeOptions); + + /** + * Handles params from options + */ + prepare(): Promise; + + /** + * Adds a new child into this block + */ + addChild(child: Block | Test): void; + + /** + * Before hooks iterator + */ + beforeHooks(): IterableIterator; + + /** + * After hooks iterator + */ + afterHooks(): IterableIterator; + + /** + * Before each hooks iterator + */ + beforeEachHooks(): IterableIterator; + + /** + * After each hooks iterator + */ + afterEachHooks(): IterableIterator; + + /** + * Checks if this block is exclusive (has skip flag) + */ + isExclusive(): boolean; + + /** + * Checks if this block is inclusive (has only flag) + */ + isInclusive(): boolean; + + /** + * Checks if this block has an inclusive node + */ + hasInclusive(): boolean; + + /** + * Skips this block + */ + skip(): this; + + /** + * Marks this block as inclusive + */ + only(): this; + + /** + * Returns the timeout of the block + */ + timeout(): number | null; + + /** + * Sets a timeout for this block + */ + timeout(ms: number): this; + + /** + * Returns the block's level, the length of parent blocks chain + */ + level(): number; + + /** + * Sets the block's level + */ + level(level: number): this; + + /** + * Returns a string of names from the root to this block + */ + chain(): string; + + /** + * Returns a chain of blocks from the root to this block + */ + blockChain(): Block[]; + } + + interface Context { + /** + * Defines a tests block + */ + describe: DescribeFunction; + + /** + * Defines a tests block + */ + context: DescribeFunction; + + /** + * Defines a test + */ + it: TestFunction; + + /** + * Defines a test + */ + specify: TestFunction; + + /** + * Defines a hook that will be called only once before the block's tests + */ + before: HookFunction; + + /** + * Defines a hook that will be called only once after the block's tests + */ + after: HookFunction; + + /** + * Defines a hook that will be called before each test + */ + beforeEach: HookFunction; + + /** + * Defines a hook that will be called after each test + */ + afterEach: HookFunction; + + /** + * Root node + */ + root: Block; + + /** + * Starts testing + */ + start(): Emitter; + } + } + + /** + * Represents a testing engine + */ + export class Engine { + constructor(options?: I.EngineOptions); + + /** + * Includes given files as test files + */ + include(...paths: string[]): void; + + /** + * Excludes given paths from testing + */ + exclude(...paths: string[]): void; + + /** + * Returns a testing context + */ + context(): I.Context; + + /** + * Starts testing + */ + start(): I.Emitter; + } + + namespace util { + namespace I { + // based on https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/sinon + + interface SpyCallApi { + /** + * The call's this value + */ + thisValue: any; + + /** + * The call's arguments + */ + args: any[]; + + /** + * Exception throws if any + */ + exception: any; + + /** + * Return value + */ + returnValue: any; + + /** + * Whether the spy was called on obj (this value) + */ + calledOn(obj: any): boolean; + + /** + * Whether the arguments were args (and possibly others) + */ + calledWith(...args: any[]): boolean; + + /** + * Whether the arguments were exactly args (no others) + */ + calledWithExactly(...args: any[]): boolean; + + /** + * Whether the call received matching args (and possibly others) + */ + calledWithMatch(...args: any[]): boolean; + + /** + * Whether the call did not receive args + */ + notCalledWith(...args: any[]): boolean; + + /** + * Whether the call did not receive matching args + */ + notCalledWithMatch(...args: any[]): boolean; + + /** + * Whether the call returned the given value + */ + returned(value: any): boolean; + + /** + * Whether the call threw an exception + */ + threw(): boolean; + + /** + * Whether the call threw an exception of provided type + */ + threw(type: string): boolean; + + /** + * Whether the call threw obj + */ + threw(obj: any): boolean; + + /** + * Calls the argument at the given index + */ + callArg(pos: number): void; + + /** + * Calls the argument at the given index on the given context + */ + callArgOn(pos: number, obj: any): void; + + /** + * Calls the argument at the given index with arguments + */ + callArgWith(pos: number, ...args: any[]): void; + + /** + * Calls the argument at the given index on the given context and with the given arguments + */ + callArgOnWith(pos: number, obj: any, ...args: any[]): void; + + /** + * Calls a callback from the arguments with the given arguments + */ + yield(...args: any[]): void; + + /** + * Calls a callback from the arguments with the given arguments on the given context + */ + yieldOn(obj: any, ...args: any[]): void; + + /** + * Calls with the given arguments a callback that is a property of the call's argument with the given name + */ + yieldTo(property: string, ...args: any[]): void; + + /** + * Calls on the given context with the given arguments a callback that + * is a property of the call's argument with the given name + */ + yieldToOn(property: string, obj: any, ...args: any[]): void; + } + + interface SpyCall extends SpyCallApi { + /** + * Whether the call was called before the given call + */ + calledBefore(call: SpyCall): boolean; + + /** + * Whether the call was called after the given call + */ + calledAfter(call: SpyCall): boolean; + + /** + * Whether the call was called using the new operator + */ + calledWithNew(call: SpyCall): boolean; + } + + interface Spy extends SpyCallApi { + /** + * The number of recorded calls + */ + callCount: number; + + /** + * Whether the spy was called + */ + called: boolean; + + /** + * Whether the spy was not called + */ + notCalled: boolean; + + /** + * Whether the spy was called once + */ + calledOnce: boolean; + + /** + * Whether the spy was called twice + */ + calledTwice: boolean; + + /** + * Whether the spy was called thrice + */ + calledThrice: boolean; + + /** + * The first call + */ + firstCall: SpyCall; + + /** + * The second call + */ + secondCall: SpyCall; + + /** + * The third call + */ + thirdCall: SpyCall; + + /** + * The last call + */ + lastCall: SpyCall; + + /** + * Array of the calls contexts + */ + thisValues: any[]; + + /** + * Array of the calls arguments + */ + args: any[][]; + + /** + * Array of the calls exceptions + */ + exceptions: any[]; + + /** + * Array of the calls return values + */ + returnValues: any[]; + + (...args: any[]): any; + /** + * Whether the spy was called before another spy + */ + calledBefore(anotherSpy: Spy): boolean; + + /** + * Whether the spy was called after another spy + */ + calledAfter(anotherSpy: Spy): boolean; + + /** + * Whether the spy was called before another spy and no spies occured between them + */ + calledImmediatelyBefore(anotherSpy: Spy): boolean; + + /** + * Whether the spy was called after another spy and no spies occured between them + */ + calledImmediatelyAfter(anotherSpy: Spy): boolean; + + /** + * Whether the spy was called using the new operator + */ + calledWithNew(): boolean; + + /** + * Creates a spy that record calls only with the given arguments + */ + withArgs(...args: any[]): Spy; + + /** + * Whether the spy was called on the given context (this value) + */ + alwaysCalledOn(obj: any): boolean; + + /** + * Whether the spy was called with the given arguments (and possibly others) + */ + alwaysCalledWith(...args: any[]): boolean; + + /** + * Whether the spy was called exactly with the given arguments (no others) + */ + alwaysCalledWithExactly(...args: any[]): boolean; + + /** + * Whether the spy was called with the matching arguments (and possibly others) + */ + alwaysCalledWithMatch(...args: any[]): boolean; + + /** + * Whether the spy was never called with the given arguments + */ + neverCalledWith(...args: any[]): boolean; + + /** + * Whether the spy was neven called with the matching arguments + */ + neverCalledWithMatch(...args: any[]): boolean; + + /** + * Whether the spy always threw exceptions + */ + alwaysThrew(): boolean; + + /** + * Whether the spy always threw exceptions of the given types + */ + alwaysThrew(type: string): boolean; + + /** + * Whether the spy always threw the given object + */ + alwaysThrew(obj: any): boolean; + + /** + * Whether the spy always returned the given object + */ + alwaysReturned(obj: any): boolean; + + /** + * Invokes the callbacks passed in the arguments with the given arguments + */ + invokeCallback(...args: any[]): void; + + /** + * Returns the call with the given index + */ + getCall(n: number): SpyCall; + + /** + * Returns all the calls + */ + getCalls(): SpyCall[]; + + /** + * Resets the state of the spy + */ + reset(): void; + + /** + * Returns the passed format string with the given replacements + */ + printf(format: string, ...args: any[]): string; + + /** + * Replaces the spy with the original method if the spy replaced an original method + */ + restore(): void; + } + + interface Stub extends Spy { + /** + * Resets the stub's behavior to the default behavior + */ + resetBehavior(): void; + + /** + * Resets the stub's history + */ + resetHistory(): void; + + /** + * Causes the stub to return promises using the given promise library + */ + usingPromise(promiseLibrary: any): Stub; + + /** + * Makes the stub return the given object + */ + returns(obj: any): Stub; + + /** + * Causes the stub to return the argument at the given index + */ + returnsArg(index: number): Stub; + + /** + * Causes the stub to return its this value + */ + returnsThis(): Stub; + + /** + * Causes the stub to return a promise that resolves to the given value + */ + resolves(value?: any): Stub; + + /* + * Causes the stub to throw an exception of the given type + */ + throws(type?: string): Stub; + + /** + * Causes the stub to throw the given object + */ + throws(obj: any): Stub; + + /** + * Causes the stub to throw the argument at the given index + */ + throwsArg(index: number): Stub; + + /* + * Causes the stub to throw an exception of the given type + */ + throwsException(type?: string): Stub; + + /** + * Causes the stub to throw the argument at the given index + */ + throwsException(obj: any): Stub; + + /** + * Causes the stub to reject + */ + rejects(): Stub; + + /** + * Causes the stub to reject with the given type + */ + rejects(errorType: string): Stub; + + /** + * Causes the stub to reject with the given value + */ + rejects(value: any): Stub; + + /** + * Causes the stub to call the argument at the provided index as a callback function + */ + callsArg(index: number): Stub; + + /** + * Causes the original method wrapped into the stub to be called when none of the conditional stubs are matched + */ + callThrough(): Stub; + + /** + * Causes the stub to call the argument at the provided index as a callback function on the given context + */ + callsArgOn(index: number, context: any): Stub; + + /** + * Causes the stub to call the argument at the provided index as a callback function with the given arguments + */ + callsArgWith(index: number, ...args: any[]): Stub; + + /** + * Causes the stub to call the argument at the provided index as a callback function on the given context with the given arguments + */ + callsArgOnWith(index: number, context: any, ...args: any[]): Stub; + + /** + * Causes the stub to asynchronously call the argument at the provided index as a callback function + */ + callsArgAsync(index: number): Stub; + + /** + * Causes the stub to asynchronously call the argument at the provided index as a callback function on the given context + */ + callsArgOnAsync(index: number, context: any): Stub; + + /** + * Causes the stub to asynchronously call the argument at the provided index as a callback function on the given context with the given arguments + */ + callsArgWithAsync(index: number, ...args: any[]): Stub; + + /** + * Causes the stub to asynchronously call the argument at the provided index as a callback function on the given context with the given arguments + */ + callsArgOnWithAsync(index: number, context: any, ...args: any[]): Stub; + + /** + * Makes the stub call the provided fake function + */ + callsFake(func: (...args: any[]) => void): Stub; + + /** + * Replaces a new getter with this stub + */ + get(func: () => any): Stub; + + /** + * Replaces a new getter with this stub + */ + set(func: (v: any) => void): Stub; + + /** + * Defines the behavior of the stub on the call with the given index + */ + onCall(n: number): Stub; + + /** + * Defines the behavior of the stub on the first call + */ + onFirstCall(): Stub; + + /** + * Defines the behavior of the stub on the second call + */ + onSecondCall(): Stub; + + /** + * Defines the behavior of the stub on the third call + */ + onThirdCall(): Stub; + + /** + * Defines a new value for this stub + */ + value(val: any): Stub; + + /** + * Causes the stub to call the first callback it receives with the provided arguments + */ + yields(...args: any[]): Stub; + + /** + * Causes the stub to call the first callback it receives with the provided arguments on the given context + */ + yieldsOn(context: any, ...args: any[]): Stub; + + /** + * Causes the stub to call the last callback it receives with the provided arguments + */ + yieldsRight(...args: any[]): Stub; + + /** + * Causes the stub to invoke a callback passed as a property of an object to the spy + */ + yieldsTo(property: string, ...args: any[]): Stub; + + /** + * Causes the stub to invoke a callback passed as a property of an object to the spy on the given context + */ + yieldsToOn(property: string, context: any, ...args: any[]): Stub; + + /** + * Causes the stub to asynchronously call the first callback it receives with the provided arguments + */ + yieldsAsync(...args: any[]): Stub; + + /** + * Causes the stub to asynchronously call the first callback it receives with the provided arguments on the given context + */ + yieldsOnAsync(context: any, ...args: any[]): Stub; + + /** + * Causes the stub to asynchronously invoke a callback passed as a property of an object to the spy + */ + yieldsToAsync(property: string, ...args: any[]): Stub; + + /** + * Causes the stub to asynchronously invoke a callback passed as a property of an object to the spy on the given context + */ + yieldsToOnAsync(property: string, context: any, ...args: any[]): Stub; + + /** + * Stubs the method only for the provided arguments + */ + withArgs(...args: any[]): Stub; + } + + interface Expectation extends Stub { + /** + * Specifies the minimum amount of calls expected + */ + atLeast(n: number): Expectation; + + /** + * Specifies the maximum amount of calls expected + */ + atMost(n: number): Expectation; + + /** + * Expects the method to never be called + */ + never(): Expectation; + + /** + * Expects the method to be called exactly once + */ + once(): Expectation; + + /** + * Expects the method to be called exactly twice + */ + twice(): Expectation; + + /** + * Expects the method to be called exactly thrice + */ + thrice(): Expectation; + + /** + * Expects the method to be called exactly n times + */ + exactly(n: number): Expectation; + + /** + * Expects the method to be called with the provided arguments and possibly others + */ + withArgs(...args: any[]): Expectation; + + /** + * Expects the method to be called with the provided arguments and no others + */ + withExactArgs(...args: any[]): Expectation; + + /** + * Expects the method to be called with obj as this + */ + on(obj: any): Expectation; + + /** + * Verifies the expectation and throws an exception if it’s not met + */ + verify(): Expectation; + + /** + * Restores all mocked methods + */ + restore(): void; + } + + interface ExpectationStatic { + /** + * Creates a new expectation + */ + create(methodName?: string): Expectation; + } + + interface Mock { + /** + * Overrides obj.method with a mock function and returns it + */ + expects(method: string): Expectation; + + /** + * Restores all mocked methods + */ + restore(): void; + + /** + * Verifies all expectations on the mock + */ + verify(): void; + } + + interface ExposeOptions { + /** + * prefix to give assertions + */ + prefix?: string; + + /** + * Whether to copy the fail and failException properties + */ + includeFail?: boolean; + } + + interface Assert { + /** + * Default error type thrown by .fail + */ + failException: string; + + /** + * Every assertion fails by calling this method + */ + fail(message?: string): void; + + /** + * Called every time assertion passes + */ + pass(assertion: any): void; + + /** + * Passes if spy was never called + */ + notCalled(spy: Spy): void; + + /** + * Passes if spy was called at least once + */ + called(spy: Spy): void; + + /** + * Passes if spy was called once and only once + */ + calledOnce(spy: Spy): void; + + /** + * Passes if spy was called exactly twice + */ + calledTwice(spy: Spy): void; + + /** + * Passes if spy was called exactly three times + */ + calledThrice(spy: Spy): void; + + /** + * Passes if spy was called exactly count times + */ + callCount(spy: Spy, count: number): void; + + /** + * Passes if provided spies were called in the specified order + */ + callOrder(...spies: Spy[]): void; + + /** + * Passes if spy was ever called with obj as its this value + */ + calledOn(spy: Spy, obj: any): void; + + /** + * Passes if spy was always called with obj as its this value + */ + alwaysCalledOn(spy: Spy, obj: any): void; + + /** + * Passes if spy was called with the provided arguments + */ + calledWith(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was always called with the provided arguments + */ + alwaysCalledWith(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was never called with the provided arguments + */ + neverCalledWith(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was called with the provided arguments and no others + */ + calledWithExactly(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was always called with the provided arguments and no others + */ + alwaysCalledWithExactly(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was called with matching arguments. + */ + calledWithMatch(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was always called with matching arguments + */ + alwaysCalledWithMatch(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was never called with matching arguments + */ + neverCalledWithMatch(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy threw + */ + threw(spy: Spy): void; + + /** + * Passes if spy threw the given exception type + */ + threw(spy: Spy, exception: string): void; + + /** + * Passes if spy threw the given object + */ + threw(spy: Spy, exception: any): void; + + /** + * Passes if always spy threw + */ + alwaysThrew(spy: Spy): void; + + /** + * Passes if spy always threw the given exception type + */ + alwaysThrew(spy: Spy, exception: string): void; + + /** + * Passes if spy always threw the given object + */ + alwaysThrew(spy: Spy, exception: any): void; + + /** + * Exposes assertions into another object, to better integrate with the test framework + */ + expose(obj: any, options?: ExposeOptions): void; + } + + interface Matcher { + /** + * Logical and + */ + and(expr: Matcher): Matcher; + + /** + * Logical or + */ + or(expr: Matcher): Matcher; + } + + interface ArrayMatcher extends Matcher { + /** + * Requires an Array to be deep equal another one. + */ + deepEquals(expected: any[]): Matcher; + + /** + * Requires an Array to start with the same values as another one. + */ + startsWith(expected: any[]): Matcher; + + /** + * Requires an Array to end with the same values as another one. + */ + endsWith(expected: any[]): Matcher; + + /** + * Requires an Array to contain each one of the values the given array has. + */ + contains(expected: any[]): Matcher; + } + + interface MapMatcher extends Matcher { + /** + * Requires a Map to be deep equal another one. + */ + deepEquals(expected: Map): Matcher; + + /** + * Requires a Map to contain each one of the items the given map has. + */ + contains(expected: Map): Matcher; + } + + interface SetMatcher extends Matcher { + /** + * Requires a Set to be deep equal another one. + */ + deepEquals(expected: Set): Matcher; + + /** + * Requires a Set to contain each one of the items the given set has. + */ + contains(expected: Set): Matcher; + } + + interface Match { + /** + * Requires the value to be == to the given number + */ + (value: number): Matcher; + + /** + * Requires the value to be a string and have the expectation as a substring + */ + (value: string): Matcher; + + /** + * Requires the value to be a string and match the given regular expression + */ + (expr: RegExp): Matcher; + + /** + * Requires the value to be not null or undefined and have at least the same properties as expectation + */ + (obj: any): Matcher; + + /** + * Specify a custom matcher + */ + (callback: (value: any) => boolean, message?: string): Matcher; + + /** + * Matches anything + */ + any: Matcher; + + /** + * Requires the value to be defined + */ + defined: Matcher; + + /** + * Requires the value to be truthy + */ + truthy: Matcher; + + /** + * Requires the value to be falsy + */ + falsy: Matcher; + + /** + * Requires the value to be a boolean + */ + bool: Matcher; + + /** + * Requires the value to be a number + */ + number: Matcher; + + /** + * Requires the value to be a string + */ + string: Matcher; + + /** + * Requires the value to be an object + */ + object: Matcher; + + /** + * Requires the value to be a function + */ + func: Matcher; + + /** + * Requires the value to be a map. + */ + map: MapMatcher; + + /** + * Requires the value to be a set. + */ + set: SetMatcher; + + /** + * Requires the value to be an array. + */ + array: ArrayMatcher; + + /** + * Requires the value to be a regular expression + */ + regexp: Matcher; + + /** + * Requires the value to be a date object + */ + date: Matcher; + + /** + * Requires the value to be a symbol + */ + symbol: Matcher; + + /** + * Requires the value to strictly equal obj + */ + same(obj: any): Matcher; + + /** + * Requires the value to be of the given type + */ + typeOf(type: adone.util.I.PossibleTypes): Matcher; + typeOf(type: string): Matcher; + + /** + * Requires the value to be an instance of the given type + */ + instanceOf(type: any): Matcher; + + /** + * Requires the value to define the given property + */ + has(property: string, expect?: any): Matcher; + + /** + * Requires the value to define the given property by itself + */ + hasOwn(property: string, expect?: any): Matcher; + } + + interface SandboxConfig { + /** + * An object to add properties to + */ + injectInto?: any; + + /** + * What properties to inject + */ + properties?: string[]; + } + + interface Sandbox { + /** + * A convenience reference for assert + */ + assert: Assert; + + /** + * Works exactly like spy, only also adds the returned spy to the internal collection of fakes + */ + spy: typeof spy; + + /** + * Works exactly like stub, only also adds the returned spy to the internal collection of fakes + */ + stub: typeof stub; + + /** + * Works exactly like mock, only also adds the returned spy to the internal collection of fakes + */ + mock: typeof mock; + + /** + * Restores all fakes created through sandbox + */ + restore(): void; + + /** + * Resets the internal state of all fakes created through sandbox + */ + reset(): void; + + /** + * Resets the history of all stubs created through the sandbox + */ + resetHistory(): void; + + /** + * Resets the behaviour of all stubs created through the sandbox + */ + resetBehavior(): void; + + /** + * Causes all stubs created from the sandbox to return promises using a specific promise library + */ + usingPromise(promiseLibrary: any): Sandbox; + + /** + * Verifies all mocks created through the sandbox + */ + verify(): void; + + /** + * Verifies all mocks and restores all fakes created through the sandbox + */ + verifyAndRestore(): void; + } + + interface SandboxStatic { + /** + * Creates a sandbox object with spies, stubs, and mocks + */ + create(config?: SandboxConfig): Sandbox; + } + } + + /** + * Return a function that records arguments, return value, the value of this and exception thrown (if any) for all its calls + */ + function spy(func?: (...args: any[]) => void): I.Spy; + function spy(object: T, method: keyof T): I.Spy; + + /** + * Creates a function (spy) with pre-programmed behavior + */ + function stub(obj?: any): I.Stub; + function stub(obj: T, method: keyof T): I.Stub; + + const expectation: I.ExpectationStatic; + + /** + * Creates a fake method (like spy) with pre-programmed behavior (like stub) + */ + function mock(): I.Expectation; + function mock(obj: any): I.Mock; + + /** + * Assertions for spies/stubs + */ + export const assert: I.Assert; + + /** + * Creates a matcher function + */ + export const match: I.Match; + + /** + * Removes the need to keep track of every fake created + */ + export const sandbox: I.SandboxStatic; + + namespace I { + interface Response extends adone.std.http.IncomingMessage { + body: Buffer; + } + + interface ExpectBodyOptions { + decompress?: boolean; + } + + interface AttachOptions { + type?: string; + filename?: string; + } + + interface Request extends Promise { + /** + * Sets the request method to GET + */ + get(path: string): this; + + /** + * Sets the request method to HEAD + */ + head(path: string): this; + + /** + * Sets the request method to POST + */ + post(path: string): this; + + /** + * Attaches an attachment + */ + attach(name: string, contents: string | Buffer, options?: AttachOptions): this; + + /** + * Attaches an attachment like a field + */ + field(name: string, value: string): this; + + /** + * Sets the request body + */ + send(value: string): this; + + /** + * Sets the request method to OPTIONS + */ + options(path: string): this; + + /** + * Sets the request method to PUT + */ + put(path: string): this; + + /** + * Sets a header value + */ + setHeader(key: string, value: string): this; + + /** + * Sets the basic auth header + */ + auth(username: string, password: string): this; + + /** + * Executes a function with the response and asserts it returns true + */ + expect(fn: (response: Response) => boolean | Promise): this; + + /** + * Asserts the response status + */ + expectStatus(code: number, message?: string): this; + + /** + * Asserts the respose status message + */ + expectStatusMessage(value: string): this; + + /** + * Asserts the response body + */ + expectBody(body: RegExp | string | Buffer, options?: ExpectBodyOptions): this; + + /** + * Asserts the response json body + */ + expectBody(body: object, options?: ExpectBodyOptions): this; + + /** + * Asserts that the response body is empty + */ + expectEmptyBody(): this; + + /** + * Asserts that the response has a header with the given key and value + */ + expectHeader(key: string, value: string | RegExp): this; + + /** + * Asserts that the response has a header with the given name + */ + expectHeaderExists(key: string): this; + + /** + * Asserts that the response does not have a header with the given name + */ + expectNoHeader(key: string): this; + } + } + + /** + * Assertion tool for http server responses + */ + function request(server: any): I.Request; // TODO: sever must be adone.net.http.server.Server or standard node.js server + + namespace FS { + // TODO: after fs + } + + namespace nock { + // TODO: after revision + } + } +} diff --git a/types/adone/glosses/std.d.ts b/types/adone/glosses/std.d.ts new file mode 100644 index 0000000000..9c30b41f62 --- /dev/null +++ b/types/adone/glosses/std.d.ts @@ -0,0 +1,65 @@ +import * as assert from "assert"; +import * as fs from "fs"; +import * as path from "path"; +import * as util from "util"; +import * as events from "events"; +import * as stream from "stream"; +import * as url from "url"; +import * as net from "net"; +import * as http from "http"; +import * as https from "https"; +import * as child_process from "child_process"; +import * as os from "os"; +import * as cluster from "cluster"; +import * as repl from "repl"; +import * as punycode from "punycode"; +import * as readline from "readline"; +import * as string_decoder from "string_decoder"; +import * as querystring from "querystring"; +import * as crypto from "crypto"; +import * as vm from "vm"; +import * as v8 from "v8"; +import * as domain from "domain"; +import * as tty from "tty"; +import * as buffer from "buffer"; +import * as constants from "constants"; +import * as zlib from "zlib"; +import * as tls from "tls"; +import * as console from "console"; +import * as dns from "dns"; +import * as timers from "timers"; +import * as dgram from "dgram"; + +export { + assert, + fs, + path, + util, + events, + stream, + url, + net, + http, + https, + child_process, + os, + cluster, + repl, + punycode, + readline, + string_decoder, + querystring, + crypto, + vm, + v8, + domain, + tty, + buffer, + constants, + zlib, + tls, + console, + dns, + timers, + dgram, +}; diff --git a/types/adone/glosses/utils.d.ts b/types/adone/glosses/utils.d.ts new file mode 100644 index 0000000000..8f90ae180b --- /dev/null +++ b/types/adone/glosses/utils.d.ts @@ -0,0 +1,473 @@ +/** + * various utility functions + */ +export namespace util { + function arrify(val: T[]): T[]; + function arrify(val: T): [T]; + + function slice(args: T[], sliceStart?: number, sliceEnd?: number): T[]; + + function spliceOne(list: any[], index: number): void; + + function normalizePath(str: string, stripTrailing?: boolean): string; + + function unixifyPath(filePath: string, unescape?: boolean): string; + + function functionName(fn: (...args: any[]) => any): string; + + function mapArguments(argmap: (...args: any[]) => any | any[]): (...args: any[]) => any; + function mapArguments(argmap: number): (...args: T[]) => T[]; + function mapArguments(...args: any[]): (x: T) => T; + + namespace I { + interface ParseMsResult { + days: number; + hours: number; + minutes: number; + seconds: number; + milliseconds: number; + } + } + function parseMs(ms: number): I.ParseMsResult; + + function pluralizeWord(str: string, plural?: string, count?: number): string; + + function functionParams(func: (...args: any[]) => any): string[]; + + function randomChoice(arrayLike: ArrayLike, from?: number, to?: number): T; + + function shuffleArray(array: T[]): T[]; + + function enumerate(iterable: Iterable, start?: number): IterableIterator<[number, T]>; + + function zip(a: Iterable, b: Iterable): IterableIterator<[T1, T2]>; + function zip(a: Iterable, b: Iterable, c: Iterable): IterableIterator<[T1, T2, T3]>; + function zip(a: Iterable, b: Iterable, c: Iterable, d: Iterable): IterableIterator<[T1, T2, T3, T4]>; + function zip(...iterables: Array>): IterableIterator; + + namespace I { + interface KeysOptions { + onlyEnumerable?: boolean; + followProto?: boolean; + all?: boolean; + } + } + function keys(object: object, options?: I.KeysOptions): string[]; + + function values(object: object, options?: I.KeysOptions): any[]; + + function entries(object: object, options?: I.KeysOptions): Array; + + function toDotNotation(object: object): object; + + namespace I { + interface FlattenOptions { + depth?: number; + } + } + function flatten(array: any[], options?: I.FlattenOptions): any[]; + + function globParent(str: string): string; + + namespace I { + interface ByResult { + (a: S, b: S): R; + compare(a: T, b: T): R; + by(a: S): T; + } + } + function by(by: (a: S) => T, compare?: (a: T, b: T) => R): I.ByResult; + + function toFastProperties(object: object): object; + + function stripBom(x: string): string; + + namespace I { + interface SortKeysOptions { + deep?: boolean; + compare?(a: any, b: any): number; + } + } + function sortKeys(object: object, options?: I.SortKeysOptions): object; + + namespace I { + interface GlobizeOptions { + exts?: string; + recursively?: boolean; + } + } + function globize(path: string, options?: I.GlobizeOptions): string; + + function unique(array: T[], projection?: (a: T) => any): T[]; + + function invertObject(source: object, options?: I.KeysOptions): object; + + namespace I { + interface HumanizeTimeOptions { + msDecimalDigits?: number; + secDecimalDigits?: number; + verbose?: boolean; + compact?: boolean; + } + } + function humanizeTime(ms: number, options?: I.HumanizeTimeOptions): string; + function humanizeSize(num: number, space?: string): string; + + function parseSize(str: string | number): number | null; + + namespace I { + interface CloneOptions { + deep?: boolean; + } + } + function clone(object: object, options?: I.CloneOptions): object; + + function toUTF8Array(str: string): number[]; + + function asyncIter(array: T[], iter: (elem: T, index: number, cb: () => void) => any, cb: () => void): void; + + function asyncFor(obj: { [key: string]: T }, iter: (key: string, value: T, index: number, length: number, next: () => void) => void, cb: () => void): void; + + namespace I { + interface OnceOptions { + silent: boolean; + } + } + function once(fn: (...args: any[]) => T, options?: I.OnceOptions): (...args: any[]) => T; + + namespace I { + type WaterFallTask = (...args: any[]) => void; + } + function asyncWaterfall(tasks: I.WaterFallTask[], callback?: (err?: Error | null, ...args: any[]) => void): void; + + function xrange(start?: number, stop?: number, step?: number): IterableIterator; + + function range(start?: number, stop?: number, step?: number): number[]; + + function reFindAll(regexp: RegExp, str: string): RegExpExecArray[]; + + function assignDeep(target: T, ...sources: object[]): T; + + namespace I { + interface MatchOptions { + index?: boolean; + start?: number; + end?: number; + dot?: boolean; + } + } + function match(criteria: any | any[], options?: I.MatchOptions): (value: any | any[], options?: I.MatchOptions) => number | boolean; + function match(criteria: any | any[], value: any | any[], options?: I.MatchOptions): number | boolean; + + namespace I { + interface ToposortFunction { + (edges: Array<[T, T]>): T[]; + array(nodes: T[], edges: Array<[T, T]>): T[]; + } + } + const toposort: I.ToposortFunction; + + namespace I { + interface JSEscOptions { + escapeEverything?: boolean; + minimal?: boolean; + isScriptContext?: boolean; + quotes?: string; + wrap?: boolean; + es6?: boolean; + json?: boolean; + compact?: boolean; + lowercaseHex?: boolean; + numbers?: string; + indent?: string; + indentLevel?: number; + __inline1__?: boolean; + __inline2__?: boolean; + } + } + function jsesc(argument: any, options?: I.JSEscOptions): string; + + namespace I { + type PossibleTypes = "object" | "class" | "null" | "global" | "Array" | "RegExp" | "Date" + | "Promise" | "Set" | "Map" | "WeakSet" | "DataView" | "Map Iterator" | "Set Iterator" + | "Array Iterator" | "String Iterator" | "Object" | "function" | "boolean" | "number" + | "undefined" | "string" | "symbol"; + } + + function typeOf(obj: any): I.PossibleTypes; + function typeOf(obj: any): string; + + namespace memcpy { + function utou(target: Buffer, targetOffset: number, source: Buffer, sourceStart: number, sourceEnd: number): number; + function atoa(target: ArrayBuffer, targetOffset: number, source: ArrayBuffer, sourceStart: number, sourceEnd: number): number; + function atou(target: Buffer, targetOffset: number, source: ArrayBuffer, sourceStart: number, sourceEnd: number): number; + function utoa(target: ArrayBuffer, targetOffset: number, source: Buffer, sourceStart: number, sourceEnd: number): number; + function copy(target: Buffer | ArrayBuffer, targetOffset: number, source: Buffer | ArrayBuffer, sourceStart: number, sourceEnd: number): number; + } + + namespace uuid { + namespace I { + interface V1Options { + clockseq?: number; + msecs?: number; + nsecs?: number; + } + } + function v1(options?: I.V1Options): string; + function v1(options: I.V1Options, buf: any[], offset?: number): number[]; + + function v4(options?: any): string; + function v4(options: any, buf: any[], offset?: number): number[]; + + function v5(name: string | number[], namespace: string | number[]): string; + function v5(name: string | number[], namespace: string | number[], buf: any[], offset?: number): number[]; + } + + namespace I { + interface Delegator { + method(name: string): Delegator; + access(name: string): Delegator; + getter(name: string): Delegator; + setter(name: string): Delegator; + } + } + function delegate(object: object, property: string): I.Delegator; + + namespace I { + interface GlobExpOptions { + nocomment?: boolean; + nonegate?: boolean; + nobrace?: boolean; + noglobstar?: boolean; + nocase?: boolean; + dot?: boolean; + noext?: boolean; + matchBase?: boolean; + flipNegate?: boolean; + } + } + + class GlobExp { + constructor(pattern: string, options?: I.GlobExpOptions); + + hasMagic(): boolean; + + static hasMagic(pattern: string, options?: I.GlobExpOptions): boolean; + + expandBraces(): string[]; + + static expandBraces(pattern: string, options?: I.GlobExpOptions): string[]; + + makeRe(): RegExp; + + static makeRe(pattern: string, options?: I.GlobExpOptions): RegExp; + + static test(p: string, pattern: string, options?: I.GlobExpOptions): boolean; + + test(p: string): boolean; + } + + namespace iconv { + // TODO: need to normalize source code + } + + namespace sqlstring { + function escapeId(val: string | string[], forbidQualified?: boolean): string; + function dateToString(date: any, timeZone?: string): string; + function arrayToList(array: any[]): string; + function bufferToString(buffer: Buffer): string; + function objectToValues(object: object, timeZone?: string): string; + function escape(value: any, stringifyObjects?: boolean, timeZone?: string): string; + function format(sql: string, values?: any | any[], stringifyObjects?: boolean, timeZone?: string): string; + } + + namespace I { + interface EditorOptions { + text?: string; + editor?: string; + path?: string; + ext?: string; + } + } + class Editor { + static DEFAULT: string; + + constructor(options?: I.EditorOptions); + + spawn(): Promise; + + run(): Promise; + + cleanup(): Promise; + + static edit(options?: I.EditorOptions): Promise; + } + + namespace I { + interface BinarySearchFunction { + (aHaystack: T[], aNeedle: number, aLow?: number, aHigh?: number, aCompare?: (a: T, b: T) => number, aBias?: number): T; + GREATEST_LOWER_BOUND: number; + LEAST_UPPER_BOUND: number; + } + } + const binarySearch: I.BinarySearchFunction; + + namespace buffer { + function concat(list: Buffer[], totalLength: number): Buffer; + function mask(buffer: Buffer, mask: Buffer, output: Buffer, offset: number, length: number): void; + function unmask(buffer: Buffer, mask: Buffer): void; + } + + function shebang(str: string): string | null; + + class ReInterval { + constructor(callback: (...args: any[]) => void, interval: number, args?: any[]); + + reschedule(interval: number): void; + + clear(): void; + + destroy(): void; + } + + class RateLimiter { + constructor(tokensPerInterval?: number, interval?: number, fireImmediately?: boolean); + + removeTokens(count: number): Promise; + + tryRemoveTokens(count: number): boolean; + + getTokensRemaining(): number; + } + + namespace I { + interface ThrottleOptions { + max?: number; + interval?: number; + ordered?: boolean; + waitForReturn?: boolean; + } + } + function throttle(fn: () => R, options?: I.ThrottleOptions): () => Promise; + function throttle(fn: (a: T1) => R, options?: I.ThrottleOptions): (a: T1) => Promise; + function throttle(fn: (a: T1, b: T2) => R, options?: I.ThrottleOptions): (a: T1, b: T2) => Promise; + function throttle(fn: (a: T1, b: T2, c: T3) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3) => Promise; + function throttle(fn: (a: T1, b: T2, c: T3, d: T4) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3, d: T4) => Promise; + function throttle(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise; + function throttle(fn: (...args: any[]) => R, options?: I.ThrottleOptions): (...args: any[]) => Promise; + + namespace I.fakeClock { + interface Timer { + id: number; + ref(): void; + unref(): void; + } + interface Clock { + setTimeout(func: (...args: any[]) => void, timeout: number, ...args: any[]): Timer; + clearTimeout(timer: Timer): void; + nextTick(func: (...args: any[]) => void, ...args: any[]): void; + setInterval(func: (...args: any[]) => void, ...args: any[]): Timer; + clearInterval(timer: Timer): void; + setImmediate(func: (...args: any[]) => void, ...args: any[]): Timer; + clearImmediate(timer: Timer): void; + updateHrTime(newNow: number): void; + tick(ms: number): number; + next(): number; + runAll(): number; + runToLast(): number; + setSystemTime(systemTime: number): void; + hrtime(prev?: [number, number]): [number, number]; + } + interface InstalledClock extends Clock { + uninstall(): void; + } + interface InstallOptions { + target?: object; + now?: number; + toFake?: string[]; + loopLimit?: number; + shouldAdvanceTime?: boolean; + advanceTimeDelta?: number; + } + + interface Timers { + setTimeout: typeof global.setTimeout; + clearTimeout: typeof global.clearTimeout; + setInterval: typeof global.setInterval; + clearInterval: typeof global.clearInterval; + setImmediate: typeof global.setImmediate; + clearImmediate: typeof global.clearImmediate; + Date: typeof global.Date; + hrtime: typeof global.process.hrtime; + nextTick: typeof global.process.nextTick; + } + + interface FakeClock { + timers: Timers; + createClock(now?: number, loopLimit?: number): Clock; + install(now?: number | Date | InstallOptions): InstalledClock; + } + } + + const fakeClock: I.fakeClock.FakeClock; + + namespace ltgt { + namespace I { + interface Range { + lt?: T; + lte?: T; + gt?: T; + gte?: T; + min?: T; + max?: T; + start?: T; + end?: T; + reverse?: boolean; + } + type Comparator = (a: T, b: T) => number; + } + function contains(range: I.Range, key: T, compare?: I.Comparator): boolean; + + function filter(range: I.Range, compare?: I.Comparator): (key: T) => boolean; + + function toLtgt( + range: I.Range, + _range: object, + map?: (value: T, isUpperBound: boolean) => R, + lowerBound?: T, + upperBound?: T + ): I.Range; + + function endInclusive(range: I.Range): boolean; + + function startInclusive(range: I.Range): boolean; + + function end(range: I.Range): T | undefined; + + function end(range: I.Range, defaultValue: R): T | R; + + function start(range: I.Range): T | undefined; + + function start(range: I.Range, defaultValue?: R): T | R; + + function upperBound(range: I.Range): T | undefined; + + function upperBound(range: I.Range, defaultValue: R): T | R; + + function upperBoundKey(range: I.Range): T | undefined; + + function upperBoundExclusive(range: I.Range): boolean; + + function lowerBoundExclusive(range: I.Range): boolean; + + function upperBoundInclusive(range: I.Range): boolean; + + function lowerBoundInclusive(range: I.Range): boolean; + + function lowerBound(range: I.Range): T | undefined; + + function lowerBound(range: I.Range, defaultValue: R): T | R; + + function lowerBoundKey(range: I.Range): T | undefined; + } +} diff --git a/types/adone/index.d.ts b/types/adone/index.d.ts new file mode 100644 index 0000000000..663e8c8407 --- /dev/null +++ b/types/adone/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for adone 0.6 +// Project: https://github.com/ciferox/adone +// Definitions by: am , Maximus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import * as adone from "./adone"; + +export default adone; diff --git a/types/adone/test/glosses/assertion.ts b/types/adone/test/glosses/assertion.ts new file mode 100644 index 0000000000..4d07c78182 --- /dev/null +++ b/types/adone/test/glosses/assertion.ts @@ -0,0 +1,653 @@ +namespace assertionTests { + const { assertion } = adone; + + namespace assertionInterface { + namespace exception { + const a: adone.x.Exception = new assertion.AssertionError(); + const b: adone.x.Exception = new assertion.AssertionError("hello"); + const c: adone.x.Exception = new assertion.AssertionError("hello", { actual: 2, expected: 3 }, () => {}); + } + + namespace config { + assertion.config.includeStack = true; + assertion.config.proxyExcludedKeys = ["a"]; + assertion.config.showDiff = false; + assertion.config.truncateThreshold = 20; + assertion.config.useProxy = false; + } + + namespace loadInterfaces { + assertion.loadAssertInterface().config.includeStack = true; + assertion.loadExpectInterface().config.includeStack = true; + assertion.loadMockInterface().config.includeStack = true; + } + + namespace use { + assertion.use(() => {}).use(() => {}).config.includeStack = true; + } + } + + const { assert } = assertion; + + namespace assertTests { + assert(1); + assert(1, "hello"); + assert.fail(); + assert.fail(1); + assert.fail(1, 2); + assert.fail(1, 2, "hello"); + assert.fail(1, 2, "hello", "<"); + + assert.isOk(1); + assert.isOk(1, "hello"); + + assert.isNotOk(1); + assert.isNotOk(1, "hello"); + + assert.equal(1, 2); + assert.equal(1, 2, "hello"); + + assert.notEqual(1, 2); + assert.notEqual(1, 2, "hello"); + + assert.strictEqual(1, 2); + assert.strictEqual(1, 2, "hello"); + + assert.notStrictEqual(1, 2); + assert.notStrictEqual(1, 2, "hello"); + + assert.deepEqual(1, 2); + assert.deepEqual(1, 2, "hello"); + + assert.deepStrictEqual(1, 2); + assert.deepStrictEqual(1, 2, "hello"); + + assert.equalArrays([1, 2, 3], [4, 5, 6]); + assert.equalArrays([1, 2, 3], [4, 5, 6], "hello"); + + assert.notDeepEqual(1, 2); + assert.notDeepEqual(1, 2, "hello"); + + assert.isAbove(1, 2); + assert.isAbove(1, 2, "hello"); + + assert.isAtLeast(1, 2); + assert.isAtLeast(1, 2, "hello"); + + assert.isBelow(1, 2); + assert.isBelow(1, 2, "hello"); + + assert.isAtMost(1, 2); + assert.isAtMost(1, 2, "hello"); + + assert.isTrue(1); + assert.isTrue(1, "hello"); + + assert.isNotTrue(1); + assert.isNotTrue(1, "hello"); + + assert.isFalse(1); + assert.isFalse(1, "hello"); + + assert.isNotFalse(1); + assert.isNotFalse(1, "hello"); + + assert.isNull(1); + assert.isNull(1, "hello"); + + assert.isNaN(1); + assert.isNaN(1, "hello"); + + assert.isNotNaN(1); + assert.isNotNaN(1, "hello"); + + assert.exists(1); + assert.exists(1, "hello"); + + assert.notExists(1); + assert.notExists(1, "hello"); + + assert.isUndefined(1); + assert.isUndefined(1, "hello"); + + assert.isDefined(1); + assert.isDefined(1, "hello"); + + assert.isFunction(1); + assert.isFunction(1, "hello"); + + assert.isNotFunction(1); + assert.isNotFunction(1, "hello"); + + assert.isObject(1); + assert.isObject(1, "hello"); + + assert.isNotObject(1); + assert.isNotObject(1, "hello"); + + assert.isArray(1); + assert.isArray(1, "hello"); + + assert.isNotArray(1); + assert.isNotArray(1, "hello"); + + assert.isString(1, "hello"); + + assert.isNotString(1); + assert.isNotString(1, "hello"); + + assert.isNumber(1); + assert.isNumber(1, "hello"); + + assert.isNotNumber(1); + assert.isNotNumber(1, "hello"); + + assert.isFinite(1); + assert.isFinite(1, "hello"); + + assert.isBoolean(1); + assert.isBoolean(1, "hello"); + + assert.isNotBoolean(1); + assert.isNotBoolean(1, "hello"); + + assert.typeOf(1, "string"); + assert.typeOf(1, "number", "hello"); + + assert.notTypeOf(1, "string"); + assert.notTypeOf(1, "number", "hello"); + + assert.instanceOf(1, Date); + class A {} + assert.instanceOf("4", A, "hello"); + + assert.notInstanceOf(1, Date); + assert.notInstanceOf(Date, A, "hello"); + + assert.include([1, 2, 3], 4); + assert.include([1, 2, 3], 4, "hello"); + assert.include("string", "string"); + assert.include("string", "string", "string"); + + assert.notInclude([1, 2, 3], 4); + assert.notInclude([1, 2, 3], 4, "hello"); + assert.notInclude("string", "string"); + assert.notInclude("string", "string", "string"); + + assert.deepInclude([1, 2, 3], 4); + assert.deepInclude([1, 2, 3], 4, "hello"); + assert.deepInclude("string", "string"); + assert.deepInclude("string", "string", "string"); + + assert.notDeepInclude([1, 2, 3], 4); + assert.notDeepInclude([1, 2, 3], 4, "hello"); + assert.notDeepInclude("string", "string"); + assert.notDeepInclude("string", "string", "string"); + + assert.nestedInclude({ a: 1 }, {}); + assert.nestedInclude({ a: 1 }, {}, "hello"); + + assert.notNestedInclude({ a: 1 }, {}); + assert.notNestedInclude({ a: 1 }, {}, "hello"); + + assert.deepNestedInclude({ a: 1 }, {}); + assert.deepNestedInclude({ a: 1 }, {}, "hello"); + + assert.notDeepNestedInclude({ a: 1 }, {}); + assert.notDeepNestedInclude({ a: 1 }, {}, "hello"); + + assert.ownInclude({ a: 1 }, {}); + assert.ownInclude({ a: 1 }, {}, "hello"); + + assert.notOwnInclude({ a: 1 }, {}); + assert.notOwnInclude({ a: 1 }, {}, "hello"); + + assert.deepOwnInclude({ a: 1 }, {}); + assert.deepOwnInclude({ a: 1 }, {}, "hello"); + + assert.notDeepOwnInclude({ a: 1 }, {}); + assert.notDeepOwnInclude({ a: 1 }, {}, "hello"); + + assert.match("1", /\d+/); + assert.match("1", /\d+/, "hello"); + + assert.notMatch("1", /\d+/); + assert.notMatch("1", /\d+/, "hello"); + + assert.property({ a: 1 }, "a"); + assert.property({ a: 1 }, "a", "hello"); + + assert.notProperty({ a: 1 }, "a"); + assert.notProperty({ a: 1 }, "a", "hello"); + + assert.propertyVal({ a: 1 }, "a", 1); + assert.propertyVal({ a: 1 }, "a", 1, "hello"); + + assert.notPropertyVal({ a: 1 }, "a", 1); + assert.notPropertyVal({ a: 1 }, "a", 1, "hello"); + + assert.deepPropertyVal({ a: 1 }, "a", 1); + assert.deepPropertyVal({ a: 1 }, "a", 1, "hello"); + + assert.notDeepPropertyVal({ a: 1 }, "a", 1); + assert.notDeepPropertyVal({ a: 1 }, "a", 1, "hello"); + + assert.ownProperty({ a: 1 }, "a"); + assert.ownProperty({ a: 1 }, "a", "hello"); + + assert.notOwnProperty({ a: 1 }, "a"); + assert.notOwnProperty({ a: 1 }, "a", "hello"); + + assert.ownPropertyVal({ a: 1 }, "a", 1); + assert.ownPropertyVal({ a: 1 }, "a", 1, "hello"); + + assert.deepOwnPropertyVal({ a: 1 }, "a", 1); + assert.deepOwnPropertyVal({ a: 1 }, "a", 1, "hello"); + + assert.notDeepOwnPropertyVal({ a: 1 }, "a", 1); + assert.notDeepOwnPropertyVal({ a: 1 }, "a", 1, "hello"); + + assert.nestedProperty({ a: 1 }, "a"); + assert.nestedProperty({ a: 1 }, "a", "hello"); + + assert.notNestedProperty({ a: 1 }, "a"); + assert.notNestedProperty({ a: 1 }, "a", "hello"); + + assert.nestedPropertyVal({ a: 1 }, "a", 1); + assert.nestedPropertyVal({ a: 1 }, "a", 1, "hello"); + + assert.notNestedPropertyVal({ a: 1 }, "a", 1); + assert.notNestedPropertyVal({ a: 1 }, "a", 1, "hello"); + + assert.deepNestedPropertyVal({ a: 1 }, "a", 1); + assert.deepNestedPropertyVal({ a: 1 }, "a", 1, "hello"); + + assert.notDeepNestedPropertyVal({ a: 1 }, "a", 1); + assert.notDeepNestedPropertyVal({ a: 1 }, "a", 1, "hello"); + + assert.lengthOf([1, 2, 3], 3); + assert.lengthOf([1, 2, 3], 3, "hello"); + + assert.hasAnyKeys({ a: 1 }, "a"); + assert.hasAnyKeys({ a: 1 }, ["a"]); + assert.hasAnyKeys({ a: 1 }, ["a"], "hello"); + + assert.hasAnyKeys({ a: 1 }, { a: 1 }); + assert.hasAnyKeys({ a: 1 }, { a: 1 }, "hello"); + + assert.hasAllKeys({ a: 1 }, "a"); + assert.hasAllKeys({ a: 1 }, ["a"]); + assert.hasAllKeys({ a: 1 }, ["a"], "hello"); + + assert.hasAllKeys({ a: 1 }, { a: 1 }); + assert.hasAllKeys({ a: 1 }, { a: 1 }, "hello"); + + assert.containsAllKeys({ a: 1 }, "a"); + assert.containsAllKeys({ a: 1 }, ["a"]); + assert.containsAllKeys({ a: 1 }, ["a"], "hello"); + + assert.containsAllKeys({ a: 1 }, { a: 1 }); + assert.containsAllKeys({ a: 1 }, { a: 1 }, "hello"); + + assert.doesNotHaveAnyKeys({ a: 1 }, "a"); + assert.doesNotHaveAnyKeys({ a: 1 }, ["a"]); + assert.doesNotHaveAnyKeys({ a: 1 }, ["a"], "hello"); + + assert.doesNotHaveAnyKeys({ a: 1 }, { a: 1 }); + assert.doesNotHaveAnyKeys({ a: 1 }, { a: 1 }, "hello"); + + assert.doesNotHaveAllDeepKeys({ a: 1 }, "a"); + assert.doesNotHaveAllDeepKeys({ a: 1 }, ["a"]); + assert.doesNotHaveAllDeepKeys({ a: 1 }, ["a"], "hello"); + + assert.doesNotHaveAllDeepKeys({ a: 1 }, { a: 1 }); + assert.doesNotHaveAllDeepKeys({ a: 1 }, { a: 1 }, "hello"); + + assert.hasAnyDeepKeys({ a: 1 }, "a"); + assert.hasAnyDeepKeys({ a: 1 }, ["a"]); + assert.hasAnyDeepKeys({ a: 1 }, ["a"], "hello"); + + assert.hasAnyDeepKeys({ a: 1 }, { a: 1 }); + assert.hasAnyDeepKeys({ a: 1 }, { a: 1 }, "hello"); + + assert.hasAllDeepKeys({ a: 1 }, "a"); + assert.hasAllDeepKeys({ a: 1 }, ["a"]); + assert.hasAllDeepKeys({ a: 1 }, ["a"], "hello"); + + assert.hasAllDeepKeys({ a: 1 }, { a: 1 }); + assert.hasAllDeepKeys({ a: 1 }, { a: 1 }, "hello"); + + assert.containsAllDeepKeys({ a: 1 }, "a"); + assert.containsAllDeepKeys({ a: 1 }, ["a"]); + assert.containsAllDeepKeys({ a: 1 }, ["a"], "hello"); + + assert.containsAllDeepKeys({ a: 1 }, { a: 1 }); + assert.containsAllDeepKeys({ a: 1 }, { a: 1 }, "hello"); + + assert.doesNotHaveAnyDeepKeys({ a: 1 }, "a"); + assert.doesNotHaveAnyDeepKeys({ a: 1 }, ["a"]); + assert.doesNotHaveAnyDeepKeys({ a: 1 }, ["a"], "hello"); + + assert.doesNotHaveAnyDeepKeys({ a: 1 }, { a: 1 }); + assert.doesNotHaveAnyDeepKeys({ a: 1 }, { a: 1 }, "hello"); + + assert.doesNotHaveAllDeepKeys({ a: 1 }, "a"); + assert.doesNotHaveAllDeepKeys({ a: 1 }, ["a"]); + assert.doesNotHaveAllDeepKeys({ a: 1 }, ["a"], "hello"); + + assert.doesNotHaveAllDeepKeys({ a: 1 }, { a: 1 }); + assert.doesNotHaveAllDeepKeys({ a: 1 }, { a: 1 }, "hello"); + + assert.throws(() => {}); + assert.throws(() => {}, Error); + assert.throws(() => {}, Error, /\d+/); + assert.throws(() => {}, Error, "string"); + assert.throws(() => {}, Error, "string", "hello"); + + assert.throws(async () => {}).then(() => 42); + assert.throws(async () => {}, Error).then(() => 42); + assert.throws(async () => {}, Error, /\d+/).then(() => 42); + assert.throws(async () => {}, Error, "string").then(() => 42); + assert.throws(async () => {}, Error, "string", "hello").then(() => 42); + + assert.doesNotThrow(() => {}); + assert.doesNotThrow(() => {}, Error); + assert.doesNotThrow(() => {}, Error, /\d+/); + assert.doesNotThrow(() => {}, Error, "string"); + assert.doesNotThrow(() => {}, Error, "string", "hello"); + + assert.doesNotThrow(async () => {}).then(() => 42); + assert.doesNotThrow(async () => {}, Error).then(() => 42); + assert.doesNotThrow(async () => {}, Error, /\d+/).then(() => 42); + assert.doesNotThrow(async () => {}, Error, "string").then(() => 42); + assert.doesNotThrow(async () => {}, Error, "string", "hello").then(() => 42); + + assert.operator(1, "<", 2); + assert.operator(1, "<", 2, "hello"); + + assert.closeTo(1, 2, 1); + assert.closeTo(1, 2, 1, "hello"); + + assert.approximately(1, 2, 2); + assert.approximately(1, 2, 2, "hello"); + + assert.sameMembers([1, 2, 3], [4, 5, 6]); + assert.sameMembers([1, 2, 3], [4, 5, 6], "hello"); + + assert.notSameMembers([1, 2, 3], [4, 5, 6]); + assert.notSameMembers([1, 2, 3], [4, 5, 6], "hello"); + + assert.sameDeepMembers([1, 2, 3], [4, 5, 6]); + assert.sameDeepMembers([1, 2, 3], [4, 5, 6], "hello"); + + assert.notSameDeepMembers([1, 2, 3], [4, 5, 6]); + assert.notSameDeepMembers([1, 2, 3], [4, 5, 6], "hello"); + + assert.sameOrderedMembers([1, 2, 3], [4, 5, 6]); + assert.sameOrderedMembers([1, 2, 3], [4, 5, 6], "hello"); + + assert.notSameOrderedMembers([1, 2, 3], [4, 5, 6]); + assert.notSameOrderedMembers([1, 2, 3], [4, 5, 6], "hello"); + + assert.includeMembers([1, 2, 3], [3]); + assert.includeMembers([1, 2, 3], [3], "hello"); + + assert.notIncludeMembers([1, 2, 3], [3]); + assert.notIncludeMembers([1, 2, 3], [3], "hello"); + + assert.includeDeepMembers([1, 2, 3], [3]); + assert.includeDeepMembers([1, 2, 3], [3], "hello"); + + assert.notIncludeDeepMembers([1, 2, 3], [3]); + assert.notIncludeDeepMembers([1, 2, 3], [3], "hello"); + + assert.includeOrderedMembers([1, 2, 3], [3]); + assert.includeOrderedMembers([1, 2, 3], [3], "hello"); + + assert.notIncludeOrderedMembers([1, 2, 3], [3]); + assert.notIncludeOrderedMembers([1, 2, 3], [3], "hello"); + + assert.includeDeepOrderedMembers([1, 2, 3], [3]); + assert.includeDeepOrderedMembers([1, 2, 3], [3], "hello"); + + assert.notIncludeDeepOrderedMembers([1, 2, 3], [3]); + assert.notIncludeDeepOrderedMembers([1, 2, 3], [3], "hello"); + + assert.oneOf(1, [1, 2, 3]); + assert.oneOf(1, [1, 2, 3], "hello"); + + assert.changes(() => {}, {}, "a"); + assert.changes(() => {}, {}, "a", "hello"); + + assert.changesBy(() => {}, {}, "a", 2); + assert.changesBy(() => {}, {}, "a", 2, "hello"); + + assert.doesNotChange(() => {}, {}, "a"); + assert.doesNotChange(() => {}, {}, "a", "hello"); + + assert.changesButNotBy(() => {}, {}, "a", 20); + assert.changesButNotBy(() => {}, {}, "a", 20, "hello"); + + assert.increases(() => {}, {}, "a"); + assert.increases(() => {}, {}, "a", "hello"); + + assert.increasesBy(() => {}, {}, "a", 20); + assert.increasesBy(() => {}, {}, "a", 20, "hello"); + + assert.doesNotIncrease(() => {}, {}, "a"); + assert.doesNotIncrease(() => {}, {}, "a", "hello"); + + assert.increasesButNotBy(() => {}, {}, "a", 20); + assert.increasesButNotBy(() => {}, {}, "a", 20, "hello"); + + assert.decreases(() => {}, {}, "a"); + assert.decreases(() => {}, {}, "a", "hello"); + + assert.decreasesBy(() => {}, {}, "a", 20); + assert.decreasesBy(() => {}, {}, "a", 20, "hello"); + + assert.doesNotDecrease(() => {}, {}, "a"); + assert.doesNotDecrease(() => {}, {}, "a", "hello"); + + assert.doesNotDecreaseBy(() => {}, {}, "a", 20); + assert.doesNotDecreaseBy(() => {}, {}, "a", 20, "hello"); + + assert.decreasesButNotBy(() => {}, {}, "a", 20); + assert.decreasesButNotBy(() => {}, {}, "a", 20, "hello"); + + assert.ifError(1); + + assert.isExtensible({}); + assert.isExtensible({}, "hello"); + + assert.isNotExtensible({}); + assert.isNotExtensible({}, "hello"); + + assert.isSealed({}); + assert.isSealed({}, "hello"); + + assert.isNotSealed({}); + assert.isNotSealed({}, "hello"); + + assert.isFrozen({}); + assert.isFrozen({}, "hello"); + + assert.isNotFrozen({}); + assert.isNotFrozen({}, "hello"); + + assert.isEmpty({}); + assert.isEmpty({}, "hello"); + } + + const { expect } = assertion; + + namespace expectTests { + expect(1); + expect(1, "hello"); + expect.fail(1, 2); + expect.fail(1, 2, "hello"); + expect.fail(1, 2, "hello", "+"); + expect(1).to.be.been.is.and.has.have.with.that.which.at.of.same.but.does.not.deep.nested.own.ordered.any.all.a("number"); + expect(1).to.be.a("number", "hello").and; + expect(1).to.be.an("array").and; + expect(1).to.be.an("array", "hello").and; + expect(1).to.include(1).and; + expect(1).to.include(1, "hello").and; + expect(1).but.includes(2).and; + expect(1).but.includes(2, "hello").and; + expect(1).to.contain(2).and; + expect(1).to.contain(2, "hello").and; + expect(1).but.contains(2).and; + expect(1).but.contains(2, "hello").and; + expect(1).to.ok.not.ok; + expect(1).to.be.true.but.false; + expect(1).to.be.false.but.true; + expect(1).to.be.null.and.null; + expect(1).to.be.undefined.and.true; + expect(1).to.be.NaN.and.null; + expect(1).to.exist.and.be.null; + expect(1).to.be.empty.and.true; + expect(1).to.be.arguments.and.a("number"); + expect(1).to.be.Arguments.and.false; + expect(1).to.be.equal(2).and; + expect(1).to.be.equal(2, "hello").and; + expect(1).but.equals(2).and; + expect(1).but.equals(2, "hello").and; + expect(1).to.eq(2).and; + expect(1).to.eq(2, "hello").and; + expect(1).but.eqls(2).and; + expect(1).but.eqls(2, "hello").and; + expect(1).to.eqlArray([1, 2, 3]).and; + expect(1).to.eqlArray([1, 2, 3], "hello").and; + expect(1).to.be.above(2).and; + expect(1).to.be.above(2, "hello").and; + expect(1).to.be.gt(2).and; + expect(1).to.be.gt(2, "hello").and; + expect(1).to.be.greaterThan(2).and; + expect(1).to.be.greaterThan(2, "hello").and; + expect(1).to.be.at.least(10).and; + expect(1).to.be.at.least(10, "hello").and; + expect(1).to.be.gte(10).and; + expect(1).to.be.gte(10, "hello").and; + expect(1).to.be.below(100).and; + expect(1).to.be.below(100, "hello").and; + expect(1).to.be.lt(10).and; + expect(1).to.be.lt(10, "hello").and; + expect(1).to.be.lessThan(10, "hello").and; + expect(1).to.be.at.most(10).and; + expect(1).to.be.at.most(10, "hello").and; + expect(1).to.be.lte(10).and; + expect(1).to.be.lte(10, "hello").and; + expect(1).to.be.within(1, 10).and; + expect(1).to.be.within(1, 10, "hello").and; + expect(1).to.be.instanceof(Number).and; + expect(1).to.be.instanceof(Number, "hello").and; + expect(1).to.be.instanceOf(Number).and; + expect(1).to.be.instanceOf(Number, "hello").and; + expect(1).to.have.property("a").and; + expect(1).to.have.property("a", 1).and; + expect(1).to.have.property("a", 1, "hello").and; + expect(1).to.have.ownProperty("a").and; + expect(1).to.have.ownProperty("a", 1).and; + expect(1).to.have.ownProperty("a", 1, "hello").and; + expect(1).to.haveOwnProperty("a").and; + expect(1).to.haveOwnProperty("a", 1).and; + expect(1).to.haveOwnProperty("a", 1, "hello").and; + expect(1).to.have.ownPropertyDescriptor("a").and; + expect(1).to.have.ownPropertyDescriptor("a", {}).and; + expect(1).to.have.ownPropertyDescriptor("a", {}, "hello").and; + expect(1).to.haveOwnPropertyDescriptor("a").and; + expect(1).to.haveOwnPropertyDescriptor("a", {}).and; + expect(1).to.haveOwnPropertyDescriptor("a", {}, "hello").and; + expect("a").to.have.length(1).and; + expect("a").to.have.length(1, "hello").and; + expect("a").to.have.lengthOf(1).and; + expect("a").to.have.lengthOf(1, "hello").and; + expect(1).to.match(/\d+/).and; + expect(1).to.match(/\d+/, "hello").and; + expect(1).to.have.string("1230").and; + expect(1).to.have.string("1230", "hello").and; + expect(1).to.have.key("a").and; + expect(1).to.have.key("a", "b").and; + expect(1).to.have.key(["a", "b"]).and; + expect(1).to.have.key({ a: 1, b: 2 }).and; + expect(1).to.have.keys("a").and; + expect(1).to.have.keys("a", "b").and; + expect(1).to.have.keys(["a", "b"]).and; + expect(1).to.have.keys({ a: 1, b: 2 }).and; + expect(() => {}).to.throw().and; + expect(() => {}).to.throw(Error).and; + expect(() => {}).to.throw(Error, "string").and; + expect(() => {}).to.throw(Error, "string", "hello").and; + expect(() => {}).to.throw(Error, /\d+/).and; + expect(() => {}).to.throw(Error, /\d+/, "hello").and; + expect(() => {}).but.throws().and; + expect(() => {}).but.throws(Error).and; + expect(() => {}).but.throws(Error, "string").and; + expect(() => {}).but.throws(Error, "string", "hello").and; + expect(() => {}).but.throws(Error, /\d+/).and; + expect(() => {}).but.throws(Error, /\d+/, "hello").and; + expect(1).to.respondTo("a").and; + expect(1).to.respondTo("a", "hello").and; + expect(1).to.respondsTo("a").and; + expect(1).to.respondsTo("a", "hello").and; + expect(1).itself.to.respondsTo("a").and; + expect(1).to.satisfy(() => true).and; + expect(1).to.satisfy(() => true, "hello").and; + expect(1).but.satisfies(() => true).and; + expect(1).but.satisfies(() => true, "hello").and; + expect(1).to.be.closeTo(2, 1).and; + expect(1).to.be.closeTo(2, 1, "hello").and; + expect(1).to.be.approximately(1, 2).and; + expect(1).to.be.approximately(1, 2, "hello").and; + expect(1).to.have.members([1, 2, 3]).and; + expect(1).to.have.members([1, 2, 3], "hello").and; + expect(1).to.be.oneOf([1, 2, 3]).and; + expect(1).to.be.oneOf([1, 2, 3], "hello").and; + expect(() => {}).to.change(() => {}).and; + expect(() => {}).to.change({}, "a").and; + expect(() => {}).to.change({}, "a", "hello").and; + expect(() => {}).but.changes(() => {}).and; + expect(() => {}).but.changes({}, "a").and; + expect(() => {}).but.changes({}, "a", "hello").and; + expect(() => {}).to.increase({}).and; + expect(() => {}).to.increase({}, "a").and; + expect(() => {}).to.increase({}, "a", "hello").and; + expect(() => {}).but.increases({}).and; + expect(() => {}).but.increases({}, "a").and; + expect(() => {}).but.increases({}, "a", "hello").and; + expect(() => {}).to.decrease({}).and; + expect(() => {}).to.decrease({}, "a").and; + expect(() => {}).to.decrease({}, "a", "hello").and; + expect(() => {}).but.decreases({}).and; + expect(() => {}).but.decreases({}, "a").and; + expect(() => {}).but.decreases({}, "a", "hello").and; + expect(() => {}).to.decreases({}).by(2).and; + expect(() => {}).to.decreases({}).by(2, "hello").and; + expect({}).to.be.extensible.and; + expect({}).to.be.sealed.and; + expect({}).to.be.frozen.and; + expect({}).to.be.finite.and; + + namespace mockTests { + const s1 = adone.shani.util.spy(); + const s2 = adone.shani.util.spy(); + + expect(s1).to.have.been.called; + expect(s1).to.have.been.calledOnce; + expect(s1).to.have.been.calledTwice; + expect(s1).to.have.been.calledThrice; + expect(s1).to.have.callCount(100); + expect(s1).to.have.been.calledBefore(s2); + expect(s1).to.have.been.calledAfter(s2); + expect(s1).to.have.been.calledImmediatelyAfter(s2); + expect(s1).to.have.been.calledImmediatelyBefore(s2); + expect(s1).to.have.been.calledOn({}); + expect(s1).to.have.been.calledOn({}); + expect(s1).to.have.been.calledWith(1, 2, 3); + expect(s1).to.have.been.calledWithExactly(1, 2, 3); + expect(s1).to.have.returned(1); + expect(s1).to.have.thrown({}); + } + } +} diff --git a/types/adone/test/glosses/common.ts b/types/adone/test/glosses/common.ts new file mode 100644 index 0000000000..c66f6a5410 --- /dev/null +++ b/types/adone/test/glosses/common.ts @@ -0,0 +1,808 @@ +namespace commonTests { + namespace is { + { const a: boolean = adone.is.null({}); } + { const a: boolean = adone.is.undefined({}); } + { const a: boolean = adone.is.exist({}); } + { const a: boolean = adone.is.nil({}); } + { const a: boolean = adone.is.number({}); } + { const a: boolean = adone.is.numeral({}); } + { const a: boolean = adone.is.infinite({}); } + { const a: boolean = adone.is.odd({}); } + { const a: boolean = adone.is.even({}); } + { const a: boolean = adone.is.float({}); } + { const a: boolean = adone.is.negativeZero({}); } + { const a: boolean = adone.is.string({}); } + { const a: boolean = adone.is.emptyString({}); } + { const a: boolean = adone.is.substring("abc", "abcdef"); } + { const a: boolean = adone.is.substring("abc", "abcdef", 0); } + { const a: boolean = adone.is.prefix("abc", "abcdef"); } + { const a: boolean = adone.is.suffix("def", "abbdef"); } + { const a: boolean = adone.is.boolean({}); } + { const a: boolean = adone.is.json({}); } + { const a: boolean = adone.is.object({}); } + { const a: boolean = adone.is.plainObject({}); } + { const a: boolean = adone.is.class({}); } + { const a: boolean = adone.is.emptyObject({}); } + { const a: boolean = adone.is.propertyOwned({}, "a"); } + { const a: boolean = adone.is.propertyDefined({}, "a"); } + { const a: boolean = adone.is.conforms({}, {}); } + { const a: boolean = adone.is.conforms({}, {}, true); } + { const a: boolean = adone.is.arrayLikeObject({}); } + { const a: boolean = adone.is.inArray(1, [1, 2, 3]); } + { const a: boolean = adone.is.inArray(1, [1, 2, 3], 0); } + { const a: boolean = adone.is.inArray(1, [1, 2, 3], 0, (a, b) => a === b); } + { const a: boolean = adone.is.sameType({}, {}); } + { const a: boolean = adone.is.primitive({}); } + { const a: boolean = adone.is.equalArrays([], []); } + { const a: boolean = adone.is.deepEqual({}, {}); } + { const a: boolean = adone.is.shallowEqual({}, {}); } + { const a: boolean = adone.is.stream({}); } + { const a: boolean = adone.is.writableStream({}); } + { const a: boolean = adone.is.readableStream({}); } + { const a: boolean = adone.is.duplexStream({}); } + { const a: boolean = adone.is.transformStream({}); } + { const a: boolean = adone.is.utf8(Buffer.alloc(10)); } + { const a: boolean = adone.is.win32PathAbsolute("abc"); } + { const a: boolean = adone.is.posixPathAbsolute("abc"); } + { const a: boolean = adone.is.pathAbsolute("abc"); } + { const a: boolean = adone.is.glob("abc"); } + { const a: boolean = adone.is.dotfile("abc"); } + { const a: boolean = adone.is.function(() => { }); } + { const a: boolean = adone.is.asyncFunction(async () => { }); } + { const a: boolean = adone.is.promise({}); } + { const a: boolean = adone.is.validDate("07.08.2017"); } + { const a: boolean = adone.is.buffer({}); } + { const a: boolean = adone.is.callback({}); } + { const a: boolean = adone.is.generator({}); } + { const a: boolean = adone.is.nan({}); } + { const a: boolean = adone.is.finite({}); } + { const a: boolean = adone.is.integer({}); } + { const a: boolean = adone.is.safeInteger({}); } + { const a: boolean = adone.is.array({}); } + { const a: boolean = adone.is.uint8Array({}); } + { const a: boolean = adone.is.configuration({}); } + { const a: boolean = adone.is.long({}); } + { const a: boolean = adone.is.bigNumber({}); } + { const a: boolean = adone.is.exbuffer({}); } + { const a: boolean = adone.is.exdate({}); } + { const a: boolean = adone.is.transform({}); } + { const a: boolean = adone.is.subsystem({}); } + { const a: boolean = adone.is.application({}); } + { const a: boolean = adone.is.logger({}); } + { const a: boolean = adone.is.coreStream({}); } + { const a: boolean = adone.is.fastStream({}); } + { const a: boolean = adone.is.fastFSStream({}); } + { const a: boolean = adone.is.fastFSMapStream({}); } + { const a: boolean = adone.is.genesisNetron({}); } + { const a: boolean = adone.is.genesisPeer({}); } + { const a: boolean = adone.is.netronAdapter({}); } + { const a: boolean = adone.is.netron({}); } + { const a: boolean = adone.is.netronPeer({}); } + { const a: boolean = adone.is.netronDefinition({}); } + { const a: boolean = adone.is.netronDefinitions({}); } + { const a: boolean = adone.is.netronReference({}); } + { const a: boolean = adone.is.netronInterface({}); } + { const a: boolean = adone.is.netronContext({}); } + { const a: boolean = adone.is.netronIMethod({}, "hello"); } + { const a: boolean = adone.is.netronIProperty({}, "hello"); } + { const a: boolean = adone.is.netronStub({}); } + { const a: boolean = adone.is.netronRemoteStub({}); } + { const a: boolean = adone.is.netronStream({}); } + { const a: boolean = adone.is.iterable({}); } + { const a: boolean = adone.is.windows; } + { const a: boolean = adone.is.linux; } + { const a: boolean = adone.is.freebsd; } + { const a: boolean = adone.is.darwin; } + { const a: boolean = adone.is.sunos; } + { const a: boolean = adone.is.uppercase("abc"); } + { const a: boolean = adone.is.lowercase("abc"); } + { const a: boolean = adone.is.digits("012"); } + { const a: boolean = adone.is.identifier("someMethod"); } + { const a: boolean = adone.is.binaryExtension("mp3"); } + { const a: boolean = adone.is.binaryPath("a.mp3"); } + { const a: boolean = adone.is.ip4("192.168.1.1"); } + { const a: boolean = adone.is.ip6("::192.168.1.1"); } + { const a: boolean = adone.is.arrayBuffer({}); } + { const a: boolean = adone.is.arrayBufferView({}); } + { const a: boolean = adone.is.date({}); } + { const a: boolean = adone.is.error({}); } + { const a: boolean = adone.is.map({}); } + { const a: boolean = adone.is.regexp({}); } + { const a: boolean = adone.is.set({}); } + { const a: boolean = adone.is.symbol({}); } + { const a: boolean = adone.is.validUTF8({}); } + } + + namespace x { + { const a: Error = new adone.x.Exception(); } + { const a: Error = new adone.x.Exception("message"); } + { const a: Error = new adone.x.Exception(new Error()); } + { const a: Error = new adone.x.Exception(new Error(), true); } + { const a: adone.x.Exception = new adone.x.Runtime(); } + { const a: adone.x.Exception = new adone.x.IncompleteBufferError(); } + { const a: adone.x.Exception = new adone.x.NotImplemented(); } + { const a: adone.x.Exception = new adone.x.IllegalState(); } + { const a: adone.x.Exception = new adone.x.NotValid(); } + { const a: adone.x.Exception = new adone.x.Unknown(); } + { const a: adone.x.Exception = new adone.x.NotExists(); } + { const a: adone.x.Exception = new adone.x.Exists(); } + { const a: adone.x.Exception = new adone.x.Empty(); } + { const a: adone.x.Exception = new adone.x.InvalidAccess(); } + { const a: adone.x.Exception = new adone.x.NotSupported(); } + { const a: adone.x.Exception = new adone.x.InvalidArgument(); } + { const a: adone.x.Exception = new adone.x.InvalidNumberOfArguments(); } + { const a: adone.x.Exception = new adone.x.NotFound(); } + { const a: adone.x.Exception = new adone.x.Timeout(); } + { const a: adone.x.Exception = new adone.x.Incorrect(); } + { const a: adone.x.Exception = new adone.x.NotAllowed(); } + { const a: adone.x.Exception = new adone.x.LimitExceeded(); } + { const a: adone.x.Exception = new adone.x.Encoding(); } + { const a: adone.x.Exception = new adone.x.Network(); } + { const a: adone.x.Exception = new adone.x.Bind(); } + { const a: adone.x.Exception = new adone.x.Connect(); } + { const a: adone.x.Exception = new adone.x.Database(); } + { const a: adone.x.Exception = new adone.x.DatabaseInitialization(); } + { const a: adone.x.Exception = new adone.x.DatabaseOpen(); } + { const a: adone.x.Exception = new adone.x.DatabaseRead(); } + { const a: adone.x.Exception = new adone.x.DatabaseWrite(); } + { const a: adone.x.Exception = new adone.x.NetronIllegalState(); } + { const a: adone.x.Exception = new adone.x.NetronPeerDisconnected(); } + { const a: adone.x.Exception = new adone.x.NetronTimeout(); } + } + + namespace EventEmitter { + namespace static { + const a: number = adone.EventEmitter.listenerCount(new adone.EventEmitter(), "event"); + const b: number = adone.EventEmitter.defaultMaxListeners; + } + + namespace addListener { + const a: adone.EventEmitter = new adone.EventEmitter().addListener("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().addListener(Symbol("event"), () => { }); + } + + namespace on { + const a: adone.EventEmitter = new adone.EventEmitter().on("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().on(Symbol("event"), () => { }); + } + + namespace once { + const a: adone.EventEmitter = new adone.EventEmitter().once("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().once(Symbol("event"), () => { }); + } + + namespace prependListener { + const a: adone.EventEmitter = new adone.EventEmitter().prependListener("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().prependListener(Symbol("event"), () => { }); + } + + namespace prependOnceListener { + const a: adone.EventEmitter = new adone.EventEmitter().prependOnceListener("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().prependOnceListener(Symbol("event"), () => { }); + } + + namespace prependOnceListener { + const a: adone.EventEmitter = new adone.EventEmitter().prependOnceListener("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().prependOnceListener(Symbol("event"), () => { }); + } + + namespace removeListener { + const a: adone.EventEmitter = new adone.EventEmitter().removeListener("event", () => { }); + const b: adone.EventEmitter = new adone.EventEmitter().removeListener(Symbol("event"), () => { }); + } + + namespace removeAllListeners { + const a: adone.EventEmitter = new adone.EventEmitter().removeAllListeners("event"); + const b: adone.EventEmitter = new adone.EventEmitter().removeAllListeners(Symbol("event")); + } + + namespace setMaxListeners { + const a: adone.EventEmitter = new adone.EventEmitter().setMaxListeners(10); + } + + namespace getMaxListeners { + const a: number = new adone.EventEmitter().getMaxListeners(); + } + + namespace listeners { + const a: Array<(...args: any[]) => any> = new adone.EventEmitter().listeners("event"); + const b: Array<(...args: any[]) => any> = new adone.EventEmitter().listeners(Symbol("event")); + } + + namespace emit { + const a: boolean = new adone.EventEmitter().emit("event", 1, 2, 3); + const b: boolean = new adone.EventEmitter().emit(Symbol("event"), 1, 2, 3); + } + + namespace eventNames { + const a: Array = new adone.EventEmitter().eventNames(); + const b: Array = new adone.EventEmitter().eventNames(); + } + + namespace listenerCount { + const a: number = new adone.EventEmitter().listenerCount("event"); + const b: number = new adone.EventEmitter().listenerCount(Symbol("event")); + } + } + + namespace AsyncEmitter { + const a: adone.EventEmitter = new adone.AsyncEmitter(); + new adone.AsyncEmitter(10); + + namespace setConcurrency { + const a: adone.AsyncEmitter = new adone.AsyncEmitter().setConcurrency(); + const b: adone.AsyncEmitter = new adone.AsyncEmitter().setConcurrency(10); + } + + namespace emitParallel { + const a: Promise = new adone.AsyncEmitter().emitParallel("even"); + const b: Promise = new adone.AsyncEmitter().emitParallel("even", 1, 2, 3); + } + + namespace emitSerial { + const a: Promise = new adone.AsyncEmitter().emitSerial("even"); + const b: Promise = new adone.AsyncEmitter().emitSerial("even", 1, 2, 3); + } + + namespace emitReduce { + const a: Promise = new adone.AsyncEmitter().emitReduce("even"); + const b: Promise = new adone.AsyncEmitter().emitReduce("even", 1, 2, 3); + } + + namespace emitReduceRight { + const a: Promise = new adone.AsyncEmitter().emitReduceRight("even"); + const b: Promise = new adone.AsyncEmitter().emitReduceRight("even", 1, 2, 3); + } + + namespace subscribe { + const a: () => void = new adone.AsyncEmitter().subscribe("event", () => { }); + const b: () => void = new adone.AsyncEmitter().subscribe("event", () => { }, true); + } + } + + namespace ExBuffer { + new adone.ExBuffer(); + new adone.ExBuffer(10); + new adone.ExBuffer(10, true); + + const buffer = new adone.ExBuffer(); + + namespace readBitSet { + const a: number[] = buffer.readBitSet(); + const b: number[] = buffer.readBitSet(10); + } + + namespace read { + const a: adone.ExBuffer = buffer.read(1); + const b: adone.ExBuffer = buffer.read(1, 10); + } + + namespace readInt8 { + const a: number = buffer.readInt8(); + const b: number = buffer.readInt8(10); + } + + namespace readUInt8 { + const a: number = buffer.readUInt8(); + const b: number = buffer.readUInt8(10); + } + + namespace readInt16LE { + const a: number = buffer.readInt16LE(); + const b: number = buffer.readInt16LE(10); + } + + namespace readUInt16LE { + const a: number = buffer.readUInt16LE(); + const b: number = buffer.readUInt16LE(10); + } + + namespace readInt16BE { + const a: number = buffer.readInt16BE(); + const b: number = buffer.readInt16BE(10); + } + + namespace readUInt16BE { + const a: number = buffer.readUInt16BE(); + const b: number = buffer.readUInt16BE(10); + } + + namespace readInt32LE { + const a: number = buffer.readInt32LE(); + const b: number = buffer.readInt32LE(10); + } + + namespace readUInt32LE { + const a: number = buffer.readUInt32LE(); + const b: number = buffer.readUInt32LE(10); + } + + namespace readInt32BE { + const a: number = buffer.readInt32BE(); + const b: number = buffer.readInt32BE(10); + } + + namespace readUInt32BE { + const a: number = buffer.readUInt32BE(); + const b: number = buffer.readUInt32BE(10); + } + + namespace readInt64LE { + const a: adone.math.Long = buffer.readInt64LE(); + const b: adone.math.Long = buffer.readInt64LE(10); + } + + namespace readUInt64LE { + const a: adone.math.Long = buffer.readUInt64LE(); + const b: adone.math.Long = buffer.readUInt64LE(10); + } + + namespace readInt64BE { + const a: adone.math.Long = buffer.readInt64BE(); + const b: adone.math.Long = buffer.readInt64BE(10); + } + + namespace readUInt64BE { + const a: adone.math.Long = buffer.readUInt64BE(); + const b: adone.math.Long = buffer.readUInt64BE(10); + } + + namespace readFloatLE { + const a: number = buffer.readFloatLE(); + const b: number = buffer.readFloatLE(10); + } + + namespace readFloatBE { + const a: number = buffer.readFloatBE(); + const b: number = buffer.readFloatBE(10); + } + + namespace readDoubleLE { + const a: number = buffer.readDoubleLE(); + const b: number = buffer.readDoubleLE(10); + } + + namespace readDoubleBE { + const a: number = buffer.readDoubleBE(); + const b: number = buffer.readDoubleBE(10); + } + + namespace write { + const a: adone.ExBuffer = buffer.write("1"); + const b: adone.ExBuffer = buffer.write(new adone.ExBuffer()); + const c: adone.ExBuffer = buffer.write(Buffer.alloc(10)); + const d: adone.ExBuffer = buffer.write(new Uint8Array([1, 2, 3])); + const e: adone.ExBuffer = buffer.write(new ArrayBuffer(10)); + const f: adone.ExBuffer = buffer.write("1", 10); + const g: adone.ExBuffer = buffer.write("1", 10, 10); + const h: adone.ExBuffer = buffer.write("1", 10, 10, "utf8"); + } + + namespace writeBitSet { + const a: adone.ExBuffer = buffer.writeBitSet([1, 2, 3]); + const b: number = buffer.writeBitSet([1, 2, 3], 10); + } + + namespace writeInt8 { + const a: adone.ExBuffer = buffer.writeInt8(10); + const b: adone.ExBuffer = buffer.writeInt8(10, 10); + } + + namespace writeUInt8 { + const a: adone.ExBuffer = buffer.writeUInt8(10); + const b: adone.ExBuffer = buffer.writeUInt8(10, 10); + } + + namespace writeInt16LE { + const a: adone.ExBuffer = buffer.writeInt16LE(10); + const b: adone.ExBuffer = buffer.writeInt16LE(10, 10); + } + + namespace writeInt16BE { + const a: adone.ExBuffer = buffer.writeInt16BE(10); + const b: adone.ExBuffer = buffer.writeInt16BE(10, 10); + } + + namespace writeUInt16LE { + const a: adone.ExBuffer = buffer.writeUInt16LE(10); + const b: adone.ExBuffer = buffer.writeUInt16LE(10, 10); + } + + namespace writeUInt16BE { + const a: adone.ExBuffer = buffer.writeUInt16BE(10); + const b: adone.ExBuffer = buffer.writeUInt16BE(10, 10); + } + + namespace writeInt32LE { + const a: adone.ExBuffer = buffer.writeInt32LE(10); + const b: adone.ExBuffer = buffer.writeInt32LE(10, 10); + } + + namespace writeInt32BE { + const a: adone.ExBuffer = buffer.writeInt32BE(10); + const b: adone.ExBuffer = buffer.writeInt32BE(10, 10); + } + + namespace writeUInt32LE { + const a: adone.ExBuffer = buffer.writeUInt32LE(10); + const b: adone.ExBuffer = buffer.writeUInt32LE(10, 10); + } + + namespace writeUInt32BE { + const a: adone.ExBuffer = buffer.writeUInt32BE(10); + const b: adone.ExBuffer = buffer.writeUInt32BE(10, 10); + } + + namespace writeInt64LE { + const a: adone.ExBuffer = buffer.writeInt64LE(10); + const b: adone.ExBuffer = buffer.writeInt64LE(10, 10); + } + + namespace writeInt64BE { + const a: adone.ExBuffer = buffer.writeInt64BE(10); + const b: adone.ExBuffer = buffer.writeInt64BE(10, 10); + } + + namespace writeUInt64LE { + const a: adone.ExBuffer = buffer.writeUInt64LE(10); + const b: adone.ExBuffer = buffer.writeUInt64LE(10, 10); + } + + namespace writeUInt64BE { + const a: adone.ExBuffer = buffer.writeUInt64BE(10); + const b: adone.ExBuffer = buffer.writeUInt64BE(10, 10); + } + + namespace writeFloatLE { + const a: adone.ExBuffer = buffer.writeFloatLE(10); + const b: adone.ExBuffer = buffer.writeFloatLE(10, 10); + } + + namespace writeFloatBE { + const a: adone.ExBuffer = buffer.writeFloatBE(10); + const b: adone.ExBuffer = buffer.writeFloatBE(10, 10); + } + + namespace writeDoubleLE { + const a: adone.ExBuffer = buffer.writeDoubleLE(10); + const b: adone.ExBuffer = buffer.writeDoubleLE(10, 10); + } + + namespace writeDoubleBE { + const a: adone.ExBuffer = buffer.writeDoubleBE(10); + const b: adone.ExBuffer = buffer.writeDoubleBE(10, 10); + } + + namespace writeVarInt32 { + const a: adone.ExBuffer = buffer.writeVarint32(10); + const b: number = buffer.writeVarint32(10, 10); + } + + namespace writeVarInt32ZigZag { + const a: adone.ExBuffer = buffer.writeVarint32ZigZag(10); + const b: number = buffer.writeVarint32ZigZag(10, 10); + } + + namespace readVarint32 { + const a: number = buffer.readVarint32(); + const b: { value: number, length: number } = buffer.readVarint32(10); + } + + namespace readVarint32ZigZag { + const a: number = buffer.readVarint32ZigZag(); + const b: { value: number, length: number } = buffer.readVarint32ZigZag(10); + } + + namespace writeVarint64 { + const a: adone.ExBuffer = buffer.writeVarint64(10); + const b: number = buffer.writeVarint64(10, 10); + } + + namespace writeVarint64ZigZag { + const a: adone.ExBuffer = buffer.writeVarint64ZigZag(10); + const b: number = buffer.writeVarint64ZigZag(10, 10); + } + + namespace readVarint64 { + const a: adone.math.Long = buffer.readVarint64(); + const b: { value: adone.math.Long, length: number } = buffer.readVarint64(10); + } + + namespace readVarint64ZigZag { + const a: adone.math.Long = buffer.readVarint64ZigZag(); + const b: { value: adone.math.Long, length: number } = buffer.readVarint64ZigZag(10); + } + + namespace writeCString { + const a: adone.ExBuffer = buffer.writeCString("asd"); + const b: number = buffer.writeCString("123", 10); + } + + namespace readCString { + const a: string = buffer.readCString(); + const b: { string: string, length: number } = buffer.readCString(10); + } + + namespace writeString { + const a: adone.ExBuffer = buffer.writeString("abc"); + const b: number = buffer.writeString("abc", 10); + } + + namespace readString { + const a: string = buffer.readString(10); + const b: string = buffer.readString(10, "b"); + const c: string = buffer.readString(10, "c"); + const d: { string: string, length: number } = buffer.readString(10, "c", 10); + } + + namespace writeVString { + const a: adone.ExBuffer = buffer.writeVString("abc"); + const b: number = buffer.writeVString("abc", 10); + } + + namespace readVString { + const a: string = buffer.readVString(); + const b: { string: string, length: number } = buffer.readVString(10); + } + + namespace appendTo { + const a: adone.ExBuffer = buffer.appendTo(new adone.ExBuffer()); + const b: adone.ExBuffer = buffer.appendTo(new adone.ExBuffer(), 10); + } + + namespace assert { + const a: adone.ExBuffer = buffer.assert(); + const b: adone.ExBuffer = buffer.assert(true); + } + + namespace capacity { + const a: number = buffer.capacity(); + } + + namespace clear { + const a: adone.ExBuffer = buffer.clear(); + } + + namespace compact { + const a: adone.ExBuffer = buffer.compact(); + const b: adone.ExBuffer = buffer.compact(1); + const c: adone.ExBuffer = buffer.compact(1, 10); + } + + namespace copyTo { + const a: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer()); + const b: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer(), 0); + const c: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer(), 0, 0); + const d: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer(), 0, 0, 10); + } + + namespace ensureCapacity { + const a: adone.ExBuffer = buffer.ensureCapacity(10); + } + + namespace fill { + const a: adone.ExBuffer = buffer.fill("0"); + const b: adone.ExBuffer = buffer.fill(0); + const c: adone.ExBuffer = buffer.fill(0, 0); + const d: adone.ExBuffer = buffer.fill(0, 0, 10); + } + + namespace flip { + const a: adone.ExBuffer = buffer.flip(); + } + + namespace mark { + const a: adone.ExBuffer = buffer.mark(); + const b: adone.ExBuffer = buffer.mark(10); + } + + namespace prepend { + const a: adone.ExBuffer = buffer.prepend(""); + const b: adone.ExBuffer = buffer.prepend(new adone.ExBuffer()); + const c: adone.ExBuffer = buffer.prepend(Buffer.alloc(10)); + const d: adone.ExBuffer = buffer.prepend(new Uint8Array([1, 2, 3])); + const e: adone.ExBuffer = buffer.prepend(new ArrayBuffer(10)); + const f: adone.ExBuffer = buffer.prepend("", "utf8"); + const g: adone.ExBuffer = buffer.prepend("", "utf8", 10); + const h: adone.ExBuffer = buffer.prepend("", 10); + } + + namespace prependTo { + const a: adone.ExBuffer = buffer.prependTo(new adone.ExBuffer()); + const b: adone.ExBuffer = buffer.prependTo(new adone.ExBuffer(), 10); + } + + namespace remaining { + const a: number = buffer.remaining(); + } + + namespace reset { + const a: adone.ExBuffer = buffer.reset(); + } + + namespace resize { + const a: adone.ExBuffer = buffer.resize(10); + } + + namespace reverse { + const a: adone.ExBuffer = buffer.reverse(); + const b: adone.ExBuffer = buffer.reverse(1); + const c: adone.ExBuffer = buffer.reverse(1, 10); + } + + namespace skip { + const a: adone.ExBuffer = buffer.skip(10); + } + + namespace slice { + const a: adone.ExBuffer = buffer.slice(); + const b: adone.ExBuffer = buffer.slice(1); + const c: adone.ExBuffer = buffer.slice(1, 10); + } + + namespace toBuffer { + const a: Buffer = buffer.toBuffer(); + const b: Buffer = buffer.toBuffer(true); + const c: Buffer = buffer.toBuffer(true, 0); + const d: Buffer = buffer.toBuffer(true, 0, 10); + } + + namespace toArrayBuffer { + const a: ArrayBuffer = buffer.toArrayBuffer(); + } + + namespace toString { + const a: string = buffer.toString(); + const b: string = buffer.toString("utf8"); + const c: string = buffer.toString("utf8", 0); + const d: string = buffer.toString("utf8", 0, 10); + } + + namespace toBase64 { + const a: string = buffer.toBase64(); + const b: string = buffer.toBase64(0); + const c: string = buffer.toBase64(0, 10); + } + + namespace toBinary { + const a: string = buffer.toBinary(); + const b: string = buffer.toBinary(0); + const c: string = buffer.toBinary(0, 10); + } + + namespace toDebug { + const a: string = buffer.toDebug(); + const b: string = buffer.toDebug(true); + } + + namespace toUTF8 { + const a: string = buffer.toUTF8(); + const b: string = buffer.toUTF8(0); + const c: string = buffer.toUTF8(0, 10); + } + + namespace static { + namespace accessor { + const a: typeof Buffer = adone.ExBuffer.accessor(); + } + + namespace allocate { + const a: adone.ExBuffer = adone.ExBuffer.allocate(); + const b: adone.ExBuffer = adone.ExBuffer.allocate(10); + const c: adone.ExBuffer = adone.ExBuffer.allocate(10, true); + } + + namespace concat { + const a: adone.ExBuffer = adone.ExBuffer.concat([ + new adone.ExBuffer(), + Buffer.alloc(10), + new Uint8Array([1, 2, 3]), + new ArrayBuffer(10) + ]); + const b: adone.ExBuffer = adone.ExBuffer.concat([ + new adone.ExBuffer(), + Buffer.alloc(10), + new Uint8Array([1, 2, 3]), + new ArrayBuffer(10) + ], "utf8"); + const c: adone.ExBuffer = adone.ExBuffer.concat([ + new adone.ExBuffer(), + Buffer.alloc(10), + new Uint8Array([1, 2, 3]), + new ArrayBuffer(10) + ], "utf8", true); + } + + namespace type { + const a: typeof Buffer = adone.ExBuffer.type(); + } + + namespace wrap { + const a: adone.ExBuffer = adone.ExBuffer.wrap(""); + const b: adone.ExBuffer = adone.ExBuffer.wrap(new adone.ExBuffer()); + const c: adone.ExBuffer = adone.ExBuffer.wrap(Buffer.alloc(10)); + const d: adone.ExBuffer = adone.ExBuffer.wrap(new Uint8Array([1, 2, 3])); + const e: adone.ExBuffer = adone.ExBuffer.wrap(new ArrayBuffer(10)); + const f: adone.ExBuffer = adone.ExBuffer.wrap("", "utf8"); + const g: adone.ExBuffer = adone.ExBuffer.wrap("", "utf8", true); + } + + namespace calculateVarint32 { + const a: number = adone.ExBuffer.calculateVarint32(10); + } + + namespace zigZagEncode32 { + const a: number = adone.ExBuffer.zigZagEncode32(10); + } + + namespace zigZagDecode32 { + const a: number = adone.ExBuffer.zigZagDecode32(10); + } + + namespace calculateVarint64 { + const a: number = adone.ExBuffer.calculateVarint64(10); + const b: number = adone.ExBuffer.calculateVarint64("10"); + } + + namespace zigZagEncode64 { + const a: adone.math.Long = adone.ExBuffer.zigZagEncode64(10); + const b: adone.math.Long = adone.ExBuffer.zigZagEncode64("10"); + const c: adone.math.Long = adone.ExBuffer.zigZagEncode64(adone.math.Long.fromValue(10)); + } + + namespace zigZagDecode64 { + const a: adone.math.Long = adone.ExBuffer.zigZagDecode64(10); + const b: adone.math.Long = adone.ExBuffer.zigZagDecode64("10"); + const c: adone.math.Long = adone.ExBuffer.zigZagDecode64(adone.math.Long.fromValue(10)); + } + + namespace calculateUTF8Chars { + const a: number = adone.ExBuffer.calculateUTF8Chars("123"); + } + + namespace calculateString { + const a: number = adone.ExBuffer.calculateString("123"); + } + + namespace fromBase64 { + const a: adone.ExBuffer = adone.ExBuffer.fromBase64("123"); + } + + namespace btoa { + const a: string = adone.ExBuffer.btoa("123"); + } + + namespace atob { + const a: string = adone.ExBuffer.atob("123"); + } + + namespace fromBinary { + const a: adone.ExBuffer = adone.ExBuffer.fromBinary("123"); + } + + namespace fromDebug { + const a: adone.ExBuffer = adone.ExBuffer.fromDebug("12"); + const b: adone.ExBuffer = adone.ExBuffer.fromDebug("12", true); + } + + namespace fromHex { + const a: adone.ExBuffer = adone.ExBuffer.fromHex("192"); + const b: adone.ExBuffer = adone.ExBuffer.fromHex("192", true); + } + + namespace fromUTF8 { + const a: adone.ExBuffer = adone.ExBuffer.fromUTF8("123"); + const b: adone.ExBuffer = adone.ExBuffer.fromUTF8("123", true); + } + + namespace constants { + const a: number = adone.ExBuffer.DEFAULT_CAPACITY; + const b: boolean = adone.ExBuffer.DEFAULT_NOASSERT; + const c: number = adone.ExBuffer.MAX_VARINT32_BYTES; + const d: number = adone.ExBuffer.MAX_VARINT64_BYTES; + const e: string = adone.ExBuffer.METRICS_CHARS; + const f: string = adone.ExBuffer.METRICS_BYTES; + } + } + } +} diff --git a/types/adone/test/glosses/math.ts b/types/adone/test/glosses/math.ts new file mode 100644 index 0000000000..8a9e9bc1cf --- /dev/null +++ b/types/adone/test/glosses/math.ts @@ -0,0 +1,259 @@ +const { math } = adone; + +namespace mathTests { + namespace Long { + new math.Long(); + new math.Long(0); + new math.Long(0, 0); + new math.Long(0, 0, true); + + namespace toInt { + const a: number = new math.Long().toInt(); + } + + namespace toNumber { + const a: number = new math.Long().toNumber(); + } + + namespace toString { + const a: string = new math.Long().toString(); + const b: string = new math.Long().toString(16); + } + + namespace getHighBits { + const a: number = new math.Long().getHighBits(); + } + + namespace getLowBits { + const a: number = new math.Long().getLowBits(); + } + + namespace getLowBitsUnsigned { + const a: number = new math.Long().getLowBitsUnsigned(); + } + + namespace getHighBitsUnsigned { + const a: number = new math.Long().getHighBitsUnsigned(); + } + + namespace getNumBitsAbs { + const a: number = new math.Long().getNumBitsAbs(); + } + + namespace isZero { + const a: boolean = new math.Long().isZero(); + } + + namespace isNegative { + const a: boolean = new math.Long().isNegative(); + } + + namespace isPositive { + const a: boolean = new math.Long().isPositive(); + } + + namespace isOdd { + const a: boolean = new math.Long().isOdd(); + } + + namespace isEven { + const a: boolean = new math.Long().isEven(); + } + + namespace equals { + const a = new math.Long(); + const b: boolean = a.equals(new math.Long()); + const c: boolean = a.equals(1); + const d: boolean = a.equals("1"); + const e: boolean = a.equals({ low: 0, high: 0 }); + } + + namespace lessThan { + const a = new math.Long(); + const b: boolean = a.lessThan(new math.Long()); + const c: boolean = a.lessThan(1); + const d: boolean = a.lessThan("1"); + const e: boolean = a.lessThan({ low: 0, high: 0 }); + } + + namespace lessThanOrEqual { + const a = new math.Long(); + const b: boolean = a.lessThanOrEqual(new math.Long()); + const c: boolean = a.lessThanOrEqual(1); + const d: boolean = a.lessThanOrEqual("1"); + const e: boolean = a.lessThanOrEqual({ low: 0, high: 0 }); + } + + namespace greaterThan { + const a = new math.Long(); + const b: boolean = a.greaterThan(new math.Long()); + const c: boolean = a.greaterThan(1); + const d: boolean = a.greaterThan("1"); + const e: boolean = a.greaterThan({ low: 0, high: 0 }); + } + + namespace greaterThanOrEqual { + const a = new math.Long(); + const b: boolean = a.greaterThanOrEqual(new math.Long()); + const c: boolean = a.greaterThanOrEqual(1); + const d: boolean = a.greaterThanOrEqual("1"); + const e: boolean = a.greaterThanOrEqual({ low: 0, high: 0 }); + } + + namespace greaterThanOrEqual { + const a = new math.Long(); + const b: number = a.compare(new math.Long()); + const c: number = a.compare(1); + const d: number = a.compare("1"); + const e: number = a.compare({ low: 0, high: 0 }); + } + + namespace negate { + const a: adone.math.Long = new math.Long().negate(); + } + + namespace add { + const a = new math.Long(); + const b: adone.math.Long = a.add(new math.Long()); + const c: adone.math.Long = a.add(1); + const d: adone.math.Long = a.add("1"); + const e: adone.math.Long = a.add({ low: 0, high: 0 }); + } + + namespace sub { + const a = new math.Long(); + const b: adone.math.Long = a.sub(new math.Long()); + const c: adone.math.Long = a.sub(1); + const d: adone.math.Long = a.sub("1"); + const e: adone.math.Long = a.sub({ low: 0, high: 0 }); + } + + namespace mul { + const a = new math.Long(); + const b: adone.math.Long = a.mul(new math.Long()); + const c: adone.math.Long = a.mul(1); + const d: adone.math.Long = a.mul("1"); + const e: adone.math.Long = a.mul({ low: 0, high: 0 }); + } + + namespace div { + const a = new math.Long(); + const b: adone.math.Long = a.div(new math.Long()); + const c: adone.math.Long = a.div(1); + const d: adone.math.Long = a.div("1"); + const e: adone.math.Long = a.div({ low: 0, high: 0 }); + } + + namespace mod { + const a = new math.Long(); + const b: adone.math.Long = a.mod(new math.Long()); + const c: adone.math.Long = a.mod(1); + const d: adone.math.Long = a.mod("1"); + const e: adone.math.Long = a.mod({ low: 0, high: 0 }); + } + + namespace not { + const a: adone.math.Long = new math.Long().not(); + } + + namespace and { + const a = new math.Long(); + const b: adone.math.Long = a.and(new math.Long()); + const c: adone.math.Long = a.and(1); + const d: adone.math.Long = a.and("1"); + const e: adone.math.Long = a.and({ low: 0, high: 0 }); + } + + namespace or { + const a = new math.Long(); + const b: adone.math.Long = a.or(new math.Long()); + const c: adone.math.Long = a.or(1); + const d: adone.math.Long = a.or("1"); + const e: adone.math.Long = a.or({ low: 0, high: 0 }); + } + + namespace xor { + const a = new math.Long(); + const b: adone.math.Long = a.xor(new math.Long()); + const c: adone.math.Long = a.xor(1); + const d: adone.math.Long = a.xor("1"); + const e: adone.math.Long = a.xor({ low: 0, high: 0 }); + } + + namespace shl { + const a = new math.Long(); + const b: adone.math.Long = a.shl(new math.Long()); + const c: adone.math.Long = a.shl(1); + } + + namespace shr { + const a = new math.Long(); + const b: adone.math.Long = a.shr(new math.Long()); + const c: adone.math.Long = a.shr(1); + } + + namespace shru { + const a = new math.Long(); + const b: adone.math.Long = a.shr(new math.Long()); + const c: adone.math.Long = a.shr(1); + } + + namespace toSigned { + const a: adone.math.Long = new math.Long().toSigned(); + } + + namespace toUnsigned { + const a: adone.math.Long = new math.Long().toUnsigned(); + } + + namespace toBytes { + const a: number[] = new math.Long().toBytes(); + } + + namespace toBytesLE { + const a: number[] = new math.Long().toBytesLE(); + } + + namespace static { + namespace fromInt { + const a: adone.math.Long = math.Long.fromInt(123); + const b: adone.math.Long = math.Long.fromInt(123, true); + } + + namespace fromNumber { + const a: adone.math.Long = math.Long.fromNumber(123); + const b: adone.math.Long = math.Long.fromNumber(123, true); + } + + namespace fromBits { + const a: adone.math.Long = math.Long.fromBits(0, 0); + const b: adone.math.Long = math.Long.fromBits(123, 0, true); + } + + namespace fromString { + const a: adone.math.Long = math.Long.fromString("123"); + const b: adone.math.Long = math.Long.fromString("123", true); + const c: adone.math.Long = math.Long.fromString("123", 16); + const d: adone.math.Long = math.Long.fromString("123", true, 16); + } + + namespace fromValue { + const a: adone.math.Long = math.Long.fromValue(new math.Long()); + const b: adone.math.Long = math.Long.fromValue(1); + const c: adone.math.Long = math.Long.fromValue("1"); + const e: adone.math.Long = math.Long.fromValue({ low: 0, high: 0 }); + } + + namespace constants { + const a: adone.math.Long = math.Long.MIN_VALUE; + const b: adone.math.Long = math.Long.MAX_VALUE; + const c: adone.math.Long = math.Long.MAX_UNSIGNED_VALUE; + const d: adone.math.Long = math.Long.ZERO; + const e: adone.math.Long = math.Long.UZERO; + const f: adone.math.Long = math.Long.ONE; + const g: adone.math.Long = math.Long.UONE; + const h: adone.math.Long = math.Long.NEG_ONE; + } + } + } +} diff --git a/types/adone/test/glosses/promise.ts b/types/adone/test/glosses/promise.ts new file mode 100644 index 0000000000..c16d1a4852 --- /dev/null +++ b/types/adone/test/glosses/promise.ts @@ -0,0 +1,97 @@ +namespace promiseTests { + const { promise } = adone; + + namespace defer { + const a = promise.defer(); + a.promise.then((x) => 2); + a.resolve(2); + a.reject(3); + const b = promise.defer(); + b.resolve("3"); + b.reject(2); + b.promise.then((x: string) => x); + } + + namespace delay { + const a: Promise = promise.delay(10); + const b: Promise = promise.delay(10, 2); + promise.delay(20, "3").then((x: string) => x); + } + + namespace timeout { + promise.timeout(Promise.resolve(2), 100).then((x: number) => x); + } + + namespace nodeify { + promise.nodeify(Promise.resolve(2), (err: any, value: number) => value).then((x: number) => x); + promise.nodeify(Promise.resolve(2), () => 42).then((x: number) => x); + } + + namespace promisify { + type Callback = (err?: any, result?: T) => void; + namespace noargs { + const f = (cb: Callback) => { + cb(null, 32); + }; + promise.promisify(f)().then((x: number) => { }); + } + namespace nargs1 { + const f = (a: number, cb: Callback) => { + cb(null, 32); + }; + promise.promisify(f)(1).then((x: number) => { }); + } + + namespace nargs2 { + const f = (a: number, b: string, cb: Callback) => { + cb(null, 32); + }; + promise.promisify(f)(1, "1").then((x: number) => { }); + } + + namespace nargs3 { + const f = (a: number, b: string, c: number, cb: Callback) => { + cb(null, 32); + }; + promise.promisify(f)(1, "1", 1).then((x: number) => { }); + } + + namespace nargs4 { + const f = (a: number, b: string, c: number, d: string, cb: Callback) => { + cb(null, 32); + }; + promise.promisify(f)(1, "1", 1, "1").then((x: number) => { }); + } + + namespace nargs5 { + const f = (a: number, b: string, c: number, d: string, e: number, cb: Callback) => { + cb(null, 32); + }; + promise.promisify(f)(1, "1", 1, "1", 1).then((x: number) => { }); + } + + namespace moreargs { + const f = (a: number, b: string, c: number, d: string, e: number, f: string, cb: Callback) => { + cb(null, 32); + }; + promise.promisify(f)(1, 2, 3).then((x) => x); + } + + namespace options { + promise.promisify((cb: Callback) => cb(null, 42), {}); + promise.promisify((cb: Callback) => cb(null, 42), { context: {} }); + } + } + + namespace promisifyAll { + const a: object = promise.promisifyAll({}); + promise.promisifyAll({}, {}); + promise.promisifyAll({}, { context: {} }); + promise.promisifyAll({}, { filter: () => true }); + promise.promisifyAll({}, { suffix: "Async" }); + } + + namespace _finally { + promise.finally(Promise.resolve(2), () => 2).then((x: number) => {}); + } +} diff --git a/types/adone/test/glosses/shani-global.ts b/types/adone/test/glosses/shani-global.ts new file mode 100644 index 0000000000..b59dce4b6a --- /dev/null +++ b/types/adone/test/glosses/shani-global.ts @@ -0,0 +1,163 @@ +namespace shaniGlobalTests { + namespace describeTests { + describe("hello", () => {}); + + describe("hello", function () { + this.skip(); + this.timeout(10); + this.a; + }); + + describe("1", "2", "3", "4", "45", function () { + this.skip(); + this.timeout(10); + this.a; + }); + + describe("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", function () { + this.skip(); + this.timeout(10); + this.a; + }); + + context("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", function () { + this.skip(); + this.timeout(10); + this.a; + }); + } + + namespace itTests { + it("should be here", () => {}); + + it("should be here", function () { + this.timeout(100); + this.skip(); + this.a; + }); + + it("should be here", function (done: () => void) { + this.timeout(1000); + done(); + this.a; + }); + + it("hello", {}, () => {}); + + it("hello", { + skip: true + }, () => {}); + + it("hello", { + skip: () => true + }, () => {}); + + it("hello", { + timeout: () => 1202 + }, () => {}); + + it("hello", { + timeout: 1010 + }, () => {}); + + it("hello", { + before() {} + }, () => {}); + + it("hello", { + before: ["hello", () => {}] + }, () => {}); + + it("hello", { + after() {} + }, () => {}); + + it("hello", { + after: ["hello", () => {}] + }, () => {}); + + specify("hello", { + after: ["hello", () => {}] + }, () => {}); + } + + namespace beforeTests { + before(function() { + this.timeout(100); + this.a; + }); + + before("description", function () { + this.timeout(100); + this.a; + }); + + before("description", function (done) { + this.timeout(100); + done(); + this.a; + }); + } + + namespace afterTests { + after(function () { + this.timeout(10); + this.a; + }); + + after("description", function () { + this.timeout(10); + this.a; + }); + + after("description", function (done) { + this.timeout(10); + this.a; + }); + } + + namespace beforeEachTests { + beforeEach(function () { + this.timeout(100); + this.a; + }); + + beforeEach("hello", function () { + this.timeout(100); + this.a; + }); + + beforeEach("hello", function (done) { + this.timeout(100); + done(); + this.a; + }); + } + + namespace afterEachTests { + afterEach(function () { + this.timeout(100); + this.a; + }); + + afterEach("asd", function () { + this.timeout(100); + this.a; + }); + + afterEach("asd", function (done) { + this.timeout(100); + done(); + this.a; + }); + } + + expect(1).to.be.a("number"); + assert.equal(1, 1); + fakeClock.install().tick(100); + stub()(1, 2, 3); + expect(spy()).to.have.been.calledOnce; + match(2).and(match(2)); + mock().alwaysCalledOn({}); + request({}).expectBody(""); +} diff --git a/types/adone/test/glosses/shani.ts b/types/adone/test/glosses/shani.ts new file mode 100644 index 0000000000..1c09ef3837 --- /dev/null +++ b/types/adone/test/glosses/shani.ts @@ -0,0 +1,544 @@ +namespace shaniTests { + const { shani } = adone; + + namespace engineOptionsTests { + new shani.Engine(); + new shani.Engine({}); + new shani.Engine({ callGc: true }); + new shani.Engine({ defaultTimeout: 1000 }); + new shani.Engine({ defaultHookTimeout: 1000 }); + new shani.Engine({ transpilerOptions: {} }); + } + + namespace contextTests { + const e = new adone.shani.Engine(); + const c = e.context(); + + namespace describeTests { + c.describe("hello", () => {}); + + c.describe("hello", function () { + this.skip(); + this.timeout(10); + this.a; + }); + + c.describe("1", "2", "3", "4", "45", function () { + this.skip(); + this.timeout(10); + this.a; + }); + + c.describe("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", function () { + this.skip(); + this.timeout(10); + this.a; + }); + + c.context("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", function () { + this.skip(); + this.timeout(10); + this.a; + }); + } + + namespace itTests { + c.it("should be here", () => {}); + + c.it("should be here", function () { + this.timeout(100); + this.skip(); + this.a; + }); + + c.it("should be here", function (done) { + this.timeout(100); + this.skip(); + done(); + this.a; + }); + + c.it("hello", {}, () => { }); + + c.it("hello", { + skip: true + }, () => { }); + + c.it("hello", { + skip: () => true + }, () => { }); + + c.it("hello", { + timeout: () => 1202 + }, () => { }); + + c.it("hello", { + timeout: 1010 + }, () => { }); + + c.it("hello", { + before() { } + }, () => { }); + + c.it("hello", { + before: ["hello", () => { }] + }, () => { }); + + c.it("hello", { + after() { } + }, () => { }); + + c.it("hello", { + after: ["hello", () => { }] + }, () => { }); + + c.specify("hello", { + after: ["hello", () => { }] + }, () => { }); + } + + namespace beforeTests { + c.before(function () { + this.timeout(100); + this.a; + }); + + c.before("description", function () { + this.timeout(100); + this.a; + }); + + c.before("description", function (done) { + this.timeout(100); + done(); + this.a; + }); + } + + namespace afterTests { + c.after(function () { + this.timeout(10); + this.a; + }); + + c.after("description", function () { + this.timeout(10); + this.a; + }); + + c.after("description", function (done) { + this.timeout(10); + done(); + this.a; + }); + } + + namespace beforeEachTests { + c.beforeEach(function () { + this.timeout(100); + this.a; + }); + + c.beforeEach("hello", function () { + this.timeout(100); + this.a; + }); + + c.beforeEach("hello", function (done) { + this.timeout(100); + done(); + this.a; + }); + } + + namespace afterEachTests { + c.afterEach(function () { + this.timeout(100); + this.a; + }); + + c.afterEach("asd", function () { + this.timeout(100); + this.a; + }); + + c.afterEach("asd", function (done) { + this.timeout(100); + done(); + this.a; + }); + } + + namespace rootTests { + const { root } = c; + root.children[0]; + root.prepare().then((x) => { }); + root.addChild(root); + const check = (hook: adone.shani.I.Hook) => { + hook.run().then((x) => x); + hook.cause(); + hook.failed() === true; + hook.timeout() + 2; + hook.timeout(10).timeout(10).timeout() + 2; + }; + for (const hook of root.beforeHooks()) { + check(hook); + } + for (const hook of root.afterHooks()) { + check(hook); + } + for (const hook of root.beforeEachHooks()) { + check(hook); + } + for (const hook of root.afterEachHooks()) { + check(hook); + } + root.isInclusive() === true; + root.isExclusive() === false; + root.hasInclusive() === true; + root.skip().only().skip(); + const a: number | null = root.timeout(); + root.timeout(100).timeout(100); + root.level() + 2; + root.level(2).level() + 2; + root.chain().toLowerCase(); + root.blockChain()[0].blockChain()[0].addChild(root); + } + + namespace eventEmitterTests { + const a = c.start(); + a.on("enter block", ({ block }) => { + block.addChild(block); + }).on("exit block", ({ block }) => { + block.addChild(block); + }).on("start test", ({ block, test }) => { + block.addChild(test); + test.chain(); + }).on("end test", ({ block, test, meta }) => { + block.addChild(test); + test.chain(); + meta.err; + meta.elapsed + 2; + }).on("start before hook", ({ block, hook }) => { + block.addChild(block); + hook.desctiption; + }).on("end before hook", ({ block, hook, meta }) => { + block.addChild(block); + hook.desctiption; + meta.err; + meta.elapsed; + }).on("start after hook", ({ block, hook }) => { + block.addChild(block); + hook.desctiption; + }).on("end after hook", ({ block, hook, meta }) => { + block.addChild(block); + hook.desctiption; + meta.err; + meta.elapsed; + }).on("start before each hook", ({ block, hook }) => { + block.addChild(block); + hook.desctiption; + }).on("end before each hook", ({ block, hook, meta }) => { + block.addChild(block); + hook.desctiption; + meta.err; + meta.elapsed; + }).on("start after each hook", ({ block, hook }) => { + block.addChild(block); + hook.desctiption; + }).on("end after each hook", ({ block, hook, meta }) => { + block.addChild(block); + hook.desctiption; + meta.err; + meta.elapsed; + }).on("start before test hook", ({ block, hook }) => { + block.addChild(block); + hook.desctiption; + }).on("end before test hook", ({ block, hook, meta }) => { + block.addChild(block); + hook.desctiption; + meta.err; + meta.elapsed; + }).on("start after test hook", ({ block, hook }) => { + block.addChild(block); + hook.desctiption; + }).on("end after test hook", ({ block, hook, meta }) => { + block.addChild(block); + hook.desctiption; + meta.err; + meta.elapsed; + }).on("error", (err) => {}).on("done", () => {}).stop(); + } + } + + namespace utilTests { + const { util } = shani; + + namespace spyCallTests { + const call = util.spy().firstCall; + call.calledBefore(call) === true; + call.calledAfter(call) === true; + call.calledWithNew(call) === true; + call.thisValue; + call.args[0]; + call.exception; + call.returnValue; + call.calledOn({}) === true; + call.calledWith(1, 2, 3) === true; + call.calledWithExactly(1, 2, 3) === true; + call.calledWithMatch(1, 2, 3) === true; + call.notCalledWith(1, 2, 3) === true; + call.notCalledWithMatch(1, 2, 3) === true; + call.returned(1) === true; + call.threw() === true; + call.threw("12") === true; + call.threw({}) === true; + call.callArg(1); + call.callArgOn(1, {}); + call.callArgWith(1, 1, 2, 3); + call.callArgOnWith(1, {}, 1, 2, 3); + call.yield(1, 2, 3); + call.yieldOn({}, 1, 2, 3); + call.yieldToOn("a", {}, 1, 2, 3); + } + + namespace spyTests { + util.spy().alwaysCalledOn({}); + util.spy(() => { }).alwaysCalledOn({}); + const a: number = util.spy().callCount; + const s = util.spy(); + s.called === true; + s.notCalled === true; + s.calledOnce === true; + s.calledTwice === true; + s.calledThrice === true; + s.firstCall.args; + s.secondCall.args; + s.thirdCall.args; + s.lastCall.args; + s.thisValues[0]; + s.args[0][0]; + s.exceptions[0]; + s.returnValues[0]; + s(1, 2, 3); + s.calledBefore(s); + s.calledAfter(s); + s.calledImmediatelyAfter(s); + s.calledImmediatelyBefore(s); + s.calledWithNew() === true; + s.withArgs(1, 2, 3).firstCall.args; + s.alwaysCalledOn({}) === true; + s.alwaysCalledWith(1, 2, 3) === true; + s.alwaysCalledWithExactly(1, 2, 3) === true; + s.alwaysCalledWithMatch(1, 2, 3) === true; + s.neverCalledWith(1, 2, 3) === true; + s.neverCalledWithMatch(1, 2, 3) === true; + s.alwaysThrew() === true; + s.alwaysThrew("a") === true; + s.alwaysThrew({}) === true; + s.alwaysReturned({}) === true; + s.invokeCallback(1, 2, 3); + s.getCall(0).args; + s.getCalls()[0].args; + s.reset(); + s.printf("%s", "1").toLowerCase(); + s.restore(); + } + + namespace stubTests { + util.stub({}); + class A { + a() {} + } + util.stub(new A(), "a").resetHistory(); + const s = util.stub(); + s.resetBehavior(); + s.resetHistory(); + s.usingPromise({}).alwaysCalledOn(2); + s.returns({}).resetBehavior(); + s.returnsArg(1).resetBehavior(); + s.returnsThis().resetBehavior(); + s.resolves().resetBehavior(); + s.resolves(1).resetBehavior(); + s.throws().resetBehavior(); + s.throws("1").resetBehavior(); + s.throwsArg(1).resetBehavior(); + s.throwsException().resetBehavior(); + s.throwsException("1").resetBehavior(); + s.throwsException({}).resetBehavior(); + s.rejects().resetBehavior(); + s.rejects("string").resetBehavior(); + s.rejects(1).resetBehavior(); + s.callsArg(1).resetBehavior(); + s.callThrough().resetBehavior(); + s.callsArgOn(1, {}).resetBehavior(); + s.callsArgOnWith(1, {}, 123).resetBehavior(); + s.callsArgAsync(1).resetBehavior(); + s.callsArgOnAsync(1, {}).resetBehavior(); + s.callsArgOnWithAsync(1, {}, 1, 2, 3).resetBehavior(); + s.callsFake(() => { }).resetBehavior(); + s.get(() => { }).resetBehavior(); + s.set((v) => 1).resetBehavior(); + s.onCall(1).resetBehavior(); + s.onFirstCall().resetBehavior(); + s.onSecondCall().resetBehavior(); + s.onThirdCall().resetBehavior(); + s.value(1).resetBehavior(); + s.yields(1, 2, 3).resetBehavior(); + s.yieldsOn({}, 1, 2).resetBehavior(); + s.yieldsRight(1, 2, 3).resetBehavior(); + s.yieldsTo("a", 1, 2, 3).resetBehavior(); + s.yieldsToOn("a", {}, 1, 2, 3).resetBehavior(); + s.yieldsAsync(1, 2, 3).resetBehavior(); + s.yieldsOnAsync({}, 1, 2, 3).resetBehavior(); + s.yieldsToAsync("a", 1, 2, 3).resetBehavior(); + s.yieldsToOnAsync("1", {}, 1, 2, 3).resetBehavior(); + s.withArgs(1, 2, 3).resetBehavior(); + } + + namespace expectationTests { + util.expectation.create(""); + const e = util.expectation.create(); + e.atLeast(1).never(); + e.atMost(2).never(); + e.never().never(); + e.once().never(); + e.twice().never(); + e.thrice().never(); + e.exactly(1).never(); + e.withArgs(1, 2, 3).never(); + e.withExactArgs(1, 2, 3).never(); + e.on({}).never(); + e.verify().never(); + e.restore(); + } + + namespace mockTests { + util.mock().never(); + util.mock({}).expects("").restore(); + util.mock({}).verify(); + } + + namespace assertTests { + util.assert.failException; + util.assert.fail(); + util.assert.fail("1"); + util.assert.pass(1); + const s = util.spy(); + util.assert.notCalled(s); + util.assert.called(s); + util.assert.calledOnce(s); + util.assert.calledTwice(s); + util.assert.calledThrice(s); + util.assert.callCount(s, 10); + util.assert.callOrder(s, s, s, s); + util.assert.calledOn(s, {}); + util.assert.calledOn(s, {}); + util.assert.alwaysCalledOn(s, {}); + util.assert.calledWith(s, {}); + util.assert.neverCalledWith(s, {}); + util.assert.calledWithExactly(s, {}); + util.assert.alwaysCalledWithExactly(s, {}); + util.assert.calledWithMatch(s, {}); + util.assert.alwaysCalledWithMatch(s, {}); + util.assert.neverCalledWithMatch(s, {}); + util.assert.threw(s); + util.assert.threw(s, "a"); + util.assert.threw(s, {}); + util.assert.alwaysThrew(s); + util.assert.alwaysThrew(s, ""); + util.assert.alwaysThrew(s, {}); + util.assert.expose({}); + util.assert.expose({}, { includeFail: true }); + util.assert.expose({}, { prefix: "a" }); + } + + namespace matchTests { + util.match(1).and(util.match(1)); + util.match("1").and(util.match(1)); + util.match(/1/).and(util.match(1)); + util.match({}).and(util.match(1)); + util.match((v: any) => true).and(util.match(1)); + util.match((v: any) => true, "a").and(util.match(1)); + util.match.any.and; + util.match.defined.and; + util.match.truthy.and; + util.match.falsy.and; + util.match.bool.and; + util.match.number.and; + util.match.string.and; + util.match.object.and; + util.match.func.and; + util.match.map.contains(new Map()); + util.match.map.deepEquals(new Map()); + util.match.set.contains(new Set()); + util.match.array.contains([]); + util.match.array.deepEquals([]); + util.match.array.endsWith([]); + util.match.array.startsWith([]); + util.match.regexp.and; + util.match.date.and; + util.match.symbol.and; + util.match.same({}).and; + util.match.typeOf("string").and; + util.match.instanceOf({}).and; + util.match.has("a").and; + util.match.has("a", {}).and; + util.match.hasOwn("a").and; + util.match.hasOwn("a", {}).and; + } + + namespace sandboxTests { + util.sandbox.create(); + util.sandbox.create({}); + util.sandbox.create({ injectInto: {} }); + util.sandbox.create({ properties: ["a"] }); + const s = util.sandbox.create(); + s.assert.alwaysCalledOn(s.spy(), {}); + s.spy().args; + s.stub().args; + s.mock().args; + s.restore(); + s.reset(); + s.resetHistory(); + s.resetBehavior(); + s.usingPromise({}).reset(); + s.verify(); + s.verifyAndRestore(); + } + } + + namespace requestTests { + const r = request({}); + r.get("/").head("/").post("/").put("/").options("/"); + r.attach("fname", "hello"); + r.attach("fname", "hello", {}); + r.attach("fname", "hello", { type: "application/javascript" }); + r.attach("fname", "hello", { filename: "a.js" }); + r.field("a", "basd"); + r.send("asd"); + r.setHeader("Cookie", "key=value"); + r.auth("user", "pass"); + r.expect(() => true); + r.expect(async () => true); + r.expect((response) => { + assert.equal(response.statusCode, 200); + return response.body.length === 0; + }); + r.expectStatus(200); + r.expectStatusMessage("OK"); + r.expectBody("body"); + r.expectBody(Buffer.from("body")); + r.expectBody(/body/); + r.expectBody({ a: 1 }); + r.expectBody("body", {}); + r.expectBody("body", { decompress: true }); + r.expectEmptyBody(); + r.expectHeader("Cookie", "key=value"); + r.expectHeaderExists("Cookie"); + r.then((x: adone.shani.util.I.Response) => { + x.statusCode === 200; + x.body.fill(0); + }); + } +} diff --git a/types/adone/test/glosses/std.ts b/types/adone/test/glosses/std.ts new file mode 100644 index 0000000000..611f9401e9 --- /dev/null +++ b/types/adone/test/glosses/std.ts @@ -0,0 +1,161 @@ +import adone from "adone"; + +import * as assert from "assert"; +import * as fs from "fs"; +import * as path from "path"; +import * as util from "util"; +import * as events from "events"; +import * as stream from "stream"; +import * as url from "url"; +import * as net from "net"; +import * as http from "http"; +import * as https from "https"; +import * as child_process from "child_process"; +import * as os from "os"; +import * as cluster from "cluster"; +import * as repl from "repl"; +import * as punycode from "punycode"; +import * as readline from "readline"; +import * as string_decoder from "string_decoder"; +import * as querystring from "querystring"; +import * as crypto from "crypto"; +import * as vm from "vm"; +import * as v8 from "v8"; +import * as domain from "domain"; +import * as tty from "tty"; +import * as buffer from "buffer"; +import * as constants from "constants"; +import * as zlib from "zlib"; +import * as tls from "tls"; +import * as console from "console"; +import * as dns from "dns"; +import * as timers from "timers"; +import * as dgram from "dgram"; + +const { std } = adone; + +namespace stdTests { + namespace assert { + std.assert(true); + } + + namespace fs { + std.fs.readFileSync("test").length; + } + + namespace path { + std.path.join("a", "b").charAt(0); + } + + namespace util { + std.util.format("hello").charAt(0); + } + + namespace events { + new std.events.EventEmitter().on("event", () => {}); + } + + namespace steam { + new std.stream.PassThrough().resume(); + } + + namespace url { + std.url.parse("https://adone.io").hostname; + } + + namespace net { + std.net.connect(31337).write("hello"); + } + + namespace http { + std.http.get("http://localhost").end(); + } + + namespace https { + std.https.get("https://adone.io").end(); + } + + namespace child_process { + std.child_process.fork(__filename, [], { stdio: ["ipc"] }).send("hello"); + } + + namespace os { + std.os.tmpdir().charAt(0); + } + + namespace cluster { + std.cluster.fork().kill(); + } + + namespace repl { + std.repl.start().close(); + } + + namespace punycode { + std.punycode.decode("ads").charAt(0); + } + + namespace readline { + std.readline.clearLine(process.stdout, 1); + } + + namespace string_decoder { + new std.string_decoder.StringDecoder().end().charAt(0); + } + + namespace querystring { + std.querystring.escape("hello").charAt(0); + } + + namespace crypto { + std.crypto.createHash("sha1").update("hello").digest("hex"); + } + + namespace vm { + std.vm.runInContext("a + 2", std.vm.createContext({ a: 1 })); + } + + namespace v8 { + std.v8.getHeapStatistics().heap_size_limit + 2; + } + + namespace domain { + std.domain.create().members; + } + + namespace tty { + std.tty.isatty(1) === true; + } + + namespace buffer { + std.buffer.Buffer.alloc(10); + } + + namespace constants { + std.constants.EACCES + 2; + } + + namespace zlib { + std.zlib.createDeflate().write("ttt"); + } + + namespace tls { + std.tls.connect({}).end(); + } + + namespace console { + std.console.trace("message"); + } + + namespace dns { + std.dns.resolve4("adone.io", (err, data) => {}); + } + + namespace timers { + std.timers.setTimeout(() => {}, 2000).unref(); + } + + namespace dgram { + std.dgram.createSocket("udp4").bind(31337); + } +} diff --git a/types/adone/test/glosses/utils.ts b/types/adone/test/glosses/utils.ts new file mode 100644 index 0000000000..9372fb4b30 --- /dev/null +++ b/types/adone/test/glosses/utils.ts @@ -0,0 +1,737 @@ +const { util } = adone; + +namespace utilTests { + namespace arrify { + const a: number[] = util.arrify([1, 2, 3]); + const b: number[] = util.arrify(1); + const c: string[] = util.arrify("2"); + const d: string[] = util.arrify(["1"]); + } + + namespace slice { + const a: number[] = util.slice([1, 2, 3]); + const b: number[] = util.slice([1, 2, 3], 1); + const c: number[] = util.slice([1, 2, 3], 1, 4); + const d: string[] = util.slice(["1"]); + } + + namespace spliceOne { + util.spliceOne([1, 2, 3], 0); + } + + namespace normalizePath { + const a: string = util.normalizePath("path"); + const b: string = util.normalizePath("path", true); + } + + namespace unixifyPath { + const a: string = util.unixifyPath("path"); + const b: string = util.unixifyPath("path", true); + } + + namespace functionName { + const a: string = util.functionName(function f() { }); + const b: string = util.functionName((a, b, c) => { }); + } + + namespace mapArguments { + const a: (...args: any[]) => any = util.mapArguments(() => { }); + const b: (...args: T[]) => T[] = util.mapArguments(1); + const c: (...args: any[]) => any = util.mapArguments([1]); + const d: (x: T) => T = util.mapArguments(); + } + + namespace parseMs { + const result: { + days: number; + hours: number; + milliseconds: number; + minutes: number; + } = util.parseMs(123); + } + + namespace pluralizeWord { + const a: string = util.pluralizeWord("day"); + const b: string = util.pluralizeWord("day", "days"); + const c: string = util.pluralizeWord("day", "days", 1); + } + + namespace functionParams { + const a: string[] = util.functionParams((a: any, b: any, c: any) => { }); + } + + namespace randomChoice { + const a: number = util.randomChoice([1, 2, 3]); + const b: string = util.randomChoice(["1", "2", "3"]); + } + + namespace shuffleArray { + const a: number[] = util.shuffleArray([1, 2, 3]); + const b: string[] = util.shuffleArray(["1", "2", "3"]); + } + + namespace enumerate { + { + const a = util.enumerate([1, 2, 3]); + const it = a[Symbol.iterator](); + const value: [number, number] = it.next().value; + for (const i of a) { + const [idx, value]: [number, number] = i; + } + } + { + const a = util.enumerate(["1", "2"]); + const it = a[Symbol.iterator](); + const value: [number, string] = it.next().value; + for (const i of a) { + const [idx, value]: [number, string] = i; + } + } + } + + namespace zip { + { + const a = util.zip([1, 2, 3], ["4", "5", "6"]); + const it = a[Symbol.iterator](); + const value: [number, string] = it.next().value; + for (const i of a) { + const [i1, i2]: [number, string] = i; + } + } + { + const a = util.zip( + [1, 2, 3], + ["4", "5", "6"], + [7, 8, 9] + ); + const it = a[Symbol.iterator](); + const value: [number, string, number] = it.next().value; + for (const i of a) { + const [i1, i2, i3]: [number, string, number] = i; + } + } + { + const a = util.zip( + [1, 2, 3], + ["4", "5", "6"], + [7, 8, 9], + ["10", "11", "12"] + ); + const it = a[Symbol.iterator](); + const value: [number, string, number, string] = it.next().value; + for (const i of a) { + const [i1, i2, i3, i4]: [number, string, number, string] = i; + } + } + { + const a = util.zip( + [1, 2, 3], + ["4", "5", "6"], + [7, 8, 9], + ["10", "11", "12"], + [13, 14, 15, 16] + ); + const it = a[Symbol.iterator](); + const value: any[] = it.next().value; + for (const i of a) { + const [i1, i2, i3, i4]: any[] = i; + } + } + } + + namespace keys { + const a: string[] = util.keys({}); + const b: string[] = util.keys({}, { all: true }); + const c: string[] = util.keys({}, { followProto: true }); + const d: string[] = util.keys({}, { onlyEnumerable: true }); + } + + namespace values { + const a: any[] = util.values({}); + const b: any[] = util.values({}, { all: true }); + const c: any[] = util.values({}, { followProto: true }); + const d: any[] = util.values({}, { onlyEnumerable: true }); + } + + namespace entries { + const a: Array<[string, any]> = util.entries({}); + const b: Array<[string, any]> = util.entries({}, { all: true }); + const c: Array<[string, any]> = util.entries({}, { followProto: true }); + const d: Array<[string, any]> = util.entries({}, { onlyEnumerable: true }); + } + + namespace toDotNotation { + const a: object = util.toDotNotation({ a: 1 }); + } + + namespace flatten { + const a: number[] = util.flatten([1, [2, 3]]); + const b: number[] = util.flatten([1, [2, 3]], {}); + const c: number[] = util.flatten([1, [2, 3]], { depth: 1 }); + } + + namespace globParent { + const a: string = util.globParent("a/b/c/**"); + } + + namespace by { + const a: (a: number, b: number) => any = util.by((x: number): number => x); + const b: (a: number, b: number) => number = util.by((x: number): string => `${x}`, (a: string, b: string) => a.length - b.length); + } + + namespace toFastProperties { + const a: object = util.toFastProperties({}); + } + + namespace stripBom { + const a: string = util.stripBom("123"); + } + + namespace sortKeys { + const a: object = util.sortKeys({}); + const b: object = util.sortKeys({}, {}); + const c: object = util.sortKeys({}, { deep: true }); + const d: object = util.sortKeys({}, { compare: (a, b) => 2 }); + } + + namespace globize { + const a: string = util.globize("test"); + const b: string = util.globize("test", {}); + const c: string = util.globize("test", { exts: "" }); + const d: string = util.globize("test", { recursively: true }); + } + + namespace unique { + const a: number[] = util.unique([1, 2, 3]); + const b: string[] = util.unique(["1", "2", "3"]); + const c: object[] = util.unique([{ a: 1 }, { a: 2 }], (obj: any) => obj.a); + } + + namespace invertObject { + const a: object = util.invertObject({}); + const b: object = util.invertObject({}, {}); + const c: object = util.invertObject({}, { all: true }); + const d: object = util.invertObject({}, { followProto: true }); + const e: object = util.invertObject({}, { onlyEnumerable: true }); + } + + namespace humanizeTime { + const a: string = util.humanizeTime(12345); + const b: string = util.humanizeTime(12345, {}); + const c: string = util.humanizeTime(12345, { compact: true }); + const d: string = util.humanizeTime(12345, { msDecimalDigits: 2 }); + const e: string = util.humanizeTime(12345, { secDecimalDigits: 2 }); + const f: string = util.humanizeTime(12345, { verbose: true }); + } + + namespace humanizeSize { + const a: string = util.humanizeSize(12345); + const b: string = util.humanizeSize(12345, ""); + } + + namespace parseSize { + const a: number | null = util.parseSize(123); + const b: number | null = util.parseSize("123Kb"); + } + + namespace clone { + const a: object = util.clone({}); + const b: object = util.clone({}, {}); + const c: object = util.clone({}, { deep: true }); + } + + namespace toUTF8Array { + const a: number[] = util.toUTF8Array("hello"); + } + + namespace asyncIter { + util.asyncIter([1, 2, 3], () => { }, () => { }); + } + + namespace asyncFor { + util.asyncFor({}, () => { }, () => { }); + } + + namespace once { + { + const f = () => 2; + const a: () => number = util.once(f); + } + { + const f = (a: number) => `${a}`; + const a: (a: number) => string = util.once(f); + } + } + + namespace asyncWaterfall { + util.asyncWaterfall([ + (callback: (a: any, b: any, c: any) => void) => { + callback(null, 'one', 'two'); + } + ], (err: any, result: any) => { + // + }); + } + + namespace xrange { + for (const i of util.xrange(10)) { + const a: number = i; + } + for (const i of util.xrange(1, 10)) { + const a: number = i; + } + for (const i of util.xrange(1, 10, 2)) { + const a: number = i; + } + } + namespace range { + const a: number[] = util.range(10); + const b: number[] = util.range(1, 10); + const c: number[] = util.range(1, 10, 2); + } + + namespace reFindAll { + const a: RegExpExecArray[] = util.reFindAll(/\d+/, "1 2 3 4 5"); + } + + namespace assignDeep { + const a: object = util.assignDeep({ a: 1 }, { a: 2 }); + } + + namespace match { + const a: number | boolean = util.match(["a", "b", "c"], "a"); + const b: (a: any, b: any) => number | boolean = util.match("a", { index: true }); + const c: number | boolean = util.match(["a", "b", "c"], "a", { dot: true }); + const d: (a: any, b: any) => number | boolean = util.match("a", { end: 2 }); + const e: (a: any, b: any) => number | boolean = util.match("a", { start: 2 }); + const f: (a: any, b: any) => number | boolean = util.match("a"); + } + + namespace toposort { + const a: number[] = util.toposort([ + [0, 1], + [2, 3], + [4, 5], + [6, 7] + ]); + const b: number[] = util.toposort.array([0, 1, 2], [ + [0, 1], + [2, 3], + [4, 5], + [6, 7] + ]); + } + + namespace jsesc { + const a: string = util.jsesc({ a: 1 }); + const b: string = util.jsesc({ a: 1 }, { escapeEverything: true }); + const c: string = util.jsesc({ a: 1 }, { minimal: true }); + const d: string = util.jsesc({ a: 1 }, { isScriptContext: true }); + const e: string = util.jsesc({ a: 1 }, { quotes: "'" }); + const f: string = util.jsesc({ a: 1 }, { wrap: true }); + const g: string = util.jsesc({ a: 1 }, { es6: true }); + const h: string = util.jsesc({ a: 1 }, { json: true }); + const i: string = util.jsesc({ a: 1 }, { compact: true }); + const j: string = util.jsesc({ a: 1 }, { lowercaseHex: true }); + const k: string = util.jsesc({ a: 1 }, { numbers: "decimal" }); + const l: string = util.jsesc({ a: 1 }, { indent: " " }); + const m: string = util.jsesc({ a: 1 }, { indentLevel: 4 }); + const n: string = util.jsesc({ a: 1 }, { __inline1__: true }); + const o: string = util.jsesc({ a: 1 }, { __inline2__: true }); + } + + namespace typeOf { + const a: string = util.typeOf(1); + } + + namespace memcpy { + const a: number = util.memcpy.utou(Buffer.alloc(10), 0, Buffer.alloc(10), 0, 10); + const b: number = util.memcpy.atoa(new ArrayBuffer(10), 0, new ArrayBuffer(10), 0, 10); + const c: number = util.memcpy.atou(Buffer.alloc(10), 0, new ArrayBuffer(10), 0, 10); + const d: number = util.memcpy.utoa(new ArrayBuffer(10), 0, Buffer.alloc(10), 0, 10); + const e: number = util.memcpy.copy(Buffer.alloc(10), 0, Buffer.alloc(10), 0, 10); + const f: number = util.memcpy.copy(new ArrayBuffer(10), 0, new ArrayBuffer(10), 0, 10); + const g: number = util.memcpy.copy(Buffer.alloc(10), 0, new ArrayBuffer(10), 0, 10); + const h: number = util.memcpy.copy(new ArrayBuffer(10), 0, Buffer.alloc(10), 0, 10); + } + + namespace uuid { + namespace v1 { + const a: string = util.uuid.v1(); + const b: number[] = util.uuid.v1({}, []); + const c: number[] = util.uuid.v1({}, [], 1); + const d: string = util.uuid.v1({}); + const e: string = util.uuid.v1({ clockseq: 1 }); + const f: string = util.uuid.v1({ msecs: 1 }); + const g: string = util.uuid.v1({ nsecs: 1 }); + } + + namespace v4 { + const a: string = util.uuid.v4(); + const b: number[] = util.uuid.v4({}, []); + const c: number[] = util.uuid.v4({}, [], 1); + const d: string = util.uuid.v4({}); + const e: string = util.uuid.v4({ clockseq: 1 }); + const f: string = util.uuid.v4({ msecs: 1 }); + const g: string = util.uuid.v4({ nsecs: 1 }); + } + + namespace v5 { + const a: string = util.uuid.v5([], []); + const b: number[] = util.uuid.v5([], [], []); + const c: number[] = util.uuid.v5([], [], [], 1); + } + } + + namespace delegate { + const a = util.delegate({}, "a"); + a.getter("a").access("b").method("c").setter("d"); + } + + namespace GlobExp { + { + const glob = new util.GlobExp("*.js"); + const a: boolean = glob.hasMagic(); + const b: string[] = glob.expandBraces(); + const c: RegExp = glob.makeRe(); + const d: boolean = glob.test("a.js"); + } + { + const a: boolean = util.GlobExp.hasMagic("*.js"); + const b: string[] = util.GlobExp.expandBraces("*.js"); + const c: RegExp = util.GlobExp.makeRe("*.js"); + const d: boolean = util.GlobExp.test("*.js", "a.js"); + } + new util.GlobExp(""); + new util.GlobExp("", {}); + new util.GlobExp("", { dot: true }); + new util.GlobExp("", { flipNegate: true }); + new util.GlobExp("", { matchBase: true }); + new util.GlobExp("", { nobrace: true }); + new util.GlobExp("", { nocase: true }); + new util.GlobExp("", { nocomment: true }); + new util.GlobExp("", { noext: true }); + new util.GlobExp("", { noglobstar: true }); + new util.GlobExp("", { nonegate: true }); + util.GlobExp.hasMagic("", {}); + util.GlobExp.hasMagic("", { dot: true }); + util.GlobExp.hasMagic("", { flipNegate: true }); + util.GlobExp.hasMagic("", { matchBase: true }); + util.GlobExp.hasMagic("", { nobrace: true }); + util.GlobExp.hasMagic("", { nocase: true }); + util.GlobExp.hasMagic("", { nocomment: true }); + util.GlobExp.hasMagic("", { noext: true }); + util.GlobExp.hasMagic("", { noglobstar: true }); + util.GlobExp.hasMagic("", { nonegate: true }); + util.GlobExp.expandBraces("", {}); + util.GlobExp.expandBraces("", { dot: true }); + util.GlobExp.expandBraces("", { flipNegate: true }); + util.GlobExp.expandBraces("", { matchBase: true }); + util.GlobExp.expandBraces("", { nobrace: true }); + util.GlobExp.expandBraces("", { nocase: true }); + util.GlobExp.expandBraces("", { nocomment: true }); + util.GlobExp.expandBraces("", { noext: true }); + util.GlobExp.expandBraces("", { noglobstar: true }); + util.GlobExp.expandBraces("", { nonegate: true }); + util.GlobExp.makeRe("", {}); + util.GlobExp.makeRe("", { dot: true }); + util.GlobExp.makeRe("", { flipNegate: true }); + util.GlobExp.makeRe("", { matchBase: true }); + util.GlobExp.makeRe("", { nobrace: true }); + util.GlobExp.makeRe("", { nocase: true }); + util.GlobExp.makeRe("", { nocomment: true }); + util.GlobExp.makeRe("", { noext: true }); + util.GlobExp.makeRe("", { noglobstar: true }); + util.GlobExp.makeRe("", { nonegate: true }); + util.GlobExp.test("a", "b", {}); + util.GlobExp.test("a", "b", { dot: true }); + util.GlobExp.test("a", "b", { flipNegate: true }); + util.GlobExp.test("a", "b", { matchBase: true }); + util.GlobExp.test("a", "b", { nobrace: true }); + util.GlobExp.test("a", "b", { nocase: true }); + util.GlobExp.test("a", "b", { nocomment: true }); + util.GlobExp.test("a", "b", { noext: true }); + util.GlobExp.test("a", "b", { noglobstar: true }); + util.GlobExp.test("a", "b", { nonegate: true }); + } + + namespace iconv { + // TODO + } + + namespace sqlstring { + namespace escapeId { + const a: string = util.sqlstring.escapeId("asd"); + const b: string = util.sqlstring.escapeId(["asd"]); + const c: string = util.sqlstring.escapeId(["asd"], true); + } + + namespace dateToString { + const a: string = util.sqlstring.dateToString(Date.now()); + const b: string = util.sqlstring.dateToString(123, "local"); + } + + namespace arrayToList { + const a: string = util.sqlstring.arrayToList(["1", "a"]); + } + + namespace bufferToString { + const a: string = util.sqlstring.bufferToString(Buffer.alloc(10)); + } + + namespace objectToValues { + const a: string = util.sqlstring.objectToValues({ a: 1 }); + const b: string = util.sqlstring.objectToValues({ a: 1 }, "local"); + } + + namespace escape { + const a: string = util.sqlstring.escape(1); + const b: string = util.sqlstring.escape(1, true); + const c: string = util.sqlstring.escape(1, true, "local"); + } + + namespace format { + const a: string = util.sqlstring.format("??"); + const b: string = util.sqlstring.format("??", "a"); + const c: string = util.sqlstring.format("??", ["a"]); + const d: string = util.sqlstring.format("??", ["a"], true); + } + } + + namespace Editor { + namespace options { + new util.Editor(); + new util.Editor({}); + new util.Editor({ text: "" }); + new util.Editor({ editor: "" }); + new util.Editor({ path: "" }); + new util.Editor({ ext: "" }); + } + + const a: string = util.Editor.DEFAULT; + new util.Editor().spawn().then((x: adone.std.child_process.ChildProcess) => { }); + new util.Editor().run().then((x: string) => { }); + new util.Editor().cleanup().then((x: undefined) => { }); + util.Editor.edit().then((x: string) => { }); + } + + namespace binarySearch { + const a: number = util.binarySearch.GREATEST_LOWER_BOUND; + const b: number = util.binarySearch.GREATEST_LOWER_BOUND; + const c: number = util.binarySearch([1, 2, 3], 2); + const d: number = util.binarySearch([1, 2, 3], 2, 0); + const e: number = util.binarySearch([1, 2, 3], 2, 0, 10); + const f: number = util.binarySearch([1, 2, 3], 2, 0, 10, (a, b) => a - b); + const g: number = util.binarySearch([1, 2, 3], 2, 0, 10, (a, b) => a - b, util.binarySearch.GREATEST_LOWER_BOUND); + } + + namespace buffer { + const a: Buffer = util.buffer.concat([Buffer.alloc(10), Buffer.alloc(20)], 30); + util.buffer.mask(Buffer.alloc(10), Buffer.alloc(10), Buffer.alloc(10), 0, 10); + util.buffer.unmask(Buffer.alloc(10), Buffer.alloc(10)); + } + + namespace shebang { + const a: string | null = util.shebang("#!/bin/sh"); + } + + namespace ReInterval { + new util.ReInterval(() => { }, 1000); + new util.ReInterval(() => { }, 1000, [1]); + const a = new util.ReInterval(() => { }, 1000); + a.reschedule(400); + a.clear(); + a.destroy(); + } + + namespace RateLimiter { + new util.RateLimiter(); + new util.RateLimiter(1); + new util.RateLimiter(1, 1000); + new util.RateLimiter(1, 1000, true); + const a = new util.RateLimiter(); + a.removeTokens(1).then((x: number) => { }); + const b: boolean = a.tryRemoveTokens(10); + const c: number = a.getTokensRemaining(); + } + + namespace throttle { + const a: () => Promise = util.throttle(() => 42); + const b: (a: number) => Promise = util.throttle((a: number) => `${a}`); + const c: (a: number, b: string) => Promise = util.throttle((a: number, b: string) => String(a) + b); + const d = util.throttle(() => { }, {}); + const e = util.throttle(() => { }, { interval: 1000 }); + const f = util.throttle(() => { }, { max: 10 }); + const g = util.throttle(() => { }, { ordered: true }); + const h = util.throttle(() => { }, { waitForReturn: true }); + } + + namespace fakeClock { + namespace timers { + const a: typeof global.setTimeout = util.fakeClock.timers.setTimeout; + const b: typeof global.clearTimeout = util.fakeClock.timers.clearTimeout; + const c: typeof global.setInterval = util.fakeClock.timers.setInterval; + const d: typeof global.clearInterval = util.fakeClock.timers.clearInterval; + const e: typeof global.setImmediate = util.fakeClock.timers.setImmediate; + const f: typeof global.clearImmediate = util.fakeClock.timers.clearImmediate; + const g: typeof global.Date = util.fakeClock.timers.Date; + const h: typeof global.process.hrtime = util.fakeClock.timers.hrtime; + const i: typeof global.process.nextTick = util.fakeClock.timers.nextTick; + } + + namespace install { + util.fakeClock.install(); + util.fakeClock.install(100); + util.fakeClock.install(new Date()); + util.fakeClock.install({}); + util.fakeClock.install({ advanceTimeDelta: 20 }); + util.fakeClock.install({ loopLimit: 20 }); + util.fakeClock.install({ now: 20 }); + util.fakeClock.install({ shouldAdvanceTime: false }); + util.fakeClock.install({ target: {} }); + const clock = util.fakeClock.install({ toFake: ["setTimeout", "clearTimeout"] }); + { + const timer = clock.setTimeout(() => {}, 100, 1, 2, 3); + const id: number = timer.id; + timer.ref(); + timer.unref(); + clock.clearTimeout(timer); + } + { + const timer = clock.setInterval(() => {}, 1, 2, 3); + const id: number = timer.id; + timer.ref(); + timer.unref(); + clock.clearInterval(timer); + } + { + const timer = clock.setImmediate(() => {}, 1, 2, 3); + const id: number = timer.id; + timer.ref(); + timer.unref(); + clock.clearImmediate(timer); + } + clock.nextTick(() => {}, 1, 2, 3); + clock.updateHrTime(10); + const a: number = clock.tick(100); + const b: number = clock.next(); + const c: number = clock.runAll(); + const d: number = clock.runToLast(); + clock.setSystemTime(100); + const e: [number, number] = clock.hrtime(); + const f: [number, number] = clock.hrtime(e); + clock.uninstall(); + } + + namespace createClock { + util.fakeClock.createClock(); + util.fakeClock.createClock(0); + const clock = util.fakeClock.createClock(0, 100); + { + const timer = clock.setTimeout(() => {}, 100, 1, 2, 3); + const id: number = timer.id; + timer.ref(); + timer.unref(); + clock.clearTimeout(timer); + } + { + const timer = clock.setInterval(() => {}, 1, 2, 3); + const id: number = timer.id; + timer.ref(); + timer.unref(); + clock.clearInterval(timer); + } + { + const timer = clock.setImmediate(() => {}, 1, 2, 3); + const id: number = timer.id; + timer.ref(); + timer.unref(); + clock.clearImmediate(timer); + } + clock.nextTick(() => {}, 1, 2, 3); + clock.updateHrTime(10); + const a: number = clock.tick(100); + const b: number = clock.next(); + const c: number = clock.runAll(); + const d: number = clock.runToLast(); + clock.setSystemTime(100); + const e: [number, number] = clock.hrtime(); + const f: [number, number] = clock.hrtime(e); + } + + namespace ltgt { + namespace contains { + const a: boolean = util.ltgt.contains({ lt: 2 }, 2); + const b: boolean = util.ltgt.contains({ lt: 2 }, 2, (a, b) => b - a); + const c: boolean = util.ltgt.contains({ lt: "2" }, "2"); + const d: boolean = util.ltgt.contains({ lt: "2" }, "2", (a, b) => b.charCodeAt(0) - a.charCodeAt(0)); + } + + namespace filter { + const a: (a: number) => boolean = util.ltgt.filter({ lt: 2 }); + const b: (a: number) => boolean = util.ltgt.filter({ lt: 2 }, (a, b) => b - a); + const c: (a: string) => boolean = util.ltgt.filter({ lt: "2" }); + const d: (a: string) => boolean = util.ltgt.filter({ lt: "2" }, (a, b) => b.charCodeAt(0) - a.charCodeAt(0)); + } + + namespace toLtgt { + const a: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}); + const b: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => `${a}`); + const c: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => a, 2); + const d: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => a, 2, 5); + } + + namespace endEnclusive { + const a: boolean = util.ltgt.endInclusive({ lt: 2 }); + } + + namespace startInclusive { + const a: boolean = util.ltgt.startInclusive({ lt: 2 }); + } + + namespace end { + const a: number | undefined = util.ltgt.end({ lt: 2 }); + const b: number | string = util.ltgt.end({ lt: 2 }, "2"); + const c: number = util.ltgt.end({ lt: 2 }, 2); + } + + namespace start { + const a: number | undefined = util.ltgt.start({ lt: 2 }); + const b: number | string = util.ltgt.start({ lt: 2 }, "2"); + const c: number = util.ltgt.start({ lt: 2 }, 2); + } + + namespace upperBound { + const a: number | undefined = util.ltgt.upperBound({ lt: 2 }); + const b: number | string = util.ltgt.upperBound({ lt: 2 }, "2"); + const c: number = util.ltgt.upperBound({ lt: 2 }, 2); + } + + namespace upperBoundKey { + const a: number | undefined = util.ltgt.upperBoundKey({ lt: 2 }); + } + + namespace upperBoundExclusive { + const a: boolean = util.ltgt.upperBoundInclusive({ lt: 2 }); + } + + namespace lowerBoundExclusive { + const a: boolean = util.ltgt.lowerBoundInclusive({ lt: 2 }); + } + + namespace upperBoundInclusive { + const a: boolean = util.ltgt.upperBoundInclusive({ lt: 2 }); + } + + namespace lowerBoundInclusive { + const a: boolean = util.ltgt.lowerBoundInclusive({ lt: 2 }); + } + + namespace lowerBound { + const a: number | undefined = util.ltgt.lowerBound({ lt: 2 }); + const b: number | string = util.ltgt.lowerBound({ lt: 2 }, "2"); + const c: number = util.ltgt.lowerBound({ lt: 2 }, 2); + } + } + } +} diff --git a/types/adone/test/index-import.ts b/types/adone/test/index-import.ts new file mode 100644 index 0000000000..906e57938c --- /dev/null +++ b/types/adone/test/index-import.ts @@ -0,0 +1,6 @@ +import adone from "adone"; + +namespace AdoneRootImportTests { + adone.falsely() === false; + adone.std.fs.createReadStream(__filename).close(); +} diff --git a/types/adone/test/index.ts b/types/adone/test/index.ts new file mode 100644 index 0000000000..a6cd5093f3 --- /dev/null +++ b/types/adone/test/index.ts @@ -0,0 +1,71 @@ +namespace AdoneRootTests { + { const a: symbol = adone.null; } + adone.noop(); + { const a: number = adone.identity(2); } + { const a: string = adone.identity("2"); } + { const a: number[] = adone.identity([1, 2]); } + { adone.truly() === true; } + { adone.falsely() === false; } + { const a: string = adone.ok; } + { const a: string = adone.bad; } + { const a: string[] = adone.exts; } + adone.log(); + adone.fatal(); + adone.error(); + adone.warn(); + adone.info(); + adone.debug(); + adone.trace(); + { const a: object = adone.o(); } + { const a: object = adone.o({}); } + { const a: typeof Date = adone.Date; } + { const a: typeof process.hrtime = adone.hrtime; } + { const a: typeof setTimeout = adone.setTimeout; } + { const a: typeof clearTimeout = adone.clearTimeout; } + { const a: typeof setInterval = adone.setInterval; } + { const a: typeof clearInterval = adone.clearInterval; } + { const a: typeof setImmediate = adone.setImmediate; } + { const a: typeof clearImmediate = adone.clearImmediate; } + adone.lazify({}); + adone.lazify({}, {}); + adone.lazify({}, {}, () => { }); + adone.lazify({}, {}, () => { }, { configurable: true }); + adone.tag.set({}, "123"); + adone.tag.has({}, "123") === true; + adone.tag.define("12"); + adone.tag.define("123", "456"); + { const a: symbol = adone.tag.SUBSYSTEM; } + { const a: symbol = adone.tag.APPLICATION; } + { const a: symbol = adone.tag.TRANSFORM; } + { const a: symbol = adone.tag.CORE_STREAM; } + { const a: symbol = adone.tag.LOGGER; } + { const a: symbol = adone.tag.LONG; } + { const a: symbol = adone.tag.BIGNUMBER; } + { const a: symbol = adone.tag.EXBUFFER; } + { const a: symbol = adone.tag.EXDATE; } + { const a: symbol = adone.tag.CONFIGURATION; } + { const a: symbol = adone.tag.GENESIS_NETRON; } + { const a: symbol = adone.tag.GENESIS_PEER; } + { const a: symbol = adone.tag.NETRON; } + { const a: symbol = adone.tag.NETRON_PEER; } + { const a: symbol = adone.tag.NETRON_ADAPTER; } + { const a: symbol = adone.tag.NETRON_DEFINITION; } + { const a: symbol = adone.tag.NETRON_DEFINITIONS; } + { const a: symbol = adone.tag.NETRON_REFERENCE; } + { const a: symbol = adone.tag.NETRON_INTERFACE; } + { const a: symbol = adone.tag.NETRON_STUB; } + { const a: symbol = adone.tag.NETRON_REMOTESTUB; } + { const a: symbol = adone.tag.NETRON_STREAM; } + { const a: symbol = adone.tag.FAST_STREAM; } + { const a: symbol = adone.tag.FAST_FS_STREAM; } + { const a: symbol = adone.tag.FAST_FS_MAP_STREAM; } + { const a: Promise = adone.run({}); } + { const a: Promise = adone.run({}, false); } + { const a: object = adone.bind("library"); } // hmm + { const a: string = adone.getAssetAbsolutePath("asset"); } + { const a: Buffer | string = adone.loadAsset("asset"); } + { const a: object = adone.require("path"); } + { const a: object = adone.package; } + { const a: typeof adone.assertion.assert = adone.assert; } + { const a: typeof adone.assertion.expect = adone.expect; } +} diff --git a/types/adone/tsconfig.json b/types/adone/tsconfig.json new file mode 100644 index 0000000000..ad90d2b5d7 --- /dev/null +++ b/types/adone/tsconfig.json @@ -0,0 +1,42 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es2017", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "adone.d.ts", + "glosses/common.d.ts", + "glosses/math.d.ts", + "glosses/std.d.ts", + "glosses/utils.d.ts", + "glosses/assertion.d.ts", + "glosses/promise.d.ts", + "glosses/shani.d.ts", + "glosses/shani-global.d.ts", + "adone-tests.ts", + "test/index.ts", + "test/index-import.ts", + "test/glosses/common.ts", + "test/glosses/math.ts", + "test/glosses/std.ts", + "test/glosses/utils.ts", + "test/glosses/assertion.ts", + "test/glosses/promise.ts", + "test/glosses/shani.ts", + "test/glosses/shani-global.ts" + ] +} diff --git a/types/adone/tslint.json b/types/adone/tslint.json new file mode 100644 index 0000000000..f0ae61d2bf --- /dev/null +++ b/types/adone/tslint.json @@ -0,0 +1,15 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "align": false, + "no-namespace": false, + "strict-export-declare-modifiers": false, + "no-boolean-literal-compare": false, + "no-mergeable-namespace": false, + "no-single-declare-module": false, + "no-unnecessary-qualifier": false, + "unified-signatures": false, + "space-before-function-paren": false + } +} \ No newline at end of file diff --git a/types/ag-grid/ag-grid-tests.ts b/types/ag-grid/ag-grid-tests.ts deleted file mode 100644 index 7c4ebb0c8c..0000000000 --- a/types/ag-grid/ag-grid-tests.ts +++ /dev/null @@ -1,136 +0,0 @@ - -checkGridOptions({}); -checkColDef({}); - -function checkGridOptions(gridOptions: ag.grid.GridOptions): void { - - gridOptions.virtualPaging = true; - gridOptions.toolPanelSuppressPivot = true; - gridOptions.toolPanelSuppressValues = true; - gridOptions.rowsAlreadyGrouped = true; - gridOptions.suppressRowClickSelection = true; - gridOptions.suppressCellSelection = true; - gridOptions.sortingOrder = ['asc','desc']; - gridOptions.suppressMultiSort = true; - gridOptions.suppressHorizontalScroll = true; - gridOptions.unSortIcon = true; - gridOptions.rowHeight = 0; - gridOptions.rowBuffer = 0; - gridOptions.enableColResize = true; - gridOptions.enableCellExpressions = true; - gridOptions.enableSorting = true; - gridOptions.enableServerSideSorting = true; - gridOptions.enableFilter = true; - gridOptions.enableServerSideFilter = true; - gridOptions.colWidth = 0; - gridOptions.suppressMenuHide = true; - gridOptions.singleClickEdit = true; - gridOptions.debug = true; - gridOptions.icons = {}; - gridOptions.angularCompileRows = true; - gridOptions.angularCompileFilters = true; - gridOptions.angularCompileHeaders = true; - gridOptions.localeText = {}; - gridOptions.localeTextFunc = function() {} - gridOptions.suppressScrollLag = true; - gridOptions.groupSuppressAutoColumn = true; - gridOptions.groupSelectsChildren = true; - gridOptions.groupHidePivotColumns = true; - gridOptions.groupIncludeFooter = true; - gridOptions.groupUseEntireRow = true; - gridOptions.groupSuppressRow = true; - gridOptions.groupSuppressBlankHeader = true; - gridOptions.forPrint = true; - gridOptions.groupColumnDef = {}; - gridOptions.context = {}; - gridOptions.rowStyle = {color: 'red'}; - gridOptions.rowClass = 'green'; - gridOptions.groupDefaultExpanded = false; - gridOptions.slaveGrids = []; - gridOptions.rowSelection = 'single'; - gridOptions.rowDeselection = true; - gridOptions.rowData = []; - gridOptions.floatingTopRowData = []; - gridOptions.floatingBottomRowData = []; - gridOptions.showToolPanel = true; - gridOptions.groupKeys = ['a','b'] - gridOptions.groupAggFields = ['a','b'] - gridOptions.columnDefs = []; - gridOptions.datasource = {}; - gridOptions.pinnedColumnCount = 0; - gridOptions.groupHeaders = true; - gridOptions.headerHeight = 0; - gridOptions.groupRowInnerRenderer = function(params) {}; - gridOptions.groupRowRenderer = {}; - gridOptions.isScrollLag = function() {return true;} - gridOptions.isExternalFilterPresent = function() { return true; }; - gridOptions.doesExternalFilterPass = function(node: ag.grid.RowNode) { return false; }; - gridOptions.getRowStyle = function() {}; - gridOptions.getRowClass = function() {}; - gridOptions.headerCellRenderer = function() {}; - gridOptions.groupAggFunction = function(nodes: any[]) {}; - gridOptions.onReady = function(api: any) {}; - gridOptions.onModelUpdated = function() {}; - gridOptions.onCellClicked = function(params) {}; - gridOptions.onCellDoubleClicked = function(params) {}; - gridOptions.onCellContextMenu = function(params) {}; - gridOptions.onCellValueChanged = function(params) {}; - gridOptions.onCellFocused = function(params) {}; - gridOptions.onRowSelected = function(params) {}; - gridOptions.onSelectionChanged = function() {}; - gridOptions.onBeforeFilterChanged = function() {}; - gridOptions.onAfterFilterChanged = function() {}; - gridOptions.onFilterModified = function() {}; - gridOptions.onBeforeSortChanged = function() {}; - gridOptions.onAfterSortChanged = function() {}; - gridOptions.onVirtualRowRemoved = function(params) {}; - gridOptions.onRowClicked = function(params) {}; - gridOptions.api = null; - gridOptions.columnApi = null; - -} - -function checkColDef(colDef: ag.grid.ColDef): void { - - colDef.sort = 'test'; - colDef.sortedAt = 0; - colDef.sortingOrder = ['asc','desc']; - colDef.headerName = 'test'; - colDef.field = 'test'; - colDef.headerValueGetter = 'test'; - colDef.colId = 'test'; - colDef.hide = true; - colDef.headerTooltip = 'test'; - colDef.valueGetter = 'test'; - colDef.headerCellRenderer = {}; - colDef.headerClass = 'test'; - colDef.width = 0; - colDef.minWidth = 0; - colDef.maxWidth = 0; - colDef.cellClass = 'test'; - colDef.cellStyle = {color: 'test'}; - colDef.cellRenderer = function() {}; - colDef.floatingCellRenderer = function() {}; - colDef.aggFunc = 'test'; - colDef.comparator = function() {}; - colDef.checkboxSelection = true; - colDef.suppressMenu = true; - colDef.suppressSorting = true; - colDef.unSortIcon = true; - colDef.suppressSizeToFit = true; - colDef.suppressResize = true; - colDef.headerGroup = 'test'; - colDef.headerGroupShow = 'test'; - colDef.editable = true; - colDef.newValueHandler = function() {}; - colDef.volatile = true; - colDef.template = 'test'; - colDef.templateUrl = 'test'; - colDef.filter = 'test'; - colDef.filterParams = {}; - colDef.onCellValueChanged = function() {}; - colDef.onCellClicked = function() {}; - colDef.onCellDoubleClicked = function() {}; - colDef.onCellContextMenu = function() {}; - colDef.cellClassRules = {}; -} diff --git a/types/ag-grid/index.d.ts b/types/ag-grid/index.d.ts deleted file mode 100644 index 3fe37571b1..0000000000 --- a/types/ag-grid/index.d.ts +++ /dev/null @@ -1,1991 +0,0 @@ -// Type definitions for ag-grid v2.1.2 -// Project: http://www.ag-grid.com/ -// Definitions by: Niall Crosby -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace ag.grid { - class ColumnChangeEvent { - private type; - private column; - private columnGroup; - private fromIndex; - private toIndex; - private pinnedColumnCount; - constructor(type: string); - toString(): string; - withColumn(column: Column): ColumnChangeEvent; - withColumnGroup(columnGroup: ColumnGroup): ColumnChangeEvent; - withFromIndex(fromIndex: number): ColumnChangeEvent; - withPinnedColumnCount(pinnedColumnCount: number): ColumnChangeEvent; - withToIndex(toIndex: number): ColumnChangeEvent; - getFromIndex(): number; - getToIndex(): number; - getPinnedColumnCount(): number; - getType(): string; - getColumn(): Column; - getColumnGroup(): ColumnGroup; - isPivotChanged(): boolean; - isValueChanged(): boolean; - isIndividualColumnResized(): boolean; - } -} -declare namespace ag.grid { - class Utils { - private static isSafari; - private static isIE; - static iterateObject(object: any, callback: (key: string, value: any) => void): void; - static cloneObject(object: any): any; - static map(array: TItem[], callback: (item: TItem) => TResult): TResult[]; - static forEach(array: T[], callback: (item: T, index: number) => void): void; - static filter(array: T[], callback: (item: T) => boolean): T[]; - static assign(object: any, source: any): void; - static getFunctionParameters(func: any): any; - static find(collection: any, predicate: any, value: any): any; - static toStrings(array: T[]): string[]; - static iterateArray(array: T[], callback: (item: T, index: number) => void): void; - static isNode(o: any): boolean; - static isElement(o: any): boolean; - static isNodeOrElement(o: any): boolean; - static addChangeListener(element: HTMLElement, listener: EventListener): void; - static makeNull(value: any): any; - static removeAllChildren(node: HTMLElement): void; - static removeElement(parent: HTMLElement, cssSelector: string): void; - static removeFromParent(node: Element): void; - static isVisible(element: HTMLElement): boolean; - /** - * loads the template and returns it as an element. makes up for no simple way in - * the dom api to load html directly, eg we cannot do this: document.createElement(template) - */ - static loadTemplate(template: string): Node; - static querySelectorAll_addCssClass(eParent: any, selector: string, cssClass: string): void; - static querySelectorAll_removeCssClass(eParent: any, selector: string, cssClass: string): void; - static querySelectorAll_replaceCssClass(eParent: any, selector: string, cssClassToRemove: string, cssClassToAdd: string): void; - static addOrRemoveCssClass(element: HTMLElement, className: string, addOrRemove: boolean): void; - static addCssClass(element: HTMLElement, className: string): void; - static offsetHeight(element: HTMLElement): number; - static offsetWidth(element: HTMLElement): number; - static removeCssClass(element: HTMLElement, className: string): void; - static removeFromArray(array: T[], object: T): void; - static defaultComparator(valueA: any, valueB: any): number; - static formatWidth(width: number | string): string; - /** - * Tries to use the provided renderer. - */ - static useRenderer(eParent: Element, eRenderer: (params: TParams) => Node | string, params: TParams): void; - /** - * If icon provided, use this (either a string, or a function callback). - * if not, then use the second parameter, which is the svgFactory function - */ - static createIcon(iconName: any, gridOptionsWrapper: any, colDefWrapper: any, svgFactoryFunc: () => Node): HTMLSpanElement; - static addStylesToElement(eElement: any, styles: any): void; - static getScrollbarWidth(): number; - static isKeyPressed(event: KeyboardEvent, keyToCheck: number): boolean; - static setVisible(element: HTMLElement, visible: boolean): void; - static isBrowserIE(): boolean; - static isBrowserSafari(): boolean; - } -} -declare namespace ag.grid { - class Constants { - static STEP_EVERYTHING: number; - static STEP_FILTER: number; - static STEP_SORT: number; - static STEP_MAP: number; - static ASC: string; - static DESC: string; - static ROW_BUFFER_SIZE: number; - static MIN_COL_WIDTH: number; - static SUM: string; - static MIN: string; - static MAX: string; - static KEY_TAB: number; - static KEY_ENTER: number; - static KEY_BACKSPACE: number; - static KEY_DELETE: number; - static KEY_ESCAPE: number; - static KEY_SPACE: number; - static KEY_DOWN: number; - static KEY_UP: number; - static KEY_LEFT: number; - static KEY_RIGHT: number; - } -} -declare namespace ag.grid { - class Column { - static colIdSequence: number; - colDef: ColDef; - actualWidth: any; - visible: any; - colId: any; - pinned: boolean; - index: number; - aggFunc: string; - pivotIndex: number; - sort: string; - sortedAt: number; - constructor(colDef: ColDef, actualWidth: any); - isGreaterThanMax(width: number): boolean; - getMinimumWidth(): number; - setMinimum(): void; - } -} -declare namespace ag.grid { - class ColumnGroup { - pinned: any; - name: any; - allColumns: Column[]; - displayedColumns: Column[]; - expandable: boolean; - expanded: boolean; - actualWidth: number; - constructor(pinned: any, name: any); - getMinimumWidth(): number; - addColumn(column: any): void; - calculateExpandable(): void; - calculateActualWidth(): void; - calculateDisplayedColumns(): void; - addToVisibleColumns(colsToAdd: any): void; - } -} -declare namespace ag.grid { - class GridOptionsWrapper { - private gridOptions; - private groupHeaders; - private headerHeight; - private rowHeight; - private floatingTopRowData; - private floatingBottomRowData; - init(gridOptions: GridOptions, eventService: EventService): void; - isRowSelection(): boolean; - isRowDeselection(): boolean; - isRowSelectionMulti(): boolean; - getContext(): any; - isVirtualPaging(): boolean; - isShowToolPanel(): boolean; - isToolPanelSuppressPivot(): boolean; - isToolPanelSuppressValues(): boolean; - isRowsAlreadyGrouped(): boolean; - isGroupSelectsChildren(): boolean; - isGroupHidePivotColumns(): boolean; - isGroupIncludeFooter(): boolean; - isGroupSuppressBlankHeader(): boolean; - isSuppressRowClickSelection(): boolean; - isSuppressCellSelection(): boolean; - isSuppressMultiSort(): boolean; - isGroupSuppressAutoColumn(): boolean; - isForPrint(): boolean; - isSuppressHorizontalScroll(): boolean; - isUnSortIcon(): boolean; - isSuppressMenuHide(): boolean; - getRowStyle(): any; - getRowClass(): any; - getRowStyleFunc(): any; - getRowClassFunc(): any; - getHeaderCellRenderer(): any; - getApi(): GridApi; - isEnableColResize(): boolean; - isSingleClickEdit(): boolean; - getGroupDefaultExpanded(): any; - getGroupKeys(): string[]; - getGroupAggFunction(): (nodes: any[]) => any; - getGroupAggFields(): string[]; - getRowData(): any[]; - isGroupUseEntireRow(): boolean; - getGroupColumnDef(): any; - isGroupSuppressRow(): boolean; - isAngularCompileRows(): boolean; - isAngularCompileFilters(): boolean; - isAngularCompileHeaders(): boolean; - isDebug(): boolean; - getColumnDefs(): any[]; - getDatasource(): any; - getRowBuffer(): number; - isEnableSorting(): boolean; - isEnableCellExpressions(): boolean; - isEnableServerSideSorting(): boolean; - isEnableFilter(): boolean; - isEnableServerSideFilter(): boolean; - isSuppressScrollLag(): boolean; - getIcons(): any; - getIsScrollLag(): () => boolean; - getSortingOrder(): string[]; - getSlaveGrids(): GridOptions[]; - getGroupRowRenderer(): Object | Function; - getRowHeight(): number; - getHeaderHeight(): number; - setHeaderHeight(headerHeight: number): void; - isGroupHeaders(): boolean; - setGroupHeaders(groupHeaders: boolean): void; - getFloatingTopRowData(): any[]; - setFloatingTopRowData(rows: any[]): void; - getFloatingBottomRowData(): any[]; - setFloatingBottomRowData(rows: any[]): void; - isExternalFilterPresent(): boolean; - doesExternalFilterPass(node: RowNode): boolean; - getGroupRowInnerRenderer(): (params: any) => void; - getColWidth(): number; - private checkForDeprecated(); - getPinnedColCount(): number; - getLocaleTextFunc(): Function; - globalEventHandler(eventName: string, event?: any): void; - private getCallbackForEvent(eventName); - } -} -declare namespace ag.grid { - class LoggerFactory { - private logging; - init(gridOptionsWrapper: GridOptionsWrapper): void; - create(name: string): Logger; - } - class Logger { - private logging; - private name; - constructor(name: string, logging: boolean); - log(message: string): void; - } -} -declare namespace ag.grid { - class Events { - /** A new set of columns has been entered, everything has potentially changed. */ - static EVENT_COLUMN_EVERYTHING_CHANGED: string; - /** A pivot column was added, removed or order changed. */ - static EVENT_COLUMN_PIVOT_CHANGE: string; - /** A value column was added, removed or agg function was changed. */ - static EVENT_COLUMN_VALUE_CHANGE: string; - /** A column was moved */ - static EVENT_COLUMN_MOVED: string; - /** One or more columns was shown / hidden */ - static EVENT_COLUMN_VISIBLE: string; - /** A column group was opened / closed */ - static EVENT_COLUMN_GROUP_OPENED: string; - /** One or more columns was resized. If just one, the column in the event is set. */ - static EVENT_COLUMN_RESIZED: string; - /** One or more columns was resized. If just one, the column in the event is set. */ - static EVENT_COLUMN_PINNED_COUNT_CHANGED: string; - static EVENT_MODEL_UPDATED: string; - static EVENT_CELL_CLICKED: string; - static EVENT_CELL_DOUBLE_CLICKED: string; - static EVENT_CELL_CONTEXT_MENU: string; - static EVENT_CELL_VALUE_CHANGED: string; - static EVENT_CELL_FOCUSED: string; - static EVENT_ROW_SELECTED: string; - static EVENT_SELECTION_CHANGED: string; - static EVENT_BEFORE_FILTER_CHANGED: string; - static EVENT_AFTER_FILTER_CHANGED: string; - static EVENT_FILTER_MODIFIED: string; - static EVENT_BEFORE_SORT_CHANGED: string; - static EVENT_AFTER_SORT_CHANGED: string; - static EVENT_VIRTUAL_ROW_REMOVED: string; - static EVENT_ROW_CLICKED: string; - static EVENT_READY: string; - } -} -declare namespace ag.grid { - class EventService { - private allListeners; - private globalListeners; - private getListenerList(eventType); - addEventListener(eventType: string, listener: Function): void; - addGlobalListener(listener: Function): void; - removeEventListener(eventType: string, listener: Function): void; - removeGlobalListener(listener: Function): void; - dispatchEvent(eventType: string, event?: any): void; - } -} -declare namespace ag.grid { - class MasterSlaveService { - private gridOptionsWrapper; - private columnController; - private gridPanel; - private logger; - private eventService; - private consuming; - init(gridOptionsWrapper: GridOptionsWrapper, columnController: ColumnController, gridPanel: GridPanel, loggerFactory: LoggerFactory, eventService: EventService): void; - private fireEvent(callback); - private onEvent(callback); - private fireColumnEvent(event); - fireHorizontalScrollEvent(horizontalScroll: number): void; - onScrollEvent(horizontalScroll: number): void; - onColumnEvent(event: ColumnChangeEvent): void; - } -} -declare namespace ag.grid { - class ColumnApi { - private _columnController; - constructor(_columnController: ColumnController); - sizeColumnsToFit(gridWidth: any): void; - hideColumns(colIds: any, hide: any): void; - columnGroupOpened(group: ColumnGroup, newValue: boolean): void; - getColumnGroup(name: string): ColumnGroup; - getDisplayNameForCol(column: any): string; - getColumn(key: any): Column; - setState(columnState: any): void; - getState(): [any]; - isPinning(): boolean; - getVisibleColAfter(col: Column): Column; - getVisibleColBefore(col: Column): Column; - setColumnVisible(column: Column, visible: boolean): void; - getAllColumns(): Column[]; - getDisplayedColumns(): Column[]; - getPivotedColumns(): Column[]; - getValueColumns(): Column[]; - moveColumn(fromIndex: number, toIndex: number): void; - movePivotColumn(fromIndex: number, toIndex: number): void; - setColumnAggFunction(column: Column, aggFunc: string): void; - setColumnWidth(column: Column, newWidth: number): void; - removeValueColumn(column: Column): void; - addValueColumn(column: Column): void; - removePivotColumn(column: Column): void; - setPinnedColumnCount(count: number): void; - addPivotColumn(column: Column): void; - getHeaderGroups(): ColumnGroup[]; - hideColumn(colId: any, hide: any): void; - } - class ColumnController { - private gridOptionsWrapper; - private angularGrid; - private selectionRendererFactory; - private expressionService; - private masterSlaveController; - private allColumns; - private visibleColumns; - private displayedColumns; - private pivotColumns; - private valueColumns; - private columnGroups; - private setupComplete; - private valueService; - private pinnedColumnCount; - private eventService; - constructor(); - init(angularGrid: Grid, selectionRendererFactory: SelectionRendererFactory, gridOptionsWrapper: GridOptionsWrapper, expressionService: ExpressionService, valueService: ValueService, masterSlaveController: MasterSlaveService, eventService: EventService): void; - getColumnApi(): ColumnApi; - isSetupComplete(): boolean; - getHeaderGroups(): ColumnGroup[]; - getPinnedContainerWidth(): number; - addPivotColumn(column: Column): void; - setPinnedColumnCount(count: number): void; - removePivotColumn(column: Column): void; - addValueColumn(column: Column): void; - removeValueColumn(column: Column): void; - private doesColumnExistInGrid(column); - setColumnWidth(column: Column, newWidth: number): void; - private updateGroupWidthsAfterColumnResize(column); - setColumnAggFunction(column: Column, aggFunc: string): void; - movePivotColumn(fromIndex: number, toIndex: number): void; - moveColumn(fromIndex: number, toIndex: number): void; - getBodyContainerWidth(): number; - getValueColumns(): Column[]; - getPivotedColumns(): Column[]; - getDisplayedColumns(): Column[]; - getAllColumns(): Column[]; - setColumnVisible(column: Column, visible: boolean): void; - getVisibleColBefore(col: any): Column; - getVisibleColAfter(col: Column): Column; - isPinning(): boolean; - getState(): [any]; - setState(columnState: any): void; - getColumns(keys: any[]): Column[]; - getColumn(key: any): Column; - getDisplayNameForCol(column: any): string; - getColumnGroup(name: string): ColumnGroup; - onColumnsChanged(): void; - private checkForDeprecatedItems(columnDefs); - columnGroupOpened(group: ColumnGroup, newValue: boolean): void; - hideColumns(colIds: any, hide: any): void; - private updateModel(); - private updateDisplayedColumns(); - sizeColumnsToFit(gridWidth: any): void; - private buildGroups(); - private updateGroups(); - private updateVisibleColumns(); - private updatePinnedColumns(); - private createColumns(colDefs); - private createPivotColumns(); - private createValueColumns(); - private createDummyColumn(field); - private calculateColInitialWidth(colDef); - private getTotalColWidth(includePinned); - } -} -declare namespace ag.grid { - interface CsvExportParams { - skipHeader?: boolean; - skipFooters?: boolean; - skipGroups?: boolean; - fileName?: string; - } - class CsvCreator { - private rowController; - private columnController; - private grid; - private valueService; - constructor(rowController: InMemoryRowController, columnController: ColumnController, grid: Grid, valueService: ValueService); - exportDataAsCsv(params?: CsvExportParams): void; - getDataAsCsv(params?: CsvExportParams): string; - private createValueForGroupNode(node); - private escape(value); - } -} -declare namespace ag.grid { - class ExpressionService { - private expressionToFunctionCache; - private logger; - init(loggerFactory: LoggerFactory): void; - evaluate(expression: string, params: any): any; - private createExpressionFunction(expression); - private createFunctionBody(expression); - } -} -declare namespace ag.grid { - interface TextAndNumberFilterParameters { - /** What to do when new rows are loaded. The default is to reset the filter, to keep it in line with 'set' filters. If you want to keep the selection, then set this value to 'keep'. */ - newRowsAction?: string; - } -} -declare namespace ag.grid { - class TextFilter implements Filter { - private filterParams; - private filterChangedCallback; - private filterModifiedCallback; - private localeTextFunc; - private valueGetter; - private filterText; - private filterType; - private api; - private eGui; - private eFilterTextField; - private eTypeSelect; - private applyActive; - private eApplyButton; - init(params: any): void; - onNewRowsLoaded(): void; - afterGuiAttached(): void; - doesFilterPass(node: any): boolean; - getGui(): any; - isFilterActive(): boolean; - private createTemplate(); - private createGui(); - private setupApply(); - private onTypeChanged(); - private onFilterChanged(); - private filterChanged(); - private createApi(); - private getApi(); - } -} -declare namespace ag.grid { - class NumberFilter implements Filter { - private filterParams; - private filterChangedCallback; - private filterModifiedCallback; - private localeTextFunc; - private valueGetter; - private filterNumber; - private filterType; - private api; - private eGui; - private eFilterTextField; - private eTypeSelect; - private applyActive; - private eApplyButton; - init(params: any): void; - onNewRowsLoaded(): void; - afterGuiAttached(): void; - doesFilterPass(node: any): boolean; - getGui(): any; - isFilterActive(): boolean; - private createTemplate(); - private createGui(); - private setupApply(); - private onTypeChanged(); - private filterChanged(); - private onFilterChanged(); - private createApi(); - private getApi(); - } -} -declare namespace ag.grid { - interface ColDef { - /** If sorting by default, set it here. Set to 'asc' or 'desc' */ - sort?: string; - /** If sorting more than one column by default, the milliseconds when this column was sorted, so we know what order to sort the columns in. */ - sortedAt?: number; - /** The sort order, provide an array with any of the following in any order ['asc','desc',null] */ - sortingOrder?: string[]; - /** The name to render in the column header */ - headerName: string; - /** The field of the row to get the cells data from */ - field: string; - /** Expression or function to get the cells value. */ - headerValueGetter?: string | Function; - /** The unique ID to give the column. This is optional. If missing, the ID will default to the field. If both field and colId are missing, a unique ID will be generated. - * This ID is used to identify the column in the API for sorting, filtering etc. */ - colId?: string; - /** Set to true for this column to be hidden. Naturally you might think, it would make more sense to call this field 'visible' and mark it false to hide, - * however we want all default values to be false and we want columns to be visible by default. */ - hide?: boolean; - /** Tooltip for the column header */ - headerTooltip?: string; - /** Expression or function to get the cells value. */ - valueGetter?: string | Function; - /** To provide custom rendering to the header. */ - headerCellRenderer?: Function | Object; - /** CSS class for the header */ - headerClass?: string | string[] | ((params: any) => string | string[]); - /** Initial width, in pixels, of the cell */ - width?: number; - /** Min width, in pixels, of the cell */ - minWidth?: number; - /** Max width, in pixels, of the cell */ - maxWidth?: number; - /** Class to use for the cell. Can be string, array of strings, or function. */ - cellClass?: string | string[] | ((cellClassParams: any) => string | string[]); - /** An object of css values. Or a function returning an object of css values. */ - cellStyle?: {} | ((params: any) => {}); - /** A function for rendering a cell. */ - cellRenderer?: Function | {}; - /** A function for rendering a floating cell. */ - floatingCellRenderer?: Function | {}; - /** Name of function to use for aggregation. One of [sum,min,max]. */ - aggFunc?: string; - /** Comparator function for custom sorting. */ - comparator?: Function; - /** Set to true to render a selection checkbox in the column. */ - checkboxSelection?: boolean; - /** Set to true if no menu should be shown for this column header. */ - suppressMenu?: boolean; - /** Set to true if no sorting should be done for this column. */ - suppressSorting?: boolean; - /** Set to true if you want the unsorted icon to be shown when no sort is applied to this column. */ - unSortIcon?: boolean; - /** Set to true if you want this columns width to be fixed during 'size to fit' operation. */ - suppressSizeToFit?: boolean; - /** Set to true if you do not want this column to be resizable by dragging it's edge. */ - suppressResize?: boolean; - /** If grouping columns, the group this column belongs to. */ - headerGroup?: string; - /** Whether to show the column when the group is open / closed. */ - headerGroupShow?: string; - /** Set to true if this col is editable, otherwise false. Can also be a function to have different rows editable. */ - editable?: boolean | (Function); - /** Callbacks for editing.See editing section for further details. */ - newValueHandler?: Function; - /** If true, this cell gets refreshed when api.softRefreshView() gets called. */ - volatile?: boolean; - /** Cell template to use for cell. Useful for AngularJS cells. */ - template?: string; - /** Cell template URL to load template from to use for cell. Useful for AngularJS cells. */ - templateUrl?: string; - /** one of the built in filter names: [set, number, text], or a filter function*/ - filter?: string | Function; - /** The filter params are specific to each filter! */ - filterParams?: SetFilterParameters | TextAndNumberFilterParameters; - /** Rules for applying css classes */ - cellClassRules?: { - [cssClassName: string]: (Function | string); - }; - /** Callbacks for editing.See editing section for further details. */ - onCellValueChanged?: Function; - /** Function callback, gets called when a cell is clicked. */ - onCellClicked?: Function; - /** Function callback, gets called when a cell is double clicked. */ - onCellDoubleClicked?: Function; - /** Function callback, gets called when a cell is right clicked. */ - onCellContextMenu?: Function; - } -} -declare namespace ag.grid { - class SetFilterModel { - private colDef; - private filterParams; - private rowModel; - private valueGetter; - private allUniqueValues; - private availableUniqueValues; - private displayedValues; - private miniFilter; - private selectedValuesCount; - private selectedValuesMap; - private showingAvailableOnly; - private usingProvidedSet; - private doesRowPassOtherFilters; - constructor(colDef: ColDef, rowModel: any, valueGetter: any, doesRowPassOtherFilters: any); - refreshAfterNewRowsLoaded(keepSelection: any, isSelectAll: boolean): void; - refreshAfterAnyFilterChanged(): void; - private createAllUniqueValues(); - private createAvailableUniqueValues(); - private getUniqueValues(filterOutNotAvailable); - setMiniFilter(newMiniFilter: any): boolean; - getMiniFilter(): any; - private processMiniFilter(); - getDisplayedValueCount(): any; - getDisplayedValue(index: any): any; - selectEverything(): void; - isFilterActive(): boolean; - selectNothing(): void; - getUniqueValueCount(): any; - getUniqueValue(index: any): any; - unselectValue(value: any): void; - selectValue(value: any): void; - isValueSelected(value: any): boolean; - isEverythingSelected(): boolean; - isNothingSelected(): boolean; - getModel(): any; - setModel(model: any, isSelectAll: boolean): void; - } -} -/** The filter parameters for set filter */ -declare namespace ag.grid { - interface SetFilterParameters { - /** Same as cell renderer for grid (you can use the same one in both locations). Setting it separatly here allows for the value to be rendered differently in the filter. */ - cellRenderer?: Function; - /** The height of the cell. */ - cellHeight?: number; - /** The values to display in the filter. */ - values?: any; - /** What to do when new rows are loaded. The default is to reset the filter, as the set of values to select from can have changed. If you want to keep the selection, then set this value to 'keep'. */ - newRowsAction?: string; - /** If true, the filter will not remove items that are no longer availabe due to other filters. */ - suppressRemoveEntries?: boolean; - } -} -declare namespace ag.grid { - class SetFilter implements Filter { - private eGui; - private filterParams; - private rowHeight; - private model; - private filterChangedCallback; - private filterModifiedCallback; - private valueGetter; - private rowsInBodyContainer; - private colDef; - private localeTextFunc; - private cellRenderer; - private eListContainer; - private eFilterValueTemplate; - private eSelectAll; - private eListViewport; - private eMiniFilter; - private api; - private applyActive; - private eApplyButton; - init(params: any): void; - afterGuiAttached(): void; - isFilterActive(): boolean; - doesFilterPass(node: any): boolean; - getGui(): any; - onNewRowsLoaded(): void; - onAnyFilterChanged(): void; - private createTemplate(); - private createGui(); - private setupApply(); - private setContainerHeight(); - private drawVirtualRows(); - private ensureRowsRendered(start, finish); - private removeVirtualRows(rowsToRemove); - private insertRow(value, rowIndex); - private onCheckboxClicked(eCheckbox, value); - private filterChanged(); - private onMiniFilterChanged(); - private refreshVirtualRows(); - private clearVirtualRows(); - private onSelectAll(); - private updateAllCheckboxes(checked); - private addScrollListener(); - getApi(): any; - private createApi(); - } -} -declare namespace ag.grid { - class PopupService { - private ePopupParent; - init(ePopupParent: any): void; - positionPopup(eventSource: any, ePopup: any, minWidth: any): void; - addAsModalPopup(eChild: any, closeOnEsc: boolean): (event: any) => void; - } -} -declare namespace ag.grid { - interface RowNode { - /** Unique ID for the node. Can be though of as the index of the row in the original list, - * however exceptions apply so don't depend on uniqueness. */ - id?: number; - /** The user provided data */ - data?: any; - /** The parent node to this node, or empty if top level */ - parent?: RowNode; - /** How many levels this node is from the top */ - level?: number; - /** True if this node is a group node (ie has children) */ - group?: boolean; - /** True if this is the first child in this group */ - firstChild?: boolean; - /** True if this is the last child in this group */ - lastChild?: boolean; - /** The index of this node in the group */ - childIndex?: number; - /** True if this row is a floating row */ - floating?: boolean; - /** True if this row is a floating top row */ - floatingTop?: boolean; - /** True if this row is a floating bottom row */ - floatingBottom?: boolean; - /** If using quick filter, stores a string representation of the row for searching against */ - quickFilterAggregateText?: string; - /** Groups only - True if row is a footer. Footers have group = true and footer = true */ - footer?: boolean; - /** Groups only - Children of this group */ - children?: RowNode[]; - /** Groups only - The field we are pivoting on eg Country*/ - field?: string; - /** Groups only - The key for the pivot eg Ireland, UK, USA */ - key?: any; - /** Groups only - Filtered children of this group */ - childrenAfterFilter?: RowNode[]; - /** Groups only - Sorted children of this group */ - childrenAfterSort?: RowNode[]; - /** Groups only - Number of children and grand children */ - allChildrenCount?: number; - /** Groups only - True if group is expanded, otherwise false */ - expanded?: boolean; - /** Groups only - If doing footers, reference to the footer node for this group */ - sibling?: RowNode; - /** Not to be used, internal temporary map used by the grid when creating groups */ - _childrenMap?: {}; - } -} -declare namespace ag.grid { - class FilterManager { - private $compile; - private $scope; - private gridOptionsWrapper; - private grid; - private allFilters; - private rowModel; - private popupService; - private valueService; - private columnController; - private quickFilter; - private advancedFilterPresent; - private externalFilterPresent; - init(grid: Grid, gridOptionsWrapper: GridOptionsWrapper, $compile: any, $scope: any, columnController: ColumnController, popupService: PopupService, valueService: ValueService): void; - setFilterModel(model: any): void; - private setModelOnFilterWrapper(filter, newModel); - getFilterModel(): any; - setRowModel(rowModel: any): void; - isAdvancedFilterPresent(): boolean; - isAnyFilterPresent(): boolean; - isFilterPresentForCol(colId: any): any; - private doesFilterPass(node, filterToSkip?); - setQuickFilter(newFilter: any): boolean; - onFilterChanged(): void; - isQuickFilterPresent(): boolean; - doesRowPassOtherFilters(filterToSkip: any, node: any): boolean; - doesRowPassFilter(node: any, filterToSkip?: any): boolean; - private aggregateRowForQuickFilter(node); - refreshDisplayedValues(): void; - onNewRowsLoaded(): void; - private createValueGetter(column); - getFilterApi(column: Column): any; - private getOrCreateFilterWrapper(column); - private createFilterWrapper(column); - private assertMethodHasNoParameters(theMethod); - showFilter(column: Column, eventSource: any): void; - } -} -declare namespace ag.grid { - class TemplateService { - templateCache: any; - waitingCallbacks: any; - $scope: any; - init($scope: any): void; - getTemplate(url: any, callback: any): any; - handleHttpResult(httpResult: any, url: any): void; - } -} -declare namespace ag.grid { - class SelectionRendererFactory { - private angularGrid; - private selectionController; - init(angularGrid: any, selectionController: any): void; - createSelectionCheckbox(node: any, rowIndex: any): HTMLInputElement; - } -} -declare namespace ag.vdom { - class VElement { - static idSequence: number; - private id; - private elementAttachedListeners; - constructor(); - getId(): number; - addElementAttachedListener(listener: (element: Element) => void): void; - protected fireElementAttached(element: Element): void; - elementAttached(element: Element): void; - toHtmlString(): string; - } -} -declare namespace ag.vdom { - class VHtmlElement extends VElement { - private type; - private classes; - private eventListeners; - private attributes; - private children; - private innerHtml; - private style; - private bound; - private element; - constructor(type: string); - getElement(): HTMLElement; - setInnerHtml(innerHtml: string): void; - addStyles(styles: any): void; - private attachEventListeners(node); - addClass(newClass: string): void; - removeClass(oldClass: string): void; - addClasses(classes: string[]): void; - toHtmlString(): string; - private toHtmlStringChildren(); - private toHtmlStringAttributes(); - private toHtmlStringClasses(); - private toHtmlStringStyles(); - appendChild(child: any): void; - setAttribute(key: string, value: string): void; - addEventListener(event: string, listener: EventListener): void; - elementAttached(element: Element): void; - fireElementAttachedToChildren(element: Element): void; - } -} -declare namespace ag.vdom { - class VWrapperElement extends VElement { - private wrappedElement; - constructor(wrappedElement: Element); - toHtmlString(): string; - elementAttached(element: Element): void; - } -} -declare namespace ag.grid { - class RenderedCell { - private vGridCell; - private vSpanWithValue; - private vCellWrapper; - private vParentOfValue; - private checkboxOnChangeListener; - private column; - private data; - private node; - private rowIndex; - private editingCell; - private scope; - private isFirstColumn; - private gridOptionsWrapper; - private expressionService; - private selectionRendererFactory; - private rowRenderer; - private selectionController; - private $compile; - private templateService; - private cellRendererMap; - private eCheckbox; - private columnController; - private valueService; - private eventService; - private value; - private checkboxSelection; - constructor(isFirstColumn: any, column: any, $compile: any, rowRenderer: RowRenderer, gridOptionsWrapper: GridOptionsWrapper, expressionService: ExpressionService, selectionRendererFactory: SelectionRendererFactory, selectionController: SelectionController, templateService: TemplateService, cellRendererMap: { - [key: string]: any; - }, node: any, rowIndex: number, scope: any, columnController: ColumnController, valueService: ValueService, eventService: EventService); - getColumn(): Column; - private getValue(); - getVGridCell(): ag.vdom.VHtmlElement; - private getDataForRow(); - private setupComponents(); - startEditing(key?: number): void; - focusCell(forceBrowserFocus: boolean): void; - private stopEditing(eInput, blurListener, reset?); - createParams(): any; - createEvent(event: any, eventSource: any): any; - private addCellDoubleClickedHandler(); - private addCellContextMenuHandler(); - isCellEditable(): any; - private addCellClickedHandler(); - private populateCell(); - private addStylesFromCollDef(); - private addClassesFromCollDef(); - private addClassesFromRules(); - private addCellNavigationHandler(); - private isKeycodeForStartEditing(key); - createSelectionCheckbox(): void; - setSelected(state: boolean): void; - private createParentOfValue(); - isVolatile(): boolean; - refreshCell(): void; - private putDataIntoCell(); - private useCellRenderer(cellRenderer); - private addClasses(); - } -} -declare namespace ag.grid { - class RenderedRow { - vPinnedRow: any; - vBodyRow: any; - private renderedCells; - private scope; - private node; - private rowIndex; - private cellRendererMap; - private gridOptionsWrapper; - private parentScope; - private angularGrid; - private columnController; - private expressionService; - private rowRenderer; - private selectionRendererFactory; - private $compile; - private templateService; - private selectionController; - private pinning; - private eBodyContainer; - private ePinnedContainer; - private valueService; - private eventService; - constructor(gridOptionsWrapper: GridOptionsWrapper, valueService: ValueService, parentScope: any, angularGrid: Grid, columnController: ColumnController, expressionService: ExpressionService, cellRendererMap: { - [key: string]: any; - }, selectionRendererFactory: SelectionRendererFactory, $compile: any, templateService: TemplateService, selectionController: SelectionController, rowRenderer: RowRenderer, eBodyContainer: HTMLElement, ePinnedContainer: HTMLElement, node: any, rowIndex: number, eventService: EventService); - onRowSelected(selected: boolean): void; - softRefresh(): void; - getRenderedCellForColumn(column: Column): RenderedCell; - getCellForCol(column: Column): any; - destroy(): void; - private destroyScope(); - isDataInList(rows: any[]): boolean; - isNodeInList(nodes: RowNode[]): boolean; - isGroup(): boolean; - private drawNormalRow(); - private bindVirtualElement(vElement); - private createGroupRow(); - private createGroupSpanningEntireRowCell(padding); - setMainRowWidth(width: number): void; - private createChildScopeOrNull(data); - private addDynamicStyles(); - private createRowContainer(); - getRowNode(): any; - getRowIndex(): any; - refreshCells(colIds: string[]): void; - private addDynamicClasses(); - } -} -declare namespace ag.grid { - class SvgFactory { - static theInstance: SvgFactory; - static getInstance(): SvgFactory; - createFilterSvg(): Element; - createColumnShowingSvg(): Element; - createColumnHiddenSvg(): Element; - createMenuSvg(): Element; - createArrowUpSvg(): Element; - createArrowLeftSvg(): Element; - createArrowDownSvg(): Element; - createArrowRightSvg(): Element; - createSmallArrowDownSvg(): Element; - createArrowUpDownSvg(): Element; - } -} -declare namespace ag.grid { - function groupCellRendererFactory(gridOptionsWrapper: GridOptionsWrapper, selectionRendererFactory: SelectionRendererFactory, expressionService: ExpressionService): (params: any) => HTMLSpanElement; -} -declare namespace ag.grid { - class RowRenderer { - private columnModel; - private gridOptionsWrapper; - private angularGrid; - private selectionRendererFactory; - private gridPanel; - private $compile; - private $scope; - private selectionController; - private expressionService; - private templateService; - private cellRendererMap; - private rowModel; - private firstVirtualRenderedRow; - private lastVirtualRenderedRow; - private focusedCell; - private valueService; - private eventService; - private renderedRows; - private renderedTopFloatingRows; - private renderedBottomFloatingRows; - private eAllBodyContainers; - private eAllPinnedContainers; - private eBodyContainer; - private eBodyViewport; - private ePinnedColsContainer; - private eFloatingTopContainer; - private eFloatingTopPinnedContainer; - private eFloatingBottomContainer; - private eFloatingBottomPinnedContainer; - private eParentsOfRows; - init(columnModel: any, gridOptionsWrapper: GridOptionsWrapper, gridPanel: GridPanel, angularGrid: Grid, selectionRendererFactory: SelectionRendererFactory, $compile: any, $scope: any, selectionController: SelectionController, expressionService: ExpressionService, templateService: TemplateService, valueService: ValueService, eventService: EventService): void; - setRowModel(rowModel: any): void; - onIndividualColumnResized(column: Column): void; - setMainRowWidths(): void; - private findAllElements(gridPanel); - refreshAllFloatingRows(): void; - private refreshFloatingRows(renderedRows, rowData, pinnedContainer, bodyContainer, isTop); - refreshView(refreshFromIndex?: any): void; - softRefreshView(): void; - refreshRows(rowNodes: RowNode[]): void; - refreshCells(rowNodes: RowNode[], colIds: string[]): void; - rowDataChanged(rows: any): void; - private refreshAllVirtualRows(fromIndex); - refreshGroupRows(): void; - private removeVirtualRow(rowsToRemove, fromIndex?); - private unbindVirtualRow(indexToRemove); - drawVirtualRows(): void; - getFirstVirtualRenderedRow(): number; - getLastVirtualRenderedRow(): number; - private ensureRowsRendered(); - private insertRow(node, rowIndex, mainRowWidth); - getRenderedNodes(): any[]; - getIndexOfRenderedNode(node: any): number; - navigateToNextCell(key: any, rowIndex: number, column: Column): void; - private getNextCellToFocus(key, lastCellToFocus); - onRowSelected(rowIndex: number, selected: boolean): void; - focusCell(eCell: any, rowIndex: number, colIndex: number, colDef: ColDef, forceBrowserFocus: any): void; - getFocusedCell(): any; - setFocusedCell(rowIndex: any, colIndex: any): void; - startEditingNextCell(rowIndex: any, column: any, shiftKey: any): void; - } -} -declare namespace ag.grid { - class SelectionController { - private eParentsOfRows; - private angularGrid; - private gridOptionsWrapper; - private $scope; - private rowRenderer; - private selectedRows; - private selectedNodesById; - private rowModel; - private eventService; - init(angularGrid: Grid, gridPanel: GridPanel, gridOptionsWrapper: GridOptionsWrapper, $scope: any, rowRenderer: RowRenderer, eventService: EventService): void; - private initSelectedNodesById(); - getSelectedNodesById(): any; - getSelectedRows(): any; - getSelectedNodes(): any; - getBestCostNodeSelection(): any; - setRowModel(rowModel: any): void; - deselectAll(): void; - selectAll(): void; - selectNode(node: any, tryMulti: any, suppressEvents?: any): void; - private recursivelySelectAllChildren(node, suppressEvents?); - private recursivelyDeselectAllChildren(node); - private doWorkOfSelectNode(node, suppressEvents); - private addCssClassForNode_andInformVirtualRowListener(node); - private doWorkOfDeselectAllNodes(nodeToKeepSelected?); - private deselectRealNode(node); - private removeCssClassForNode(node); - deselectIndex(rowIndex: any): void; - deselectNode(node: any): void; - selectIndex(index: any, tryMulti: any, suppressEvents?: any): void; - private syncSelectedRowsAndCallListener(suppressEvents?); - private recursivelyCheckIfSelected(node); - isNodeSelected(node: any): boolean; - private updateGroupParentsIfNeeded(); - } -} -declare namespace ag.grid { - class RenderedHeaderElement { - private eRoot; - private dragStartX; - constructor(eRoot: HTMLElement); - getERoot(): HTMLElement; - destroy(): void; - refreshFilterIcon(): void; - refreshSortIcon(): void; - onDragStart(): void; - onDragging(dragChange: number): void; - onIndividualColumnResized(column: Column): void; - addDragHandler(eDraggableElement: any): void; - stopDragging(listenersToRemove: any): void; - } -} -declare namespace ag.grid { - class RenderedHeaderCell extends RenderedHeaderElement { - private static DEFAULT_SORTING_ORDER; - private eHeaderCell; - private eSortAsc; - private eSortDesc; - private eSortNone; - private eFilterIcon; - private column; - private gridOptionsWrapper; - private parentScope; - private childScope; - private filterManager; - private columnController; - private $compile; - private angularGrid; - private parentGroup; - private startWidth; - constructor(column: Column, parentGroup: RenderedHeaderGroupCell, gridOptionsWrapper: GridOptionsWrapper, parentScope: any, filterManager: FilterManager, columnController: ColumnController, $compile: any, angularGrid: Grid, eRoot: HTMLElement); - getGui(): HTMLElement; - destroy(): void; - private createScope(); - private addAttributes(); - private addClasses(); - private addMenu(); - private addSortIcons(headerCellLabel); - private setupComponents(); - private useRenderer(headerNameValue, headerCellRenderer, headerCellLabel); - refreshFilterIcon(): void; - refreshSortIcon(): void; - private getNextSortDirection(); - private addSortHandling(headerCellLabel); - onDragStart(): void; - onDragging(dragChange: number): void; - onIndividualColumnResized(column: Column): void; - private addHeaderClassesFromCollDef(); - } -} -declare namespace ag.grid { - class RenderedHeaderGroupCell extends RenderedHeaderElement { - private eHeaderGroup; - private eHeaderGroupCell; - private eHeaderCellResize; - private columnGroup; - private gridOptionsWrapper; - private columnController; - private children; - private groupWidthStart; - private childrenWidthStarts; - private minWidth; - private parentScope; - private filterManager; - private $compile; - private angularGrid; - constructor(columnGroup: ColumnGroup, gridOptionsWrapper: GridOptionsWrapper, columnController: ColumnController, eRoot: HTMLElement, angularGrid: Grid, parentScope: any, filterManager: FilterManager, $compile: any); - getGui(): HTMLElement; - destroy(): void; - refreshFilterIcon(): void; - refreshSortIcon(): void; - onIndividualColumnResized(column: Column): void; - private setupComponents(); - private isColumnInOurDisplayedGroup(column); - private setWidthOfGroupHeaderCell(); - private addGroupExpandIcon(eGroupCellLabel); - onDragStart(): void; - onDragging(dragChange: any): void; - } -} -declare namespace ag.grid { - class HeaderRenderer { - private gridOptionsWrapper; - private columnController; - private angularGrid; - private filterManager; - private $scope; - private $compile; - private ePinnedHeader; - private eHeaderContainer; - private eRoot; - private headerElements; - init(gridOptionsWrapper: GridOptionsWrapper, columnController: ColumnController, gridPanel: GridPanel, angularGrid: Grid, filterManager: FilterManager, $scope: any, $compile: any): void; - private findAllElements(gridPanel); - refreshHeader(): void; - private insertHeadersWithGrouping(); - private insertHeadersWithoutGrouping(); - updateSortIcons(): void; - updateFilterIcons(): void; - onIndividualColumnResized(column: Column): void; - } -} -declare namespace ag.grid { - class GroupCreator { - private valueService; - init(valueService: ValueService): void; - group(rowNodes: RowNode[], groupedCols: Column[], expandByDefault: any): RowNode[]; - isExpanded(expandByDefault: any, level: any): boolean; - } -} -declare namespace ag.grid { - class InMemoryRowController { - private gridOptionsWrapper; - private columnController; - private angularGrid; - private filterManager; - private $scope; - private allRows; - private rowsAfterGroup; - private rowsAfterFilter; - private rowsAfterSort; - private rowsAfterMap; - private model; - private groupCreator; - private valueService; - private eventService; - constructor(); - init(gridOptionsWrapper: GridOptionsWrapper, columnController: ColumnController, angularGrid: any, filterManager: FilterManager, $scope: any, groupCreator: GroupCreator, valueService: ValueService, eventService: EventService): void; - private createModel(); - getModel(): any; - forEachInMemory(callback: Function): void; - forEachNode(callback: Function): void; - forEachNodeAfterFilter(callback: Function): void; - forEachNodeAfterFilterAndSort(callback: Function): void; - private recursivelyWalkNodesAndCallback(list, callback); - updateModel(step: any): void; - private defaultGroupAggFunctionFactory(valueColumns, valueKeys); - doAggregate(): void; - expandOrCollapseAll(expand: boolean, rowNodes: RowNode[]): void; - private recursivelyClearAggData(nodes); - private recursivelyCreateAggData(nodes, groupAggFunction, level); - private doSort(); - private recursivelyResetSort(rowNodes); - private sortList(nodes, sortOptions); - private updateChildIndexes(nodes); - onPivotChanged(): void; - private doPivoting(); - private doFilter(); - private filterItems(rowNodes); - private recursivelyResetFilter(nodes); - setAllRows(rows: RowNode[], firstId?: number): void; - private recursivelyAddIdToNodes(nodes, index); - private recursivelyCheckUserProvidedNodes(nodes, parent, level); - private getTotalChildCount(rowNodes); - private doGroupMapping(); - private addToMap(mappedData, originalNodes); - private createFooterNode(groupNode); - } -} -declare namespace ag.grid { - class VirtualPageRowController { - rowRenderer: any; - datasourceVersion: any; - gridOptionsWrapper: any; - angularGrid: any; - datasource: any; - virtualRowCount: any; - foundMaxRow: any; - pageCache: any; - pageCacheSize: any; - pageLoadsInProgress: any; - pageLoadsQueued: any; - pageAccessTimes: any; - accessTime: any; - maxConcurrentDatasourceRequests: any; - maxPagesInCache: any; - pageSize: any; - overflowSize: any; - init(rowRenderer: any, gridOptionsWrapper: any, angularGrid: any): void; - setDatasource(datasource: any): void; - reset(): void; - createNodesFromRows(pageNumber: any, rows: any): any; - removeFromLoading(pageNumber: any): void; - pageLoadFailed(pageNumber: any): void; - pageLoaded(pageNumber: any, rows: any, lastRow: any): void; - putPageIntoCacheAndPurge(pageNumber: any, rows: any): void; - checkMaxRowAndInformRowRenderer(pageNumber: any, lastRow: any): void; - isPageAlreadyLoading(pageNumber: any): boolean; - doLoadOrQueue(pageNumber: any): void; - addToQueueAndPurgeQueue(pageNumber: any): void; - findLeastRecentlyAccessedPage(pageIndexes: any): number; - checkQueueForNextLoad(): void; - loadPage(pageNumber: any): void; - requestIsDaemon(datasourceVersionCopy: any): boolean; - getVirtualRow(rowIndex: any): any; - forEachNode(callback: any): void; - getModel(): { - getVirtualRow: (index: any) => any; - getVirtualRowCount: () => any; - forEachInMemory: (callback: any) => void; - forEachNode: (callback: any) => void; - forEachNodeAfterFilter: (callback: any) => void; - forEachNodeAfterFilterAndSort: (callback: any) => void; - }; - } -} -declare namespace ag.grid { - class PaginationController { - eGui: any; - btNext: any; - btPrevious: any; - btFirst: any; - btLast: any; - lbCurrent: any; - lbTotal: any; - lbRecordCount: any; - lbFirstRowOnPage: any; - lbLastRowOnPage: any; - ePageRowSummaryPanel: any; - angularGrid: any; - callVersion: any; - gridOptionsWrapper: any; - datasource: any; - pageSize: any; - rowCount: any; - foundMaxRow: any; - totalPages: any; - currentPage: any; - init(angularGrid: any, gridOptionsWrapper: any): void; - setDatasource(datasource: any): void; - reset(): void; - setTotalLabels(): void; - calculateTotalPages(): void; - pageLoaded(rows: any, lastRowIndex: any): void; - updateRowLabels(): void; - loadPage(): void; - isCallDaemon(versionCopy: any): boolean; - onBtNext(): void; - onBtPrevious(): void; - onBtFirst(): void; - onBtLast(): void; - isZeroPagesToDisplay(): boolean; - enableOrDisableButtons(): void; - createTemplate(): string; - getGui(): any; - setupComponents(): void; - } -} -declare namespace ag.grid { - class BorderLayout { - private eNorthWrapper; - private eSouthWrapper; - private eEastWrapper; - private eWestWrapper; - private eCenterWrapper; - private eOverlayWrapper; - private eCenterRow; - private eNorthChildLayout; - private eSouthChildLayout; - private eEastChildLayout; - private eWestChildLayout; - private eCenterChildLayout; - private isLayoutPanel; - private fullHeight; - private layoutActive; - private eGui; - private id; - private childPanels; - private centerHeightLastTime; - private sizeChangeListners; - constructor(params: any); - addSizeChangeListener(listener: Function): void; - fireSizeChanged(): void; - private setupPanels(params); - private setupPanel(content, ePanel); - getGui(): any; - doLayout(): boolean; - private layoutChild(childPanel); - private layoutHeight(); - private layoutHeightFullHeight(); - private layoutHeightNormal(); - getCentreHeight(): number; - private layoutWidth(); - setEastVisible(visible: any): void; - setOverlayVisible(visible: any): void; - setSouthVisible(visible: any): void; - } -} -declare namespace ag.grid { - class GridPanel { - private masterSlaveService; - private gridOptionsWrapper; - private columnModel; - private rowRenderer; - private rowModel; - private layout; - private forPrint; - private scrollWidth; - private scrollLagCounter; - private eBodyViewport; - private eRoot; - private eBody; - private eBodyContainer; - private ePinnedColsContainer; - private eHeaderContainer; - private ePinnedHeader; - private eHeader; - private eParentsOfRows; - private eBodyViewportWrapper; - private ePinnedColsViewport; - private eFloatingTop; - private ePinnedFloatingTop; - private eFloatingTopContainer; - private eFloatingBottom; - private ePinnedFloatingBottom; - private eFloatingBottomContainer; - init(gridOptionsWrapper: GridOptionsWrapper, columnModel: ColumnController, rowRenderer: RowRenderer, masterSlaveService: MasterSlaveService): void; - getLayout(): BorderLayout; - private setupComponents(); - getPinnedFloatingTop(): HTMLElement; - getFloatingTopContainer(): HTMLElement; - getPinnedFloatingBottom(): HTMLElement; - getFloatingBottomContainer(): HTMLElement; - private createTemplate(); - ensureIndexVisible(index: any): void; - ensureColIndexVisible(index: any): void; - showLoading(loading: any): void; - getWidthForSizeColsToFit(): number; - setRowModel(rowModel: any): void; - getBodyContainer(): HTMLElement; - getBodyViewport(): HTMLElement; - getPinnedColsContainer(): HTMLElement; - getHeaderContainer(): HTMLElement; - getRoot(): HTMLElement; - getPinnedHeader(): HTMLElement; - getRowsParent(): HTMLElement[]; - private queryHtmlElement(selector); - private findElements(); - private mouseWheelListener(event); - setBodyContainerWidth(): void; - setPinnedColContainerWidth(): void; - showPinnedColContainersIfNeeded(): void; - onBodyHeightChange(): void; - private sizeHeaderAndBody(); - private sizeHeaderAndBodyNormal(); - private sizeHeaderAndBodyForPrint(); - setHorizontalScrollPosition(hScrollPosition: number): void; - private addScrollListener(); - private requestDrawVirtualRows(); - private scrollHeader(bodyLeftPosition); - private scrollPinned(bodyTopPosition); - } -} -declare namespace ag.grid { - class DragAndDropService { - static theInstance: DragAndDropService; - static getInstance(): DragAndDropService; - dragItem: any; - constructor(); - stopDragging(): void; - setDragCssClasses(eListItem: any, dragging: any): void; - addDragSource(eDragSource: any, dragSourceCallback: any): void; - onMouseDownDragSource(eDragSource: any, dragSourceCallback: any): void; - addDropTarget(eDropTarget: any, dropTargetCallback: any): void; - } -} -declare namespace ag.grid { - class AgList { - private eGui; - private uniqueId; - private modelChangedListeners; - private itemSelectedListeners; - private beforeDropListeners; - private itemMovedListeners; - private dragSources; - private emptyMessage; - private eFilterValueTemplate; - private eListParent; - private model; - private cellRenderer; - private readOnly; - constructor(); - setReadOnly(readOnly: boolean): void; - setEmptyMessage(emptyMessage: any): void; - getUniqueId(): any; - addStyles(styles: any): void; - addCssClass(cssClass: any): void; - addDragSource(dragSource: any): void; - addModelChangedListener(listener: Function): void; - addItemSelectedListener(listener: any): void; - addItemMovedListener(listener: any): void; - addBeforeDropListener(listener: any): void; - private fireItemMoved(fromIndex, toIndex); - private fireModelChanged(); - private fireItemSelected(item); - private fireBeforeDrop(item); - private setupComponents(); - setModel(model: any): void; - getModel(): any; - setCellRenderer(cellRenderer: any): void; - refreshView(): void; - private insertRows(); - private insertBlankMessage(); - private setupAsDropTarget(); - private externalAcceptDrag(dragEvent); - private externalDrop(dragEvent); - private externalNoDrop(); - private addItemToList(newItem); - private addDragAndDropToListItem(eListItem, item); - private internalAcceptDrag(targetColumn, dragItem, eListItem); - private internalDrop(targetColumn, draggedColumn); - private internalNoDrop(eListItem); - private dragAfterThisItem(targetColumn, draggedColumn); - private setDropCssClasses(eListItem, state); - getGui(): any; - } -} -declare namespace ag.grid { - class ColumnSelectionPanel { - private gridOptionsWrapper; - private columnController; - private cColumnList; - layout: any; - private eRootPanel; - constructor(columnController: ColumnController, gridOptionsWrapper: GridOptionsWrapper, eventService: EventService); - private columnsChanged(); - getDragSource(): any; - private columnCellRenderer(params); - private setupComponents(); - private onItemMoved(fromIndex, toIndex); - getGui(): any; - } -} -declare namespace ag.grid { - class GroupSelectionPanel { - gridOptionsWrapper: any; - columnController: ColumnController; - inMemoryRowController: any; - cColumnList: any; - layout: any; - constructor(columnController: ColumnController, inMemoryRowController: any, gridOptionsWrapper: GridOptionsWrapper, eventService: EventService); - private columnsChanged(); - addDragSource(dragSource: any): void; - private columnCellRenderer(params); - private setupComponents(); - private onBeforeDrop(newItem); - private onItemMoved(fromIndex, toIndex); - } -} -declare namespace ag.grid { - class AgDropdownList { - private itemSelectedListeners; - private eValue; - private agList; - private eGui; - private hidePopupCallback; - private selectedItem; - private cellRenderer; - private popupService; - constructor(popupService: PopupService); - setWidth(width: any): void; - addItemSelectedListener(listener: any): void; - fireItemSelected(item: any): void; - setupComponents(): void; - itemSelected(item: any): void; - onClick(): void; - getGui(): any; - setSelected(item: any): void; - setCellRenderer(cellRenderer: any): void; - refreshView(): void; - setModel(model: any): void; - } -} -declare namespace ag.grid { - class ValuesSelectionPanel { - private gridOptionsWrapper; - private columnController; - private cColumnList; - private layout; - private popupService; - constructor(columnController: ColumnController, gridOptionsWrapper: GridOptionsWrapper, popupService: PopupService, eventService: EventService); - getLayout(): any; - private columnsChanged(); - addDragSource(dragSource: any): void; - private cellRenderer(params); - private setupComponents(); - private beforeDropListener(newItem); - } -} -declare namespace ag.grid { - class VerticalStack { - isLayoutPanel: any; - childPanels: any; - eGui: any; - constructor(); - addPanel(panel: any, height: any): void; - getGui(): any; - doLayout(): void; - } -} -declare namespace ag.grid { - class ToolPanel { - layout: any; - constructor(); - init(columnController: any, inMemoryRowController: any, gridOptionsWrapper: GridOptionsWrapper, popupService: PopupService, eventService: EventService): void; - } -} -declare namespace ag.grid { - interface GridOptions { - virtualPaging?: boolean; - toolPanelSuppressPivot?: boolean; - toolPanelSuppressValues?: boolean; - rowsAlreadyGrouped?: boolean; - suppressRowClickSelection?: boolean; - suppressCellSelection?: boolean; - sortingOrder?: string[]; - suppressMultiSort?: boolean; - suppressHorizontalScroll?: boolean; - unSortIcon?: boolean; - rowHeight?: number; - rowBuffer?: number; - enableColResize?: boolean; - enableCellExpressions?: boolean; - enableSorting?: boolean; - enableServerSideSorting?: boolean; - enableFilter?: boolean; - enableServerSideFilter?: boolean; - colWidth?: number; - suppressMenuHide?: boolean; - singleClickEdit?: boolean; - debug?: boolean; - icons?: any; - angularCompileRows?: boolean; - angularCompileFilters?: boolean; - angularCompileHeaders?: boolean; - localeText?: any; - localeTextFunc?: Function; - suppressScrollLag?: boolean; - groupSuppressAutoColumn?: boolean; - groupSelectsChildren?: boolean; - groupHidePivotColumns?: boolean; - groupIncludeFooter?: boolean; - groupUseEntireRow?: boolean; - groupSuppressRow?: boolean; - groupSuppressBlankHeader?: boolean; - forPrint?: boolean; - groupColumnDef?: any; - context?: any; - rowStyle?: any; - rowClass?: any; - groupDefaultExpanded?: any; - slaveGrids?: GridOptions[]; - rowSelection?: string; - rowDeselection?: boolean; - rowData?: any[]; - floatingTopRowData?: any[]; - floatingBottomRowData?: any[]; - showToolPanel?: boolean; - groupKeys?: string[]; - groupAggFields?: string[]; - columnDefs?: any[]; - datasource?: any; - pinnedColumnCount?: number; - groupHeaders?: boolean; - headerHeight?: number; - groupRowInnerRenderer?(params: any): void; - groupRowRenderer?: Function | Object; - isScrollLag?(): boolean; - isExternalFilterPresent?(): boolean; - doesExternalFilterPass?(node: RowNode): boolean; - getRowStyle?: any; - getRowClass?: any; - headerCellRenderer?: any; - groupAggFunction?(nodes: any[]): any; - onReady?(api: any): void; - onModelUpdated?(): void; - onCellClicked?(params: any): void; - onCellDoubleClicked?(params: any): void; - onCellContextMenu?(params: any): void; - onCellValueChanged?(params: any): void; - onCellFocused?(params: any): void; - onRowSelected?(params: any): void; - onSelectionChanged?(): void; - onBeforeFilterChanged?(): void; - onAfterFilterChanged?(): void; - onFilterModified?(): void; - onBeforeSortChanged?(): void; - onAfterSortChanged?(): void; - onVirtualRowRemoved?(params: any): void; - onRowClicked?(params: any): void; - api?: GridApi; - columnApi?: ColumnApi; - } -} -declare namespace ag.grid { - class GridApi { - private grid; - private rowRenderer; - private headerRenderer; - private filterManager; - private columnController; - private inMemoryRowController; - private selectionController; - private gridOptionsWrapper; - private gridPanel; - private valueService; - private masterSlaveService; - private eventService; - private csvCreator; - constructor(grid: Grid, rowRenderer: RowRenderer, headerRenderer: HeaderRenderer, filterManager: FilterManager, columnController: ColumnController, inMemoryRowController: InMemoryRowController, selectionController: SelectionController, gridOptionsWrapper: GridOptionsWrapper, gridPanel: GridPanel, valueService: ValueService, masterSlaveService: MasterSlaveService, eventService: EventService); - /** Used internally by grid. Not intended to be used by the client. Interface may change between releases. */ - __getMasterSlaveService(): MasterSlaveService; - getDataAsCsv(params?: CsvExportParams): string; - exportDataAsCsv(params?: CsvExportParams): void; - setDatasource(datasource: any): void; - onNewDatasource(): void; - setRowData(rowData: any): void; - setRows(rows: any): void; - onNewRows(): void; - setFloatingTopRowData(rows: any[]): void; - setFloatingBottomRowData(rows: any[]): void; - onNewCols(): void; - setColumnDefs(colDefs: ColDef[]): void; - unselectAll(): void; - refreshRows(rowNodes: RowNode[]): void; - refreshCells(rowNodes: RowNode[], colIds: string[]): void; - rowDataChanged(rows: any): void; - refreshView(): void; - softRefreshView(): void; - refreshGroupRows(): void; - refreshHeader(): void; - isAnyFilterPresent(): boolean; - isAdvancedFilterPresent(): boolean; - isQuickFilterPresent(): boolean; - getModel(): any; - onGroupExpandedOrCollapsed(refreshFromIndex: any): void; - expandAll(): void; - collapseAll(): void; - addVirtualRowListener(rowIndex: any, callback: any): void; - setQuickFilter(newFilter: any): void; - selectIndex(index: any, tryMulti: any, suppressEvents: any): void; - deselectIndex(index: any): void; - selectNode(node: any, tryMulti: any, suppressEvents: any): void; - deselectNode(node: any): void; - selectAll(): void; - deselectAll(): void; - recomputeAggregates(): void; - sizeColumnsToFit(): void; - showLoading(show: any): void; - isNodeSelected(node: any): boolean; - getSelectedNodesById(): { - [nodeId: number]: RowNode; - }; - getSelectedNodes(): RowNode[]; - getSelectedRows(): any[]; - getBestCostNodeSelection(): any; - getRenderedNodes(): any[]; - ensureColIndexVisible(index: any): void; - ensureIndexVisible(index: any): void; - ensureNodeVisible(comparator: any): void; - forEachInMemory(callback: Function): void; - forEachNode(callback: Function): void; - forEachNodeAfterFilter(callback: Function): void; - forEachNodeAfterFilterAndSort(callback: Function): void; - getFilterApiForColDef(colDef: any): any; - getFilterApi(key: any): any; - getColumnDef(key: any): ColDef; - onFilterChanged(): void; - setSortModel(sortModel: any): void; - getSortModel(): any; - setFilterModel(model: any): void; - getFilterModel(): any; - getFocusedCell(): any; - setFocusedCell(rowIndex: any, colIndex: any): void; - setHeaderHeight(headerHeight: number): void; - setGroupHeaders(groupHeaders: boolean): void; - showToolPanel(show: any): void; - isToolPanelShowing(): boolean; - hideColumn(colId: any, hide: any): void; - hideColumns(colIds: any, hide: any): void; - getColumnState(): [any]; - setColumnState(state: any): void; - doLayout(): void; - getValue(colDef: ColDef, data: any, node: any): any; - addEventListener(eventType: string, listener: Function): void; - addGlobalListener(listener: Function): void; - removeEventListener(eventType: string, listener: Function): void; - removeGlobalListener(listener: Function): void; - refreshPivot(): void; - } -} -declare namespace ag.grid { - class ValueService { - private gridOptionsWrapper; - private expressionService; - private columnController; - init(gridOptionsWrapper: GridOptionsWrapper, expressionService: ExpressionService, columnController: ColumnController): void; - getValue(colDef: ColDef, data: any, node: any): any; - private executeValueGetter(valueGetter, data, colDef, node); - private getValueCallback(data, node, field); - } -} -declare namespace ag.grid { - class Grid { - private virtualRowCallbacks; - private gridOptions; - private gridOptionsWrapper; - private inMemoryRowController; - private doingVirtualPaging; - private paginationController; - private virtualPageRowController; - private finished; - private selectionController; - private columnController; - private rowRenderer; - private headerRenderer; - private filterManager; - private valueService; - private masterSlaveService; - private eventService; - private toolPanel; - private gridPanel; - private eRootPanel; - private toolPanelShowing; - private doingPagination; - private usingInMemoryModel; - private rowModel; - constructor(eGridDiv: any, gridOptions: any, globalEventListener?: Function, $scope?: any, $compile?: any, quickFilterOnScope?: any); - getRowModel(): any; - private periodicallyDoLayout(); - private setupComponents($scope, $compile, eUserProvidedDiv, globalEventListener); - private onColumnChanged(event); - refreshPivot(): void; - getEventService(): EventService; - private onIndividualColumnResized(column); - showToolPanel(show: any): void; - isToolPanelShowing(): boolean; - isUsingInMemoryModel(): boolean; - setDatasource(datasource?: any): void; - private refreshHeaderAndBody(); - setFinished(): void; - onQuickFilterChanged(newFilter: any): void; - onFilterModified(): void; - onFilterChanged(): void; - onRowClicked(event: any, rowIndex: any, node: any): void; - showLoadingPanel(show: any): void; - private setupColumns(); - updateModelAndRefresh(step: any, refreshFromIndex?: any): void; - setRows(rows?: any, firstId?: any): void; - ensureNodeVisible(comparator: any): void; - getFilterModel(): any; - setFocusedCell(rowIndex: any, colIndex: any): void; - getSortModel(): any; - setSortModel(sortModel: any): void; - onSortingChanged(): void; - addVirtualRowListener(rowIndex: any, callback: any): void; - onVirtualRowSelected(rowIndex: any, selected: any): void; - onVirtualRowRemoved(rowIndex: any): void; - setColumnDefs(colDefs?: ColDef[]): void; - updateBodyContainerWidthAfterColResize(): void; - updatePinnedColContainerWidthAfterColResize(): void; - doLayout(): void; - } -} -declare namespace ag.grid { - class ComponentUtil { - static SIMPLE_PROPERTIES: string[]; - static SIMPLE_NUMBER_PROPERTIES: string[]; - static SIMPLE_BOOLEAN_PROPERTIES: string[]; - static WITH_IMPACT_NUMBER_PROPERTIES: string[]; - static WITH_IMPACT_BOOLEAN_PROPERTIES: string[]; - static WITH_IMPACT_OTHER_PROPERTIES: string[]; - static CALLBACKS: string[]; - static ALL_PROPERTIES: string[]; - static copyAttributesToGridOptions(gridOptions: GridOptions, component: any): GridOptions; - static processOnChange(changes: any, gridOptions: GridOptions, component: any): void; - static toBoolean(value: any): boolean; - static toNumber(value: any): number; - } -} -declare namespace ag.grid { - class AgGridNg2 { - private elementDef; - private _agGrid; - private _initialised; - private gridOptions; - private api; - private columnApi; - modelUpdated: any; - cellClicked: any; - cellDoubleClicked: any; - cellContextMenu: any; - cellValueChanged: any; - cellFocused: any; - rowSelected: any; - selectionChanged: any; - beforeFilterChanged: any; - afterFilterChanged: any; - filterModified: any; - beforeSortChanged: any; - afterSortChanged: any; - virtualRowRemoved: any; - rowClicked: any; - ready: any; - columnEverythingChanged: any; - columnPivotChanged: any; - columnValueChanged: any; - columnMoved: any; - columnVisible: any; - columnGroupOpened: any; - columnResized: any; - columnPinnedCountChanged: any; - virtualPaging: boolean; - toolPanelSuppressPivot: boolean; - toolPanelSuppressValues: boolean; - rowsAlreadyGrouped: boolean; - suppressRowClickSelection: boolean; - suppressCellSelection: boolean; - sortingOrder: string[]; - suppressMultiSort: boolean; - suppressHorizontalScroll: boolean; - unSortIcon: boolean; - rowHeight: number; - rowBuffer: number; - enableColResize: boolean; - enableCellExpressions: boolean; - enableSorting: boolean; - enableServerSideSorting: boolean; - enableFilter: boolean; - enableServerSideFilter: boolean; - colWidth: number; - suppressMenuHide: boolean; - debug: boolean; - icons: any; - angularCompileRows: boolean; - angularCompileFilters: boolean; - angularCompileHeaders: boolean; - localeText: any; - localeTextFunc: Function; - groupSuppressAutoColumn: boolean; - groupSelectsChildren: boolean; - groupHidePivotColumns: boolean; - groupIncludeFooter: boolean; - groupUseEntireRow: boolean; - groupSuppressRow: boolean; - groupSuppressBlankHeader: boolean; - groupColumnDef: any; - forPrint: boolean; - context: any; - rowStyle: any; - rowClass: any; - headerCellRenderer: any; - groupDefaultExpanded: any; - slaveGrids: GridOptions[]; - rowSelection: string; - rowDeselection: boolean; - rowData: any[]; - floatingTopRowData: any[]; - floatingBottomRowData: any[]; - showToolPanel: boolean; - groupKeys: string[]; - groupAggFunction: (nodes: any[]) => void; - groupAggFields: string[]; - columnDefs: any[]; - datasource: any; - pinnedColumnCount: number; - quickFilterText: string; - groupHeaders: boolean; - headerHeight: number; - constructor(elementDef: any); - onInit(): void; - onChange(changes: any): void; - private globalEventListener(eventType, event); - } -} -declare namespace ag.grid { -} -declare var exports: any; -declare var module: any; -declare namespace ag.grid { - interface Filter { - getGui(): any; - isFilterActive(): boolean; - doesFilterPass(params: any): boolean; - afterGuiAttached?(params?: { - hidePopup?: Function; - }): void; - onNewRowsLoaded?(): void; - } -} diff --git a/types/ag-grid/tsconfig.json b/types/ag-grid/tsconfig.json deleted file mode 100644 index fd05cca8e1..0000000000 --- a/types/ag-grid/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "files": [ - "index.d.ts", - "ag-grid-tests.ts" - ], - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - } -} \ No newline at end of file diff --git a/types/aggregate-error/aggregate-error-tests.ts b/types/aggregate-error/aggregate-error-tests.ts new file mode 100644 index 0000000000..69e544f9ee --- /dev/null +++ b/types/aggregate-error/aggregate-error-tests.ts @@ -0,0 +1,9 @@ +import AggregateError = require('aggregate-error'); + +const err = new AggregateError([new Error('foo'), 'bar']); + +for (const el of Array.from(err)) { + const err: Error = el; +} + +throw err; diff --git a/types/aggregate-error/index.d.ts b/types/aggregate-error/index.d.ts new file mode 100644 index 0000000000..8c8c4cd3b2 --- /dev/null +++ b/types/aggregate-error/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for aggregate-error 1.0 +// Project: https://github.com/sindresorhus/aggregate-error#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = AggregateError; + +declare class AggregateError extends Error implements Iterable { + constructor(errors: Iterable); + + [Symbol.iterator](): Iterator; +} diff --git a/types/aggregate-error/tsconfig.json b/types/aggregate-error/tsconfig.json new file mode 100644 index 0000000000..253c743b98 --- /dev/null +++ b/types/aggregate-error/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "aggregate-error-tests.ts" + ] +} diff --git a/types/stripe/tslint.json b/types/aggregate-error/tslint.json similarity index 100% rename from types/stripe/tslint.json rename to types/aggregate-error/tslint.json diff --git a/types/alertify/index.d.ts b/types/alertify/index.d.ts index fa71118381..1eb2699f6f 100644 --- a/types/alertify/index.d.ts +++ b/types/alertify/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for alertify 0.3.11 // Project: http://fabien-d.github.io/alertify.js/ -// Definitions by: John Jeffery +// Definitions by: John Jeffery // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var alertify: alertify.IAlertifyStatic; diff --git a/types/alexa-sdk/alexa-sdk-tests.ts b/types/alexa-sdk/alexa-sdk-tests.ts index cbf1ba70a3..c77bc93091 100644 --- a/types/alexa-sdk/alexa-sdk-tests.ts +++ b/types/alexa-sdk/alexa-sdk-tests.ts @@ -1,12 +1,13 @@ import * as Alexa from "alexa-sdk"; -const handler = (event: Alexa.RequestBody, context: Alexa.Context, callback: () => void) => { - let alexa = Alexa.handler(event, context); +const handler = (event: Alexa.RequestBody, context: Alexa.Context, callback: () => void) => { + const alexa = Alexa.handler(event, context); + alexa.resources = {}; alexa.registerHandlers(handlers); alexa.execute(); }; -let handlers: Alexa.Handlers = { +const handlers: Alexa.Handlers = { 'LaunchRequest': function() { this.emit('SayHello'); }, diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 256d3fee9a..983c2fa063 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -3,45 +3,47 @@ // Definitions by: Pete Beegle // Huw // pascalwhoop +// Ben // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -export function handler(event: RequestBody, context: Context, callback?: (err: any, response: any) => void ): AlexaObject; +export function handler(event: RequestBody, context: Context, callback?: (err: any, response: any) => void): AlexaObject; export function CreateStateHandler(state: string, obj: any): any; export let StateString: string; export type ConfirmationStatuses = "NONE" | "DENIED" | "CONFIRMED"; export type DialogStates = "STARTED" | "IN_PROGRESS" | "COMPLETED"; -export interface AlexaObject extends Handler { +export interface AlexaObject extends Handler { _event: any; _context: any; _callback: any; state: any; appId: any; response: any; + resources: any; dynamoDBTableName: any; saveBeforeResponse: boolean; - registerHandlers: (...handlers: Handlers[]) => any; + registerHandlers: (...handlers: Array>) => any; execute: () => void; } -export interface Handlers { - [intent: string]: (this: Handler) => void; +export interface Handlers { + [intent: string]: (this: Handler) => void; } -export interface Handler { +export interface Handler { on: any; emit(event: string, ...args: any[]): boolean; emitWithState: any; state: any; handler: any; - event: RequestBody; + event: RequestBody; attributes: any; context: any; name: any; isOverriden: any; - t: (token: string) => void; + t: (token: string, ...args: any[]) => void; } export interface Context { @@ -55,10 +57,10 @@ export interface Context { awsRequestId: string; } -export interface RequestBody { +export interface RequestBody { version: string; session: Session; - request: LaunchRequest | IntentRequest | SessionEndedRequest; + request: T; } export interface Session { @@ -75,36 +77,37 @@ export interface SessionApplication { export interface SessionUser { userId: string; - accessToken: string; + accessToken?: string; } export interface LaunchRequest extends Request { } export interface IntentRequest extends Request { - dialogState: DialogStates; - intent: Intent; -} - -export interface SlotValue { - confirmationStatus: ConfirmationStatuses; - name: string; - value?: any; -} - -export interface Intent { - confirmationStatus: ConfirmationStatuses; - name: string; - slots: Record; + dialogState?: DialogStates; + intent?: Intent; } export interface SessionEndedRequest extends Request { - reason: string; + reason?: string; } export interface Request { type: "LaunchRequest" | "IntentRequest" | "SessionEndedRequest"; requestId: string; - timeStamp: string; + timestamp: string; + locale?: string; +} + +export interface SlotValue { + confirmationStatus?: ConfirmationStatuses; + name: string; + value?: any; +} + +export interface Intent { + confirmationStatus?: ConfirmationStatuses; + name: string; + slots: Record; } export interface ResponseBody { diff --git a/types/alexa-sdk/tslint.json b/types/alexa-sdk/tslint.json index 0c1ca3b5b4..78f1939ba2 100644 --- a/types/alexa-sdk/tslint.json +++ b/types/alexa-sdk/tslint.json @@ -4,6 +4,7 @@ "object-literal-key-quote": false, "no-empty-interface": false, "prefer-method-signature": false, - "object-literal-key-quotes": false + "object-literal-key-quotes": false, + "no-any": false } } diff --git a/types/algebra.js/algebra.js-tests.ts b/types/algebra.js/algebra.js-tests.ts index 0dc7f260e7..0ecaccd2ef 100644 --- a/types/algebra.js/algebra.js-tests.ts +++ b/types/algebra.js/algebra.js-tests.ts @@ -5,9 +5,9 @@ import { Equation, Expression, Fraction, parse, toTex } from 'algebra.js'; expr = expr.subtract(3); expr = expr.add("x"); expr.toString(); - let eq = new Equation(expr, 4); + const eq = new Equation(expr, 4); eq.toString(); - let x = eq.solveFor("x"); + const x = eq.solveFor("x"); x.toString(); } { @@ -29,14 +29,14 @@ import { Equation, Expression, Fraction, parse, toTex } from 'algebra.js'; x.toString(); x = x.add("y"); x.toString(); - let otherExp = new Expression("x").add(6); + const otherExp = new Expression("x").add(6); x = x.add(otherExp); x.toString(); let expr1 = new Expression("a").add("b").add("c"); let expr2 = new Expression("c").subtract("b"); let expr3 = expr1.subtract(expr2); - expr1.toString() + " - (" + expr2.toString() + ") = " + expr3.toString(); + `${expr1.toString()} - (${expr2.toString()}) = ${expr3.toString()}`; expr1 = new Expression("x"); expr1 = expr1.add(2); @@ -46,7 +46,7 @@ import { Equation, Expression, Fraction, parse, toTex } from 'algebra.js'; expr2 = expr2.multiply(new Fraction(1, 3)); expr2 = expr2.add(4); expr3 = expr1.multiply(expr2); - "(" + expr1.toString() + ")(" + expr2.toString() + ") = " + expr3.toString(); + `(${expr1.toString()})(${expr2.toString()}) = ${expr3.toString()}`; x = new Expression("x").divide(2).divide(new Fraction(1, 5)); x.toString(); @@ -54,11 +54,11 @@ import { Equation, Expression, Fraction, parse, toTex } from 'algebra.js'; exp = exp.add("y"); exp = exp.add(3); exp.toString(); - let sum = exp.summation("x", 3, 6); + const sum = exp.summation("x", 3, 6); sum.toString(); exp = new Expression("x").add(2); - let exp3 = exp.pow(3); - "(" + exp.toString() + ")^3 = " + exp3.toString(); + const exp3 = exp.pow(3); + `(${exp.toString()})^3 = ${exp3.toString()}`; let expr = new Expression("x"); expr = expr.multiply(2); @@ -66,14 +66,14 @@ import { Equation, Expression, Fraction, parse, toTex } from 'algebra.js'; expr = expr.add("y"); expr = expr.add(new Fraction(1, 3)); expr.toString(); - let answer1 = expr.eval({ x: 2 }); - let answer2 = expr.eval({ x: 2, y: new Fraction(3, 4) }); + const answer1 = expr.eval({ x: 2 }); + const answer2 = expr.eval({ x: 2, y: new Fraction(3, 4) }); answer1.toString(); answer2.toString(); expr = new Expression("x").add(2); expr.toString(); - let sub = new Expression("y").add(4); - let answer = expr.eval({ x: sub }); + const sub = new Expression("y").add(4); + const answer = expr.eval({ x: sub }); answer.toString(); exp = new Expression("x").add(2); exp.toString(); @@ -91,23 +91,23 @@ import { Equation, Expression, Fraction, parse, toTex } from 'algebra.js'; exp.toString(); exp = exp.simplify(); exp.toString(); - let z = new Expression("z"); - let eq1 = new Equation(z.subtract(4).divide(9), z.add(6)); + const z = new Expression("z"); + const eq1 = new Equation(z.subtract(4).divide(9), z.add(6)); eq1.toString(); - let eq2 = new Equation(z.add(4).multiply(9), 6); + const eq2 = new Equation(z.add(4).multiply(9), 6); eq2.toString(); - let eq3 = new Equation(z.divide(2).multiply(7), new Fraction(1, 4)); + const eq3 = new Equation(z.divide(2).multiply(7), new Fraction(1, 4)); eq3.toString(); } { - let x1 = parse("1/5 * x + 2/15"); - let x2 = parse("1/7 * x + 4"); + const x1 = parse("1/5 * x + 2/15"); + const x2 = parse("1/7 * x + 4"); let eq = new Equation(x1 as Expression, x2 as Expression); eq.toString(); - let answer = eq.solveFor("x"); + const answer = eq.solveFor("x"); "x = " + answer.toString(); - let expr1 = parse("1/4 * x + 5/4"); - let expr2 = parse("3 * y - 12/5"); + const expr1 = parse("1/4 * x + 5/4"); + const expr2 = parse("3 * y - 12/5"); eq = new Equation(expr1 as Expression, expr2 as Expression); eq.toString(); let xAnswer = eq.solveFor("x"); @@ -116,14 +116,14 @@ import { Equation, Expression, Fraction, parse, toTex } from 'algebra.js'; "y = " + yAnswer.toString(); let n1 = parse("x + 5") as Expression; let n2 = parse("x - 3/4") as Expression; - let quad = new Equation(n1.multiply(n2), 0); + const quad = new Equation(n1.multiply(n2), 0); quad.toString(); let answers = quad.solveFor("x"); "x = " + answers.toString(); n1 = parse("x + 2") as Expression; n2 = parse("x + 3") as Expression; - let n3 = parse("x + 4") as Expression; - let cubic = new Equation(n1.multiply(n2).multiply(n3), 0); + const n3 = parse("x + 4") as Expression; + const cubic = new Equation(n1.multiply(n2).multiply(n3), 0); cubic.toString(); answers = cubic.solveFor("x"); "x = " + answers.toString(); @@ -143,20 +143,20 @@ import { Equation, Expression, Fraction, parse, toTex } from 'algebra.js'; exp.toString(); } { - let eq = parse("x^2 + 4 * x + 4 = 0") as Equation; + const eq = parse("x^2 + 4 * x + 4 = 0") as Equation; eq.toString(); - let ans = eq.solveFor("x"); + const ans = eq.solveFor("x"); "x = " + ans.toString(); - let a = new Expression("x").pow(2); - let b = new Expression("x").multiply(new Fraction(5, 4)); - let c = new Fraction(-21, 4); - let expr = a.add(b).add(c); - let quad = new Equation(expr, 0); + const a = new Expression("x").pow(2); + const b = new Expression("x").multiply(new Fraction(5, 4)); + const c = new Fraction(-21, 4); + const expr = a.add(b).add(c); + const quad = new Equation(expr, 0); toTex(quad); - let answers = quad.solveFor("x"); + const answers = quad.solveFor("x"); toTex(answers); - let lambda = new Expression("lambda").add(3).divide(4); - let Phi = new Expression("Phi").subtract(new Fraction(1, 5)).add(lambda); + const lambda = new Expression("lambda").add(3).divide(4); + const Phi = new Expression("Phi").subtract(new Fraction(1, 5)).add(lambda); toTex(lambda); toTex(Phi); } diff --git a/types/algoliasearch/algoliasearch-tests.ts b/types/algoliasearch/algoliasearch-tests.ts index 43a4d677cf..dfcf27c94f 100644 --- a/types/algoliasearch/algoliasearch-tests.ts +++ b/types/algoliasearch/algoliasearch-tests.ts @@ -48,7 +48,7 @@ let _algoliaSecuredApiOptions: AlgoliaSecuredApiOptions = { let _algoliaIndexSettings: AlgoliaIndexSettings = { attributesToIndex: [""], - attributesforFaceting: [""], + attributesForFaceting: [""], unretrievableAttributes: [""], attributesToRetrieve: [""], ranking: [""], diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index 2fdd00f983..1bb77a50e9 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -976,7 +976,7 @@ declare namespace algoliasearch { * default: null * https://github.com/algolia/algoliasearch-client-js#attributesforfaceting */ - attributesforFaceting?: string[]; + attributesForFaceting?: string[]; /** * The list of attributes that cannot be retrieved at query time * default: null diff --git a/types/amazon-product-api/index.d.ts b/types/amazon-product-api/index.d.ts index 6cb7389c73..797adf45f4 100644 --- a/types/amazon-product-api/index.d.ts +++ b/types/amazon-product-api/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for amazon-product-api // Project: https://github.com/t3chnoboy/amazon-product-api -// Definitions by: Matti Lehtinen +// Definitions by: Matti Lehtinen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/amplify-deferred/index.d.ts b/types/amplify-deferred/index.d.ts index fd738e9cbe..508cb5bb11 100644 --- a/types/amplify-deferred/index.d.ts +++ b/types/amplify-deferred/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AmplifyJs (using JQuery Deferred) 1.1 // Project: http://amplifyjs.com/ -// Definitions by: Jonas Eriksson , Laurentiu Stamate +// Definitions by: Jonas Eriksson , Laurentiu Stamate // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/amplify/amplify-tests.ts b/types/amplify/amplify-tests.ts index 62b00052dd..d26ff023bd 100644 --- a/types/amplify/amplify-tests.ts +++ b/types/amplify/amplify-tests.ts @@ -151,7 +151,7 @@ amplify.request.define("twitter-search", "ajax", { } }); -amplify.request("twitter-search", { term: "amplifyjs" } ); +amplify.request("twitter-search", { term: "amplifyjs" }); // Similarly, we can create a request that searches for mentions, by accepting a username: @@ -168,19 +168,24 @@ amplify.request("twitter-mentions", { user: "amplifyjs" }); // Example: const appEnvelopeDecoder: amplify.Decoder = (data, status, xhr, success, error) => { - if (data.status === "success") { - success(data.data); - } else if (data.status === "fail" || data.status === "error") { - error(data.message, data.status); - } else { - error(data.message, "fatal"); + switch (data.status) { + case "success": + success(data.data); + break; + case "fail": + case "error": + error(data.message, data.status); + break; + default: + error(data.message, "fatal"); + break; } }; // a new decoder can be added to the amplifyDecoders interface declare module "amplify" { interface Decoders { - appEnvelope: amplify.Decoder; + appEnvelope: Decoder; } } @@ -213,12 +218,17 @@ amplify.request.define("decoderSingleExample", "ajax", { url: "/myAjaxUrl", type: "POST", decoder(data, status, xhr, success, error) { - if (data.status === "success") { - success(data.data); - } else if (data.status === "fail" || data.status === "error") { - error(data.message, data.status); - } else { - error(data.message, "fatal"); + switch (data.status) { + case "success": + success(data.data); + break; + case "fail": + case "error": + error(data.message, data.status); + break; + default: + error(data.message, "fatal"); + break; } } }); diff --git a/types/amplify/index.d.ts b/types/amplify/index.d.ts index 2c3e2e1e5a..b88a2d5e80 100644 --- a/types/amplify/index.d.ts +++ b/types/amplify/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AmplifyJs 1.1 // Project: http://amplifyjs.com/ -// Definitions by: Jonas Eriksson +// Definitions by: Jonas Eriksson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/amqp-rpc/index.d.ts b/types/amqp-rpc/index.d.ts index 337f8d8a16..de2e3c25e6 100644 --- a/types/amqp-rpc/index.d.ts +++ b/types/amqp-rpc/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for amqp-rpc v0.0.8 // Project: https://github.com/demchenkoe/node-amqp-rpc/ -// Definitions by: Wonshik Kim +// Definitions by: Wonshik Kim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/amqp/index.d.ts b/types/amqp/index.d.ts index a7dae4eb56..ea7d6bcc65 100644 --- a/types/amqp/index.d.ts +++ b/types/amqp/index.d.ts @@ -49,6 +49,7 @@ export interface AMQPQueue extends events.EventEmitter { export interface AMQPExchange extends events.EventEmitter { on(event: 'open' | 'ack' | 'error' | 'exchangeBindOk' | 'exchangeUnbindOk', callback: Callback): this; + publish(routingKey: string, message: Buffer | {}, callback: (err?: boolean, msg?: string) => void): void; publish(routingKey: string, message: Buffer | {}, options: ExchangePublishOptions, callback?: (err?: boolean, msg?: string) => void): void; /** diff --git a/types/amqplib/amqplib-tests.ts b/types/amqplib/amqplib-tests.ts index 8bfcf3c9b4..ef448d5b36 100644 --- a/types/amqplib/amqplib-tests.ts +++ b/types/amqplib/amqplib-tests.ts @@ -16,13 +16,19 @@ amqp.connect('amqp://localhost') .then(connection => { return connection.createChannel() .tap(channel => channel.checkQueue('myQueue')) - .then(channel => channel.consume('myQueue', newMsg => console.log('New Message: ' + newMsg.content.toString()))) + .then(channel => { + return channel.consume('myQueue', newMsg => { + if (newMsg != null) { + // test promise api properties + if (newMsg.properties.contentType === 'application/json') { + console.log('New Message: ' + newMsg.content.toString()); + } + } + }); + }) .finally(() => connection.close()); }); -// test promise api properties -let amqpMessage: amqp.Message; -amqpMessage.properties.contentType = 'application/json'; let amqpAssertExchangeOptions: amqp.Options.AssertExchange; let anqpAssertExchangeReplies: amqp.Replies.AssertExchange; @@ -49,7 +55,14 @@ amqpcb.connect('amqp://localhost', (err, connection) => { if (!err) { channel.assertQueue('myQueue', {}, (err, ok) => { if (!err) { - channel.consume('myQueue', newMsg => console.log('New Message: ' + newMsg.content.toString())); + channel.consume('myQueue', newMsg => { + if (newMsg != null) { + // test callback api properties + if (newMsg.properties.contentType === 'application/json') { + console.log('New Message: ' + newMsg.content.toString()); + } + } + }); } }); } @@ -57,8 +70,5 @@ amqpcb.connect('amqp://localhost', (err, connection) => { } }); -// test callback api properties -let amqpcbMessage: amqpcb.Message; -amqpcbMessage.properties.contentType = 'application/json'; let amqpcbAssertExchangeOptions: amqpcb.Options.AssertExchange; let anqpcbAssertExchangeReplies: amqpcb.Replies.AssertExchange; diff --git a/types/amqplib/callback_api.d.ts b/types/amqplib/callback_api.d.ts index d36a849873..60ff8cf622 100644 --- a/types/amqplib/callback_api.d.ts +++ b/types/amqplib/callback_api.d.ts @@ -31,7 +31,7 @@ export interface Channel extends events.EventEmitter { 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; + consume(queue: string, onMessage: (msg: Message | null) => 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 | false) => void): void; diff --git a/types/amqplib/index.d.ts b/types/amqplib/index.d.ts index 45b5e6e3ca..91060d23b0 100644 --- a/types/amqplib/index.d.ts +++ b/types/amqplib/index.d.ts @@ -40,7 +40,7 @@ export interface Channel extends events.EventEmitter { publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; - consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): Promise; + consume(queue: string, onMessage: (msg: Message | null) => any, options?: Options.Consume): Promise; cancel(consumerTag: string): Promise; get(queue: string, options?: Options.Get): Promise; diff --git a/types/amqplib/tsconfig.json b/types/amqplib/tsconfig.json index 1f880d1396..16ed704846 100644 --- a/types/amqplib/tsconfig.json +++ b/types/amqplib/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,4 +20,4 @@ "callback_api.d.ts", "amqplib-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/amqplib/tslint.json b/types/amqplib/tslint.json index 4f44991c3c..bfc9508c49 100644 --- a/types/amqplib/tslint.json +++ b/types/amqplib/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { - "no-empty-interface": false + // All are TODOs + "no-empty-interface": false, + "prefer-const": false } } diff --git a/types/angular-block-ui/angular-block-ui-tests.ts b/types/angular-block-ui/angular-block-ui-tests.ts index 4b3903f9cc..58547fff4d 100644 --- a/types/angular-block-ui/angular-block-ui-tests.ts +++ b/types/angular-block-ui/angular-block-ui-tests.ts @@ -37,5 +37,5 @@ app.controller('Ctrl', ($scope: ng.IScope, blockUI: angular.blockUI.BlockUIServi blockUI.reset(); blockUI.message("Hello Types"); blockUI.done(); - let b: boolean = blockUI.isBlocking(); + const b: boolean = blockUI.isBlocking(); }); diff --git a/types/angular-block-ui/index.d.ts b/types/angular-block-ui/index.d.ts index 7733bc72f7..47ba9902b9 100644 --- a/types/angular-block-ui/index.d.ts +++ b/types/angular-block-ui/index.d.ts @@ -70,7 +70,7 @@ declare module 'angular' { * @param {angular.IRequestConfig} config - the Angular request config object. * */ - requestFilter?(config: angular.IRequestConfig): (string | boolean); + requestFilter?(config: IRequestConfig): (string | boolean); /** * When the module is started it will inject the main block element diff --git a/types/angular-clipboard/angular-clipboard-tests.ts b/types/angular-clipboard/angular-clipboard-tests.ts index b043a85d5a..6df5af0c5e 100644 --- a/types/angular-clipboard/angular-clipboard-tests.ts +++ b/types/angular-clipboard/angular-clipboard-tests.ts @@ -1,8 +1,12 @@ import * as angular from "angular"; -import {ClipboardService} from "angular-clipboard"; +import { ClipboardService } from "angular-clipboard"; + +interface TestScope extends ng.IScope { + [index: string]: any; +} const app = angular.module('testModule', ['angular-clipboard']); -app.controller('TestController', ($scope: ng.IScope, clipboard: ClipboardService) => { +app.controller('TestController', ($scope: TestScope, clipboard: ClipboardService) => { $scope['testCopy'] = () => { if (clipboard.supported) { clipboard.copyText('hiiiiiii'); diff --git a/types/angular-clipboard/index.d.ts b/types/angular-clipboard/index.d.ts index 0f59feaf56..a9a15821b6 100644 --- a/types/angular-clipboard/index.d.ts +++ b/types/angular-clipboard/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for angular-clipboard v1.5 // Project: https://github.com/omichelsen/angular-clipboard -// Definitions by: Bradford Wagner +// Definitions by: Bradford Wagner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/angular-cookies/index.d.ts b/types/angular-cookies/index.d.ts index 502e83a2e9..dc6fd913e9 100644 --- a/types/angular-cookies/index.d.ts +++ b/types/angular-cookies/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS (ngCookies module) 1.4 // Project: http://angularjs.org -// Definitions by: Diego Vilar , Anthony Ciccarello +// Definitions by: Diego Vilar , Anthony Ciccarello // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/angular-deferred-bootstrap/index.d.ts b/types/angular-deferred-bootstrap/index.d.ts index df489e48ee..2c1a2d141c 100644 --- a/types/angular-deferred-bootstrap/index.d.ts +++ b/types/angular-deferred-bootstrap/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for angular-deferred-bootstrap v0.1.9 // Project: https://github.com/philippd/angular-deferred-bootstrap -// Definitions by: Markus Wagner +// Definitions by: Markus Wagner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/angular-es/index.d.ts b/types/angular-es/index.d.ts index 0972b42da0..a3a57edcfc 100644 --- a/types/angular-es/index.d.ts +++ b/types/angular-es/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for angular-es v0.0.3 // Project: https://github.com/mbutsykin/angular-es -// Definitions by: mbutsykin +// Definitions by: mbutsykin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'angular-es' { diff --git a/types/angular-feature-flags/angular-feature-flags-tests.ts b/types/angular-feature-flags/angular-feature-flags-tests.ts index ac956dd657..bd44d7b5cf 100644 --- a/types/angular-feature-flags/angular-feature-flags-tests.ts +++ b/types/angular-feature-flags/angular-feature-flags-tests.ts @@ -1,8 +1,8 @@ -import * as angular from "angular"; +import * as ng from 'angular'; -let myApp = angular.module('myApp', ['feature-flags']); +const myApp = ng.module('myApp', ['feature-flags']); -const flagsData: Array = [ +const flagsData: Array = [ { key: '1', active: true, @@ -17,15 +17,16 @@ const flagsData: Array = [ } ]; -myApp.config(function (featureFlagsProvider: angular.featureflags.FeatureFlagsProvider) { +myApp.config(function(featureFlagsProvider: ng.featureflags.FeatureFlagsProvider) { featureFlagsProvider.setInitialFlags(flagsData); }); -myApp.run(function ($q: angular.IQService, $http: angular.IHttpService, featureFlags: angular.featureflags.FeatureFlagsService) { - let deferred = $q.defer(); - deferred.resolve(flagsData); - - featureFlags.set(deferred.promise); - +myApp.run(function( + $q: ng.IQService, + $http: ng.IHttpService, + featureFlags: ng.featureflags.FeatureFlagsService +) { + featureFlags.set($q.resolve(flagsData)); featureFlags.set($http.get('/data/flags.json')); -}); \ No newline at end of file + featureFlags.set($http.get>('/data/flags.json')); +}); diff --git a/types/angular-feature-flags/index.d.ts b/types/angular-feature-flags/index.d.ts index 2335bf0eba..0efb9379c6 100644 --- a/types/angular-feature-flags/index.d.ts +++ b/types/angular-feature-flags/index.d.ts @@ -1,14 +1,14 @@ // Type definitions for angular-feature-flags 1.4.0 // Project: https://github.com/mjt01/angular-feature-flags -// Definitions by: Borislav Zhivkov +// Definitions by: Borislav Zhivkov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// -import * as angular from "angular"; +import * as ng from 'angular'; -declare module "angular" { +declare module 'angular' { namespace featureflags { export interface FlagData { /** @@ -27,17 +27,22 @@ declare module "angular" { name: string; /** - * A long description of the flag to further explain the feature being toggled (only visible in the list of flags) + * A long description of the flag to further explain the feature being toggled + * (only visible in the list of flags) */ description: string; } export interface FeatureFlagsProvider { - setInitialFlags(flags: Array): void; + setInitialFlags(flags: ReadonlyArray): void; } export interface FeatureFlagsService { - set(flagsPromise: angular.IPromise | angular.IHttpPromise): void; + set( + flagsPromise: + | ng.IPromise> + | ng.IHttpPromise> + ): void; } } } diff --git a/types/angular-file-saver/index.d.ts b/types/angular-file-saver/index.d.ts index cee78df620..9ba224fba1 100644 --- a/types/angular-file-saver/index.d.ts +++ b/types/angular-file-saver/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for angular-file-saver 1.1 // Project: https://github.com/alferov/angular-file-saver -// Definitions by: Donald Nairn +// Definitions by: Donald Nairn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/angular-gridster/angular-gridster-tests.ts b/types/angular-gridster/angular-gridster-tests.ts index f8c5a93c81..6c88263214 100644 --- a/types/angular-gridster/angular-gridster-tests.ts +++ b/types/angular-gridster/angular-gridster-tests.ts @@ -1,4 +1,3 @@ -import * as ng from "angular"; import * as angular from "angular"; import gridster from "angular-gridster"; diff --git a/types/angular-gridster/index.d.ts b/types/angular-gridster/index.d.ts index 3d4fbbe799..22c02b4050 100644 --- a/types/angular-gridster/index.d.ts +++ b/types/angular-gridster/index.d.ts @@ -89,13 +89,13 @@ declare module "angular" { handles?: string[]; // optional callback fired when drag is started - start?(event: angular.IAngularEvent, $element: angular.IAugmentedJQuery, options: any): void; + start?(event: IAngularEvent, $element: IAugmentedJQuery, options: any): void; // optional callback fired when item is resized - resize?(event: angular.IAngularEvent, $element: angular.IAugmentedJQuery, options: any): void; + resize?(event: IAngularEvent, $element: IAugmentedJQuery, options: any): void; // optional callback fired when item is finished dragging - stop?(event: angular.IAngularEvent, $element: angular.IAugmentedJQuery, options: any): void; + stop?(event: IAngularEvent, $element: IAugmentedJQuery, options: any): void; }; // options to pass to draggable handler @@ -113,13 +113,13 @@ declare module "angular" { handle?: string; // optional callback fired when drag is started - start?(event: angular.IAngularEvent, $element: angular.IAugmentedJQuery, options: any): void; + start?(event: IAngularEvent, $element: IAugmentedJQuery, options: any): void; // optional callback fired when item is moved, - drag?(event: angular.IAngularEvent, $element: angular.IAugmentedJQuery, options: any): void; + drag?(event: IAngularEvent, $element: IAugmentedJQuery, options: any): void; // optional callback fired when item is finished dragging - stop?(event: angular.IAngularEvent, $element: angular.IAugmentedJQuery, options: any): void; + stop?(event: IAngularEvent, $element: IAugmentedJQuery, options: any): void; }; } diff --git a/types/angular-hotkeys/index.d.ts b/types/angular-hotkeys/index.d.ts index 3db766706a..38ff06a969 100644 --- a/types/angular-hotkeys/index.d.ts +++ b/types/angular-hotkeys/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jason Zhao , Stefan Steinhart // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -//readme written by David Valentine +//readme written by David Valentine /// diff --git a/types/angular-locker/angular-locker-tests.ts b/types/angular-locker/angular-locker-tests.ts index a82f6a86cb..368dd1d308 100644 --- a/types/angular-locker/angular-locker-tests.ts +++ b/types/angular-locker/angular-locker-tests.ts @@ -1,5 +1,10 @@ import * as angular from 'angular'; + +interface TestScope extends angular.IScope { + [index: string]: any; +} + angular .module('angular-locker-tests', ['angular-locker']) .config(['lockerProvider', function config(lockerProvider: angular.locker.ILockerProvider) { @@ -13,7 +18,7 @@ angular lockerProvider.defaults(lockerSettings); }]) -.controller('LockerController', ['$scope', 'locker', function ($scope: angular.IScope, locker: angular.locker.ILockerService) { +.controller('LockerController', ['$scope', 'locker', function ($scope: TestScope, locker: angular.locker.ILockerService) { locker.put('someKey', 'someVal'); // put an item into session storage diff --git a/types/angular-material/angular-material-tests.ts b/types/angular-material/angular-material-tests.ts index d1af7c8159..79f72f0b5d 100644 --- a/types/angular-material/angular-material-tests.ts +++ b/types/angular-material/angular-material-tests.ts @@ -1,5 +1,9 @@ const myApp = angular.module('testModule', ['ngMaterial']); +interface TestScope extends ng.IScope { + [index: string]: any; +} + myApp.config(( $mdThemingProvider: ng.material.IThemingProvider, $mdIconProvider: ng.material.IIconProvider, @@ -45,12 +49,12 @@ myApp.config(( return c * t * t + b; }, easeFnIndeterminate(t, b, c, d) { - return c * Math.pow(2, 10 * (t / d - 1)) + b; + return c * Math.pow(2, (t / d - 1) * 10) + b; } }); }); -myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng.material.IBottomSheetService, $q: ng.IQService) => { +myApp.controller('BottomSheetController', ($scope: TestScope, $mdBottomSheet: ng.material.IBottomSheetService, $q: ng.IQService) => { $scope['openBottomSheet'] = () => { $mdBottomSheet.show({ template: 'Hello!', @@ -84,7 +88,7 @@ myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng $scope['cancelBottomSheet'] = $mdBottomSheet.cancel.bind($mdBottomSheet, 'cancel'); }); -myApp.controller('ColorController', ($scope: ng.IScope, $mdColor: ng.material.IColorService) => { +myApp.controller('ColorController', ($scope: TestScope, $mdColor: ng.material.IColorService) => { const colorExpression: ng.material.IColorExpression = { color: '#FFFFFF' }; const element: Element = new Element(); @@ -99,7 +103,7 @@ myApp.controller('ColorController', ($scope: ng.IScope, $mdColor: ng.material.IC }; }); -myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material.IDialogService, $q: ng.IQService) => { +myApp.controller('DialogController', ($scope: TestScope, $mdDialog: ng.material.IDialogService, $q: ng.IQService) => { $scope['openDialog'] = () => { $mdDialog.show({ template: 'Hello!' @@ -201,7 +205,7 @@ class IconDirective implements ng.IDirective { } myApp.directive('icon-directive', ($mdIcon: ng.material.IIcon) => new IconDirective($mdIcon)); -myApp.controller('MediaController', ($scope: ng.IScope, $mdMedia: ng.material.IMedia) => { +myApp.controller('MediaController', ($scope: TestScope, $mdMedia: ng.material.IMedia) => { $scope.$watch(() => $mdMedia('lg'), (big: boolean) => { $scope['bigScreen'] = big; }); @@ -210,7 +214,7 @@ myApp.controller('MediaController', ($scope: ng.IScope, $mdMedia: ng.material.IM $scope['anotherCustom'] = $mdMedia('max-width: 300px'); }); -myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.material.ISidenavService) => { +myApp.controller('SidenavController', ($scope: TestScope, $mdSidenav: ng.material.ISidenavService) => { const componentId = 'left'; $scope['toggle'] = () => $mdSidenav(componentId).toggle(); $scope['open'] = () => $mdSidenav(componentId).open(); @@ -229,7 +233,7 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia $scope['onClose'] = $mdSidenav(componentId).onClose(() => { }); }); -myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService, $q: ng.IQService) => { +myApp.controller('ToastController', ($scope: TestScope, $mdToast: ng.material.IToastService, $q: ng.IQService) => { $scope['openToast'] = () => { $mdToast.show($mdToast.simple().textContent('Hello!')); $mdToast.updateTextContent('New Content'); @@ -260,7 +264,7 @@ myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IT }; }); -myApp.controller('PanelController', ($scope: ng.IScope, $mdPanel: ng.material.IPanelService, $q: ng.IQService) => { +myApp.controller('PanelController', ($scope: TestScope, $mdPanel: ng.material.IPanelService, $q: ng.IQService) => { $scope['createPanel'] = () => { const config: ng.material.IPanelConfig = { id: 'myPanel', diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 58e1ae5dd6..a8808f92ff 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -18,7 +18,7 @@ declare module 'angular' { interface IBottomSheetOptions { templateUrl?: string; template?: string; - scope?: angular.IScope; // default: new child scope + scope?: IScope; // default: new child scope preserveScope?: boolean; // default: false controller?: string | Injectable; locals?: { [index: string]: any }; @@ -28,12 +28,12 @@ declare module 'angular' { escapeToClose?: boolean; resolve?: ResolveObject; controllerAs?: string; - parent?: ((scope: angular.IScope, element: JQuery) => Element | JQuery) | string | Element | JQuery; // default: root node + parent?: ((scope: IScope, element: JQuery) => Element | JQuery) | string | Element | JQuery; // default: root node disableParentScroll?: boolean; // default: true } interface IBottomSheetService { - show(options: IBottomSheetOptions): angular.IPromise; + show(options: IBottomSheetOptions): IPromise; hide(response?: any): void; cancel(response?: any): void; } @@ -47,7 +47,7 @@ declare module 'angular' { templateUrl(templateUrl?: string): T; template(template?: string): T; targetEvent(targetEvent?: MouseEvent): T; - scope(scope?: angular.IScope): T; // default: new child scope + scope(scope?: IScope): T; // default: new child scope preserveScope(preserveScope?: boolean): T; // default: false disableParentScroll(disableParentScroll?: boolean): T; // default: true hasBackdrop(hasBackdrop?: boolean): T; // default: true @@ -61,6 +61,9 @@ declare module 'angular' { controllerAs(controllerAs?: string): T; parent(parent?: string | Element | JQuery): T; // default: root node ariaLabel(ariaLabel: string): T; + openFrom(from: string | Element | Event | { top: number, left: number }): T; + closeTo(to: string | Element | { top: number, left: number }): T; + multiple(multiple: boolean): T; } // tslint:disable-next-line no-empty-interface @@ -95,7 +98,7 @@ declare module 'angular' { targetEvent?: MouseEvent; openFrom?: any; closeTo?: any; - scope?: angular.IScope; // default: new child scope + scope?: IScope; // default: new child scope preserveScope?: boolean; // default: false disableParentScroll?: boolean; // default: true hasBackdrop?: boolean; // default: true @@ -108,24 +111,24 @@ declare module 'angular' { resolve?: ResolveObject; controllerAs?: string; parent?: string | Element | JQuery; // default: root node - onShowing?(scope: angular.IScope, element: JQuery): void; - onComplete?(scope: angular.IScope, element: JQuery): void; - onRemoving?(element: JQuery, removePromise: angular.IPromise): void; + onShowing?(scope: IScope, element: JQuery): void; + onComplete?(scope: IScope, element: JQuery): void; + onRemoving?(element: JQuery, removePromise: IPromise): void; skipHide?: boolean; multiple?: boolean; fullscreen?: boolean; // default: false } interface IDialogService { - show(dialog: IDialogOptions | IAlertDialog | IConfirmDialog | IPromptDialog): angular.IPromise; + show(dialog: IDialogOptions | IAlertDialog | IConfirmDialog | IPromptDialog): IPromise; confirm(): IConfirmDialog; alert(): IAlertDialog; prompt(): IPromptDialog; - hide(response?: any): angular.IPromise; + hide(response?: any): IPromise; cancel(response?: any): void; } - type IIcon = (id: string) => angular.IPromise; // id is a unique ID or URL + type IIcon = (id: string) => IPromise; // id is a unique ID or URL interface IIconProvider { icon(id: string, url: string, viewBoxSize?: number): IIconProvider; // viewBoxSize default: 24 @@ -138,16 +141,16 @@ declare module 'angular' { type IMedia = (media: string) => boolean; interface ISidenavObject { - toggle(): angular.IPromise; - open(): angular.IPromise; - close(): angular.IPromise; + toggle(): IPromise; + open(): IPromise; + close(): IPromise; isOpen(): boolean; isLockedOpen(): boolean; onClose(onClose: () => void): void; } interface ISidenavService { - (component: string, enableWait: boolean): angular.IPromise; + (component: string, enableWait: boolean): IPromise; (component: string): ISidenavObject; } @@ -172,7 +175,7 @@ declare module 'angular' { templateUrl?: string; template?: string; autoWrap?: boolean; - scope?: angular.IScope; // default: new child scope + scope?: IScope; // default: new child scope preserveScope?: boolean; // default: false hideDelay?: number | false; // default (ms): 3000 position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left' @@ -186,8 +189,8 @@ declare module 'angular' { } interface IToastService { - show(optionsOrPreset: IToastOptions | IToastPreset): angular.IPromise; - showSimple(content: string): angular.IPromise; + show(optionsOrPreset: IToastOptions | IToastPreset): IPromise; + showSimple(content: string): IPromise; simple(): ISimpleToastPreset; build(): IToastPreset; updateContent(newContent: string): void; @@ -303,7 +306,7 @@ declare module 'angular' { } interface IMenuService { - hide(response?: any, options?: any): angular.IPromise; + hide(response?: any, options?: any): IPromise; } interface IColorPalette { @@ -363,19 +366,19 @@ declare module 'angular' { isAttached: boolean; panelContainer: JQuery; panelEl: JQuery; - open(): angular.IPromise; - close(): angular.IPromise; - attach(): angular.IPromise; - detach(): angular.IPromise; - show(): angular.IPromise; - hide(): angular.IPromise; + open(): IPromise; + close(): IPromise; + attach(): IPromise; + detach(): IPromise; + show(): IPromise; + hide(): IPromise; destroy(): void; addClass(newClass: string): void; removeClass(oldClass: string): void; toggleClass(toggleClass: string): void; updatePosition(position: IPanelPosition): void; - registerInterceptor(type: string, callback: () => angular.IPromise): IPanelRef; - removeInterceptor(type: string, callback: () => angular.IPromise): IPanelRef; + registerInterceptor(type: string, callback: () => IPromise): IPanelRef; + removeInterceptor(type: string, callback: () => IPromise): IPanelRef; removeAllInterceptors(type?: string): IPanelRef; } @@ -404,7 +407,7 @@ declare module 'angular' { interface IPanelService { create(opt_config: IPanelConfig): IPanelRef; - open(opt_config: IPanelConfig): angular.IPromise; + open(opt_config: IPanelConfig): IPromise; newPanelPosition(): IPanelPosition; newPanelAnimation(): IPanelAnimation; xPosition: { diff --git a/types/angular-material/tslint.json b/types/angular-material/tslint.json index 8e8a076d2c..4c42fed648 100644 --- a/types/angular-material/tslint.json +++ b/types/angular-material/tslint.json @@ -1,7 +1,9 @@ { "extends": "dtslint/dt.json", "rules": { + // TODOs "interface-name": false, - "max-line-length": false + "max-line-length": false, + "no-void-expression": false } } \ No newline at end of file diff --git a/types/angular-meteor/angular-meteor-tests.ts b/types/angular-meteor/angular-meteor-tests.ts index 6a379b8bac..21cbb4e3a3 100644 --- a/types/angular-meteor/angular-meteor-tests.ts +++ b/types/angular-meteor/angular-meteor-tests.ts @@ -27,6 +27,8 @@ interface CustomScope extends angular.meteor.IScope { removeAll: () => void; removeAuto: (todo: ITodo) => void; toSticky: (todo: ITodo) => void; + + picture: any; } var Todos = new Mongo.Collection('todos'); diff --git a/types/angular-mocks/index.d.ts b/types/angular-mocks/index.d.ts index 14571e2eba..ac9e6cece3 100644 --- a/types/angular-mocks/index.d.ts +++ b/types/angular-mocks/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS (ngMock, ngMockE2E module) 1.5 // Project: http://angularjs.org -// Definitions by: Diego Vilar , Tony Curtis +// Definitions by: Diego Vilar , Tony Curtis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/angular-oauth2/index.d.ts b/types/angular-oauth2/index.d.ts index 1c5e3ac6ed..ef11ee3680 100644 --- a/types/angular-oauth2/index.d.ts +++ b/types/angular-oauth2/index.d.ts @@ -27,9 +27,9 @@ declare module 'angular' { interface OAuth { isAuthenticated(): boolean; - getAccessToken(data: Data, options?: any): angular.IPromise; - getRefreshToken(data?: Data, options?: any): angular.IPromise; - revokeToken(data?: Data, options?: any): angular.IPromise; + getAccessToken(data: Data, options?: any): IPromise; + getRefreshToken(data?: Data, options?: any): IPromise; + revokeToken(data?: Data, options?: any): IPromise; } interface OAuthTokenConfig { diff --git a/types/angular-pdfjs-viewer/angular-pdfjs-viewer-tests.ts b/types/angular-pdfjs-viewer/angular-pdfjs-viewer-tests.ts new file mode 100644 index 0000000000..123b497dcb --- /dev/null +++ b/types/angular-pdfjs-viewer/angular-pdfjs-viewer-tests.ts @@ -0,0 +1,11 @@ +import * as angular from "angular"; +import "angular-pdfjs-viewer"; + +angular.module('app').config((pdfjsViewerConfigProvider: angular.pdfjsViewer.ConfigProvider) => { + pdfjsViewerConfigProvider.setWorkerSrc("/assets/pdf.js-viewer/pdf.worker.js"); + pdfjsViewerConfigProvider.setCmapDir("/assets/pdf.js-viewer/cmaps"); + pdfjsViewerConfigProvider.setImageDir("/assets/pdf.js-viewer/images"); + + pdfjsViewerConfigProvider.disableWorker(); + pdfjsViewerConfigProvider.setVerbosity("infos"); // "errors", "warnings" or "infos" +}); diff --git a/types/angular-pdfjs-viewer/index.d.ts b/types/angular-pdfjs-viewer/index.d.ts new file mode 100644 index 0000000000..e9c41ef1fe --- /dev/null +++ b/types/angular-pdfjs-viewer/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for angular-pdfjs-viewer 1.0 +// Project: https://github.com/legalthings/angular-pdfjs-viewer +// Definitions by: Bastien Moulia +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as angular from 'angular'; + +declare module 'angular' { + namespace pdfjsViewer { + interface ConfigProvider extends IServiceProvider { + setWorkerSrc(src: string): void; + setCmapDir(dir: string): void; + setImageDir(dir: string): void; + disableWorker(): void; + setVerbosity(verbosity: "errors" | "warnings" | "infos"): void; + } + } +} diff --git a/types/angular-pdfjs-viewer/tsconfig.json b/types/angular-pdfjs-viewer/tsconfig.json new file mode 100644 index 0000000000..a8d322df87 --- /dev/null +++ b/types/angular-pdfjs-viewer/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "angular-pdfjs-viewer-tests.ts" + ] +} diff --git a/types/stripe/v2/tslint.json b/types/angular-pdfjs-viewer/tslint.json similarity index 100% rename from types/stripe/v2/tslint.json rename to types/angular-pdfjs-viewer/tslint.json diff --git a/types/angular-promise-tracker/index.d.ts b/types/angular-promise-tracker/index.d.ts index ec2f7fd498..85a87bad63 100644 --- a/types/angular-promise-tracker/index.d.ts +++ b/types/angular-promise-tracker/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for angular-promise-tracker 2.2.2 // Project: https://github.com/ajoslin/angular-promise-tracker -// Definitions by: Rufus Linke +// Definitions by: Rufus Linke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/angular-resource/angular-resource-tests.ts b/types/angular-resource/angular-resource-tests.ts index d2e25a72b5..c35f27a98d 100644 --- a/types/angular-resource/angular-resource-tests.ts +++ b/types/angular-resource/angular-resource-tests.ts @@ -1,15 +1,74 @@ +// Examples of working with resource, previously from the angular.d.ts. readme +// Working with $resource -import IHttpPromiseCallbackArg = angular.IHttpPromiseCallbackArg; +// We have the option to define arguments for a custom resource +interface IArticleParameters { + id: number; +} + +interface IArticleResource extends ng.resource.IResource { + title: string; + text: string; + date: Date; + author: number; + + // Although all actions defined on IArticleResourceClass are avaiable with + // the '$' prefix, we have the choice to expose only what we will use + $publish(): IArticleResource; + $unpublish(): IArticleResource; +} + +// Let's define a custom resource +interface IArticleResourceClass extends ng.resource.IResourceClass { + // Overload get to accept our custom parameters + get(): IArticleResource; + get(params: IArticleParameters, onSuccess: Function): IArticleResource; + + // Add our custom resource actions + publish(params?: IArticleParameters): IArticleResource; + unpublish(params: IArticleParameters): IArticleResource; +} + +function MainController($resource: ng.resource.IResourceService): void { + // IntelliSense will provide IActionDescriptor interface and will validate + // your assignment against it + const publishDescriptor: ng.resource.IActionDescriptor = { + method: 'GET', + isArray: false + }; + + // A call to the $resource service returns a IResourceClass. Since + // our own IArticleResourceClass defines 2 more actions, we cast the return + // value to make the compiler aware of that + const articleResource: IArticleResourceClass = $resource('/articles/:id', null, { + publish : publishDescriptor, + unpublish : { + method: 'POST' + } + }); + + // Now we can do this + articleResource.unpublish({ id: 1 }); + + // IResourceClass.get() will be automatically available here + const article: IArticleResource = articleResource.get({id: 1}, function success(): void { + // Again, default + custom action here... + article.title = 'New Title'; + article.$save(); + article.$publish(); + }); +} + +import IHttpResponse = angular.IHttpResponse; interface IMyData {} -interface IMyHttpPromiseCallbackArg extends IHttpPromiseCallbackArg {} -interface IMyResource extends angular.resource.IResource { } -interface IMyResourceClass extends angular.resource.IResourceClass { } +interface IMyResource extends angular.resource.IResource {} +interface IMyResourceClass extends angular.resource.IResourceClass {} /////////////////////////////////////// // IActionDescriptor /////////////////////////////////////// -var actionDescriptor: angular.resource.IActionDescriptor; +let actionDescriptor: angular.resource.IActionDescriptor; angular.injector(['ng']).invoke(function ($cacheFactory: angular.ICacheFactoryService) { actionDescriptor.method = 'method action'; @@ -27,19 +86,18 @@ angular.injector(['ng']).invoke(function ($cacheFactory: angular.ICacheFactorySe actionDescriptor.withCredentials = true; actionDescriptor.responseType = 'response type'; actionDescriptor.interceptor = { - response: function () { return {}; }, - responseError: function () {} + response() { return {} as IHttpResponse; }, + responseError() {} }; actionDescriptor.cancellable = true; }); - /////////////////////////////////////// // IResourceClass /////////////////////////////////////// -var resourceClass: IMyResourceClass; -var resource: IMyResource; -var resourceArray: angular.resource.IResourceArray; +let resourceClass: IMyResourceClass; +let resource: IMyResource; +let resourceArray: angular.resource.IResourceArray; resource = resourceClass.delete(); resource = resourceClass.delete({ key: 'value' }); @@ -94,9 +152,9 @@ resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { // IResource /////////////////////////////////////// -var promise : angular.IPromise; -var arrayPromise : angular.IPromise; -var json: IMyResource; +let promise: angular.IPromise; +let arrayPromise: angular.IPromise; +let json: IMyResource; promise = resource.$delete(); promise = resource.$delete({ key: 'value' }); @@ -140,7 +198,7 @@ json = resource.toJSON(); /////////////////////////////////////// // IResourceService /////////////////////////////////////// -var resourceService: angular.resource.IResourceService; +let resourceService: angular.resource.IResourceService; resourceClass = resourceService('test'); resourceClass = resourceService('test'); resourceClass = resourceService('test'); @@ -148,22 +206,20 @@ resourceClass = resourceService('test'); /////////////////////////////////////// // IModule /////////////////////////////////////// -var mod: ng.IModule; -var resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction; -var resourceService: angular.resource.IResourceService; +let mod: ng.IModule; +let resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction; resourceClass = resourceServiceFactoryFunction(resourceService); -resourceServiceFactoryFunction = function (resourceService: angular.resource.IResourceService) { return resourceClass; }; +resourceServiceFactoryFunction = function (resourceService: angular.resource.IResourceService) { return resourceClass as any; }; mod = mod.factory('factory name', resourceServiceFactoryFunction); /////////////////////////////////////// // IResource /////////////////////////////////////// - /////////////////////////////////////// // IResourceServiceProvider /////////////////////////////////////// -var resourceServiceProvider: angular.resource.IResourceServiceProvider; +let resourceServiceProvider: angular.resource.IResourceServiceProvider; resourceServiceProvider.defaults.stripTrailingSlashes = false; diff --git a/types/angular-resource/index.d.ts b/types/angular-resource/index.d.ts index 6b33790de5..1ebd198b82 100644 --- a/types/angular-resource/index.d.ts +++ b/types/angular-resource/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS (ngResource module) 1.5 // Project: http://angularjs.org -// Definitions by: Diego Vilar , Michael Jess +// Definitions by: Diego Vilar , Michael Jess // Definitions: https://github.com/daptiv/DefinitelyTyped // TypeScript Version: 2.3 @@ -37,23 +37,35 @@ declare module 'angular' { // that deeply. /////////////////////////////////////////////////////////////////////////// interface IResourceService { - (url: string, paramDefaults?: any, - /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } - where deleteDescriptor : IActionDescriptor */ - actions?: IActionHash, options?: IResourceOptions): IResourceClass>; - (url: string, paramDefaults?: any, - /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } - where deleteDescriptor : IActionDescriptor */ - actions?: IActionHash, options?: IResourceOptions): U; - (url: string, paramDefaults?: any, - /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } - where deleteDescriptor : IActionDescriptor */ - actions?: IActionHash, options?: IResourceOptions): IResourceClass; + /** + * A factory which creates a resource object that lets you interact with RESTful server-side data sources. + * @param url A parameterized URL template with parameters prefixed by : as in /user/:username + * @param paramDefaults Default values for url parameters. + * @param actions example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor: IActionDescriptor + * @param options Hash with custom settings that should extend the default $resourceProvider behavior + */ + (url: string, paramDefaults?: any, actions?: IActionHash, options?: IResourceOptions): IResourceClass>; + (url: string, paramDefaults?: any, actions?: IActionHash, options?: IResourceOptions): IResourceClass; + (url: string, paramDefaults?: any, actions?: IActionHash, options?: IResourceOptions): U; } // Hash of action descriptors allows custom action names interface IActionHash { - [action: string]: IActionDescriptor + [action: string]: IActionDescriptor; + } + + interface IResourceResponse { + config: any; + data: any; + headers: any; + resource: any; + status: number; + statusText: string; + } + + interface IResourceInterceptor { + response?(response: IResourceResponse): any; + responseError?(rejection: any): any; } // Just a reference to facilitate describing new actions @@ -62,20 +74,20 @@ declare module 'angular' { params?: any; url?: string; isArray?: boolean; - transformRequest?: angular.IHttpRequestTransformer | angular.IHttpRequestTransformer[]; - transformResponse?: angular.IHttpResponseTransformer | angular.IHttpResponseTransformer[]; + transformRequest?: IHttpRequestTransformer | IHttpRequestTransformer[]; + transformResponse?: IHttpResponseTransformer | IHttpResponseTransformer[]; headers?: any; - cache?: boolean | angular.ICacheObject; + cache?: boolean | ICacheObject; /** * Note: In contrast to $http.config, promises are not supported in $resource, because the same value * would be used for multiple requests. If you are looking for a way to cancel requests, you should * use the cancellable option. */ - timeout?: number + timeout?: number; cancellable?: boolean; withCredentials?: boolean; responseType?: string; - interceptor?: angular.IHttpInterceptor; + interceptor?: IResourceInterceptor; } // Allow specify more resource methods @@ -106,17 +118,17 @@ declare module 'angular' { // 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 + // https://github.com/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 + // https://github.com/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 + // https://github.com/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 + // https://github.com/angular/js/blob/v1.2.0/src/ngResource/resource.js#L538-L549 interface IResourceClass { - new(dataOrParams? : any) : T & IResource; + new(dataOrParams?: any): T & IResource; get: IResourceMethod; query: IResourceArrayMethod; @@ -129,32 +141,32 @@ declare module 'angular' { } // 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 + // https://github.com/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; + $get(): IPromise; + $get(params?: Object, success?: Function, error?: Function): IPromise; + $get(success: Function, error?: Function): IPromise; - $query(): angular.IPromise>; - $query(params?: Object, success?: Function, error?: Function): angular.IPromise>; - $query(success: Function, error?: Function): angular.IPromise>; + $query(): IPromise>; + $query(params?: Object, success?: Function, error?: Function): IPromise>; + $query(success: Function, error?: Function): IPromise>; - $save(): angular.IPromise; - $save(params?: Object, success?: Function, error?: Function): angular.IPromise; - $save(success: Function, error?: Function): angular.IPromise; + $save(): IPromise; + $save(params?: Object, success?: Function, error?: Function): IPromise; + $save(success: Function, error?: Function): IPromise; - $remove(): angular.IPromise; - $remove(params?: Object, success?: Function, error?: Function): angular.IPromise; - $remove(success: Function, error?: Function): angular.IPromise; + $remove(): IPromise; + $remove(params?: Object, success?: Function, error?: Function): IPromise; + $remove(success: Function, error?: Function): IPromise; - $delete(): angular.IPromise; - $delete(params?: Object, success?: Function, error?: Function): angular.IPromise; - $delete(success: Function, error?: Function): angular.IPromise; + $delete(): IPromise; + $delete(params?: Object, success?: Function, error?: Function): IPromise; + $delete(success: Function, error?: Function): IPromise; $cancelRequest(): void; - /** the promise of the original server interaction that created this instance. **/ - $promise: angular.IPromise; + /** The promise of the original server interaction that created this instance. */ + $promise: IPromise; $resolved: boolean; toJSON(): T; } @@ -165,42 +177,40 @@ declare module 'angular' { interface IResourceArray extends Array> { $cancelRequest(): void; - /** the promise of the original server interaction that created this collection. **/ - $promise: angular.IPromise>; + /** The promise of the original server interaction that created this collection. */ + $promise: IPromise>; $resolved: boolean; } /** when creating a resource factory via IModule.factory */ interface IResourceServiceFactoryFunction { - ($resource: angular.resource.IResourceService): IResourceClass; - >($resource: angular.resource.IResourceService): U; + ($resource: IResourceService): IResourceClass; + >($resource: IResourceService): U; } // IResourceServiceProvider used to configure global settings - interface IResourceServiceProvider extends angular.IServiceProvider { - + interface IResourceServiceProvider extends IServiceProvider { defaults: IResourceOptions; } - } /** extensions to base ng based on using angular-resource */ interface IModule { /** creating a resource service factory */ - factory(name: string, resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction): IModule; + factory(name: string, resourceServiceFactoryFunction: resource.IResourceServiceFactoryFunction): IModule; } namespace auto { interface IInjectorService { - get(name: '$resource'): ng.resource.IResourceService; + get(name: '$resource'): resource.IResourceService; } } } declare global { interface Array { - /** the promise of the original server interaction that created this collection. **/ - $promise: angular.IPromise>; + /** The promise of the original server interaction that created this collection. */ + $promise: angular.IPromise; $resolved: boolean; } } diff --git a/types/angular-resource/tslint.json b/types/angular-resource/tslint.json new file mode 100644 index 0000000000..ff19c22fa3 --- /dev/null +++ b/types/angular-resource/tslint.json @@ -0,0 +1,13 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO: Fix up types to remove these + "interface-name": false, + "only-arrow-functions": false, + "no-empty-interface": false, + "no-object-literal-type-assertion": false, + "ban-types": false, + "space-before-function-paren": false, + "unified-signatures": false + } +} diff --git a/types/angular-sanitize/index.d.ts b/types/angular-sanitize/index.d.ts index 89273b42fb..ad42ec362e 100644 --- a/types/angular-sanitize/index.d.ts +++ b/types/angular-sanitize/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS (ngSanitize module) 1.3 // Project: http://angularjs.org -// Definitions by: Diego Vilar +// Definitions by: Diego Vilar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/angular-strap/angular-strap-tests.ts b/types/angular-strap/angular-strap-tests.ts index c81e0056e9..64e51a238b 100644 --- a/types/angular-strap/angular-strap-tests.ts +++ b/types/angular-strap/angular-strap-tests.ts @@ -30,6 +30,8 @@ namespace angularStrapTests { myOtherModalOptions.scope = $scope; myOtherModalOptions.template = 'modal/docs/modal.demo.tpl.html'; myOtherModalOptions.show = false; + myOtherModalOptions.controller = demoCtrl; + myOtherModalOptions.controllerAs = "ctrl"; var myOtherModal = $modal(myOtherModalOptions); diff --git a/types/angular-strap/index.d.ts b/types/angular-strap/index.d.ts index 2b31f00148..9aebcdf480 100644 --- a/types/angular-strap/index.d.ts +++ b/types/angular-strap/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for angular-strap v2.2.x +// Type definitions for angular-strap v2.3.x // Project: http://mgcrea.github.io/angular-strap/ // Definitions by: Sam Herrmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -42,12 +42,19 @@ declare namespace mgcrea.ngStrap { keyboard?: boolean; show?: boolean; container?: string | boolean; + controller?: any; + controllerAs?: string; template?: string; templateUrl?: string; contentTemplate?: string; + prefixClass?: string; prefixEvent?: string; id?: string; scope?: ng.IScope; + onBeforeHide?: (modal: IModal) => void; + onHide?: (modal: IModal) => void; + onBeforeShow?: (modal: IModal) => void; + onShow?: (modal: IModal) => void; } interface IModalScope extends ng.IScope { diff --git a/types/angular-ui-bootstrap/index.d.ts b/types/angular-ui-bootstrap/index.d.ts index 7eca42520d..548f0e1ef9 100644 --- a/types/angular-ui-bootstrap/index.d.ts +++ b/types/angular-ui-bootstrap/index.d.ts @@ -312,7 +312,7 @@ declare module 'angular' { openClass?: string; } - interface IModalProvider extends IServiceProvider { + interface IModalProvider extends angular.IServiceProvider { /** * Default options all modals will use. */ @@ -876,7 +876,7 @@ declare module 'angular' { useContentExp?: boolean; } - interface ITooltipProvider extends IServiceProvider { + interface ITooltipProvider extends angular.IServiceProvider { /** * Provide a set of defaults for certain tooltip and popover attributes. */ diff --git a/types/angular-ui-router-default/angular-ui-router-default-tests.ts b/types/angular-ui-router-default/angular-ui-router-default-tests.ts deleted file mode 100644 index 39e792e3a1..0000000000 --- a/types/angular-ui-router-default/angular-ui-router-default-tests.ts +++ /dev/null @@ -1,39 +0,0 @@ -import * as angular from "angular"; - -angular.module("test", [ - "ui.router", - "ui.router.default" -]) - .config(function($stateProvider: angular.ui.IStateProvider) { - $stateProvider - .state('concrete', { - // no abstract or default - }) - .state('string', { - abstract: true, - default: 'concrete' - }) - .state('func_str', { - abstract: true, - default: function($rootScope): string { return $rootScope.test; } - }) - .state('func_promise', { - abstract: true, - default: function($q: ng.IQService): ng.IPromise { - return $q.when("concrete"); - } - }) - .state('injection_str', { - abstract: true, - default: ["$rootScope", function($rootScope) { - return $rootScope.test; - }] - }) - .state('injection_promise', { - abstract: true, - default: ["$q", function($q: ng.IQService) { - return $q.when("concrete"); - }] - }) - ; - }); diff --git a/types/angular-ui-router-default/index.d.ts b/types/angular-ui-router-default/index.d.ts deleted file mode 100644 index 98bb93b51b..0000000000 --- a/types/angular-ui-router-default/index.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// Type definitions for angular-ui-router-default 0.5 -// Project: https://github.com/nonplus/angular-ui-router-default -// Definitions by: Stepan Riha -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -import * as aur from "angular-ui-router"; - -declare module "angular" { - namespace ui { - export type StateDefaultSpecifier = string - | ((...args: any[]) => string) - | ((...args: any[]) => ng.IPromise) - | (string | ((...args: any[]) => string))[] - | (string | ((...args: any[]) => ng.IPromise))[]; - interface IState { - default?: StateDefaultSpecifier - } - } -} diff --git a/types/angular-ui-router-default/tsconfig.json b/types/angular-ui-router-default/tsconfig.json deleted file mode 100644 index 7cda72ddf5..0000000000 --- a/types/angular-ui-router-default/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "angular-ui-router-default-tests.ts" - ] -} \ No newline at end of file diff --git a/types/angular-ui-router-uib-modal/angular-ui-router-uib-modal-tests.ts b/types/angular-ui-router-uib-modal/angular-ui-router-uib-modal-tests.ts deleted file mode 100644 index 2ca6e18806..0000000000 --- a/types/angular-ui-router-uib-modal/angular-ui-router-uib-modal-tests.ts +++ /dev/null @@ -1,28 +0,0 @@ -angular.module("test", [ - "ui.bootstrap", - "ui.router", - "ui.router.default" -]) - .config(function($stateProvider: angular.ui.IStateProvider) { - $stateProvider - .state('contacts', { - // no modal - resolve: { - a: function() { - return "a"; - }, - b: function() { - return ["a", "b"]; - } - } - }) - .state('contacts.contact', { - // boolean modal - modal: true - }) - .state('contacts.contact.edit', { - // string[] modal - modal: ["a", "b"] - }) - ; - }); diff --git a/types/angular-ui-router-uib-modal/index.d.ts b/types/angular-ui-router-uib-modal/index.d.ts deleted file mode 100644 index b0abfdb031..0000000000 --- a/types/angular-ui-router-uib-modal/index.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Type definitions for angular-ui-uib-modal (ui.router module) 0.11 -// Project: https://github.com/nonplus/angular-ui-router-uib-modal -// Definitions by: Stepan Riha -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -import * as auir from "angular-ui-router"; - -declare module "angular" { - namespace ui { - interface IState { - modal?: boolean | string[]; - } - } -} diff --git a/types/angular-ui-router-uib-modal/tsconfig.json b/types/angular-ui-router-uib-modal/tsconfig.json deleted file mode 100644 index 7924c64716..0000000000 --- a/types/angular-ui-router-uib-modal/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "angular-ui-router-uib-modal-tests.ts" - ] -} \ No newline at end of file diff --git a/types/angular-ui-router/angular-ui-router-tests.ts b/types/angular-ui-router/angular-ui-router-tests.ts index 174c319f97..8f9ec67486 100644 --- a/types/angular-ui-router/angular-ui-router-tests.ts +++ b/types/angular-ui-router/angular-ui-router-tests.ts @@ -157,7 +157,7 @@ class UrlLocatorTestService implements IUrlLocatorTestService { // Note that we do not concern ourselves with what to do if this request fails, // because if it fails, the web page will be redirected away to the login screen. - this.$http({ url: "/api/me", method: "GET" }).then((response: ng.IHttpPromiseCallbackArg) => { + this.$http({ url: "/api/me", method: "GET" }).then((response: ng.IHttpResponse) => { this.currentUser = response.data; // sync the ui-state with the location in the browser, which effectively diff --git a/types/angular-ui-scroll/angular-ui-scroll-tests.ts b/types/angular-ui-scroll/angular-ui-scroll-tests.ts index e226b664bc..9be5609d16 100644 --- a/types/angular-ui-scroll/angular-ui-scroll-tests.ts +++ b/types/angular-ui-scroll/angular-ui-scroll-tests.ts @@ -23,8 +23,12 @@ namespace application { myApp.factory('DatasourceTest', factory); + interface TestScope extends ng.IScope { + [index: string]: any; + } + // demo/examples/adapter - myApp.controller('mainController', ['$scope', 'DatasourceTest', function($scope: ng.IScope, datasource: DatasourceTest) { + myApp.controller('mainController', ['$scope', 'DatasourceTest', function($scope: TestScope, datasource: DatasourceTest) { var firstListAdapter: ng.ui.IScrollAdapter, secondListAdapter: ng.ui.IScrollAdapter; $scope['datasource'] = datasource; diff --git a/types/angular/README.md b/types/angular/README.md index 1b3affc92c..871d9d37fa 100644 --- a/types/angular/README.md +++ b/types/angular/README.md @@ -2,27 +2,23 @@ ## Referencing AngularJS definition files in 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. +Read the [TypeScript handbook](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html) for details on consuming these type definitions. 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. + + +Having these modules in separated packages 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. The following extra definition files are available for referencing: -* angular-resource.d.ts (for the **ngResource** module) -* angular-route.d.ts (for the **ngRoute** module) -* angular-cookies.d.ts (for the **ngCookies** module) -* angular-sanitize.d.ts (for the **ngSanitize** module) -* angular-animate.d.ts (for the **ngAnimate** module) -* angular-mocks.d.ts (for the **ngMock** and **ngMockE2E** modules) - -(postfix with version number for specific verion, eg. angular-resource-1.0.d.ts) +* angular-resource/index.d.ts (for the **ngResource** module) +* angular-route/index.d.ts (for the **ngRoute** module) +* angular-cookies/index.d.ts (for the **ngCookies** module) +* angular-sanitize/index.d.ts (for the **ngSanitize** module) +* angular-animate/index.d.ts (for the **ngAnimate** module) +* angular-mocks/index.d.ts (for the **ngMock** and **ngMockE2E** modules) ## The Angular Static @@ -31,7 +27,7 @@ The definitions declare the AngularJS static variable `angular` as ambient. That ## Definitions modularized -To avoid cluttering the list of suggestions as you type in your IDE, all interfaces reside in their respective module namespace: +To avoid cluttering the list of suggestions as you type in your IDE, all interfaces reside in their respective module namespace after you include their respective definitions: * `ng` for AngularJS' **ng** module * `ng.auto` for **AUTO** @@ -105,128 +101,3 @@ function Controller($scope: ICustomScope) { ## Examples -### Working with $resource -```ts - - - -// We have the option to define arguments for a custom resource -interface IArticleParameters { - id: number; -} - -interface IArticleResource extends ng.resource.IResource { - title: string; - text: string; - date: Date; - author: number; - - // Although all actions defined on IArticleResourceClass are avaiable with - // the '$' prefix, we have the choice to expose only what we will use - $publish(): IArticleResource; - $unpublish(): IArticleResource; -} - -// Let's define a custom resource -interface IArticleResourceClass extends ng.resource.IResourceClass { - // Overload get to accept our custom parameters - get(): ng.resource.IResource; - get(params: IArticleParameters, onSuccess: Function): IArticleResource; - - // Add our custom resource actions - publish(): IArticleResource; - publish(params: IArticleParameters): IArticleResource; - unpublish(params: IArticleParameters): IArticleResource; -} - -function MainController($resource: ng.resource.IResourceService) { - - // IntelliSense will provide IActionDescriptor interface and will validate - // your assignment against it - var publishDescriptor: ng.resource.IActionDescriptor; - publishDescriptor = { - method: 'GET', - isArray: false - }; - - // I could still create a descriptor without the interface... - var unpublishDescriptor = { - method: 'POST' - } - - // A call to the $resource service returns a IResourceClass. Since - // our own IArticleResourceClass defines 2 more actions, we cast the return - // value to make the compiler aware of that - var articleResource = $resource('/articles/:id', null, { - publish : publishDescriptor, - unpublish : unpublishDescriptor - }); - - // Now we can do this - articleResource.unpublish({ id: 1 }); - - // IResourceClass.get() will be automatically available here - var article: IArticleResource = articleResource.get({id: 1}, function success() { - // Again, default + custom action here... - article.title = 'New Title'; - article.$save(); - article.$publish(); - }); -} -``` - -### Working with $resource in angular-1.0 definitions -```ts - - - -// Let's define a custom resource -interface IArticleResourceClass extends ng.resource.IResourceClass { - publish: ng.resource.IActionCall; - unpublish: ng.resource.IActionCall; -} -interface IArticleResource extends ng.resource.IResource { - title: string; - text: string; - date: Date; - author: number; - $publish: ng.resource.IActionCall; - $unpublish: ng.resource.IActionCall; -} - -function MainController($resource: ng.resource.IResourceService) { - - // IntelliSense will provide IActionDescriptor interface and will validate - // your assignment against it - var publishDescriptor: ng.resource.IActionDescriptor; - publishDescriptor = { - method: 'GET', - isArray: false - }; - - // I could still create a descriptor without the interface... - var unpublishDescriptor = { - method: 'POST' - } - - // A call to the $resource service returns a IResourceClass. Since - // our own IArticleResourceClass defines 2 more actions, we cast the return - // value to make the compiler aware of that - var articles = $resource('/articles/:id', null, { - publish : publishDescriptor, - unpublish : unpublishDescriptor - }); - - // Now we can do this - articles.unpublish({ id: 1 }); - - // IResourceClass.get() will be automatically available here - var article = articles.get({id: 1}); - - // Again, default + custom action here... - article.title = 'New Title'; - article.$save(); - article.$publish(); - -} -``` diff --git a/types/angular/angular-component-router.d.ts b/types/angular/angular-component-router.d.ts index da3afc7a71..b8cd8d097e 100644 --- a/types/angular/angular-component-router.d.ts +++ b/types/angular/angular-component-router.d.ts @@ -1,7 +1,7 @@ /* tslint:disable:dt-header variable-name */ // Type definitions for Angular JS 1.5 component router // Project: http://angularjs.org -// Definitions by: David Reher +// Definitions by: David Reher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace angular { @@ -15,7 +15,7 @@ declare namespace angular { * ### Example * * ``` - * import {Component} from 'angular2/core'; + * import { Component } from 'angular2/core'; * import {bootstrap} from 'angular2/platform/browser'; * import {Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router'; * diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index 20de01f71f..c60da29504 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -61,31 +61,38 @@ angular.module('http-auth-interceptor', []) * $http interceptor. * On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'. */ - .config(['$httpProvider', 'authServiceProvider', ($httpProvider: ng.IHttpProvider, authServiceProvider: any) => { - $httpProvider.defaults.headers.common = {Authorization: 'Bearer token'}; - $httpProvider.defaults.headers.get['Authorization'] = 'Bearer token'; - $httpProvider.defaults.headers.post['Authorization'] = (config: ng.IRequestConfig) => 'Bearer token'; + .config([ + '$httpProvider', 'authServiceProvider', + ($httpProvider: ng.IHttpProvider, authServiceProvider: AuthService) => { + $httpProvider.defaults.headers.common = { Authorization: 'Bearer token' }; + $httpProvider.defaults.headers.get.Authorization = 'Bearer token'; + $httpProvider.defaults.headers.post['Authorization'] = (config: ng.IRequestConfig) => + 'Bearer token'; - const interceptor = ['$rootScope', '$q', ($rootScope: ng.IScope, $q: ng.IQService) => { - function success(response: ng.IHttpPromiseCallbackArg) { - return response; - } - - function error(response: ng.IHttpPromiseCallbackArg) { - if (response.status === 401) { - const deferred = $q.defer(); - authServiceProvider.pushToBuffer(response.config, deferred); - $rootScope.$broadcast('event:auth-loginRequired'); - return deferred.promise; + const interceptor = [ + '$rootScope', '$q', + ($rootScope: ng.IScope, $q: ng.IQService) => { + return { + request(config: ng.IRequestConfig) { + if (!config.params) config.params = {}; + config.params.rnd = Math.random(); + return config; + }, + responseError(rejection: any) { + if (rejection.status === 401) { + const deferred = $q.defer>(); + authServiceProvider.pushToBuffer(rejection.config, deferred); + $rootScope.$broadcast('event:auth-loginRequired'); + return deferred.promise; + } + return $q.reject(rejection); + } + }; } - // otherwise - return $q.reject(response); - } - - return (promise: ng.IHttpPromise) => promise.then(success, error); - }]; - $httpProvider.interceptors.push(interceptor); - }]); + ]; + $httpProvider.interceptors.push(interceptor); + } + ]); namespace HttpAndRegularPromiseTests { interface Person { @@ -105,7 +112,7 @@ namespace HttpAndRegularPromiseTests { function someController($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) { $http.get('http://somewhere/some/resource') - .then((response: ng.IHttpPromiseCallbackArg) => { + .then((response: ng.IHttpResponse) => { // typing lost, so something like // const i: number = response.data // would type check @@ -113,7 +120,7 @@ namespace HttpAndRegularPromiseTests { }); $http.get('http://somewhere/some/resource') - .then((response: ng.IHttpPromiseCallbackArg) => { + .then((response: ng.IHttpResponse) => { // typing lost, so something like // const i: number = response.data // would NOT type check @@ -339,12 +346,12 @@ namespace TestQ { result = $q.all<{a: number; b: string; }>({a: promiseAny, b: promiseAny}); } { - let result = $q.all({ num: $q.when(2), str: $q.when('test') }); + const result = $q.all({ num: $q.when(2), str: $q.when('test') }); // TS should infer that num is a number and str is a string result.then(r => (r.num * 2) + r.str.indexOf('s')); } { - let result = $q.all({ num: $q.when(2), str: 'test' }); + const result = $q.all({ num: $q.when(2), str: 'test' }); // TS should infer that num is a number and str is a string result.then(r => (r.num * 2) + r.str.indexOf('s')); } @@ -378,7 +385,7 @@ namespace TestQ { let result: angular.IPromise; result = $q.resolve(tResult); result = $q.resolve(promiseTResult); - let result2: angular.IPromise = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther); + const result2: angular.IPromise = $q.resolve(Math.random() > 0.5 ? tResult : promiseTOther); } // $q.when @@ -388,7 +395,6 @@ namespace TestQ { } { let result: angular.IPromise; - let other: angular.IPromise; let resultOther: angular.IPromise; result = $q.when(tResult); @@ -427,7 +433,7 @@ httpFoo.then((x) => { x.toFixed(); }); -httpFoo.then((response: ng.IHttpPromiseCallbackArg) => { +httpFoo.then((response: ng.IHttpResponse) => { const h = response.headers('test'); h.charAt(0); const hs = response.headers(); @@ -450,8 +456,8 @@ namespace TestDeferred { // deferred.resolve { let result: void; - result = deferred.resolve() as void; - result = deferred.resolve(tResult) as void; + result = deferred.resolve(); + result = deferred.resolve(tResult); } // deferred.reject @@ -488,7 +494,7 @@ namespace TestInjector { class Foobar { constructor($q) {} } - let result: Foobar = $injector.instantiate(Foobar); + const result: Foobar = $injector.instantiate(Foobar); } // $injector.invoke @@ -496,14 +502,14 @@ namespace TestInjector { function foobar(v: boolean): number { return 7; } - let result = $injector.invoke(foobar); + const result = $injector.invoke(foobar); if (!(typeof result === 'number')) { // This fails to compile if 'result' is not exactly a number. - let expectNever: never = result; + const expectNever: never = result; } - let anyFunction: Function = foobar; - let anyResult: string = $injector.invoke(anyFunction); + const anyFunction: Function = foobar; + const anyResult: string = $injector.invoke(anyFunction); } } @@ -566,7 +572,7 @@ namespace TestPromise { (reason) => anyOf3(reject, tresult, tresultPromise) )); - assertPromiseType>(promise.then((result) => tresultHttpPromise)); + assertPromiseType>(promise.then((result) => tresultHttpPromise)); assertPromiseType(promise.then((result) => result, (any) => tother)); assertPromiseType | angular.IPromise | TOther | angular.IPromise>(promise.then( @@ -581,8 +587,8 @@ namespace TestPromise { assertPromiseType(promise.then((result) => result, (any) => tother, (any) => any)); assertPromiseType(promise.then((result) => tresultPromise, (any) => totherPromise)); assertPromiseType(promise.then((result) => tresultPromise, (any) => totherPromise, (any) => any)); - assertPromiseType>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise)); - assertPromiseType>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise, (any) => any)); + assertPromiseType>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise)); + assertPromiseType>(promise.then((result) => tresultHttpPromise, (any) => totherHttpPromise, (any) => any)); assertPromiseType(promise.then((result) => tother)); assertPromiseType(promise.then((result) => tother, (any) => any)); @@ -590,9 +596,9 @@ namespace TestPromise { assertPromiseType(promise.then((result) => totherPromise)); assertPromiseType(promise.then((result) => totherPromise, (any) => any)); assertPromiseType(promise.then((result) => totherPromise, (any) => any, (any) => any)); - assertPromiseType>(promise.then((result) => totherHttpPromise)); - assertPromiseType>(promise.then((result) => totherHttpPromise, (any) => any)); - assertPromiseType>(promise.then((result) => totherHttpPromise, (any) => any, (any) => any)); + assertPromiseType>(promise.then((result) => totherHttpPromise)); + assertPromiseType>(promise.then((result) => totherHttpPromise, (any) => any)); + assertPromiseType>(promise.then((result) => totherHttpPromise, (any) => any, (any) => any)); assertPromiseType(promise.then((result) => tresult, (any) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); @@ -603,10 +609,10 @@ namespace TestPromise { assertPromiseType>(promise.catch((err) => anyOf2(tresult, reject))); assertPromiseType(promise.catch((err) => anyOf3(tresult, tresultPromise, reject))); assertPromiseType(promise.catch((err) => tresultPromise)); - assertPromiseType>(promise.catch((err) => tresultHttpPromise)); + assertPromiseType>(promise.catch((err) => tresultHttpPromise)); assertPromiseType(promise.catch((err) => tother)); assertPromiseType(promise.catch((err) => totherPromise)); - assertPromiseType>(promise.catch((err) => totherHttpPromise)); + assertPromiseType>(promise.catch((err) => totherHttpPromise)); assertPromiseType(promise.catch((err) => tother).then(ambiguous => isTResult(ambiguous) ? ambiguous.c : ambiguous.f)); @@ -621,7 +627,7 @@ function test_angular_forEach() { const log: string[] = []; angular.forEach(values, (value, key, obj) => { obj[key] = value; - this.push(key + ': ' + value); + this.push(`${key}: ${value}`); }, log); // expect(log).toEqual(['name: misko', 'gender: male']); } @@ -1160,11 +1166,7 @@ function NgModelControllerTyping() { ngModel.$asyncValidators['uniqueUsername'] = (modelValue, viewValue) => { const value = modelValue || viewValue; return $http.get('/api/users/' + value). - then(function resolved() { - return $q.reject('exists'); - }, function rejected() { - return true; - }); + then(() => $q.reject('exists'), () => true); }; } diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 3683c1aed6..8415c6e6b7 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -1,7 +1,7 @@ // Type definitions for Angular JS 1.6 // Project: http://angularjs.org -// Definitions by: Diego Vilar -// Georgii Dolzhykov +// Definitions by: Diego Vilar +// Georgii Dolzhykov // Caleb St-Denis // Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,6 +9,9 @@ /// +// NOTE: @types/angular technically doesn't require TypeScript 2.3, only TypeScript 2.1. +// It has a TypeScript 2.3 header so that merging tests with @types/jquery v3 will work. + declare var angular: angular.IAngularStatic; // Support for painless dependency injection @@ -451,8 +454,6 @@ declare namespace angular { * 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; @@ -976,7 +977,7 @@ declare namespace angular { // DocumentService // see http://docs.angularjs.org/api/ng.$document /////////////////////////////////////////////////////////////////////////// - interface IDocumentService extends JQuery { + interface IDocumentService extends JQLite { // Must return intersection type for index signature compatibility with JQuery [index: number]: HTMLElement & Document; } @@ -993,7 +994,7 @@ declare namespace angular { // RootElementService // see http://docs.angularjs.org/api/ng.$rootElement /////////////////////////////////////////////////////////////////////////// - interface IRootElementService extends JQuery {} + interface IRootElementService extends JQLite {} interface IQResolveReject { (): void; @@ -1037,6 +1038,12 @@ declare namespace angular { * Creates a Deferred object which represents a task which will finish in the future. */ defer(): IDeferred; + /** + * Returns a promise that resolves or rejects as soon as one of those promises resolves or rejects, with the value or reason from that promise. + * + * @param promises A list or hash of promises. + */ + race(promises: Array> | {[key: string]: IPromise}): IPromise; /** * 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. * @@ -1298,12 +1305,12 @@ declare namespace angular { interface ICloneAttachFunction { // Let's hint but not force cloneAttachFn's signature - (clonedElement?: JQuery, scope?: IScope): any; + (clonedElement?: JQLite, scope?: IScope): any; } // This corresponds to the "publicLinkFn" returned by $compile. interface ITemplateLinkingFunction { - (scope: IScope, cloneAttachFn?: ICloneAttachFunction, options?: ITemplateLinkingFunctionOptions): JQuery; + (scope: IScope, cloneAttachFn?: ICloneAttachFunction, options?: ITemplateLinkingFunctionOptions): JQLite; } interface ITemplateLinkingFunctionOptions { @@ -1321,9 +1328,9 @@ declare namespace angular { */ interface ITranscludeFunction { // If the scope is provided, then the cloneAttachFn must be as well. - (scope: IScope, cloneAttachFn: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQuery; + (scope: IScope, cloneAttachFn: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQLite; // If one argument is provided, then it's assumed to be the cloneAttachFn. - (cloneAttachFn?: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQuery; + (cloneAttachFn?: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQLite; /** * Returns true if the specified slot contains content (i.e. one or more DOM nodes) @@ -1474,6 +1481,12 @@ declare namespace angular { * See [XMLHttpRequest.responseType]https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype */ responseType?: string; + + /** + * Name of the parameter added (by AngularJS) to the request to specify the name (in the server response) of the JSON-P callback to invoke. + * If unspecified, $http.defaults.jsonpCallbackParam will be used by default. This property is only applicable to JSON-P requests. + */ + jsonpCallbackParam?: string; } /** @@ -1510,23 +1523,27 @@ declare namespace angular { (data: T, status: number, headers: IHttpHeadersGetter, config: IRequestConfig): void; } - interface IHttpPromiseCallbackArg { - data?: T; - status?: number; - headers?: IHttpHeadersGetter; - config?: IRequestConfig; - statusText?: string; + interface IHttpResponse { + data: T; + status: number; + headers: IHttpHeadersGetter; + config: IRequestConfig; + statusText: string; + /** Added in AngularJS 1.6.6 */ + xhrStatus: 'complete' | 'error' | 'timeout' | 'abort'; } - interface IHttpPromise extends IPromise> { - } + /** @deprecated The old name of IHttpResponse. Kept for compatibility. */ + type IHttpPromiseCallbackArg = IHttpResponse; + + type IHttpPromise = IPromise>; // 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 + // The definition of fields are the same as IHttpResponse interface IHttpResponseTransformer { (data: any, headersGetter: IHttpHeadersGetter, status: number): any; } @@ -1599,10 +1616,10 @@ declare namespace angular { } interface IHttpInterceptor { - request?(config: IRequestConfig): IRequestConfig|IPromise; - requestError?(rejection: any): any; - response?(response: IHttpPromiseCallbackArg): IPromise>|IHttpPromiseCallbackArg; - responseError?(rejection: any): any; + request?(config: IRequestConfig): IRequestConfig | IPromise; + requestError?(rejection: any): IRequestConfig | IPromise; + response?(response: IHttpResponse): IPromise> | IHttpResponse; + responseError?(rejection: any): IPromise> | IHttpResponse; } interface IHttpInterceptorFactory { @@ -1952,7 +1969,7 @@ declare namespace angular { interface IDirectiveLinkFn { ( scope: IScope, - instanceElement: JQuery, + instanceElement: JQLite, instanceAttributes: IAttributes, controller?: IController | IController[] | {[key: string]: IController}, transclude?: ITranscludeFunction @@ -1966,7 +1983,7 @@ declare namespace angular { interface IDirectiveCompileFn { ( - templateElement: JQuery, + templateElement: JQLite, templateAttributes: IAttributes, /** * @deprecated @@ -1998,9 +2015,9 @@ declare namespace angular { require?: string | string[] | {[controller: string]: string}; restrict?: string; scope?: boolean | {[boundProperty: string]: string}; - template?: string | ((tElement: JQuery, tAttrs: IAttributes) => string); + template?: string | ((tElement: JQLite, tAttrs: IAttributes) => string); templateNamespace?: string; - templateUrl?: string | ((tElement: JQuery, tAttrs: IAttributes) => string); + templateUrl?: string | ((tElement: JQLite, tAttrs: IAttributes) => string); terminal?: boolean; transclude?: boolean | 'element' | {[slot: string]: string}; } @@ -2013,7 +2030,7 @@ declare namespace angular { * See: http://docs.angularjs.org/api/angular.element */ interface IAugmentedJQueryStatic extends JQueryStatic {} - interface IAugmentedJQuery extends JQuery {} + interface IAugmentedJQuery extends JQLite {} /** * Same as IController. Keeping it for compatibility with older versions of these type definitions. diff --git a/types/angular/jqlite.d.ts b/types/angular/jqlite.d.ts index 150c50b5dd..fd199da74b 100644 --- a/types/angular/jqlite.d.ts +++ b/types/angular/jqlite.d.ts @@ -25,6 +25,10 @@ // Definitions copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/0480c5ec87fab41aa23047a02b27f0ea71aaf975/types/jquery/v2/index.d.ts +interface JQLite extends JQuery { + [index: number]: HTMLElement; +} + interface JQuery { /** * Adds the specified class(es) to each of the set of matched elements. @@ -32,7 +36,7 @@ interface JQuery { * @param className One or more space-separated classes to be added to the class attribute of each matched element. * @see {@link https://api.jquery.com/addClass/#addClass-className} */ - addClass(className: string): JQuery; + addClass(className: string): this; /** * Insert content, specified by the parameter, after each element in the set of matched elements. @@ -41,14 +45,14 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/after/#after-content-content} */ - after(content1: JQuery | any[] | Element | DocumentFragment | Text | string, ...content2: any[]): JQuery; + after(content1: JQuery | any[] | Element | DocumentFragment | Text | string, ...content2: any[]): this; /** * 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. * @see {@link https://api.jquery.com/after/#after-function} */ - after(func: (index: number, html: string) => string | Element | JQuery): JQuery; + after(func: (index: number, html: string) => string | Element | JQuery): this; /** * Insert content, specified by the parameter, to the end of each element in the set of matched elements. @@ -57,14 +61,14 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/append/#append-content-content} */ - append(content1: JQuery | any[] | Element | DocumentFragment | Text | string, ...content2: any[]): JQuery; + append(content1: JQuery | any[] | Element | DocumentFragment | Text | string, ...content2: any[]): this; /** * 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. * @see {@link https://api.jquery.com/append/#append-function} */ - append(func: (index: number, html: string) => string | Element | JQuery): JQuery; + append(func: (index: number, html: string) => string | Element | JQuery): this; /** * Get the value of an attribute for the first element in the set of matched elements. @@ -80,14 +84,14 @@ interface JQuery { * @param value A value to set for the attribute. If this is `null`, the attribute will be deleted. * @see {@link https://api.jquery.com/attr/#attr-attributeName-value} */ - attr(attributeName: string, value: string | number | null): JQuery; + attr(attributeName: string, value: string | number | null): this; /** * Set one or more attributes for the set of matched elements. * * @param attributes An object of attribute-value pairs to set. * @see {@link https://api.jquery.com/attr/#attr-attributes} */ - attr(attributes: Object): JQuery; + attr(attributes: Object): this; /** * Attach a handler to an event for the elements. @@ -96,7 +100,7 @@ interface JQuery { * @param handler A function to execute each time the event is triggered. * @see {@link https://api.jquery.com/bind/#bind-eventType-eventData-handler} */ - bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): this; /** * Attach a handler to an event for the elements. * @@ -104,21 +108,21 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/bind/#bind-eventType-eventData-preventBubble} */ - bind(eventType: string, preventBubble: boolean): JQuery; + bind(eventType: string, preventBubble: boolean): this; /** * 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. * @see {@link https://api.jquery.com/bind/#bind-events} */ - bind(events: any): JQuery; + bind(events: any): this; /** * Get the children of each element in the set of matched elements, optionally filtered by a selector. * * @see {@link https://api.jquery.com/children/} */ - children(): JQuery; + children(): this; /** * Create a deep copy of the set of matched elements. @@ -127,13 +131,13 @@ interface JQuery { * @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). * @see {@link https://api.jquery.com/clone/} */ - clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; + clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): this; /** * Get the children of each element in the set of matched elements, including text and comment nodes. * @see {@link https://api.jquery.com/contents/} */ - contents(): JQuery; + contents(): this; /** * Get the value of style properties for the first element in the set of matched elements. @@ -157,7 +161,7 @@ interface JQuery { * @param value A value to set for the property. * @see {@link https://api.jquery.com/css/#css-propertyName-value} */ - css(propertyName: string, value: string | number): JQuery; + css(propertyName: string, value: string | number): this; /** * Set one or more CSS properties for the set of matched elements. * @@ -165,14 +169,14 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/css/#css-propertyName-function} */ - css(propertyName: string, value: (index: number, value: string) => string | number): JQuery; + css(propertyName: string, value: (index: number, value: string) => string | number): this; /** * Set one or more CSS properties for the set of matched elements. * * @param properties An object of property-value pairs to set. * @see {@link https://api.jquery.com/css/#css-properties} */ - css(properties: JQLiteCssProperties): JQuery; + css(properties: JQLiteCssProperties): this; /** * Store arbitrary data associated with the matched elements. @@ -181,7 +185,7 @@ interface JQuery { * @param value The new data value; it can be any JavaScript type including Array or Object. * @see {@link https://api.jquery.com/data/#data-key-value} */ - data(key: string, value: any): JQuery; + data(key: string, value: any): this; /** * 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. * @@ -195,7 +199,7 @@ interface JQuery { * @param obj An object of key-value pairs of data to update. * @see {@link https://api.jquery.com/data/#data-obj} */ - data(obj: { [key: string]: any; }): JQuery; + data(obj: { [key: string]: any; }): this; /** * 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. * @see {@link https://api.jquery.com/data/#data} @@ -208,13 +212,13 @@ interface JQuery { * @param selector A selector expression that filters the set of matched elements to be removed. * @see {@link https://api.jquery.com/detach/} */ - detach(selector?: string): JQuery; + detach(selector?: string): this; /** * Remove all child nodes of the set of matched elements from the DOM. * @see {@link https://api.jquery.com/empty/} */ - empty(): JQuery; + empty(): this; /** * Reduce the set of matched elements to the one at the specified index. @@ -222,7 +226,7 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/eq/} */ - eq(index: number): JQuery; + eq(index: number): this; /** * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. @@ -230,9 +234,9 @@ interface JQuery { * @param selector A string containing a selector expression to match elements against. * @see {@link https://api.jquery.com/find/#find-selector} */ - find(selector: string): JQuery; - find(element: any): JQuery; - find(obj: JQuery): JQuery; + find(selector: string): this; + find(element: any): this; + find(obj: JQuery): this; /** * Determine whether any of the matched elements are assigned the given class. @@ -253,21 +257,21 @@ interface JQuery { * @param htmlString A string of HTML to set as the content of each matched element. * @see {@link https://api.jquery.com/html/#html-htmlString} */ - html(htmlString: string): JQuery; + html(htmlString: string): this; /** * 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. * @see {@link https://api.jquery.com/html/#html-function} */ - html(func: (index: number, oldhtml: string) => string): JQuery; + html(func: (index: number, oldhtml: string) => string): this; /** * 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. * * @see {@link https://api.jquery.com/next/} */ - next(): JQuery; + next(): this; /** * Attach an event handler function for one or more events to the selected elements. @@ -276,7 +280,7 @@ interface JQuery { * @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). * @see {@link https://api.jquery.com/on/#on-events-selector-data-handler} */ - on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): this; /** * Attach an event handler function for one or more events to the selected elements. * @@ -285,7 +289,7 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/on/#on-events-selector-data-handler} */ - on(events: string, data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + on(events: string, data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): this; /** * Attach an event handler function for one or more events to the selected elements. * @@ -294,7 +298,7 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/on/#on-events-selector-data-handler} */ - on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): this; /** * Attach an event handler function for one or more events to the selected elements. * @@ -304,7 +308,7 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/on/#on-events-selector-data-handler} */ - on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): this; /** * Attach an event handler function for one or more events to the selected elements. * @@ -313,7 +317,7 @@ interface JQuery { * @param data Data to be passed to the handler in event.data when an event occurs. * @see {@link https://api.jquery.com/on/#on-events-selector-data} */ - on(events: { [key: string]: (eventObject: JQueryEventObject, ...args: any[]) => any; }, selector?: string, data?: any): JQuery; + on(events: { [key: string]: (eventObject: JQueryEventObject, ...args: any[]) => any; }, selector?: string, data?: any): this; /** * Attach an event handler function for one or more events to the selected elements. * @@ -321,13 +325,13 @@ interface JQuery { * @param data Data to be passed to the handler in event.data when an event occurs. * @see {@link https://api.jquery.com/on/#on-events-selector-data} */ - on(events: { [key: string]: (eventObject: JQueryEventObject, ...args: any[]) => any; }, data?: any): JQuery; + on(events: { [key: string]: (eventObject: JQueryEventObject, ...args: any[]) => any; }, data?: any): this; /** * Remove an event handler. * @see {@link https://api.jquery.com/off/#off} */ - off(): JQuery; + off(): this; /** * Remove an event handler. * @@ -336,7 +340,7 @@ interface JQuery { * @param handler A handler function previously attached for the event(s), or the special value false. * @see {@link https://api.jquery.com/off/#off-events-selector-handler} */ - off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): this; /** * Remove an event handler. * @@ -344,7 +348,7 @@ interface JQuery { * @param handler A handler function previously attached for the event(s), or the special value false. Takes handler with extra args that can be attached with on(). * @see {@link https://api.jquery.com/off/#off-events-selector-handler} */ - off(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + off(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): this; /** * Remove an event handler. * @@ -352,7 +356,7 @@ interface JQuery { * @param handler A handler function previously attached for the event(s), or the special value false. * @see {@link https://api.jquery.com/off/#off-events-selector-handler} */ - off(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + off(events: string, handler: (eventObject: JQueryEventObject) => any): this; /** * Remove an event handler. * @@ -360,7 +364,7 @@ interface JQuery { * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. * @see {@link https://api.jquery.com/off/#off-events-selector} */ - off(events: { [key: string]: any; }, selector?: string): JQuery; + off(events: { [key: string]: any; }, selector?: string): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. @@ -369,7 +373,7 @@ interface JQuery { * @param handler A function to execute at the time the event is triggered. * @see {@link https://api.jquery.com/one/#one-events-data-handler} */ - one(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + one(events: string, handler: (eventObject: JQueryEventObject) => any): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @@ -378,7 +382,7 @@ interface JQuery { * @param handler A function to execute at the time the event is triggered. * @see {@link https://api.jquery.com/one/#one-events-data-handler} */ - one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @@ -387,7 +391,7 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/one/#one-events-selector-data-handler} */ - one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @@ -397,7 +401,7 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/one/#one-events-selector-data-handler} */ - one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @@ -406,7 +410,7 @@ interface JQuery { * @param data Data to be passed to the handler in event.data when an event occurs. * @see {@link https://api.jquery.com/one/#one-events-selector-data} */ - one(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; + one(events: { [key: string]: any; }, selector?: string, data?: any): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @@ -414,14 +418,14 @@ interface JQuery { * @param data Data to be passed to the handler in event.data when an event occurs. * @see {@link https://api.jquery.com/one/#one-events-selector-data} */ - one(events: { [key: string]: any; }, data?: any): JQuery; + one(events: { [key: string]: any; }, data?: any): this; /** * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. * * @see {@link https://api.jquery.com/parent/} */ - parent(): JQuery; + parent(): this; /** * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. @@ -430,14 +434,14 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/prepend/#prepend-content-content} */ - prepend(content1: JQuery | any[] | Element | DocumentFragment | Text | string, ...content2: any[]): JQuery; + prepend(content1: JQuery | any[] | Element | DocumentFragment | Text | string, ...content2: any[]): this; /** * 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. * @see {@link https://api.jquery.com/prepend/#prepend-function} */ - prepend(func: (index: number, html: string) => string | Element | JQuery): JQuery; + prepend(func: (index: number, html: string) => string | Element | JQuery): this; /** * Get the value of a property for the first element in the set of matched elements. @@ -453,14 +457,14 @@ interface JQuery { * @param value A value to set for the property. * @see {@link https://api.jquery.com/prop/#prop-propertyName-value} */ - prop(propertyName: string, value: string | number | boolean): JQuery; + prop(propertyName: string, value: string | number | boolean): this; /** * Set one or more properties for the set of matched elements. * * @param properties An object of property-value pairs to set. * @see {@link https://api.jquery.com/prop/#prop-properties} */ - prop(properties: Object): JQuery; + prop(properties: Object): this; /** * Set one or more properties for the set of matched elements. * @@ -468,7 +472,7 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/prop/#prop-propertyName-function} */ - prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): JQuery; + prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): this; /** * Specify a function to execute when the DOM is fully loaded. @@ -476,7 +480,7 @@ interface JQuery { * @param handler A function to execute after the DOM is ready. * @see {@link https://api.jquery.com/ready/} */ - ready(handler: (jQueryAlias?: JQueryStatic) => any): JQuery; + ready(handler: (jQueryAlias?: JQueryStatic) => any): this; /** * Remove the set of matched elements from the DOM. @@ -484,7 +488,7 @@ interface JQuery { * @param selector A selector expression that filters the set of matched elements to be removed. * @see {@link https://api.jquery.com/remove/} */ - remove(selector?: string): JQuery; + remove(selector?: string): this; /** * Remove an attribute from each element in the set of matched elements. @@ -492,7 +496,7 @@ interface JQuery { * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. * @see {@link https://api.jquery.com/removeAttr/} */ - removeAttr(attributeName: string): JQuery; + removeAttr(attributeName: string): this; /** * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. @@ -500,7 +504,7 @@ interface JQuery { * @param className One or more space-separated classes to be removed from the class attribute of each matched element. * @see {@link https://api.jquery.com/removeClass/#removeClass-className} */ - removeClass(className?: string): JQuery; + removeClass(className?: string): this; /** * Remove a previously-stored piece of data. @@ -508,19 +512,19 @@ interface JQuery { * @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete. * @see {@link https://api.jquery.com/removeData/#removeData-name} */ - removeData(name: string): JQuery; + removeData(name: string): this; /** * Remove a previously-stored piece of data. * * @param list An array of strings naming the pieces of data to delete. * @see {@link https://api.jquery.com/removeData/#removeData-list} */ - removeData(list: string[]): JQuery; + removeData(list: string[]): this; /** * Remove all previously-stored piece of data. * @see {@link https://api.jquery.com/removeData/} */ - removeData(): JQuery; + removeData(): this; /** * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. @@ -528,14 +532,14 @@ interface JQuery { * @param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. * @see {@link https://api.jquery.com/replaceWith/#replaceWith-newContent} */ - replaceWith(newContent: JQuery | any[] | Element | Text | string): JQuery; + replaceWith(newContent: JQuery | any[] | Element | Text | string): this; /** * 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. * @see {@link https://api.jquery.com/replaceWith/#replaceWith-function} */ - replaceWith(func: () => Element | JQuery): JQuery; + replaceWith(func: () => Element | JQuery): this; /** * Get the combined text contents of each element in the set of matched elements, including their descendants. @@ -548,14 +552,14 @@ interface JQuery { * @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. * @see {@link https://api.jquery.com/text/#text-text} */ - text(text: string | number | boolean): JQuery; + text(text: string | number | boolean): this; /** * 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. * @see {@link https://api.jquery.com/text/#text-function} */ - text(func: (index: number, text: string) => string): JQuery; + text(func: (index: number, text: string) => string): this; /** * 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. @@ -564,14 +568,14 @@ interface JQuery { * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. * @see {@link https://api.jquery.com/toggleClass/#toggleClass-className} */ - toggleClass(className: string, swtch?: boolean): JQuery; + toggleClass(className: string, swtch?: boolean): this; /** * 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. * @see {@link https://api.jquery.com/toggleClass/#toggleClass-state} */ - toggleClass(swtch?: boolean): JQuery; + toggleClass(swtch?: boolean): this; /** * Execute all handlers attached to an element for an event. @@ -597,7 +601,7 @@ interface JQuery { * @param handler The function that is to be no longer executed. * @see {@link https://api.jquery.com/unbind/#unbind-eventType-handler} */ - unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): this; /** * Remove a previously-attached event handler from the elements. * @@ -605,14 +609,14 @@ interface JQuery { * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). * @see {@link https://api.jquery.com/unbind/#unbind-eventType-false} */ - unbind(eventType: string, fls: boolean): JQuery; + unbind(eventType: string, fls: boolean): this; /** * Remove a previously-attached event handler from the elements. * * @param evt A JavaScript event object as passed to an event handler. * @see {@link https://api.jquery.com/unbind/#unbind-event} */ - unbind(evt: any): JQuery; + unbind(evt: any): this; /** * Get the current value of the first element in the set of matched elements. @@ -625,14 +629,14 @@ interface JQuery { * @param value A string of text, an array of strings or number corresponding to the value of each matched element to set as selected/checked. * @see {@link https://api.jquery.com/val/#val-value} */ - val(value: string | string[] | number): JQuery; + val(value: string | string[] | number): this; /** * 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. * @see {@link https://api.jquery.com/val/#val-function} */ - val(func: (index: number, value: string) => string): JQuery; + val(func: (index: number, value: string) => string): this; /** * Wrap an HTML structure around each element in the set of matched elements. @@ -640,14 +644,14 @@ interface JQuery { * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. * @see {@link https://api.jquery.com/wrap/#wrap-wrappingElement} */ - wrap(wrappingElement: JQuery | Element | string): JQuery; + wrap(wrappingElement: JQuery | Element | string): this; /** * 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. * @see {@link https://api.jquery.com/wrap/#wrap-function} */ - wrap(func: (index: number) => string | JQuery): JQuery; + wrap(func: (index: number) => string | JQuery): this; // Undocumented length: number; @@ -661,13 +665,13 @@ interface JQuery { scope(): T; isolateScope(): T; - inheritedData(key: string, value: any): JQuery; - inheritedData(obj: { [key: string]: any; }): JQuery; + inheritedData(key: string, value: any): this; + inheritedData(obj: { [key: string]: any; }): this; inheritedData(key?: string): any; } interface JQueryStatic { - (element: string | Element | Document | JQuery | ArrayLike): JQuery; + (element: string | Element | Document | JQuery | ArrayLike): JQLite; } /** diff --git a/types/angular/test/jqlite-tests.ts b/types/angular/test/jqlite-tests.ts new file mode 100644 index 0000000000..11d46d6fe7 --- /dev/null +++ b/types/angular/test/jqlite-tests.ts @@ -0,0 +1,7 @@ +import * as angular from 'angular'; + +function JQLite() { + function indexSignature() { + angular.element('p')[0]; // $ExpectType HTMLElement + } +} diff --git a/types/angular/test/jquery3-merging-tests.ts b/types/angular/test/jquery3-merging-tests.ts index 0dbe37f640..510519466b 100644 --- a/types/angular/test/jquery3-merging-tests.ts +++ b/types/angular/test/jquery3-merging-tests.ts @@ -1,7 +1,11 @@ -import * as $ from 'jquery'; +import $ = require('jquery'); import * as angular from 'angular'; function JQuery() { + function indexSignature() { + $('p')[0]; // $ExpectType HTMLElement + } + function addClass() { // $ExpectType JQuery $('p').addClass('className'); @@ -82,11 +86,14 @@ function JQuery() { alt: 'jQuery Logo' }); - // $ExpectType string - $('img').attr('src'); + // @types/angular's definition wins here + // // $ExpectType string | undefined + // $('img').attr('src'); } function bind() { + interface I1 { kind: 'I1'; } + // $ExpectType JQuery $('p').bind('myEvent', 'myData', function(event) { // $ExpectType HTMLElement @@ -95,6 +102,14 @@ function JQuery() { event; }); + // $ExpectType JQuery + $('p').bind('myEvent', 'myData', function(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + }); + // $ExpectType JQuery $('p').bind('myEvent', function(event) { // $ExpectType HTMLElement @@ -103,16 +118,32 @@ function JQuery() { event; }); + // $ExpectType JQuery + $('p').bind('myEvent', function(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + }); + // $ExpectType JQuery $('p').bind('myEvent', false); // $ExpectType JQuery $('p').bind({ - myEvent1(event) { + myEvent1: false, + myEvent2(event) { // $ExpectType HTMLElement this; + // $ExpectType Event + event; }, - myEvent2: false + myEvent3(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + } }); // $ExpectType JQuery @@ -123,19 +154,35 @@ function JQuery() { } function children() { - $('p').children(); - + // $ExpectType JQuery $('p').children('span'); + + // $ExpectType JQuery + $('p').children(); } function off() { + function defaultContext_defaultData(this: HTMLElement, event: JQuery.Event) { } + + function defaultContext_customData(this: HTMLElement, event: JQuery.Event) { } + + function customContext_defaultData(this: I1, event: JQuery.Event) { } + + function customContext_customData(this: I1, event: JQuery.Event) { } + + interface I1 { kind: 'I1'; } + // $ExpectType JQuery - $('table').off('myEvent', 'td', function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event - event; - }); + $('table').off('myEvent', 'td', defaultContext_defaultData); + + // $ExpectType JQuery + $('table').off('myEvent', 'td', defaultContext_customData); + + // $ExpectType JQuery + $('table').off('myEvent', 'td', customContext_defaultData); + + // $ExpectType JQuery + $('table').off('myEvent', 'td', customContext_customData); // $ExpectType JQuery $('table').off('myEvent', 'td', false); @@ -144,12 +191,16 @@ function JQuery() { $('table').off('myEvent', 'td'); // $ExpectType JQuery - $('table').off('myEvent', function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event - event; - }); + $('table').off('myEvent', defaultContext_defaultData); + + // $ExpectType JQuery + $('table').off('myEvent', defaultContext_customData); + + // $ExpectType JQuery + $('table').off('myEvent', customContext_defaultData); + + // $ExpectType JQuery + $('table').off('myEvent', customContext_customData); // $ExpectType JQuery $('table').off('myEvent', false); @@ -159,24 +210,20 @@ function JQuery() { // $ExpectType JQuery $('table').off({ - myEvent1(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event - event; - }, - myEvent2: false + myEvent1: false, + defaultContext_defaultData, + defaultContext_customData, + customContext_defaultData, + customContext_customData }, 'td'); // $ExpectType JQuery $('table').off({ - myEvent1(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event - event; - }, - myEvent2: false + myEvent1: false, + defaultContext_defaultData, + defaultContext_customData, + customContext_defaultData, + customContext_customData }); // $ExpectType JQuery @@ -187,6 +234,8 @@ function JQuery() { } function on() { + interface I1 { kind: 'I1'; } + // $ExpectType JQuery $('table').on('myEvent', 'td', 'myData', function(event) { // $ExpectType HTMLElement @@ -195,6 +244,14 @@ function JQuery() { event; }); + // $ExpectType JQuery + $('table').on('myEvent', 'td', 'myData', function(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + }); + // $ExpectType JQuery $('table').on('myEvent', null, 'myData', function(event) { // $ExpectType HTMLElement @@ -203,6 +260,14 @@ function JQuery() { event; }); + // $ExpectType JQuery + $('table').on('myEvent', null, 'myData', function(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + }); + // $ExpectType JQuery $('table').on('myEvent', 'td', function(event) { // $ExpectType HTMLElement @@ -211,6 +276,14 @@ function JQuery() { event; }); + // $ExpectType JQuery + $('table').on('myEvent', 'td', function(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + }); + // $ExpectType JQuery $('table').on('myEvent', 'td', false); @@ -222,6 +295,14 @@ function JQuery() { event; }); + // $ExpectType JQuery + $('table').on('myEvent', 3, function(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + }); + // $ExpectType JQuery $('table').on('myEvent', function(event) { // $ExpectType HTMLElement @@ -230,66 +311,106 @@ function JQuery() { event; }); + // $ExpectType JQuery + $('table').on('myEvent', function(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + }); + // $ExpectType JQuery $('table').on('myEvent', false); // $ExpectType JQuery $('table').on({ - myEvent1(event) { + myEvent1: false, + myEvent2(event) { // $ExpectType HTMLElement this; // $ExpectType Event event; }, - myEvent2: false + myEvent3(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + } }, 'td', 'myData'); // $ExpectType JQuery $('table').on({ - myEvent1(event) { + myEvent1: false, + myEvent2(event) { // $ExpectType HTMLElement this; // $ExpectType Event event; }, - myEvent2: false + myEvent3(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + } }, null, 'myData'); // $ExpectType JQuery $('table').on({ - myEvent1(event) { + myEvent1: false, + myEvent2(event) { // $ExpectType HTMLElement this; // $ExpectType Event event; }, - myEvent2: false + myEvent3(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + } }, 'td'); // $ExpectType JQuery $('table').on({ - myEvent1(event) { + myEvent1: false, + myEvent2(event) { // $ExpectType HTMLElement this; // $ExpectType Event event; }, - myEvent2: false + myEvent3(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + } }, 3); // $ExpectType JQuery $('table').on({ - myEvent1(event) { + myEvent1: false, + myEvent2(event) { // $ExpectType HTMLElement this; // $ExpectType Event event; }, - myEvent2: false + myEvent3(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + } }); } function one() { + interface I1 { kind: 'I1'; } + // $ExpectType JQuery $('table').one('myEvent', 'td', 'myData', function(event) { // $ExpectType HTMLElement @@ -298,6 +419,14 @@ function JQuery() { event; }); + // $ExpectType JQuery + $('table').one('myEvent', 'td', 'myData', function(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + }); + // $ExpectType JQuery $('table').one('myEvent', null, 'myData', function(event) { // $ExpectType HTMLElement @@ -306,6 +435,14 @@ function JQuery() { event; }); + // $ExpectType JQuery + $('table').one('myEvent', null, 'myData', function(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + }); + // $ExpectType JQuery $('table').one('myEvent', 'td', function(event) { // $ExpectType HTMLElement @@ -314,6 +451,14 @@ function JQuery() { event; }); + // $ExpectType JQuery + $('table').one('myEvent', 'td', function(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + }); + // $ExpectType JQuery $('table').one('myEvent', 'td', false); @@ -325,6 +470,14 @@ function JQuery() { event; }); + // $ExpectType JQuery + $('table').one('myEvent', 3, function(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + }); + // $ExpectType JQuery $('table').one('myEvent', function(event) { // $ExpectType HTMLElement @@ -333,62 +486,100 @@ function JQuery() { event; }); + // $ExpectType JQuery + $('table').one('myEvent', function(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + }); + // $ExpectType JQuery $('table').one('myEvent', false); // $ExpectType JQuery $('table').one({ - myEvent1(event) { + myEvent1: false, + myEvent2(event) { // $ExpectType HTMLElement this; // $ExpectType Event event; }, - myEvent2: false + myEvent3(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + } }, 'td', 'myData'); // $ExpectType JQuery $('table').one({ - myEvent1(event) { + myEvent1: false, + myEvent2(event) { // $ExpectType HTMLElement this; // $ExpectType Event event; }, - myEvent2: false + myEvent3(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + } }, null, 'myData'); // $ExpectType JQuery $('table').one({ - myEvent1(event) { + myEvent1: false, + myEvent2(event) { // $ExpectType HTMLElement this; // $ExpectType Event event; }, - myEvent2: false + myEvent3(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + } }, 'td'); // $ExpectType JQuery $('table').one({ - myEvent1(event) { + myEvent1: false, + myEvent2(event) { // $ExpectType HTMLElement this; // $ExpectType Event event; }, - myEvent2: false + myEvent3(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + } }, 3); // $ExpectType JQuery $('table').one({ - myEvent1(event) { + myEvent1: false, + myEvent2(event) { // $ExpectType HTMLElement this; // $ExpectType Event event; }, - myEvent2: false + myEvent3(this: I1, event) { + // $ExpectType I1 + this; + // $ExpectType Event + event; + } }); } diff --git a/types/angular/tsconfig.json b/types/angular/tsconfig.json index 33c9531cab..f102aff22f 100644 --- a/types/angular/tsconfig.json +++ b/types/angular/tsconfig.json @@ -3,6 +3,7 @@ "index.d.ts", "jqlite.d.ts", "angular-tests.ts", + "test/jqlite-tests.ts", "test/jquery3-merging-tests.ts" ], "compilerOptions": { diff --git a/types/angular/tslint.json b/types/angular/tslint.json index 50c4474b7c..77b236700e 100644 --- a/types/angular/tslint.json +++ b/types/angular/tslint.json @@ -14,6 +14,8 @@ "max-line-length": false, "no-empty-interface": false, "no-namespace": false, + "no-unnecessary-qualifier": false, + "no-void-expression": false, "unified-signatures": false, "void-return": false } diff --git a/types/angularfire/index.d.ts b/types/angularfire/index.d.ts index e27cbf5721..de1482b0e3 100644 --- a/types/angularfire/index.d.ts +++ b/types/angularfire/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AngularFire 0.8.2 // Project: http://angularfire.com -// Definitions by: Dénes Harmath +// Definitions by: Dénes Harmath // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/angularlocalstorage/index.d.ts b/types/angularlocalstorage/index.d.ts index 67b84b925e..63a9731dd0 100644 --- a/types/angularlocalstorage/index.d.ts +++ b/types/angularlocalstorage/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AngularLocalStorage 0.1.7 // Project: https://github.com/agrublev/angularLocalStorage -// Definitions by: Horiuchi_H +// Definitions by: Horiuchi_H // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/animejs/animejs-tests.ts b/types/animejs/animejs-tests.ts new file mode 100644 index 0000000000..697c79f738 --- /dev/null +++ b/types/animejs/animejs-tests.ts @@ -0,0 +1,71 @@ +import * as anime from 'animejs'; + +const test1 = anime({ + targets: 'div', + duration: 40, + color: "#FFFFFF" +}); + +const callback = (anim: any) => { + console.log(anim.completed); +}; + +const test2 = anime({ + targets: 'div', + translateX: (el: HTMLElement, i: number, index: number) => { + return 0; + }, + translateY: '40px', + color: [ + {value: '#FF0000', duration: 2000}, + {value: '#00FF00', duration: 2000}, + {value: '#0000FF', duration: 2000}, + ], + duration: () => { + return 1000000000000; + }, + update: callback, + complete: callback +}); + +const someNodes = document.querySelector('button'); + +const test3 = anime({ + targets: someNodes, + top: "-5000000em" +}); + +const tl = anime.timeline({ + loop: false, + direction: 'normal' +}); + +tl.add({ + targets: ".tiny-divvy-div", + scale: 10000000 +}); + +const path = anime.path('#motionPath path'); + +test1.play(); +test2.reverse(); +test3.pause(); +tl.seek(4000); + +tl.finished.then(() => { + console.log("I wonder if anyone will ever actually read this."); +}); + +const usesEnums = anime({ + targets: ".usingEnumsIsAReallyHandyThing", + direction: "reverse", + easing: "inoutexpo", + someProperty: "+=4000" +}); + +const bezier = anime.bezier(0, 0, 100, 100); +// anime.speed = 100000000; +(anime as any).speed = 4000; +anime.easings['hello'] = anime.bezier(0, 0, 1900, 3020); +const runningAnims = anime.running; +anime.remove(".tiny-divvy-div"); diff --git a/types/animejs/index.d.ts b/types/animejs/index.d.ts new file mode 100644 index 0000000000..a975f59513 --- /dev/null +++ b/types/animejs/index.d.ts @@ -0,0 +1,137 @@ +// Type definitions for animejs 2.0 +// Project: http://animejs.com +// Definitions by: Andrew Babin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +type FunctionBasedParamter = (element: HTMLElement, index: number, length: number) => number; +type AnimeCallbackFunction = (anim: anime.AnimeInstance) => void; +// Allowing null is necessary because DOM queries may not return anything. +type AnimeTarget = string | object | HTMLElement | SVGElement | NodeList | null; + +declare namespace anime { + type EasingOptions = + | "linear" + | "easeInQuad" + | "easeInCubic" + | "easeInQuart" + | "easeInQuint" + | "easeInSine" + | "easeInExpo" + | "easeInCirc" + | "easeInBack" + | "easeInElastic" + | "easeOutQuad" + | "easeOutCubic" + | "easeOutQuart" + | "easeOutQuint" + | "easeOutSine" + | "easeOutExpo" + | "easeOutCirc" + | "easeOutBack" + | "easeOutElastic" + | "easeInOutQuad" + | "easeInOutCubic" + | "easeInOutQuart" + | "easeInOutQuint" + | "easeInOutSine" + | "easeInOutExpo" + | "easeInOutCirc" + | "easeInOutBack" + | "easeInOutElastic"; + type DirectionOptions = "reverse" | "alternate" | "normal"; + + interface AnimeInstanceParams { + loop?: number | boolean; + autoplay?: boolean; + direction?: DirectionOptions | string; + + begin?: AnimeCallbackFunction; + run?: AnimeCallbackFunction; + update?: AnimeCallbackFunction; + complete?: AnimeCallbackFunction; + } + + interface AnimeAnimParams { + targets: AnimeTarget | ReadonlyArray; + + duration?: number | FunctionBasedParamter; + delay?: number | FunctionBasedParamter; + elasticity?: number | FunctionBasedParamter; + round?: number | boolean | FunctionBasedParamter; + + easing?: EasingOptions | string | ReadonlyArray; + + begin?: AnimeCallbackFunction; + run?: AnimeCallbackFunction; + update?: AnimeCallbackFunction; + complete?: AnimeCallbackFunction; + [AnyAnimatedProperty: string]: any; + } + + interface AnimeParams extends AnimeInstanceParams, AnimeAnimParams { + // Just need this to merge both Params interfaces. + } + + interface AnimeInstance { + play(): void; + pause(): void; + restart(): void; + reverse(): void; + seek(time: number): void; + + began: boolean; + paused: boolean; + completed: boolean; + finished: Promise; + + begin: AnimeCallbackFunction; + run: AnimeCallbackFunction; + update: AnimeCallbackFunction; + complete: AnimeCallbackFunction; + + autoplay: boolean; + currentTime: number; + delay: number; + direction: string; + duration: number; + loop: number | boolean; + offset: number; + progress: number; + remaining: number; + reversed: boolean; + + animatables: ReadonlyArray; + animations: ReadonlyArray; + } + + interface AnimeTimelineAnimParams extends AnimeAnimParams { + offset: number | string | FunctionBasedParamter; + } + + interface AnimeTimelineInstance extends AnimeInstance { + add(params: AnimeAnimParams): AnimeTimelineInstance; + } + + // Helpers + const speed: number; + const running: AnimeInstance[]; + const easings: { [EasingFunction: string]: (t: number) => any }; + function remove(targets: AnimeTarget | ReadonlyArray): void; + function getValue(targets: AnimeTarget, prop: string): string | number; + function path(path: string | HTMLElement | SVGElement | null, percent?: number): (prop: string) => { + el: HTMLElement | SVGElement, + property: string, + totalLength: number + }; + function setDashoffset(el: HTMLElement | SVGElement | null): number; + function bezier(x1: number, y1: number, x2: number, y2: number): (t: number) => number; + // Timeline + function timeline(params?: AnimeInstanceParams | ReadonlyArray): AnimeTimelineInstance; + function random(min: number, max: number): number; +} + +declare function anime(params: anime.AnimeParams): anime.AnimeInstance; + +export = anime; +export as namespace anime; diff --git a/types/animejs/tsconfig.json b/types/animejs/tsconfig.json new file mode 100644 index 0000000000..506b75ade3 --- /dev/null +++ b/types/animejs/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "animejs-tests.ts" + ] +} diff --git a/types/animejs/tslint.json b/types/animejs/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/animejs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/annyang/annyang-tests.ts b/types/annyang/annyang-tests.ts new file mode 100644 index 0000000000..b394d20856 --- /dev/null +++ b/types/annyang/annyang-tests.ts @@ -0,0 +1,71 @@ +import { Annyang, CommandOption } from 'annyang'; + +declare const annyang: Annyang; +declare const console: any; + +// Tests based on API documentation at https://github.com/TalAter/annyang/blob/master/docs/README.md + +function testStartListening() { + annyang.start({ autoRestart: false }); // $ExpectType void + annyang.start({ autoRestart: false, continuous: false }); // $ExpectType void +} + +function testAddComments() { + const helloFunction = (): string => { + return 'hello'; + }; + + const commands: CommandOption = {'hello :name': helloFunction, howdy: helloFunction}; + const commands2: CommandOption = {hi: helloFunction}; + + annyang.addCommands(commands); // $ExpectType void + annyang.addCommands(commands2); // $ExpectType void + annyang.removeCommands(); // $ExpectType void + annyang.addCommands(commands); // $ExpectType void + annyang.removeCommands('hello'); // $ExpectType void + annyang.removeCommands(['howdy', 'hi']); // $ExpectType void +} + +const notConnected = () => { console.error('network connection error'); }; + +function testAddCallback() { + annyang.addCallback('error', () => console.error('There was an error!')); // $ExpectType void + + // $ExpectType void + annyang.addCallback('resultMatch', (userSaid, commandText, phrases) => { + console.log(userSaid); + console.log(commandText); + console.log(phrases); + }); + + annyang.addCallback('errorNetwork', notConnected, annyang); // $ExpectType void +} + +function testRemoveCallback() { + const start = () => { console.log('start'); }; + const end = () => { console.log('end'); }; + + annyang.addCallback('start', start); // $ExpectType void + annyang.addCallback('end', end); // $ExpectType void + + annyang.removeCallback(); // $ExpectType void + + annyang.removeCallback('end'); // $ExpectType void + + annyang.removeCallback('start', start); // $ExpectType void + + annyang.removeCallback(undefined, start); // $ExpectType void +} + +function testTrigger() { + annyang.trigger('Time for some thrilling heroics'); + + // $ExpectType void + annyang.trigger( + ['Time for some thrilling heroics', 'Time for some thrilling aerobics'] + ); +} + +function testIsListening() { + annyang.isListening(); // $ExpectType boolean +} diff --git a/types/annyang/index.d.ts b/types/annyang/index.d.ts new file mode 100644 index 0000000000..fee0cb9acb --- /dev/null +++ b/types/annyang/index.d.ts @@ -0,0 +1,230 @@ +// Type definitions for annyang 2.6 +// Project: https://www.talater.com/annyang/ +// Definitions by: Hisham Al-Shurafa +// Lukas Klinzing +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Options for function `start` + * + * @export + * @interface StartOptions + */ +export interface StartOptions { + /** + * Should annyang restart itself if it is closed indirectly, because of silence or window conflicts? + * + * @type {boolean} + */ + autoRestart?: boolean; + /** + * Allow forcing continuous mode on or off. Annyang is pretty smart about this, so only set this if you know what you're doing. + * + * @type {boolean} + */ + continuous?: boolean; +} + +/** + * A command option that supports custom regular expressions + * + * @export + * @interface CommandOptionRegex + */ +export interface CommandOptionRegex { + /** + * @type {RegExp} + */ + regexp: RegExp; + /** + * @type {() => any} + */ + callback(): void; +} + +/** + * Commands that annyang should listen to + * + * #### Examples: + * ````javascript + * {'hello :name': helloFunction, 'howdy': helloFunction}; + * {'hi': helloFunction}; + * ```` + * @export + * @interface CommandOption + */ +export interface CommandOption { + [command: string]: CommandOptionRegex | (() => void); +} + +/** + * Supported Events that will be triggered to listeners, you attach using `annyang.addCallback()` + * + * `start` - Fired as soon as the browser's Speech Recognition engine starts listening + * `error` - Fired when the browser's Speech Recogntion engine returns an error, this generic error callback will be followed by more accurate error callbacks (both will fire if both are defined) + * `errorNetwork` - Fired when Speech Recognition fails because of a network error + * `errorPermissionBlocked` - Fired when the browser blocks the permission request to use Speech Recognition. + * `errorPermissionDenied` - Fired when the user blocks the permission request to use Speech Recognition. + * `end` - Fired when the browser's Speech Recognition engine stops + * `result` - Fired as soon as some speech was identified. This generic callback will be followed by either the `resultMatch` or `resultNoMatch` callbacks. + * Callback functions registered to this event will include an array of possible phrases the user said as the first argument + * `resultMatch` - Fired when annyang was able to match between what the user said and a registered command + * Callback functions registered to this event will include three arguments in the following order: + * * The phrase the user said that matched a command + * * The command that was matched + * * An array of possible alternative phrases the user might've said + * `resultNoMatch` - Fired when what the user said didn't match any of the registered commands. + * Callback functions registered to this event will include an array of possible phrases the user might've said as the first argument + */ +export type Events = + 'start' | + 'soundstart' | + 'error' | + 'end' | + 'result' | + 'resultMatch' | + 'resultNoMatch' | + 'errorNetwork' | + 'errorPermissionBlocked' | + 'errorPermissionDenied'; + +export interface Annyang { + /** + * Start listening. + * It's a good idea to call this after adding some commands first, but not mandatory. + * + * @param {StartOptions} options + */ + start(options?: StartOptions): void; + + /** + * Stop listening, and turn off mic. + * + */ + abort(): void; + + /** + * Pause listening. annyang will stop responding to commands (until the resume or start methods are called), without turning off the browser's SpeechRecognition engine or the mic. + * + */ + pause(): void; + + /** + * Resumes listening and restores command callback execution when a result matches. + * If SpeechRecognition was aborted (stopped), start it. + * + */ + resume(): void; + + /** + * Turn on output of debug messages to the console. Ugly, but super-handy! + * + * @export + * @param {boolean} [newState=true] Turn on/off debug messages + */ + debug(newState?: boolean): void; + + /** + * Set the language the user will speak in. If this method is not called, defaults to 'en-US'. + * + * @param {string} lang + * @see [Languages](https://github.com/TalAter/annyang/blob/master/docs/FAQ.md#what-languages-are-supported) + */ + setLanguage(lang: string): void; + + /** + * Add commands that annyang will respond to. Similar in syntax to init(), but doesn't remove existing commands. + * + * #### Examples: + * ````javascript + * var commands = {'hello :name': helloFunction, 'howdy': helloFunction}; + * var commands2 = {'hi': helloFunction}; + * + * annyang.addCommands(commands); + * annyang.addCommands(commands2); + * // annyang will now listen to all three commands + * ```` + * + * @param {CommandOption} commands + */ + addCommands(commands: CommandOption): void; + + /** + * Removes all existing commands or a specific command + * #### Examples: + * ````javascript + * var commands : annyang.CommandOption = {'hello': helloFunction, 'howdy': helloFunction, 'hi': helloFunction}; + * + * // Don't respond to hello + * annyang.removeCommands('hello'); + * + * // Remove all existing commands + * annyang.removeCommands(); + * ```` + * @param {string} command + */ + removeCommands(command?: string): void; + + /** + * Removes a list of commands + * #### Examples: + * ````javascript + * var commands : annyang.CommandOption = {'hello': helloFunction, 'howdy': helloFunction, 'hi': helloFunction}; + * // Add some commands + * annyang.addCommands(commands); + * // Don't respond to howdy or hi + * annyang.removeCommands(['howdy', 'hi']); + * ```` + * + * @param {string[]} command + */ + removeCommands(command: string[]): void; + + /** + * @param {Events} event + * @param {(userSaid : string, commandText : string, results : string[]) => void} callback + * @param {*} [context] + */ + addCallback(event: Events, callback: (userSaid?: string, commandText?: string, results?: string[]) => void, context?: any): void; + + /** + * @param {Events} [event] + * @param {Function} [callback] + */ + removeCallback(event?: Events, callback?: (userSaid: string, commandText: string, results: string[]) => void): void; + + /** + * Returns true if speech recognition is currently on. + * Returns false if speech recognition is off or annyang is paused. + * + * @returns {boolean} + */ + isListening(): boolean; + + /** + * Returns the instance of the browser's SpeechRecognition object used by annyang. + * Useful in case you want direct access to the browser's Speech Recognition engine. + * + * @returns {*} + */ + getSpeechRecognizer(): any; + + /** + * Simulate speech being recognized. This will trigger the same events and behavior as when the Speech Recognition + * detects speech. + * + * Can accept either a string containing a single sentence, or an array containing multiple sentences to be checked + * in order until one of them matches a command (similar to the way Speech Recognition Alternatives are parsed) + * + * #### Examples: + * ````javascript + * annyang.trigger('Time for some thrilling heroics'); + * annyang.trigger( + * ['Time for some thrilling heroics', 'Time for some thrilling aerobics'] + * ); + * ```` + * + * @param {string} command + */ + trigger(command: string | string[]): void; +} diff --git a/types/annyang/tsconfig.json b/types/annyang/tsconfig.json new file mode 100644 index 0000000000..f54c7cd18c --- /dev/null +++ b/types/annyang/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "annyang-tests.ts" + ] +} diff --git a/types/annyang/tslint.json b/types/annyang/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/annyang/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/anymatch/anymatch-tests.ts b/types/anymatch/anymatch-tests.ts new file mode 100644 index 0000000000..3333903760 --- /dev/null +++ b/types/anymatch/anymatch-tests.ts @@ -0,0 +1,43 @@ +import anymatch = require('anymatch'); + +const matchers = [ + 'path/to/file.js', + 'path/anyjs/**/*.js', + /foo\.js$/, + (str: string) => str.indexOf('bar') !== -1 && str.length > 10 +]; + +// $ExpectType boolean +anymatch(matchers, 'path/to/file.js'); +// $ExpectType boolean +anymatch(matchers, 'path/to/file.js', false); +// $ExpectType boolean +anymatch(matchers, 'path/to/file.js', false, 1); +// $ExpectType boolean +anymatch(matchers, 'path/to/file.js', false, 1, 2); + +// $ExpectType number +anymatch(matchers, 'foo.js', true); +// $ExpectType number +anymatch(matchers, 'path/anyjs/foo.js', true, 2); +// $ExpectType number +anymatch(matchers, 'path/anyjs/foo.js', true, 2, 3); + +const matcher = anymatch(matchers); +// $ExpectType boolean +matcher('path/to/file.js'); +// $ExpectType boolean +matcher('path/to/file.js', false); +// $ExpectType boolean +matcher('path/to/file.js', false, 1); +// $ExpectType boolean +matcher('path/to/file.js', false, 1, 2); +// $ExpectType number +matcher('path/anyjs/baz.js', true); +// $ExpectType number +matcher('path/anyjs/baz.js', true, 2); +// $ExpectType number +matcher('path/anyjs/baz.js', true, 2, 3); + +// tslint:disable-next-line no-unnecessary-callback-wrapper +['foo.js', 'bar.js'].filter(str => matcher(str)); diff --git a/types/anymatch/index.d.ts b/types/anymatch/index.d.ts new file mode 100644 index 0000000000..4eb90734a4 --- /dev/null +++ b/types/anymatch/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for anymatch 1.3 +// Project: https://github.com/es128/anymatch +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = anymatch; + +declare function anymatch(matcher: anymatch.Matcher): CurrriedMatcher; +declare function anymatch(matcher: anymatch.Matcher, testString: string | string[], returnIndex: true, startIndex?: number, endIndex?: number): number; +declare function anymatch(matcher: anymatch.Matcher, testString: string | string[], returnIndex?: boolean, startIndex?: number, endIndex?: number): boolean; + +declare namespace anymatch { + type Matcher = MatcherType | MatcherType[]; + type MatcherType = string | RegExp | ((...testStrings: string[]) => boolean); +} + +interface CurrriedMatcher { + (testString: string | string[], returnIndex: true, startIndex?: number, endIndex?: number): number; + (testString: string | string[], returnIndex?: boolean, startIndex?: number, endIndex?: number): boolean; +} diff --git a/types/anymatch/tsconfig.json b/types/anymatch/tsconfig.json new file mode 100644 index 0000000000..e4fad1c219 --- /dev/null +++ b/types/anymatch/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "anymatch-tests.ts" + ] +} diff --git a/types/anymatch/tslint.json b/types/anymatch/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/anymatch/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/apn/apn-tests.ts b/types/apn/apn-tests.ts deleted file mode 100644 index ea4bb34ae3..0000000000 --- a/types/apn/apn-tests.ts +++ /dev/null @@ -1,145 +0,0 @@ -import apn = require("apn"); - -//Hand made TypeScript tests -//========================== - -//Create with a hex string -var device1 = new apn.Device("ca11ab1e"); -//Create with a Buffer -var device2 = new apn.Device(new Buffer("ca55e77e")); - -//Create the notification -var notification = new apn.Notification(); -notification.alert = { - title: "The Title", - body: "This is the body", -}; -notification.badge = 5; -//Fluid api -notification.setAlertTitle("The Title") - .setAlertText("This is the body") - .setLaunchImage("LaunchImage"); - -//Establish the connection -var connection = new apn.Connection({ - cert: "path/to/cert.pem", - key: "path/to/cert.pem" -}); -//Testing some specialized event listeners -connection.on("error", (error) => { - console.log("push error", error.name, error.message); -}); -connection.on("transmissionError", (errorCode, notification, device) => { - console.log("push failed", errorCode, "notification", notification.alert, "device id: ", device.toString()); -}); - -//Send it using hex string -connection.pushNotification(notification, "ba5eba11"); -//Send it using Buffer -connection.pushNotification(notification, new Buffer("5ca1ab1e")); -//Send it using Device -connection.pushNotification(notification, device1); - -//Connecting to feedback service -var feedbackService = new apn.Feedback({ - cert: "path/to/cert.pem", - key: "path/to/cert.pem", - interval: 0 -}); -feedbackService.on("error", (error:Error) => { - console.log("push feedback error", error.name, error.message); -}); -function processFeedbackData(device:apn.Device, time:number) { -} -feedbackService.on("feedback", (feedbackData) => { - feedbackData.forEach((data) => { - processFeedbackData(data.device, data.time); - }) -}); -feedbackService.start(); - - -//Original examples from apn package -//================================== - -//sending-to-multiple-devices.js -//------------------------------ - -var tokens = ["", ""]; - -if(tokens[0] === "") { - console.log("Please set token to a valid device token for the push notification service"); - process.exit(); -} - -// Create a connection to the service using mostly default parameters. - -var service = new apn.connection({ production: false }); - -service.on("connected", function() { - console.log("Connected"); -}); - -service.on("transmitted", function(notification, device) { - console.log("Notification transmitted to:" + device.token.toString("hex")); -}); - -service.on("transmissionError", function(errCode, notification, device) { - console.error("Notification caused error: " + errCode + " for device ", device, notification); - if (errCode === 8) { - console.log("A error code of 8 indicates that the device token is invalid. This could be for a number of reasons - are you using the correct environment? i.e. Production vs. Sandbox"); - } -}); - -service.on("timeout", function () { - console.log("Connection Timeout"); -}); - -service.on("disconnected", function() { - console.log("Disconnected from APNS"); -}); - -service.on("socketError", console.error); - - -// If you plan on sending identical paylods to many devices you can do something like this. -function pushNotificationToMany() { - console.log("Sending the same notification each of the devices with one call to pushNotification."); - var note = new apn.notification(); - note.setAlertText("Hello, from node-apn!"); - note.badge = 1; - - service.pushNotification(note, tokens); -} - -pushNotificationToMany(); - - -// If you have a list of devices for which you want to send a customised notification you can create one and send it to and individual device. -function pushSomeNotifications() { - console.log("Sending a tailored notification to %d devices", tokens.length); - tokens.forEach(function(token, i) { - var note = new apn.notification(); - note.setAlertText("Hello, from node-apn! You are number: " + i); - note.badge = i; - - service.pushNotification(note, token); - }); -} - -pushSomeNotifications(); - -//feedback.js -//----------- - -function handleFeedback(feedbackData:apn.FeedbackData[]) { - feedbackData.forEach(function(feedbackItem) { - console.log("Device: " + feedbackItem.device.toString() + " has been unreachable, since: " + feedbackItem.time); - }); -} - -// Setup a connection to the feedback service using a custom interval (10 seconds) -var feedback = new apn.feedback({ production: false, interval: 10 }); - -feedback.on("feedback", handleFeedback); -feedback.on("feedbackError", console.error); diff --git a/types/apn/index.d.ts b/types/apn/index.d.ts deleted file mode 100644 index 96ce6e9720..0000000000 --- a/types/apn/index.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 - -/// - -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; - subtitle?: 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/types/apn/tsconfig.json b/types/apn/tsconfig.json deleted file mode 100644 index a6d716d8fe..0000000000 --- a/types/apn/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "apn-tests.ts" - ] -} \ No newline at end of file diff --git a/types/applepayjs/applepayjs-tests.ts b/types/applepayjs/applepayjs-tests.ts index 5adf61e45c..505dbd2daf 100644 --- a/types/applepayjs/applepayjs-tests.ts +++ b/types/applepayjs/applepayjs-tests.ts @@ -6,7 +6,7 @@ declare function it(desc: string, fn: () => void): void; describe("ApplePaySession", () => { it("the constants are defined", () => { - let status = 0; + const status = 0; switch (status) { case ApplePaySession.STATUS_FAILURE: case ApplePaySession.STATUS_INVALID_BILLING_POSTAL_ADDRESS: @@ -43,8 +43,8 @@ describe("ApplePaySession", () => { it("can call static methods", () => { const merchantIdentifier = "MyMerchantId"; - let canMakePayments: boolean = ApplePaySession.canMakePayments(); - let supported: boolean = ApplePaySession.supportsVersion(2); + const canMakePayments: boolean = ApplePaySession.canMakePayments(); + const supported: boolean = ApplePaySession.supportsVersion(2); ApplePaySession.canMakePaymentsWithActiveCard(merchantIdentifier) .then((status: boolean) => { @@ -168,7 +168,7 @@ describe("ApplePaySession", () => { }); describe("ApplePayPaymentRequest", () => { it("can create a new instance", () => { - let paymentRequest: ApplePayJS.ApplePayPaymentRequest = { + const paymentRequest: ApplePayJS.ApplePayPaymentRequest = { applicationData: "ApplicationData", countryCode: "GB", currencyCode: "GBP", @@ -181,8 +181,8 @@ describe("ApplePayPaymentRequest", () => { "amex", "discover", "jcb", - "master​Card", - "private​Label", + "masterCard", + "privateLabel", "visa" ], total: { diff --git a/types/applepayjs/index.d.ts b/types/applepayjs/index.d.ts index 34d3c41a99..f705a4fad2 100644 --- a/types/applepayjs/index.d.ts +++ b/types/applepayjs/index.d.ts @@ -10,7 +10,7 @@ declare class ApplePaySession extends EventTarget { /** * Creates a new instance of the ApplePaySession class. * @param version - The version of the ApplePay JS API you are using. - * @param paymentRequest - An Apple​Pay​Payment​Request object that contains the information that is displayed on the Apple Pay payment sheet. + * @param paymentRequest - An ApplePayPaymentRequest object that contains the information that is displayed on the Apple Pay payment sheet. */ constructor(version: number, paymentRequest: ApplePayJS.ApplePayPaymentRequest); @@ -95,8 +95,8 @@ declare class ApplePaySession extends EventTarget { /** * Call after a payment method has been selected. - * @param newTotal - An Apple​Pay​Line​Item dictionary representing the total price for the purchase. - * @param newLineItems - A sequence of Apple​Pay​Line​Item dictionaries. + * @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase. + * @param newLineItems - A sequence of ApplePayLineItem dictionaries. */ completePaymentMethodSelection(newTotal: ApplePayJS.ApplePayLineItem, newLineItems: ApplePayJS.ApplePayLineItem[]): void; @@ -104,8 +104,8 @@ declare class ApplePaySession extends EventTarget { * Call after a shipping contact has been selected. * @param status - The status of the shipping contact update. * @param newShippingMethods - A sequence of ApplePayShippingMethod dictionaries. - * @param newTotal - An Apple​Pay​Line​Item dictionary representing the total price for the purchase. - * @param newLineItems - A sequence of Apple​Pay​Line​Item dictionaries. + * @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase. + * @param newLineItems - A sequence of ApplePayLineItem dictionaries. */ completeShippingContactSelection( status: number, @@ -116,8 +116,8 @@ declare class ApplePaySession extends EventTarget { /** * Call after the shipping method has been selected. * @param status - The status of the shipping method update. - * @param newTotal - An Apple​Pay​Line​Item dictionary representing the total price for the purchase. - * @param newLineItems - A sequence of Apple​Pay​Line​Item dictionaries. + * @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase. + * @param newLineItems - A sequence of ApplePayLineItem dictionaries. */ completeShippingMethodSelection(status: number, newTotal: ApplePayJS.ApplePayLineItem, newLineItems: ApplePayJS.ApplePayLineItem[]): void; @@ -204,7 +204,7 @@ declare namespace ApplePayJS { } /** - * The Apple​Pay​Payment​Authorized​Event class defines the attributes contained by the ApplePaySession.onpaymentauthorized callback function. + * The ApplePayPaymentAuthorizedEvent class defines the attributes contained by the ApplePaySession.onpaymentauthorized callback function. */ abstract class ApplePayPaymentAuthorizedEvent extends Event { /** @@ -279,7 +279,7 @@ declare namespace ApplePayJS { /** * A string, suitable for display, that is the name of the payment network backing the card. - * The value is one of the supported networks specified in the supported​Networks property of the Apple​Pay​Payment​Request. + * The value is one of the supported networks specified in the supportedNetworks property of the ApplePayPaymentRequest. */ network: string; @@ -295,7 +295,7 @@ declare namespace ApplePayJS { } /** - * The Apple​Pay​Payment​Method​Selected​Event class defines the attributes contained by the ApplePaySession.onpaymentmethodselected callback function. + * The ApplePayPaymentMethodSelectedEvent class defines the attributes contained by the ApplePaySession.onpaymentmethodselected callback function. */ abstract class ApplePayPaymentMethodSelectedEvent extends Event { /** @@ -426,7 +426,7 @@ declare namespace ApplePayJS { } /** - * The Apple​Pay​Shipping​Contact​Selected​Event class defines the attributes contained by the ApplePaySession.onshippingcontactselected callback function. + * The ApplePayShippingContactSelectedEvent class defines the attributes contained by the ApplePaySession.onshippingcontactselected callback function. */ abstract class ApplePayShippingContactSelectedEvent extends Event { /** @@ -461,7 +461,7 @@ declare namespace ApplePayJS { } /** - * The Apple​Pay​Shipping​Method​Selected​Event class defines the attribute contained by the ApplePaySession.onshippingmethodselected callback function. + * The ApplePayShippingMethodSelectedEvent class defines the attribute contained by the ApplePaySession.onshippingmethodselected callback function. */ abstract class ApplePayShippingMethodSelectedEvent extends Event { /** @@ -471,7 +471,7 @@ declare namespace ApplePayJS { } /** - * The Apple​Pay​Validate​Merchant​Event class defines the attributes contained by the ApplePaySession.onvalidatemerchant callback function. + * The ApplePayValidateMerchantEvent class defines the attributes contained by the ApplePaySession.onvalidatemerchant callback function. */ abstract class ApplePayValidateMerchantEvent extends Event { /** diff --git a/types/applepayjs/tslint.json b/types/applepayjs/tslint.json index 3db14f85ea..65c83fb1e3 100644 --- a/types/applepayjs/tslint.json +++ b/types/applepayjs/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "dt-header": false + } +} diff --git a/types/applicationinsights-js/applicationinsights-js-tests.ts b/types/applicationinsights-js/applicationinsights-js-tests.ts index ecefb6d41a..49c68181f8 100644 --- a/types/applicationinsights-js/applicationinsights-js-tests.ts +++ b/types/applicationinsights-js/applicationinsights-js-tests.ts @@ -123,7 +123,7 @@ context.addTelemetryInitializer(envelope => { }); // a sample from: https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#example context.addTelemetryInitializer(envelope => { - let telemetryItem = envelope.data.baseData; + const telemetryItem = envelope.data.baseData; if (envelope.name === Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType) { telemetryItem.url = "URL CENSORED"; } diff --git a/types/applicationinsights-js/tslint.json b/types/applicationinsights-js/tslint.json index 0cc2f62b56..4b24c7ab0a 100644 --- a/types/applicationinsights-js/tslint.json +++ b/types/applicationinsights-js/tslint.json @@ -1,8 +1,11 @@ { "extends": "dtslint/dt.json", "rules": { - "interface-name": [ false ], + // All are TODOs + "interface-name": false, "no-internal-module": false, - "no-single-declare-module": false + "no-mergeable-namespace": false, + "no-single-declare-module": false, + "no-unnecessary-qualifier": false } } diff --git a/types/applicationinsights/index.d.ts b/types/applicationinsights/index.d.ts index 45c89556a6..471089a96f 100644 --- a/types/applicationinsights/index.d.ts +++ b/types/applicationinsights/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Application Insights v0.15.12 // Project: https://github.com/Microsoft/ApplicationInsights-node.js -// Definitions by: Scott Southwood +// Definitions by: Scott Southwood // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface AutoCollectConsole { @@ -341,9 +341,9 @@ interface Client { trackMetric(name: string, value: number, count?:number, min?: number, max?: number, stdDev?: number, properties?: { [key: string]: string; }): void; - + /** - * Log an incoming http request to your server. The request data will be tracked during the response "finish" event if it is successful or the request "error" + * Log an incoming http request to your server. The request data will be tracked during the response "finish" event if it is successful or the request "error" * event if it fails. The request duration is automatically calculated as the timespan between when the trackRequest method was called, and when the response "finish" * or request "error" events were fired. * @param request The http.IncomingMessage object to track @@ -353,7 +353,7 @@ interface Client { trackRequest(request: any /* http.IncomingMessage */, response: any /* http.ServerResponse */, properties?: { [key: string]: string; }): void; - + /** * Log an incoming http request to your server. The request data is tracked synchronously rather than waiting for the response "finish"" or request "error"" events. * Use this if you need your request telemetry to respect custom app insights operation and user context (for example if you set any appInsights.client.context.tags). @@ -365,7 +365,7 @@ interface Client { */ trackRequestSync(request: any /*http.IncomingMessage */, response: any /*http.ServerResponse */, ellapsedMilliseconds?: number, properties?: { [key: string]: string;}, error?: any) : void; - + /** * Log information about a dependency of your app. Typically used to track the time database calls or outgoing http requests take from your server. * @param name The name of the dependency (i.e. "myDatabse") diff --git a/types/archiver/archiver-tests.ts b/types/archiver/archiver-tests.ts index d4ea423a4f..bbbc7c7abf 100644 --- a/types/archiver/archiver-tests.ts +++ b/types/archiver/archiver-tests.ts @@ -1,6 +1,26 @@ import * as Archiver from 'archiver'; import * as fs from 'fs'; +const options: Archiver.ArchiverOptions = { + statConcurrency: 1, + allowHalfOpen: true, + readableObjectMode: true, + writeableObjectMode: true, + decodeStrings: true, + encoding: 'test', + highWaterMark: 1, + objectmode: true, + comment: 'test', + forceLocalTime: true, + forceZip64: true, + store: true, + zlib: {}, + gzip: true, + gzipOptions: {}, +}; + +Archiver('zip', options); + const archiver = Archiver.create('zip'); const writeStream = fs.createWriteStream('./archiver.d.ts'); @@ -14,8 +34,6 @@ archiver.append(readStream, { name: 'archiver.d.ts' }); archiver.append(readStream, {name: 'archiver.d.ts'}) .append(readStream, {name: 'archiver.d.ts'}); -archiver.bulk({ mappaing: {} }); - archiver.directory('./path', './someOtherPath'); archiver.directory('./path', { name: "testName" }); archiver.directory('./', "", {}); @@ -38,4 +56,6 @@ archiver.setModule(() => {}); archiver.pointer(); archiver.use(() => {}); -archiver.finalize(); +archiver.finalize().then(); + +archiver.symlink('./path', './target'); diff --git a/types/archiver/index.d.ts b/types/archiver/index.d.ts index 0dc91ec554..a8c7de0502 100644 --- a/types/archiver/index.d.ts +++ b/types/archiver/index.d.ts @@ -1,22 +1,11 @@ -// Type definitions for archiver 1.3 +// Type definitions for archiver 2.0 // Project: https://github.com/archiverjs/node-archiver -// Definitions by: Esri , Dolan Miu +// Definitions by: Esri , Dolan Miu , Crevil // 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 stream from 'stream'; import * as glob from 'glob'; +import { ZlibOptions } from 'zlib'; declare function archiver(format: archiver.Format, options?: archiver.ArchiverOptions): archiver.Archiver; @@ -36,27 +25,48 @@ declare namespace archiver { abort(): this; append(source: stream.Readable | Buffer | string, name?: EntryData): this; - bulk(mappings: any): this; - directory(dirpath: string, options: EntryData | string, data?: EntryData): this; file(filename: string, data: EntryData): this; glob(pattern: string, options?: glob.IOptions, data?: EntryData): this; - finalize(): this; + finalize(): Promise; setFormat(format: string): this; setModule(module: Function): this; pointer(): number; use(plugin: Function): this; + + symlink(filepath: string, target: string): this; } - interface ArchiverOptions { + type ArchiverOptions = CoreOptions & TransformOptions & ZipOptions & TarOptions; + + interface CoreOptions { + statConcurrency?: number; + } + + interface TransformOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writeableObjectMode?: boolean; + decodeStrings?: boolean; + encoding?: string; + highWaterMark?: number; + objectmode?: boolean; + } + + interface ZipOptions { + comment?: string; + forceLocalTime?: boolean; + forceZip64?: boolean; store?: boolean; + zlib?: ZlibOptions; + } + + interface TarOptions { gzip?: boolean; - gzipOptions?: { - level: number, - }; + gzipOptions?: ZlibOptions; } } diff --git a/types/archiver/tslint.json b/types/archiver/tslint.json index a62d0d4e68..10e16aef18 100644 --- a/types/archiver/tslint.json +++ b/types/archiver/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { - "ban-types": false + // TODOs + "ban-types": false, + "dt-header": false } } diff --git a/types/archy/index.d.ts b/types/archy/index.d.ts index 82b101236c..6dedf21db2 100644 --- a/types/archy/index.d.ts +++ b/types/archy/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for archy // Project: https://github.com/substack/node-archy -// Definitions by: vvakame +// Definitions by: vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/are-we-there-yet/are-we-there-yet-tests.ts b/types/are-we-there-yet/are-we-there-yet-tests.ts index 1750cac0c2..463ca428c4 100644 --- a/types/are-we-there-yet/are-we-there-yet-tests.ts +++ b/types/are-we-there-yet/are-we-there-yet-tests.ts @@ -1,6 +1,6 @@ import { Tracker, TrackerStream, TrackerGroup } from "are-we-there-yet"; -let simple = new Tracker("simple"); +const simple = new Tracker("simple"); simple.addListener("change", (name, completed, tracker) => { console.log(`name: ${name}, completed: ${completed}`); }); @@ -8,13 +8,13 @@ simple.addWork(10); simple.completeWork(1); console.log(simple.completed() < 1); -let group = new TrackerGroup("group"); +const group = new TrackerGroup("group"); group.addUnit(simple); -let subgroup = group.newGroup("subgroup"); +const subgroup = group.newGroup("subgroup"); console.log(group.completed()); -let stream = new TrackerStream("stream", 100, { encoding: "utf8" }); +const stream = new TrackerStream("stream", 100, { encoding: "utf8" }); subgroup.addUnit(stream); stream.addListener("change", (name, completed, tracker) => { diff --git a/types/argparse/argparse-tests.ts b/types/argparse/argparse-tests.ts index cec1ece95b..f5b9e76f81 100644 --- a/types/argparse/argparse-tests.ts +++ b/types/argparse/argparse-tests.ts @@ -1,7 +1,7 @@ // near copy of each of the tests from https://github.com/nodeca/argparse/tree/master/examples -import {ArgumentParser, RawDescriptionHelpFormatter} from 'argparse'; +import { ArgumentParser, RawDescriptionHelpFormatter } from 'argparse'; var args: any; var simpleExample = new ArgumentParser({ diff --git a/types/argparse/index.d.ts b/types/argparse/index.d.ts index 845d5d8fd3..2661b01c12 100644 --- a/types/argparse/index.d.ts +++ b/types/argparse/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for argparse v1.0.3 // Project: https://github.com/nodeca/argparse -// Definitions by: Andrew Schurman +// Definitions by: Andrew Schurman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/arrify/arrify-tests.ts b/types/arrify/arrify-tests.ts new file mode 100644 index 0000000000..319e86897a --- /dev/null +++ b/types/arrify/arrify-tests.ts @@ -0,0 +1,14 @@ +import arrify = require("arrify"); + +arrify(null); +arrify(null); + +arrify(undefined); +arrify(undefined); + +arrify(1); +arrify([2, 3]); + +function test(val?: string | string[]) { + arrify(val); +} diff --git a/types/arrify/index.d.ts b/types/arrify/index.d.ts new file mode 100644 index 0000000000..896ee23224 --- /dev/null +++ b/types/arrify/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for arrify 1.0 +// Project: https://github.com/sindresorhus/arrify +// Definitions by: AnJun Wang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * @example + * arrify(undefined) // returns [] + * @example + * arrify(null) // returns [] + * @example + * arrify(1) // returns [1] + * @example + * arrify([2, 3]) // returns [2, 3] + * @param val + */ +declare function arrify(val: undefined | null | T | T[]): T[]; +export = arrify; diff --git a/types/arrify/tsconfig.json b/types/arrify/tsconfig.json new file mode 100644 index 0000000000..e0ac439953 --- /dev/null +++ b/types/arrify/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "arrify-tests.ts" + ] +} diff --git a/types/arrify/tslint.json b/types/arrify/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/arrify/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ascii2mathml/ascii2mathml-tests.ts b/types/ascii2mathml/ascii2mathml-tests.ts new file mode 100644 index 0000000000..7280900922 --- /dev/null +++ b/types/ascii2mathml/ascii2mathml-tests.ts @@ -0,0 +1,17 @@ +import * as ascii2mathml from 'ascii2mathml'; + +const fn = ascii2mathml({}); // $ExpectType any +fn(''); // $ExpectType string +ascii2mathml('', {}); // $ExpectType string + +// $ExpectType string +ascii2mathml('', { + decimalMark: '.', + colSep: ',', + rowSep: ';', + display: 'inline', + dir: 'ltr', + bare: false, + standalone: false, + annotate: false +}); diff --git a/types/ascii2mathml/index.d.ts b/types/ascii2mathml/index.d.ts new file mode 100644 index 0000000000..2b02dfea15 --- /dev/null +++ b/types/ascii2mathml/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for ascii2mathml 0.5 +// Project: https://github.com/runarberg/ascii2mathml +// Definitions by: Muhammad Ragib Hasin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = A2MML; + +declare var A2MML: ascii2mathml; + +interface Options { + decimalMark?: string; + colSep?: string; + rowSep?: string; + display?: 'inline' | 'block'; + dir?: 'ltr' | 'rtl'; + bare?: boolean; + standalone?: boolean; + annotate?: boolean; +} + +interface ascii2mathml { + /** + * Generates a function with default options set to convert + * ASCIIMath expression to MathML markup. + * @param options Options + */ + (options: Options): ascii2mathml; + + /** + * Converts ASCIIMath expression to MathML markup. + * @param asciimath {string} ASCIIMath expression + * @param options Options + */ + (asciimath: string, options?: Options): string; +} diff --git a/types/ascii2mathml/tsconfig.json b/types/ascii2mathml/tsconfig.json new file mode 100644 index 0000000000..22e7823b58 --- /dev/null +++ b/types/ascii2mathml/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ascii2mathml-tests.ts" + ] +} diff --git a/types/ascii2mathml/tslint.json b/types/ascii2mathml/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ascii2mathml/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/asenv/asenv-tests.ts b/types/asenv/asenv-tests.ts new file mode 100644 index 0000000000..0448672d10 --- /dev/null +++ b/types/asenv/asenv-tests.ts @@ -0,0 +1,26 @@ +import { unlessProduction, isDevelopment, isTest, isProduction, getEnv, setEnv } from 'asenv'; +import { equal, throws } from 'assert'; + +// Test isDevelopment() +setEnv('development'); +equal(getEnv(), 'development', 'Should return be true'); +equal(isDevelopment(), true, 'NODE_ENV should be "development"'); +equal(isTest(), false, 'NODE_ENV should be "development"'); +equal(isProduction(), false, 'NODE_ENV should be "development"'); +equal(unlessProduction(() => true), true, "Shound return true"); + +// Test isTest() +setEnv('test'); +equal(getEnv(), 'test', 'Should return be true'); +equal(isDevelopment(), false, 'NODE_ENV should be "test"'); +equal(isTest(), true, 'NODE_ENV should be "test"'); +equal(isProduction(), false, 'NODE_ENV should be "test"'); +equal(unlessProduction(() => true), true, "Shound return true"); + +// Test isProduction() +setEnv('production'); +equal(getEnv(), 'production', 'Should return be true'); +equal(isDevelopment(), false, 'NODE_ENV should be "production"'); +equal(isTest(), false, 'NODE_ENV should be "production"'); +equal(isProduction(), true, 'NODE_ENV should be "production"'); +equal(unlessProduction(() => true), false, "Shound return false"); diff --git a/types/asenv/index.d.ts b/types/asenv/index.d.ts new file mode 100644 index 0000000000..f127664d13 --- /dev/null +++ b/types/asenv/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for asenv 1.1 +// Project: https://github.com/a-labo/asenv#readme +// Definitions by: Remisery +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export function getEnv(): string; + +export function isDevelopment(): boolean; + +export function isProduction(): boolean; + +export function isTest(): boolean; + +export function setEnv(env: string): void; + +export function unlessProduction(handle: () => any): any; diff --git a/types/asenv/tsconfig.json b/types/asenv/tsconfig.json new file mode 100644 index 0000000000..129dd1caf0 --- /dev/null +++ b/types/asenv/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "asenv-tests.ts" + ] +} diff --git a/types/asenv/tslint.json b/types/asenv/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/asenv/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/askmethat-rating/askmethat-rating-tests.ts b/types/askmethat-rating/askmethat-rating-tests.ts index 2f17ad0b62..af985d6358 100644 --- a/types/askmethat-rating/askmethat-rating-tests.ts +++ b/types/askmethat-rating/askmethat-rating-tests.ts @@ -1,6 +1,6 @@ import { AskmethatRating, AskmethatRatingSteps } from "askmethat-rating"; -let options = { +const options = { backgroundColor: "#e5e500", hoverColor: "#ffff66", fontClass: "fa fa-star", @@ -11,5 +11,8 @@ let options = { inputName: "AskmethatRating" }; -let div = document.createElement("div"); -let amcRating = new AskmethatRating(div, 2 , options); +const div = document.createElement("div"); +const amcRating = new AskmethatRating(div, 2 , options); + +options.readonly = true; +amcRating.defaultOptions = options; diff --git a/types/askmethat-rating/index.d.ts b/types/askmethat-rating/index.d.ts index ff31f81747..a183ecdc30 100644 --- a/types/askmethat-rating/index.d.ts +++ b/types/askmethat-rating/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for askmethat-rating 0.3 // Project: https://alexteixeira.github.io/Askmethat-Rating/ -// Definitions by: Alexandre Teixeira +// Definitions by: Alexandre Teixeira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -75,7 +75,12 @@ export class AskmethatRating { * * @return options based on @type AskmethatRatingOptions */ - readonly defaultOptions: any; + /** + * @function set the default option for the rating + * + * @return options based on @type AskmethatRatingOptions + */ + defaultOptions: AskmethatRatingOptions; /** * constructor with div element, default rating value & default options * @@ -122,6 +127,12 @@ export class AskmethatRating { * Update readonly status if needed for the rating */ private mutationEvent(); + /** + * This is fired by mutation observer when an attribute changed in the hidden input + * Is protected to have some unit tests + * @param {MutationRecord[]} mutations list of mutations record + */ + protected mutationDisableEvent(mutations: MutationRecord[]): void; /** * @function static method to retrieve with identifier the value * @param {string} identifier: string container identifier diff --git a/types/assert-plus/index.d.ts b/types/assert-plus/index.d.ts index d79172bc49..6c1f369729 100644 --- a/types/assert-plus/index.d.ts +++ b/types/assert-plus/index.d.ts @@ -5,7 +5,7 @@ /// -import {Stream} from 'stream'; +import { Stream } from 'stream'; export function array(arr: any[], message ?: string): void; diff --git a/types/assets-webpack-plugin/assets-webpack-plugin-tests.ts b/types/assets-webpack-plugin/assets-webpack-plugin-tests.ts new file mode 100644 index 0000000000..6851f853f2 --- /dev/null +++ b/types/assets-webpack-plugin/assets-webpack-plugin-tests.ts @@ -0,0 +1,25 @@ +import * as webpack from 'webpack'; +import * as AssetsPlugin from 'assets-webpack-plugin'; + +const config: webpack.Configuration = { + plugins: [ + new AssetsPlugin(), + new AssetsPlugin({ + filename: 'assets.json' + }), + new AssetsPlugin({ + filename: 'assets.json', + fullPath: false, + includeManifest: true, + path: '/foo/bar', + prettyPrint: true, + processOutput: (assets) => ( + 'window.assets = ' + JSON.stringify(assets) + ), + update: true, + metadata: { + meta: 'data' + }, + }) + ] +}; diff --git a/types/assets-webpack-plugin/index.d.ts b/types/assets-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..660fbc6052 --- /dev/null +++ b/types/assets-webpack-plugin/index.d.ts @@ -0,0 +1,76 @@ +// Type definitions for assets-webpack-plugin 3.5 +// Project: https://github.com/sporto/assets-webpack-plugin +// Definitions by: Michael Strobel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as webpack from 'webpack'; + +declare namespace AssetsWebpackPlugin { + interface Assets { + [name: string]: { + [ext: string]: string; + }; + } + + type ProcessOutputFn = (assets: Assets) => string; + + interface Options { + /** + * Name for the created json file. + * "webpack-assets.json" by default + */ + filename?: string; + + /** + * If false the output will not include the full path of the generated file. + * true by default + */ + fullPath?: boolean; + + /** + * Inserts the manifest javascript as a text property in your assets. + * Accepts the name of your manifest chunk. + * A manifest is the last CommonChunk that only contains the webpack bootstrap code. + * This is useful for production use when you want to inline the manifest + * in your HTML skeleton for long-term caching. + * false by default + */ + includeManifest?: boolean; + + /** + * Inject metadata into the output file. All values will be injected into the key "metadata" + */ + metadata?: object; + + /** + * Path where to save the created JSON file. + * Defaults to the current directory + */ + path?: string; + + /** + * Whether to format the JSON output for readability. + * false by default + */ + prettyPrint?: boolean; + + /** + * Formats the assets output. + * Defaults to JSON.stringify + */ + processOutput?: ProcessOutputFn; + + /** + * When set to true, the output JSON file will be updated instead of overwritten. + * false by default + */ + update?: boolean; + } +} + +declare class AssetsWebpackPlugin extends webpack.Plugin { + constructor(options?: AssetsWebpackPlugin.Options); +} + +export = AssetsWebpackPlugin; diff --git a/types/assets-webpack-plugin/tsconfig.json b/types/assets-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..0d71c8ce0b --- /dev/null +++ b/types/assets-webpack-plugin/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "assets-webpack-plugin-tests.ts" + ] +} diff --git a/types/assets-webpack-plugin/tslint.json b/types/assets-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/assets-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/async-cache/async-cache-tests.ts b/types/async-cache/async-cache-tests.ts new file mode 100644 index 0000000000..58a1b565f2 --- /dev/null +++ b/types/async-cache/async-cache-tests.ts @@ -0,0 +1,26 @@ +import AsyncCache = require('async-cache'); + +const stats = new AsyncCache({ + max: 1000, + maxAge: 1000 * 60 * 10, + load(key, cb) { + key; // $ExpectType string + cb; // $ExpectType (error: any, asyncValue: number, maxAge?: number | undefined) => void + } +}); +AsyncCache({ + load(key, cb) {} +}); + +stats.get('', (er, stat) => { + er; // $ExpectType any + stat; // $ExpectType number +}); + +stats.keys(); // $ExpectType string[] +stats.set('', 1); // $ExpectType boolean +stats.set('', 1, 1); +stats.reset(); +stats.has(''); // $ExpectType boolean +stats.del(''); +stats.peek(''); // $ExpectType number | undefined diff --git a/types/async-cache/index.d.ts b/types/async-cache/index.d.ts new file mode 100644 index 0000000000..1e00f35d51 --- /dev/null +++ b/types/async-cache/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for async-cache 1.1 +// Project: https://github.com/isaacs/async-cache#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Options as LRUOptions } from 'lru-cache'; + +export = AsyncCache; + +declare const AsyncCache: AsyncCacheFactory; + +interface AsyncCacheFactory { + (options: AsyncCache.Options): AsyncCache.Cache; + new (options: AsyncCache.Options): AsyncCache.Cache; +} + +declare namespace AsyncCache { + interface Cache { + readonly itemCount: number; + + get(key: string, cb: (error: any, value: T) => void): void; + keys(): string[]; + set(key: string, value: T, maxAge?: number): boolean; + reset(): void; + has(key: string): boolean; + del(key: string): void; + peek(key: string): T | undefined; + } + + interface Options extends LRUOptions { + load(key: string, callback: (error: any, asyncValue: T, maxAge?: number) => void): void; + } +} diff --git a/types/async-cache/tsconfig.json b/types/async-cache/tsconfig.json new file mode 100644 index 0000000000..1358c8a3e4 --- /dev/null +++ b/types/async-cache/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "async-cache-tests.ts" + ] +} diff --git a/types/async-cache/tslint.json b/types/async-cache/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/async-cache/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/async-lock/index.d.ts b/types/async-lock/index.d.ts index 296307300c..4a19590d73 100644 --- a/types/async-lock/index.d.ts +++ b/types/async-lock/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for async-lock // Project: https://github.com/rain1017/async-lock -// Definitions by: Elisée MAURER +// Definitions by: Elisée MAURER // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/async-polling/index.d.ts b/types/async-polling/index.d.ts index 640c863874..78789aeafc 100644 --- a/types/async-polling/index.d.ts +++ b/types/async-polling/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AsyncPolling // Project: https://github.com/cGuille/async-polling -// Definitions by: Zlatko Andonovski +// Definitions by: Zlatko Andonovski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace AsyncPolling { diff --git a/types/async.nexttick/async.nexttick-tests.ts b/types/async.nexttick/async.nexttick-tests.ts index 90f6ae7f15..876a8e0f88 100644 --- a/types/async.nexttick/async.nexttick-tests.ts +++ b/types/async.nexttick/async.nexttick-tests.ts @@ -1,4 +1,4 @@ -import {nextTick} from 'async.nexttick'; +import { nextTick } from 'async.nexttick'; function calledOnNextTick(a: string): number { return parseInt(a, 10); diff --git a/types/async/index.d.ts b/types/async/index.d.ts index 33bb1a6c0e..139689ea2f 100644 --- a/types/async/index.d.ts +++ b/types/async/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Async 2.0.1 // Project: https://github.com/caolan/async -// Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman , Angus Fenying , Pascal Martin +// Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman , Angus Fenying , Pascal Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Dictionary { [key: string]: T; } @@ -28,7 +28,7 @@ interface AsyncQueue { idle(): boolean; concurrency: number; push(task: T, callback?: ErrorCallback): void; - push(task: T, callback?: AsyncResultCallback): void; + push(task: T, callback?: AsyncResultCallback): void; push(task: T[], callback?: ErrorCallback): void; unshift(task: T, callback?: ErrorCallback): void; unshift(task: T[], callback?: ErrorCallback): void; @@ -53,8 +53,8 @@ interface AsyncPriorityQueue { concurrency: number; started: boolean; paused: boolean; - push(task: T, priority: number, callback?: AsyncResultArrayCallback): void; - push(task: T[], priority: number, callback?: AsyncResultArrayCallback): void; + push(task: T, priority: number, callback?: AsyncResultArrayCallback): void; + push(task: T[], priority: number, callback?: AsyncResultArrayCallback): void; saturated: () => any; empty: () => any; drain: () => any; diff --git a/types/async/test/index.ts b/types/async/test/index.ts index b30ca4c7ba..60234a0ca4 100644 --- a/types/async/test/index.ts +++ b/types/async/test/index.ts @@ -271,9 +271,9 @@ async.waterfall([ ], function (err, result) { }); -var q = async.queue(function (task: any, callback: () => void) { +var q = async.queue(function (task: any, callback: (err?:Error,msg?:string) => void) { console.log('hello ' + task.name); - callback(); + callback(undefined,'a message.'); }, 2); @@ -291,6 +291,10 @@ q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { console.log('finished processing bar'); }); +q.push({name: 'foo'}, function (err,msg) { + console.log('foo finished with a message "'+ msg! + '"'); +}); + q.unshift({ name: 'foo' }); q.unshift({ name: 'bar' }, function (err) { diff --git a/types/asyncblock/index.d.ts b/types/asyncblock/index.d.ts index c4f8d3da21..e848f509fb 100644 --- a/types/asyncblock/index.d.ts +++ b/types/asyncblock/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for asyncblock 2.1.23 // Project: https://github.com/scriby/asyncblock -// Definitions by: Hiroki Horiuchi +// Definitions by: Hiroki Horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/atmosphere/index.d.ts b/types/atmosphere/index.d.ts index e62df1ea64..5e88c2c8fb 100644 --- a/types/atmosphere/index.d.ts +++ b/types/atmosphere/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Atmosphere v2.1.5 // Project: https://github.com/Atmosphere/atmosphere-javascript -// Definitions by: Kai Toedter +// Definitions by: Kai Toedter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Atmosphere { diff --git a/types/atom-keymap/index.d.ts b/types/atom-keymap/index.d.ts index c066867a5b..58d75ec709 100644 --- a/types/atom-keymap/index.d.ts +++ b/types/atom-keymap/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for atom-keymap v5.1.5 // Project: https://github.com/atom/atom-keymap/ -// Definitions by: Vadim Macagon +// Definitions by: Vadim Macagon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/atom/index.d.ts b/types/atom/index.d.ts index 30aa6b881b..718cc2747a 100644 --- a/types/atom/index.d.ts +++ b/types/atom/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Atom // Project: https://atom.io/ -// Definitions by: vvakame +// Definitions by: vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/auth0-js/auth0-js-tests.ts b/types/auth0-js/auth0-js-tests.ts index 5356dc605a..73426dbd37 100644 --- a/types/auth0-js/auth0-js-tests.ts +++ b/types/auth0-js/auth0-js-tests.ts @@ -130,7 +130,10 @@ webAuth.signupAndAuthorize({ connection: 'the_connection', email: 'me@example.com', password: '123456', - scope: 'openid' + scope: 'openid', + user_metadata: { + foo: 'bar' + } }, function (err, data) { }); diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index 4e6afded1d..37914e887f 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for Auth0.js 8.6 // Project: https://github.com/auth0/auth0.js // Definitions by: Adrian Chia +// Matt Durrant // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace auth0; @@ -624,6 +625,7 @@ interface DbSignUpOptions { password: string; connection: string; scope?: string; + user_metadata?: any; } interface ParseHashOptions { diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index 3abe93a7c2..0642453a13 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -4,7 +4,7 @@ import Auth0Lock from 'auth0-lock'; const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; const DOMAIN = "YOUR_DOMAIN_AT.auth0.com"; -var lock: Auth0LockStatic = new Auth0Lock(CLIENT_ID, DOMAIN); +const lock: Auth0LockStatic = new Auth0Lock(CLIENT_ID, DOMAIN); lock.show(); lock.hide(); @@ -12,7 +12,7 @@ lock.logout(() => {}); // Show supports UI arguments -var showOptions : Auth0LockShowOptions = { +const showOptions : Auth0LockShowOptions = { allowedConnections: [ "twitter", "facebook" ], allowSignUp: true, allowForgotPassword: false, @@ -63,7 +63,7 @@ lock.on("authenticated", function(authResult : any) { // test theme -var themeOptions : Auth0LockConstructorOptions = { +const themeOptions : Auth0LockConstructorOptions = { theme: { authButtons: { fooProvider: { @@ -86,7 +86,7 @@ new Auth0Lock(CLIENT_ID, DOMAIN, themeOptions); // test empty theme -var themeOptionsEmpty : Auth0LockConstructorOptions = { +const themeOptionsEmpty : Auth0LockConstructorOptions = { theme: { } }; @@ -94,7 +94,7 @@ new Auth0Lock(CLIENT_ID, DOMAIN, themeOptions); // test authentication -var authOptions : Auth0LockConstructorOptions = { +const authOptions : Auth0LockConstructorOptions = { auth: { params: { state: "foo" }, redirect: true, @@ -108,7 +108,7 @@ new Auth0Lock(CLIENT_ID, DOMAIN, authOptions); // test multi-variant example -var multiVariantOptions : Auth0LockConstructorOptions = { +const multiVariantOptions : Auth0LockConstructorOptions = { container: "myContainer", closable: false, languageDictionary: { @@ -122,7 +122,7 @@ new Auth0Lock(CLIENT_ID, DOMAIN, multiVariantOptions); // test text-field additional sign up field -var textFieldOptions : Auth0LockConstructorOptions = { +const textFieldOptions : Auth0LockConstructorOptions = { additionalSignUpFields: [{ name: "address", placeholder: "enter your address", @@ -142,7 +142,7 @@ new Auth0Lock(CLIENT_ID, DOMAIN, textFieldOptions); // test select-field additional sign up field -var selectFieldOptions : Auth0LockConstructorOptions = { +const selectFieldOptions : Auth0LockConstructorOptions = { additionalSignUpFields: [{ type: "select", name: "location", @@ -162,7 +162,7 @@ new Auth0Lock(CLIENT_ID, DOMAIN, selectFieldOptions); // test select-field additional sign up field with callbacks for -var selectFieldOptionsWithCallbacks : Auth0LockConstructorOptions = { +const selectFieldOptionsWithCallbacks : Auth0LockConstructorOptions = { additionalSignUpFields: [{ type: "select", name: "location", @@ -171,7 +171,7 @@ var selectFieldOptionsWithCallbacks : Auth0LockConstructorOptions = { // obtain options, in case of error you call cb with the error in the // first arg instead of null - let options = [ + const options = [ {value: "us", label: "United States"}, {value: "fr", label: "France"}, {value: "ar", label: "Argentina"} @@ -184,7 +184,7 @@ var selectFieldOptionsWithCallbacks : Auth0LockConstructorOptions = { // obtain prefill, in case of error you call cb with the error in the // first arg instead of null - let prefill = "us"; + const prefill = "us"; cb(null, prefill); } @@ -195,13 +195,13 @@ new Auth0Lock(CLIENT_ID, DOMAIN, selectFieldOptionsWithCallbacks); // test Avatar options -var avatarOptions : Auth0LockConstructorOptions = { +const avatarOptions : Auth0LockConstructorOptions = { avatar: { url: (email : string, cb : Auth0LockAvatarUrlCallback) => { // obtain url for email, in case of error you call cb with the error in // the first arg instead of null - let url = "url"; + const url = "url"; cb(null, url); }, @@ -209,7 +209,7 @@ var avatarOptions : Auth0LockConstructorOptions = { // obtain displayName for email, in case of error you call cb with the // error in the first arg instead of null - let displayName = "displayName"; + const displayName = "displayName"; cb(null, displayName); } @@ -218,7 +218,7 @@ var avatarOptions : Auth0LockConstructorOptions = { new Auth0Lock(CLIENT_ID, DOMAIN, avatarOptions); -var authResult : AuthResult = { +const authResult : AuthResult = { accessToken: 'fake_access_token', idToken: 'fake_id_token', idTokenPayload: { diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index e49c23a308..0a57d988ce 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -155,7 +155,7 @@ interface Auth0LockStatic { getProfile(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void; getUserInfo(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void; // https://github.com/auth0/lock#resumeauthhash-callback - resumeAuth( hash: string, callback: (error: auth0.Auth0Error, authResult: AuthResult) => void): void; + resumeAuth(hash: string, callback: (error: auth0.Auth0Error, authResult: AuthResult) => void): void; show(options?: Auth0LockShowOptions): void; hide(): void; logout(query: any): void; diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index 07a316268a..cb84c7a6bd 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -360,6 +360,7 @@ export class ManagementClient { // Users getUsers(params?: GetUsersData): Promise; + getUsers(cb: (err: Error, users: User[]) => void): void; getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void; getUser(params: ObjectWithId): Promise; diff --git a/types/auto-launch/auto-launch-tests.ts b/types/auto-launch/auto-launch-tests.ts index ae6ace9620..af141358bd 100644 --- a/types/auto-launch/auto-launch-tests.ts +++ b/types/auto-launch/auto-launch-tests.ts @@ -1,24 +1,23 @@ - - import AutoLaunch = require('auto-launch'); -var a1 = new AutoLaunch({ - name: 'Foo', +const minecraftAutoLauncher = new AutoLaunch({ + name: 'Minecraft', + path: '/Applications/Minecraft.app', + mac: { + useLaunchAgent: true + } }); -var a2 = new AutoLaunch({ - name: 'Foo', - path: '/Applications/Foo.app', - isHidden: true, -}); +minecraftAutoLauncher.enable(); +minecraftAutoLauncher.disable(); -a1.enable(); -a2.disable(); - -a1.isEnabled(function(enabled: boolean) { - if (enabled) { - return; +minecraftAutoLauncher.isEnabled() + .then((isEnabled) => { + if (isEnabled) { + return; } - - a1.enable(function(err){ console.log(err.message); }); -}); + minecraftAutoLauncher.enable(); + }) + .catch((err) => { + console.error(err); + }); diff --git a/types/auto-launch/index.d.ts b/types/auto-launch/index.d.ts index 8a6af4e5dd..1ea4fcc25a 100644 --- a/types/auto-launch/index.d.ts +++ b/types/auto-launch/index.d.ts @@ -1,41 +1,47 @@ -// Type definitions for auto-launch 0.1.18 +// Type definitions for auto-launch 5.0 // Project: https://github.com/Teamwork/node-auto-launch -// Definitions by: rhysd +// Definitions by: rhysd , Daniel Perez Alvarez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface AutoLaunchOption { - /** - * Application name. - */ - name: string; - /** - * Hidden on launch or not. Default is false. - */ - isHidden?: boolean; - /** - * Path to application directory. - * Default is process.execPath. - */ - path?: string; +interface AutoLaunchOptions { + /** + * Application name. + */ + name: string; + /** + * Path to application. Default is `process.execPath`. + */ + path?: string; + /** + * Hidden on launch. Default is `false`. + */ + isHidden?: boolean; + /** + * For Mac-only options. + */ + mac?: { + /** + * By default, AppleScript is used to add a Login Item. If this is `true`, Launch Agent will be used to auto-launch your app. Defaults is `false`. + */ + useLaunchAgent?: boolean; + }; } declare class AutoLaunch { - constructor(opts: AutoLaunchOption); - /** - * Enables to launch at start up - */ - enable(callback?: (err: Error) => void): void; - /** - * Disables to launch at start up - */ - disable(callback?: (err: Error) => void): void; - /** - * Returns if auto start up is enabled - */ - isEnabled(callback: (enabled: boolean) => void): void; + constructor(options: AutoLaunchOptions); + + /** + * Enables auto-launch at start up. + */ + enable(): Promise; + /** + * Disables auto-launch at start up. + */ + disable(): Promise; + /** + * Returns true if auto-launch is enabled. + */ + isEnabled(): Promise; } -declare module "auto-launch" { - var al: typeof AutoLaunch; - export = al; -} +export = AutoLaunch; diff --git a/types/auto-launch/tsconfig.json b/types/auto-launch/tsconfig.json index 2200ea7a60..ba69bba12b 100644 --- a/types/auto-launch/tsconfig.json +++ b/types/auto-launch/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,4 +20,4 @@ "index.d.ts", "auto-launch-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/auto-launch/tslint.json b/types/auto-launch/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/auto-launch/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/auto-sni/auto-sni-tests.ts b/types/auto-sni/auto-sni-tests.ts index a271a1a1ad..6be54148fb 100644 --- a/types/auto-sni/auto-sni-tests.ts +++ b/types/auto-sni/auto-sni-tests.ts @@ -1,5 +1,5 @@ import * as autosni from "auto-sni"; -let a = autosni({ +const a = autosni({ agreeTos: true, email: '', domains: [''] diff --git a/types/auto-sni/index.d.ts b/types/auto-sni/index.d.ts index bc252831ca..19272446a6 100644 --- a/types/auto-sni/index.d.ts +++ b/types/auto-sni/index.d.ts @@ -5,7 +5,7 @@ /// -import {Server} from "https"; +import { Server } from "https"; declare namespace createServer { interface Options { diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts index 6741bcccd1..3c576e2dc8 100644 --- a/types/autobahn/index.d.ts +++ b/types/autobahn/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AutobahnJS v0.9.7 // Project: http://autobahn.ws/js/ -// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino +// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/autobind-decorator/index.d.ts b/types/autobind-decorator/index.d.ts index 51ba89c9bf..d8d74bbfec 100644 --- a/types/autobind-decorator/index.d.ts +++ b/types/autobind-decorator/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for autobind-decorator v1.3.3 // Project: https://github.com/andreypopp/autobind-decorator -// Definitions by: Ivo Stratev +// Definitions by: Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'autobind-decorator' { diff --git a/types/autosize/index.d.ts b/types/autosize/index.d.ts index 0886904e3f..a189b32817 100644 --- a/types/autosize/index.d.ts +++ b/types/autosize/index.d.ts @@ -1,20 +1,66 @@ -// Type definitions for jquery.autosize 3.0.7 +// Type definitions for jquery.autosize 3.0 // Project: http://www.jacklmoore.com/autosize/ -// Definitions by: Aaron T. King , keika299 +// Definitions by: Aaron T. King , keika299 , NeekSandhu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +/** + * Attach autosize to NodeList + * @param elements + */ +declare function autosize(elements: NodeList): NodeList; +/** + * Attach autosize to Element + * @param element + */ +declare function autosize(element: Element): Element; +/** + * Attach autosize to JQuery collection + * @param collection + */ +declare function autosize(collection: JQuery): JQuery; declare namespace autosize { - interface AutosizeStatic { - (el: Element): void; - (el: NodeList): void; - update(el: Element): void; - update(el: NodeList): void; - destroy(el: Element): void; - destroy(el: NodeList): void; - } -} + /** + * Triggers the height adjustment for an assigned textarea element. + * Autosize will automatically adjust the textarea height on keyboard and window resize events. + * There is no efficient way for Autosize to monitor for when another script has changed the textarea value or for changes in layout that impact the textarea element. + * @param elements + */ + function update(elements: NodeList): NodeList; + /** + * Triggers the height adjustment for an assigned textarea element. + * Autosize will automatically adjust the textarea height on keyboard and window resize events. + * There is no efficient way for Autosize to monitor for when another script has changed the textarea value or for changes in layout that impact the textarea element. + * @param element + */ + function update(element: Element): Element; + /** + * Triggers the height adjustment for an assigned textarea element. + * Autosize will automatically adjust the textarea height on keyboard and window resize events. + * There is no efficient way for Autosize to monitor for when another script has changed the textarea value or for changes in layout that impact the textarea element. + * @param collection + */ + function update(collection: JQuery): JQuery; -declare var autosize: autosize.AutosizeStatic; + /** + * Removes Autosize and reverts any changes it made to the textarea element. + * @param elements + */ + function destroy(elements: NodeList): NodeList; + /** + * Removes Autosize and reverts any changes it made to the textarea element. + * @param element + */ + function destroy(element: Element): Element; + /** + * Removes Autosize and reverts any changes it made to the textarea element. + * @param collection + */ + function destroy(collection: JQuery): JQuery; +} export = autosize; export as namespace autosize; diff --git a/types/autosize/tslint.json b/types/autosize/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/autosize/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/awesomplete/awesomplete-tests.ts b/types/awesomplete/awesomplete-tests.ts index 6cea0e1bca..f9ff4fed77 100644 --- a/types/awesomplete/awesomplete-tests.ts +++ b/types/awesomplete/awesomplete-tests.ts @@ -35,7 +35,7 @@ new Awesomplete('input[type="email"]', { "hotmail.co.uk", "mac.com", "me.com", "mail.com", "msn.com", "live.com", "sbcglobal.net", "verizon.net", "yahoo.com", "yahoo.co.uk"], data: (text: string, input: string) => { - return input.slice(0, input.indexOf("@")) + "@" + text; + return `${input.slice(0, input.indexOf("@"))}@${text}`; }, filter: Awesomplete.FILTER_STARTSWITH }); @@ -47,7 +47,7 @@ new Awesomplete('input[data-multiple]', { replace: (text: string) => { const before = this.input.value.match(/^.+,\s*|/)[0]; - this.input.value = before + text + ", "; + this.input.value = `${before}${text}, `; } }); diff --git a/types/awesomplete/index.d.ts b/types/awesomplete/index.d.ts index 4612d66210..149b87e9f6 100644 --- a/types/awesomplete/index.d.ts +++ b/types/awesomplete/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Awesomplete 1.1 // Project: https://leaverou.github.io/awesomplete/ -// Definitions by: webbiesdk , Ben Dixon , Trevor Bekolay +// Definitions by: webbiesdk , Ben Dixon , Trevor Bekolay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare class Awesomplete { diff --git a/types/aws-lambda-mock-context/tslint.json b/types/aws-lambda-mock-context/tslint.json index f93cf8562a..bafaae7817 100644 --- a/types/aws-lambda-mock-context/tslint.json +++ b/types/aws-lambda-mock-context/tslint.json @@ -1,3 +1,7 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + // TODO + "dt-header": false + } } diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 7f8b8fabdd..4e404fcd55 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -22,43 +22,44 @@ var snsEvtRec: AWSLambda.SNSEventRecord; var snsMsg: AWSLambda.SNSMessage; var snsMsgAttr: AWSLambda.SNSMessageAttribute; var snsMsgAttrs: AWSLambda.SNSMessageAttributes; -var S3CreateEvent: AWSLambda.S3CreateEvent = { - Records: [{ - eventVersion: 'string', - eventSource: 'string', - awsRegion: 'string', - eventTime: 'string', - eventName: 'string', - userIdentity: { - principalId: 'string' - }, - requestParameters: { - sourceIPAddress: 'string' - }, - responseElements: { - 'x-amz-request-id': 'string', - 'x-amz-id-2': 'string' - }, - s3: { - s3SchemaVersion: 'string', - configurationId: 'string', - bucket: { - name: 'string', - ownerIdentity: { - principalId: 'string' - }, - arn: 'string' +var S3EvtRec: AWSLambda.S3EventRecord = { + eventVersion: '2.0', + eventSource: 'aws:s3', + awsRegion: 'us-east-1', + eventTime: '1970-01-01T00:00:00.000Z', + eventName: 'ObjectCreated:Put', + userIdentity: { + principalId: 'AIDAJDPLRKLG7UEXAMPLE' + }, + requestParameters:{ + sourceIPAddress: '127.0.0.1' + }, + responseElements: { + 'x-amz-request-id': 'C3D13FE58DE4C810', + 'x-amz-id-2': 'FMyUVURIY8/IgAtTv8xRjskZQpcIZ9KG4V5Wp6S7S/JRWeUWerMUE5JgHvANOjpD' + }, + s3: { + s3SchemaVersion: '1.0', + configurationId: 'testConfigRule', + bucket: { + name: 'mybucket', + ownerIdentity: { + principalId: 'A3NL1KOZZKExample' }, - object: { - key: 'string', - size: 1, - eTag: 'string', - versionId: 'string', - sequencer: 'string' - } + arn: 'arn:aws:s3:::mybucket' + }, + object: { + key: 'HappyFace.jpg', + size: 1024, + eTag: 'd41d8cd98f00b204e9800998ecf8427e', + versionId: '096fKKXTRTtl3on89fVO.nfljtsv6qko', + sequencer: '0055AED6DCD90281E5' } } - ] +}; + +var S3CreateEvent: AWSLambda.S3CreateEvent = { + Records: [S3EvtRec] }; var cognitoUserPoolEvent: AWSLambda.CognitoUserPoolEvent; var cloudformationCustomResourceEvent: AWSLambda.CloudFormationCustomResourceEvent; @@ -129,6 +130,7 @@ num = proxyResult.statusCode; proxyResult.headers["example"] = str; proxyResult.headers["example"] = b; proxyResult.headers["example"] = num; +b = proxyResult.isBase64Encoded; str = proxyResult.body; /* API Gateway CustomAuthorizer AuthResponse */ diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index df8effb82b..0c8f0fc26d 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AWS Lambda // Project: http://docs.aws.amazon.com/lambda -// Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath , Toby Hede , Rich Buggy , Yoriki Yamaguchi +// Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath , Toby Hede , Rich Buggy , Yoriki Yamaguchi , wwwy3y3 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // API Gateway "event" @@ -85,43 +85,44 @@ interface SNSEvent { * S3Create event * https://docs.aws.amazon.com/AmazonS3/latest/dev/notification-content-structure.html */ -interface S3CreateEvent { - Records: [{ - eventVersion: string; - eventSource: string; - awsRegion: string - eventTime: string; - eventName: string; - userIdentity: { - principalId: string; - }, - requestParameters: { - sourceIPAddress: string; - }, - responseElements: { - 'x-amz-request-id': string; - 'x-amz-id-2': string; - }, - s3: { - s3SchemaVersion: string; - configurationId: string; - bucket: { - name: string; - ownerIdentity: { - principalId: string; - }, - arn: string; +interface S3EventRecord { + eventVersion: string; + eventSource: string; + awsRegion: string + eventTime: string; + eventName: string; + userIdentity: { + principalId: string; + }, + requestParameters: { + sourceIPAddress: string; + }, + responseElements: { + 'x-amz-request-id': string; + 'x-amz-id-2': string; + }, + s3: { + s3SchemaVersion: string; + configurationId: string; + bucket: { + name: string; + ownerIdentity: { + principalId: string; }, - object: { - key: string; - size: number; - eTag: string; - versionId: string; - sequencer: string; - } + arn: string; + }, + object: { + key: string; + size: number; + eTag: string; + versionId: string; + sequencer: string; } } - ]; +} + +interface S3CreateEvent { + Records: Array; } /** @@ -287,6 +288,7 @@ interface ProxyResult { [header: string]: boolean | number | string; }, body: string; + isBase64Encoded?: boolean; } /** diff --git a/types/aws-serverless-express/aws-serverless-express-tests.ts b/types/aws-serverless-express/aws-serverless-express-tests.ts index 97d236e043..4770163b3b 100644 --- a/types/aws-serverless-express/aws-serverless-express-tests.ts +++ b/types/aws-serverless-express/aws-serverless-express-tests.ts @@ -5,7 +5,7 @@ import { eventContext } from 'aws-serverless-express/middleware'; const app = express(); app.use(eventContext()); -const server = awsServerlessExpress.createServer(app, () => {}); +const server = awsServerlessExpress.createServer(app, () => {}, []); const mockEvent = { key: 'value' diff --git a/types/aws-serverless-express/index.d.ts b/types/aws-serverless-express/index.d.ts index db49e6ca6b..e612d5d8d6 100644 --- a/types/aws-serverless-express/index.d.ts +++ b/types/aws-serverless-express/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for aws-serverless-express 2.1 // Project: https://github.com/awslabs/aws-serverless-express -// Definitions by: Ben Speakman , Josh Caffey +// Definitions by: Ben Speakman , Josh Caffey , Matthias Meyer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -9,7 +9,8 @@ import * as lambda from 'aws-lambda'; export function createServer( requestListener: (request: http.IncomingMessage, response: http.ServerResponse) => http.Server, - serverListenCallback?: () => any + serverListenCallback?: () => any, + binaryMimeTypes?: string[] ): http.Server; export function proxy( diff --git a/types/azure-mobile-services-client/index.d.ts b/types/azure-mobile-services-client/index.d.ts index 8dbb12d2e4..2109633a69 100644 --- a/types/azure-mobile-services-client/index.d.ts +++ b/types/azure-mobile-services-client/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Microsoft Windows AzureMobile Service 1.0.0 // Project: http://www.windowsazure.com/en-us/develop/mobile/ -// Definitions by: Morosinotto Daniele +// Definitions by: Morosinotto Daniele // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Microsoft.WindowsAzure { diff --git a/types/azure-sb/index.d.ts b/types/azure-sb/index.d.ts index 1c8b087815..bae1af04a9 100644 --- a/types/azure-sb/index.d.ts +++ b/types/azure-sb/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for azure-sb // Project: https://github.com/Azure/azure-sdk-for-node/tree/master/lib/services/serviceBus -// Definitions by: Microsoft Azure +// Definitions by: Microsoft Azure // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Azure.ServiceBus { diff --git a/types/babel-core/babel-core-tests.ts b/types/babel-core/babel-core-tests.ts index 4c62d3c2f5..b3839d151f 100644 --- a/types/babel-core/babel-core-tests.ts +++ b/types/babel-core/babel-core-tests.ts @@ -1,7 +1,5 @@ - 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 */ }); @@ -9,9 +7,8 @@ result.code; // Generated code result.map; // Sourcemap result.ast; // AST - // Examples from http://babeljs.io/docs/usage/api/ -let options: babel.TransformOptions = { +const options: babel.TransformOptions = { plugins: [ "es2015-arrow-functions", "es2015-block-scoped-functions", @@ -23,10 +20,27 @@ let options: babel.TransformOptions = { sourceMaps: true }; -babel.transformFile("filename.js", options, function (err, result) { +babel.transformFile("filename.js", options, (err, result) => { result.code; result.map; result.ast; }); babel.transformFileSync("filename.js", options).code; + +// Slightly modified example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#-pre-and-post-in-plugins +export default function(): babel.PluginObj<{ cache: Map}> { + return { + pre(state) { + this.cache = new Map(); + }, + visitor: { + StringLiteral(path) { + this.cache.set(path.node.value, 1); + } + }, + post(state) { + return this.cache; + } + }; +} diff --git a/types/babel-core/index.d.ts b/types/babel-core/index.d.ts index a3cd7019ab..1ea5d888d8 100644 --- a/types/babel-core/index.d.ts +++ b/types/babel-core/index.d.ts @@ -1,20 +1,30 @@ -// Type definitions for babel-core v6.7 +// Type definitions for babel-core 6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-core // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// -/// +// TypeScript Version: 2.3 import * as t from 'babel-types'; -export {t as types}; -type Node = t.Node; +export { t as types }; +export type Node = t.Node; export import template = require('babel-template'); -export var version: string; -import traverse, {Visitor} from "babel-traverse"; -export {traverse, Visitor}; +export const version: string; +import traverse, { Visitor } from "babel-traverse"; +export { traverse, Visitor }; +// A babel plugin is a simple function which must return an object matching +// the following interface. Babel will throw if it finds unknown properties. +// The list of allowed plugin keys is here: +// https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-core/src/config/option-manager.js#L71 +export interface PluginObj { + name?: string; + manipulateOptions?(opts: any, parserOpts: any): void; + pre?(this: S, state: any): void; + visitor: Visitor; + post?(this: S, state: any): void; + inherits?: any; +} /** Transforms the passed in `code`. Returning an object with the generated code, source map, and AST. */ export function transform(code: string, opts?: TransformOptions): BabelFileResult; @@ -28,7 +38,6 @@ export function transformFileSync(filename: string, opts?: TransformOptions): Ba 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; @@ -36,7 +45,7 @@ export interface TransformOptions { filenameRelative?: string; /** A source map object that the output source map will be based on. */ - inputSourceMap?: Object; + inputSourceMap?: object; /** * This is an object of keys that represent different environments. For example, you may have: @@ -44,7 +53,7 @@ export interface TransformOptions { * 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; + env?: object; /** Retain line numbers - will result in really ugly code. Default: `false` */ retainLines?: boolean; @@ -83,7 +92,7 @@ export interface TransformOptions { * 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; + shouldPrintComment?(comment: string): boolean; /** * Do not include superfluous whitespace characters and line terminators. When set to `"auto"`, `compact` is set to @@ -120,7 +129,7 @@ export interface TransformOptions { * 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; + getModuleId?(moduleName: string): string; /** Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions. */ moduleRoot?: string; @@ -138,7 +147,6 @@ export interface TransformOptions { export interface BabelFileResult { ast?: Node; code?: string; - map?: Object; + map?: object; } export as namespace babel; - diff --git a/types/babel-core/tslint.json b/types/babel-core/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-core/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/babel-generator/babel-generator-tests.ts b/types/babel-generator/babel-generator-tests.ts index 92c65b7f54..5efb98ba24 100644 --- a/types/babel-generator/babel-generator-tests.ts +++ b/types/babel-generator/babel-generator-tests.ts @@ -1,5 +1,5 @@ // Example from https://github.com/babel/babel/tree/master/packages/babel-generator -import {parse} from 'babylon'; +import { parse } from 'babylon'; import generate from 'babel-generator'; const code = 'class Example {}'; @@ -11,7 +11,7 @@ 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, { +const result = generate(ast, { retainLines: false, compact: "auto", concise: false, diff --git a/types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts b/types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts new file mode 100644 index 0000000000..4dcb7b4882 --- /dev/null +++ b/types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts @@ -0,0 +1,10 @@ +import jsx from "babel-plugin-syntax-jsx"; + +// Example taken from the babel plugin handbook: +// https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#-enabling-syntax-in-plugins +export default function myBabelPlugin() { + return { + visitor: {}, + inherits: jsx, + }; +} diff --git a/types/babel-plugin-syntax-jsx/index.d.ts b/types/babel-plugin-syntax-jsx/index.d.ts new file mode 100644 index 0000000000..c7b0ede972 --- /dev/null +++ b/types/babel-plugin-syntax-jsx/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for babel-plugin-syntax-jsx 6.18 +// Project: https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-jsx +// Definitions by: Marvin Hagemeister +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// NB: This export doesn't match the handbook example, where `jsx` is the default export. +// But it does match the runtime behaviour (at least at the time of this writing). For some reason, +// babel-plugin-syntax-jsx/lib/index.js has this line at the bottom: module.exports = exports["default"]; +declare function jsx(): { + manipulateOptions(opts: any, parserOpts: { plugins: string[] }): void; +}; + +export default jsx; diff --git a/types/babel-plugin-syntax-jsx/tsconfig.json b/types/babel-plugin-syntax-jsx/tsconfig.json new file mode 100644 index 0000000000..bb19fbf329 --- /dev/null +++ b/types/babel-plugin-syntax-jsx/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "babel-plugin-syntax-jsx-tests.ts" + ] +} diff --git a/types/babel-plugin-syntax-jsx/tslint.json b/types/babel-plugin-syntax-jsx/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-plugin-syntax-jsx/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/babel-template/babel-template-tests.ts b/types/babel-template/babel-template-tests.ts index 31e3bd44d9..684a291be7 100644 --- a/types/babel-template/babel-template-tests.ts +++ b/types/babel-template/babel-template-tests.ts @@ -1,5 +1,3 @@ -/// - // Example from https://github.com/babel/babel/tree/master/packages/babel-template import template = require('babel-template'); import generate from 'babel-generator'; diff --git a/types/babel-template/index.d.ts b/types/babel-template/index.d.ts index 7d73adc466..467b0193e7 100644 --- a/types/babel-template/index.d.ts +++ b/types/babel-template/index.d.ts @@ -1,13 +1,11 @@ -// Type definitions for babel-template v6.7 +// Type definitions for babel-template 6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-template // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -/// -/// - - -import {BabylonOptions} from 'babylon'; +import { BabylonOptions } from 'babylon'; import * as t from 'babel-types'; type Node = t.Node; @@ -18,4 +16,3 @@ export = template; declare function template(code: string, opts?: BabylonOptions): UseTemplate; type UseTemplate = (nodes?: {[placeholder: string]: Node}) => Node; - diff --git a/types/babel-template/tslint.json b/types/babel-template/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-template/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/babel-traverse/babel-traverse-tests.ts b/types/babel-traverse/babel-traverse-tests.ts index 5952faefd1..1dd95060e4 100644 --- a/types/babel-traverse/babel-traverse-tests.ts +++ b/types/babel-traverse/babel-traverse-tests.ts @@ -1,11 +1,7 @@ -/// - - import * as babylon from "babylon"; -import traverse, {Visitor} from 'babel-traverse'; +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: { @@ -24,7 +20,6 @@ const MyVisitor2: Visitor = { } }; - // 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; @@ -34,18 +29,16 @@ const ast = babylon.parse(code); traverse(ast, { enter(path) { - let node = path.node; + const 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)) { // ... @@ -92,10 +85,10 @@ const v1: Visitor = { // ... } - let id1 = path.scope.generateUidIdentifier("uid"); + const id1 = path.scope.generateUidIdentifier("uid"); id1.type; id1.name; - let id2 = path.scope.generateUidIdentifier("uid"); + const id2 = path.scope.generateUidIdentifier("uid"); id2.type; id2.name; diff --git a/types/babel-traverse/index.d.ts b/types/babel-traverse/index.d.ts index 8d34144d0a..682550b161 100644 --- a/types/babel-traverse/index.d.ts +++ b/types/babel-traverse/index.d.ts @@ -1,15 +1,14 @@ -// Type definitions for babel-traverse v6.7 +// Type definitions for babel-traverse 6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-traverse // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - +// TypeScript Version: 2.3 import * as t from 'babel-types'; -type Node = t.Node; +export type Node = t.Node; -export default function traverse(parent: Node | Node[], opts?: TraverseOptions, scope?: Scope, state?: any, parentPath?: NodePath): void; +export default function traverse(parent: Node | Node[], opts?: TraverseOptions, scope?: Scope, state?: any, parentPath?: NodePath): void; export interface TraverseOptions extends Visitor { scope?: Scope; @@ -17,8 +16,8 @@ export interface TraverseOptions extends Visitor { } export class Scope { - constructor(path: NodePath, parentScope?: Scope); - path: NodePath; + constructor(path: NodePath, parentScope?: Scope); + path: NodePath; block: Node; parentBlock: Node; parent: Scope; @@ -54,7 +53,7 @@ export class Scope { /** 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; + checkBlockScopedCollisions(local: Node, kind: string, name: string, id: object): void; rename(oldName: string, newName?: string, block?: Node): void; @@ -62,13 +61,13 @@ export class Scope { toArray(node: Node, i?: number): Node; - registerDeclaration(path: NodePath): void; + registerDeclaration(path: NodePath): void; buildUndefinedNode(): Node; - registerConstantViolation(path: NodePath): void; + registerConstantViolation(path: NodePath): void; - registerBinding(kind: string, path: NodePath, bindingPath?: NodePath): void; + registerBinding(kind: string, path: NodePath, bindingPath?: NodePath): void; addGlobal(node: Node): void; @@ -95,13 +94,13 @@ export class Scope { getBlockParent(): Scope; /** Walks the scope tree and gathers **all** bindings. */ - getAllBindings(...kinds: string[]): Object; + getAllBindings(...kinds: string[]): object; bindingIdentifierEquals(name: string, node: Node): boolean; - getBinding(name: string): Binding; + getBinding(name: string): Binding | undefined; - getOwnBinding(name: string): Binding; + getOwnBinding(name: string): Binding | undefined; getBindingIdentifier(name: string): t.Identifier; @@ -122,216 +121,221 @@ export class Scope { } export class Binding { - constructor(opts: { existing: Binding; identifier: t.Identifier; scope: Scope; path: NodePath; kind: 'var' | 'let' | 'const'; }); + constructor(opts: { existing: Binding; identifier: t.Identifier; scope: Scope; path: NodePath; kind: 'var' | 'let' | 'const'; }); identifier: t.Identifier; scope: Scope; - path: NodePath; + path: NodePath; kind: 'var' | 'let' | 'const' | 'module'; referenced: boolean; references: number; - referencePaths: NodePath[]; + referencePaths: NodePath[]; constant: boolean; - constantViolations: NodePath[]; + 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; - Scope?: VisitNode; +// The Visitor has to be generic because babel binds `this` for each property. +// `this` is usually used in babel plugins to pass plugin state from +// `pre` -> `visitor` -> `post`. An example of this can be seen in the official +// babel handbook: +// https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#-pre-and-post-in-plugins +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; + Scope?: VisitNode; } -export type VisitNode = VisitNodeFunction | VisitNodeObject; +export type VisitNode = VisitNodeFunction | VisitNodeObject; -export type VisitNodeFunction = (path: NodePath, state: any) => void; +export type VisitNodeFunction = (this: T, path: NodePath

      , state: any) => void; export interface VisitNodeObject { enter?(path: NodePath, state: any): void; exit?(path: NodePath, state: any): void; } -export class NodePath { +export class NodePath { constructor(hub: Hub, parent: Node); parent: Node; hub: Hub; contexts: TraversalContext[]; - data: Object; + data: object; shouldSkip: boolean; shouldStop: boolean; removed: boolean; state: any; - opts: Object; - skipKeys: Object; - parentPath: NodePath; + opts: object; + skipKeys: object; + parentPath: NodePath; context: TraversalContext; - container: Object | Object[]; + container: object | object[]; listKey: string; inList: boolean; parentKey: string; @@ -339,7 +343,7 @@ export class NodePath { node: T; scope: Scope; type: string; - typeAnnotation: Object; + typeAnnotation: object; getScope(scope: Scope): Scope; @@ -355,22 +359,23 @@ export class NodePath { getPathLocation(): string; - debug(buildMessage: Function): void; + // Example: https://github.com/babel/babel/blob/63204ae51e020d84a5b246312f5eeb4d981ab952/packages/babel-traverse/src/path/modification.js#L83 + debug(buildMessage: () => string): 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; + findParent(callback: (path: NodePath) => boolean): NodePath; - find(callback: (path: NodePath) => boolean): NodePath; + find(callback: (path: NodePath) => boolean): NodePath; /** Get the parent function of the current path. */ - getFunctionParent(): NodePath; + getFunctionParent(): NodePath; /** Walk up the tree until we hit a parent node path in a list. */ - getStatementParent(): NodePath; + getStatementParent(): NodePath; /** * Get the deepest common ancestor and then from it, get the earliest relationship path @@ -379,17 +384,20 @@ export class NodePath { * Earliest is defined as being "before" all the other nodes in terms of list container * position and visiting key. */ - getEarliestCommonAncestorFrom(paths: NodePath[]): NodePath; + getEarliestCommonAncestorFrom(paths: NodePath[]): NodePath[]; /** Get the earliest path in the tree where the provided `paths` intersect. */ - getDeepestCommonAncestorFrom(paths: NodePath[], filter?: Function): NodePath; + getDeepestCommonAncestorFrom( + paths: NodePath[], + filter?: (deepest: Node, i: number, ancestries: NodePath[]) => NodePath + ): 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[]; + getAncestry(): NodePath[]; inType(...candidateTypes: string[]): boolean; @@ -401,7 +409,7 @@ export class NodePath { couldBeBaseType(name: string): boolean; - baseTypeStrictlyMatches(right: NodePath): boolean; + baseTypeStrictlyMatches(right: NodePath): boolean; isGenericType(genericName: string): boolean; @@ -425,7 +433,7 @@ export class NodePath { replaceWithSourceString(replacement: any): void; /** Replace the current node with another. */ - replaceWith(replacement: Node | NodePath): void; + replaceWith(replacement: Node | NodePath): void; /** * This method takes an array of statements nodes and then explodes it @@ -570,15 +578,13 @@ export class NodePath { hoist(scope: Scope): void; // ------------------------- family ------------------------- - getStatementParent(): NodePath; + getOpposite(): NodePath; - getOpposite(): NodePath; + getCompletionRecords(): NodePath[]; - getCompletionRecords(): NodePath[]; + getSibling(key: string): NodePath; - getSibling(key: string): NodePath; - - get(key: string, context?: boolean | TraversalContext): NodePath; + get(key: string, context?: boolean | TraversalContext): NodePath; getBindingIdentifiers(duplicates?: boolean): Node[]; @@ -594,362 +600,362 @@ export class NodePath { 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; + 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; + 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 { @@ -958,8 +964,8 @@ export class Hub { options: any; } -interface TraversalContext { - parentPath: NodePath; +export interface TraversalContext { + parentPath: NodePath; scope: Scope; state: any; opts: any; diff --git a/types/babel-traverse/tslint.json b/types/babel-traverse/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-traverse/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/babel-types/babel-types-tests.ts b/types/babel-types/babel-types-tests.ts index 5974a64885..af8ab2d0b7 100644 --- a/types/babel-types/babel-types-tests.ts +++ b/types/babel-types/babel-types-tests.ts @@ -1,16 +1,12 @@ - -/// - - // 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; +declare const ast: t.Node; traverse(ast, { enter(path) { - let node = path.node; + const node = path.node; if (t.isIdentifier(node, { name: "n" })) { node.name = "x"; } @@ -25,7 +21,34 @@ if (t.isBinaryExpression(ast)) { ast.right; ast.operator; } + t.assertBinaryExpression(ast); t.assertBinaryExpression(ast, { operator: "*" }); -var exp: t.Expression = t.nullLiteral(); +const exp: t.Expression = t.nullLiteral(); + +// React examples: +// https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-plugin-transform-react-inline-elements/src/index.js#L61 +traverse(ast, { + JSXElement(path, file) { + const { node } = path; + const open = node.openingElement; + + // init + const type = open.name; + + let newType: t.StringLiteral; + if (t.isJSXIdentifier(type) && t.react.isCompatTag(type.name)) { + newType = t.stringLiteral(type.name); + } + + const args: any[] = []; + if (node.children.length) { + const children = t.react.buildChildren(node); + args.push( + t.unaryExpression("void", t.numericLiteral(0), true), + ...children, + ); + } + } +}); diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index 77ea8b54de..1879c81e85 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -1,7 +1,10 @@ -// Type definitions for babel-types v6.7 +// Type definitions for babel-types 6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-types -// Definitions by: Troy Gerwien , Sam Baxter +// Definitions by: Troy Gerwien +// Sam Baxter +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export interface Comment { value: string; @@ -32,9 +35,9 @@ export interface SourceLocation { export interface Node { type: string; - leadingComments?: Array; - innerComments?: Array; - trailingComments?: Array; + leadingComments?: Comment[]; + innerComments?: Comment[]; + trailingComments?: Comment[]; start: number; end: number; loc: SourceLocation; @@ -148,7 +151,7 @@ export interface ForStatement extends Node { export interface FunctionDeclaration extends Node { type: "FunctionDeclaration"; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -159,7 +162,7 @@ export interface FunctionDeclaration extends Node { export interface FunctionExpression extends Node { type: "FunctionExpression"; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -252,7 +255,7 @@ export interface ObjectMethod extends Node { value: Expression; decorators?: Decorator[]; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -359,14 +362,14 @@ export interface AssignmentPattern extends Node { export interface ArrayPattern extends Node { type: "ArrayPattern"; - elements: Array; + elements: Expression[]; typeAnnotation?: TypeAnnotation; } export interface ArrowFunctionExpression extends Node { type: "ArrowFunctionExpression"; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement | Expression; generator: boolean; async: boolean; @@ -472,7 +475,7 @@ export interface ClassMethod extends Node { static: boolean; decorators?: Decorator[]; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -870,12 +873,33 @@ export interface SpreadProperty extends Node { argument: Expression; } -export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | 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 Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression + | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral + | NullLiteral | 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 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 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; @@ -887,7 +911,11 @@ 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 | NullLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression; -export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + +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 | NullLiteral | RegExpLiteral | TemplateLiteral; export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement; @@ -901,15 +929,36 @@ 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 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 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 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; @@ -925,8 +974,8 @@ export function expressionStatement(expression?: Expression): ExpressionStatemen 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?: Array, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; -export function functionExpression(id?: Identifier, params?: Array, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression; +export function functionDeclaration(id?: Identifier, params?: LVal[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; +export function functionExpression(id?: Identifier, params?: LVal[], 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; @@ -940,7 +989,7 @@ export function memberExpression(object?: Expression | Super, property?: Express 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?: Array, body?: BlockStatement, computed?: boolean): ObjectMethod; +export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: LVal[], 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; @@ -957,8 +1006,8 @@ export function variableDeclarator(id?: LVal, init?: Expression): VariableDeclar 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?: Array, body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression; +export function arrayPattern(elements?: Expression[], typeAnnotation?: TypeAnnotation): ArrayPattern; +export function arrowFunctionExpression(params?: LVal[], 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; @@ -972,11 +1021,11 @@ export function importDefaultSpecifier(local?: Identifier): ImportDefaultSpecifi 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?: Array, body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod; +export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: LVal[], 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 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; @@ -1042,360 +1091,367 @@ export function exportNamespaceSpecifier(exported?: Identifier): ExportNamespace 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 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; +// tslint:disable-next-line ban-types +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 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; +// React specific +export interface ReactHelpers { + isCompatTag(tagName?: string): boolean; + buildChildren(node: object): Node[]; +} +export const react: ReactHelpers; +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/types/babel-types/tslint.json b/types/babel-types/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-types/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/babelify/index.d.ts b/types/babelify/index.d.ts index c69eef42b2..f394d2ba44 100644 --- a/types/babelify/index.d.ts +++ b/types/babelify/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for babelify v7.3.0 // Project: https://github.com/babel/babelify // Definitions by: TeamworkGuy2 +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/babylon/babylon-tests.ts b/types/babylon/babylon-tests.ts index 769d635e89..2a5ddfcb57 100644 --- a/types/babylon/babylon-tests.ts +++ b/types/babylon/babylon-tests.ts @@ -6,13 +6,12 @@ const code = `function square(n) { return n * n; }`; -let node = babylon.parse(code); +const 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/types/babylon/index.d.ts b/types/babylon/index.d.ts index eb35a5d799..eb22f30c13 100644 --- a/types/babylon/index.d.ts +++ b/types/babylon/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for babylon v6.16.1 +// Type definitions for babylon 6.16 // Project: https://github.com/babel/babylon // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// +// TypeScript Version: 2.3 import { File, Expression } from 'babel-types'; diff --git a/types/babylon/tslint.json b/types/babylon/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babylon/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/backbone-associations/index.d.ts b/types/backbone-associations/index.d.ts index 9d0aa36614..d0681c6651 100644 --- a/types/backbone-associations/index.d.ts +++ b/types/backbone-associations/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Backbone-associations 0.6.4 // Project: https://github.com/dhruvaray/backbone-associations/ -// Definitions by: Craig Brett +// Definitions by: Craig Brett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -25,14 +25,14 @@ declare module 'backbone' { interface IRelation { /** The type of model for this relationship */ - relatedModel: string|typeof Backbone.Associations.AssociatedModel; + relatedModel: string | (new() => 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; + collectionType?: string | (new() => Backbone.Collection); /** 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. */ diff --git a/types/backbone-fetch-cache/index.d.ts b/types/backbone-fetch-cache/index.d.ts index c5e8d84426..e5e6ebf751 100644 --- a/types/backbone-fetch-cache/index.d.ts +++ b/types/backbone-fetch-cache/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for backbone-fetch-cache 1.4.0 // Project: https://github.com/madglory/backbone-fetch-cache -// Definitions by: delphinus +// Definitions by: delphinus // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/backbone-relational/index.d.ts b/types/backbone-relational/index.d.ts index b51c46f1d7..a1c8c3eefb 100644 --- a/types/backbone-relational/index.d.ts +++ b/types/backbone-relational/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Backbone-relational 0.8.5 // Project: http://backbonerelational.org/ -// Definitions by: Eirik Hoem +// Definitions by: Eirik Hoem // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/backbone.layoutmanager/index.d.ts b/types/backbone.layoutmanager/index.d.ts index f4eb340e7c..7e35de1192 100644 --- a/types/backbone.layoutmanager/index.d.ts +++ b/types/backbone.layoutmanager/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Backbone.LayoutManager 0.9.5 // Project: http://layoutmanager.org/ -// Definitions by: He Jiang +// Definitions by: He Jiang // Definitions: https://github.com/hejiang2000/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/backbone.localstorage/index.d.ts b/types/backbone.localstorage/index.d.ts index 9fd089cdec..94bb53c65a 100644 --- a/types/backbone.localstorage/index.d.ts +++ b/types/backbone.localstorage/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for backbone.localStorage 1.0.0 // Project: https://github.com/jeromegn/Backbone.localStorage -// Definitions by: Louis Grignon +// Definitions by: Louis Grignon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/backbone.paginator/index.d.ts b/types/backbone.paginator/index.d.ts index fc7c39e995..66b43c0b69 100644 --- a/types/backbone.paginator/index.d.ts +++ b/types/backbone.paginator/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for backbone.paginator 2.0.2 // Project: https://github.com/backbone-paginator/backbone.paginator -// Definitions by: Nyamazing +// Definitions by: Nyamazing // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/backbone.radio/index.d.ts b/types/backbone.radio/index.d.ts index 61c996f6de..12fc6d384f 100644 --- a/types/backbone.radio/index.d.ts +++ b/types/backbone.radio/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Backbone.Radio v0.8.3 // Project: https://github.com/marionettejs/backbone.radio -// Definitions by: Peter Palotas +// Definitions by: Peter Palotas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index f151b2f42e..806086943e 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Backbone 1.3.3 // Project: http://backbonejs.org/ -// Definitions by: Boris Yankov , Natan Vivo +// Definitions by: Boris Yankov , Natan Vivo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -111,7 +111,7 @@ declare namespace Backbone { /** * Do not use, prefer TypeScript's extend functionality. **/ - private static extend(properties: any, classProperties?: any): any; + public static extend(properties: any, classProperties?: any): any; attributes: any; changed: any[]; @@ -205,7 +205,7 @@ declare namespace Backbone { /** * Do not use, prefer TypeScript's extend functionality. **/ - private static extend(properties: any, classProperties?: any): any; + public static extend(properties: any, classProperties?: any): any; model: new (...args:any[]) => TModel; models: TModel[]; @@ -322,7 +322,7 @@ declare namespace Backbone { /** * Do not use, prefer TypeScript's extend functionality. **/ - private static extend(properties: any, classProperties?: any): any; + public 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. @@ -388,7 +388,7 @@ declare namespace Backbone { /** * Do not use, prefer TypeScript's extend functionality. **/ - private static extend(properties: any, classProperties?: any): any; + public static extend(properties: any, classProperties?: any): any; constructor(options?: ViewOptions); initialize(options?: ViewOptions): void; diff --git a/types/backgrid/index.d.ts b/types/backgrid/index.d.ts index fdf7785b59..bd8cad018c 100644 --- a/types/backgrid/index.d.ts +++ b/types/backgrid/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Backgrid 0.2.6 // Project: http://backgridjs.com/ -// Definitions by: Jeremy Lujan +// Definitions by: Jeremy Lujan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/bagpipes/bagpipes-tests.ts b/types/bagpipes/bagpipes-tests.ts index af7dfa0a31..eaa412d56b 100755 --- a/types/bagpipes/bagpipes-tests.ts +++ b/types/bagpipes/bagpipes-tests.ts @@ -56,11 +56,11 @@ const pipesConfigFullEmpty: Bagpipes.Config = { userViewsDirs: [] }; -let pipesA = Bagpipes.create(perDefsMixed, { +const pipesA = Bagpipes.create(perDefsMixed, { connectMiddlewareDirs: ['some_dir', 'ssssss'], swaggerNodeRunner: {} }); -let pipeA = pipesA.getPipe('HelloWorld'); +const pipeA = pipesA.getPipe('HelloWorld'); // log the output to standard out pipeA.fit((context, cb) => { @@ -81,7 +81,7 @@ const pipeErrTest = pipesEnty.pipes['any'].fit((context, cb) => { pipesEnty.play(pipeErrTest, {}); const fittingsC = ["xxxx", "aaa"].map((name) => { - let fittingDef = {} as Bagpipes.PipeDefMap; + const fittingDef = {} as Bagpipes.PipeDefMap; fittingDef[name] = 'nothing'; return fittingDef; }); @@ -95,6 +95,6 @@ bagpipesD.play(bagpipesD.getPipe('objPipe'), {}); // Test full create const userFittingsDirs = ['./fixtures/fittings']; const pipeWithString = ['emit']; -let contextPlain = {}; +const contextPlain = {}; const bagpipesWithPipeAndFittings = Bagpipes.create({ myCustomPipe: pipeWithString }, { userFittingsDirs }); bagpipesWithPipeAndFittings.play(bagpipesWithPipeAndFittings.getPipe('myCustomPipe'), contextPlain); diff --git a/types/bagpipes/tslint.json b/types/bagpipes/tslint.json index a4bcc87748..03a7f353ed 100755 --- a/types/bagpipes/tslint.json +++ b/types/bagpipes/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { - "callable-types": false + // TODOs + "callable-types": false, + "no-object-literal-type-assertion": false } } diff --git a/types/baidumap-web-sdk/baidumap-web-sdk-tests.ts b/types/baidumap-web-sdk/baidumap-web-sdk-tests.ts index cc525509c6..8ac6457975 100644 --- a/types/baidumap-web-sdk/baidumap-web-sdk-tests.ts +++ b/types/baidumap-web-sdk/baidumap-web-sdk-tests.ts @@ -4,8 +4,8 @@ namespace BMapTests { //document: http://lbsyun.baidu.com/index.php?title=jspopular public createMap(container: string | HTMLElement) { navigator.geolocation.getCurrentPosition((position: Position) => { - let point = new BMap.Point(position.coords.longitude, position.coords.latitude); - let map = new BMap.Map(container); + const point = new BMap.Point(position.coords.longitude, position.coords.latitude); + const map = new BMap.Map(container); map.centerAndZoom(point, 15); }, console.log, { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }); } @@ -16,7 +16,7 @@ namespace BMapTests { map.addControl(new BMap.OverviewMapControl({ isOpen: true, anchor: BMAP_ANCHOR_BOTTOM_RIGHT })); } public addMarker(map: BMap.Map, point: BMap.Point) { - var marker = new BMap.Marker(point); + const marker = new BMap.Marker(point); map.addOverlay(marker); marker.setAnimation(BMAP_ANIMATION_BOUNCE); } diff --git a/types/base64-js/base64-js-tests.ts b/types/base64-js/base64-js-tests.ts index 402ce43e88..f9bb761f22 100644 --- a/types/base64-js/base64-js-tests.ts +++ b/types/base64-js/base64-js-tests.ts @@ -2,4 +2,4 @@ import * as base64js from "base64-js"; base64js.byteLength(""); // $ExpectType number base64js.toByteArray(""); // $ExpectType Uint8Array -base64js.fromByteArray(new Uint8Array(0)); // $ExpectTpe string +base64js.fromByteArray(new Uint8Array(0)); // $ExpectType string diff --git a/types/base64url/base64url-tests.ts b/types/base64url/base64url-tests.ts deleted file mode 100644 index f9f206fbc9..0000000000 --- a/types/base64url/base64url-tests.ts +++ /dev/null @@ -1,24 +0,0 @@ -import * as base64url from "base64url"; - -// default -let str = base64url("some value"); -str = base64url("some value", "hex"); -str = base64url(new Buffer("some value")); - -// encode -str = base64url.encode("some value"); -str = base64url.encode("some value", "hex"); -str = base64url.encode(new Buffer("some value")); - -// decode -str = base64url.decode("ADA="); -str = base64url.decode("ADA=", "binary"); - -// toBase64 -str = base64url.toBase64("ADA="); -str = base64url.toBase64(new Buffer("ADA=", "base64")); - -// fromBase64 -str = base64url.fromBase64("ADA="); - -let buf = base64url.toBase64("ADA="); \ No newline at end of file diff --git a/types/base64url/index.d.ts b/types/base64url/index.d.ts deleted file mode 100644 index e99ae3d2b3..0000000000 --- a/types/base64url/index.d.ts +++ /dev/null @@ -1,72 +0,0 @@ -// Type definitions for base64url v2.0.0 -// Project: https://github.com/brianloveswords/base64url -// Definitions by: Stepan Miroshin -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -/** - * For encoding and decoding base64url! - * v2.0.0 - */ - -/** - * Encoding type - */ -declare type Encoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "utf16le" | "base64" | "binary" | "hex" - -interface IBase64Url { - /** - * Encode input to base64url - * @param {string} input Incoming input - * @param {Encoding} encoding Default 'utf8' - * @return {string} - */ - (input: string, encoding?: Encoding): string; - /** - * Encode input to base64url - * @param {Buffer} input Incoming value - */ - (inout: Buffer): string; - /** - * Encode input to base64url - * - * @param {string} input Incoming input - * @param {Encoding} encoding Default 'utf8' - * @returns {string} - */ - encode(input: string, encoding?: Encoding): string; - /** - * Encode input to base64url - * @param {Buffer} input Incoming value - */ - encode(input: Buffer): string; - /** - * Convert a base64url encoded string into a raw string. - * @param {string} base64url base64url encoded string - * @param {Encoding} encoding Encoding defaults to 'utf8' - * @returns {string} - */ - decode(base64url: string, encoding?: string): string; - /** - * Convert a base64url encoded string to a base64 encoded string - * @param {string | Buffer} base64url base64url encoded value - * @returns {string} - */ - toBase64(base64url: string | Buffer): string; - /** - * Convert a base64 encoded string to a base64url encoded string - * @param {string} base64 encoded string - * @returns {string} - */ - fromBase64(base64: string): string; - /** - * Convert a base64url encoded string to a Buffer - * @param {string} base64url encoded string - * @returns {Buffer} - */ - toBuffer(base64url: string): Buffer; -} - -declare const base64url: IBase64Url; -export = base64url; \ No newline at end of file diff --git a/types/base64url/tsconfig.json b/types/base64url/tsconfig.json deleted file mode 100644 index d362086905..0000000000 --- a/types/base64url/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "base64url-tests.ts" - ] -} \ No newline at end of file diff --git a/types/basic-auth/basic-auth-tests.ts b/types/basic-auth/basic-auth-tests.ts index e416afe352..9c03137b37 100644 --- a/types/basic-auth/basic-auth-tests.ts +++ b/types/basic-auth/basic-auth-tests.ts @@ -1,4 +1,4 @@ -import {IncomingMessage} from 'http'; +import { IncomingMessage } from 'http'; import auth = require('basic-auth'); const loginData = auth(undefined! as IncomingMessage); diff --git a/types/basic-auth/index.d.ts b/types/basic-auth/index.d.ts index 276b5b8af6..3af8f5a699 100644 --- a/types/basic-auth/index.d.ts +++ b/types/basic-auth/index.d.ts @@ -19,7 +19,7 @@ declare namespace auth { /** * Parse basic auth to object. */ - function parse(authorizationHeader: string): auth.BasicAuthResult | undefined; + function parse(authorizationHeader: string): BasicAuthResult | undefined; } export = auth; diff --git a/types/batch-stream/index.d.ts b/types/batch-stream/index.d.ts index 26c433a04b..2ab8c6b8c5 100644 --- a/types/batch-stream/index.d.ts +++ b/types/batch-stream/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for batch-stream 0.1.2 // Project: https://github.com/segmentio/batch-stream -// Definitions by: Nicholas Penree +// Definitions by: Nicholas Penree // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/bcryptjs/index.d.ts b/types/bcryptjs/index.d.ts index c081ed33fd..b19413c92d 100644 --- a/types/bcryptjs/index.d.ts +++ b/types/bcryptjs/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bcryptjs v2.4.0 // Project: https://github.com/dcodeIO/bcrypt.js -// Definitions by: Joshua Filby , Rafael Kraut +// Definitions by: Joshua Filby , Rafael Kraut // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/bem-cn/bem-cn-tests.ts b/types/bem-cn/bem-cn-tests.ts index d57e138777..97b3bae8c5 100644 --- a/types/bem-cn/bem-cn-tests.ts +++ b/types/bem-cn/bem-cn-tests.ts @@ -1,4 +1,5 @@ import * as block from "bem-cn"; +import { Settings } from "bem-cn"; // expected 'block' block("block")(); @@ -44,3 +45,10 @@ block("block")("elem"); // expected 'block block--mod-value' block("block")({ mod: "value"}); + +// I can use bem-cn interfaces +const customSettings: Settings = { + ns: 'prefix' +}; + +block.setup(customSettings); diff --git a/types/bem-cn/index.d.ts b/types/bem-cn/index.d.ts index 5a78df4435..068298f0f7 100644 --- a/types/bem-cn/index.d.ts +++ b/types/bem-cn/index.d.ts @@ -3,39 +3,39 @@ // Definitions by: Vitaly Selkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -type StateFn = (states: { [key: string]: boolean }) => Inner; +type StateFn = (states: { [key: string]: boolean }) => BemCn.Inner; +declare function BemCn(name: string): BemCn.Inner; -interface Modifications { - [key: string]: (string | boolean); +declare namespace BemCn { + function reset(): void; + function setup(settings?: Settings): void; + + interface Modifications { + [key: string]: (string | boolean); + } + + interface Inner { + (elem: string | Modifications): Inner; + (elem: string, mods: Modifications): Inner; + (): string; + + mix(mixes: string | string[]): Inner; + has: StateFn; + state: StateFn; + is: StateFn; + toString(): string; + valueOf(): string; + split(separator: string, limit?: number): string[]; + } + + interface Settings { + ns?: string; + el?: string; + mod?: string; + modValue?: string; + classMap?: { [className: string]: string } | null; + } } -interface Block { - (name: string): Inner; - - reset(): void; - setup(settings?: Settings): void; -} - -interface Inner { - (elem: string | Modifications): Inner; - (elem: string, mods: Modifications): Inner; - (): string; - - mix(mixes: string | string[]): Inner; - has: StateFn; - state: StateFn; - is: StateFn; - toString(): string; - split(separator: string, limit?: number): string[]; -} - -interface Settings { - ns?: string; - el?: string; - mod?: string; - modValue?: string; - classMap?: { [className: string]: string } | null; -} - -declare const block: Block; -export = block; +export as namespace BemCn; +export = BemCn; diff --git a/types/bem-cn/tslint.json b/types/bem-cn/tslint.json index f93cf8562a..091817f734 100644 --- a/types/bem-cn/tslint.json +++ b/types/bem-cn/tslint.json @@ -1,3 +1,7 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-duplicate-imports": false + } } diff --git a/types/better-sqlite3/better-sqlite3-tests.ts b/types/better-sqlite3/better-sqlite3-tests.ts new file mode 100644 index 0000000000..43d78e1503 --- /dev/null +++ b/types/better-sqlite3/better-sqlite3-tests.ts @@ -0,0 +1,32 @@ +import * as Database from 'better-sqlite3'; + +const integer = Database.Integer(1); +const err = new Database.SqliteError('ok', 'ok'); + +let db = Database('.'); +db = new Database('.', {memory: true}); +db.exec('CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL);'); +db.exec('INSERT INTO test(name) VALUES("name");'); +db.pragma('data_version', true); +db.checkpoint(); +db.checkpoint('main'); +db.register(() => {}); +db.register({name: 'noop', deterministic: true, varargs: true}, () => {}); +db.defaultSafeIntegers(); +db.defaultSafeIntegers(true); + +const stmt = db.prepare('SELECT * FROM test WHERE name == ?;'); +stmt.get(['name']); +stmt.all({name: 'name'}); +stmt.each('name', (row: {name: string}) => {}); +stmt.each((row: {name: string}) => {}); +stmt.pluck(); +stmt.pluck(true); +stmt.bind('name'); +stmt.safeIntegers(); +stmt.safeIntegers(true); + +const trans = db.transaction(['INSERT INTO test(name) VALUES(?);']); +trans.run('name'); +trans.bind('name'); +trans.run(); diff --git a/types/better-sqlite3/index.d.ts b/types/better-sqlite3/index.d.ts new file mode 100644 index 0000000000..98de770ccf --- /dev/null +++ b/types/better-sqlite3/index.d.ts @@ -0,0 +1,89 @@ +// Type definitions for better-sqlite3 3.1 +// Project: http://github.com/JoshuaWise/better-sqlite3 +// Definitions by: Ben Davies +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as Integer from 'integer'; + +interface RunResult { + changes: number; + lastInsertROWID: Integer.IntLike; +} + +declare class Statement { + database: Database; + source: string; + returnsData: boolean; + constructor(db: Database, sources: string[]); + + run(...params: any[]): RunResult; + get(...params: any[]): any; + all(...params: any[]): any[]; + each(params: any, cb: (row: any) => void): void; + each(cb: (row: any) => void): void; + each(...params: any[]): void; + pluck(toggleState?: boolean): this; + bind(...params: any[]): this; + safeIntegers(toggleState?: boolean): this; +} + +declare class Transaction { + database: Database; + source: string; + constructor(db: Database, sources: string[]); + + run(...params: any[]): RunResult; + bind(...params: any[]): this; + safeIntegers(toggleState?: boolean): this; +} + +interface DatabaseOptions { + memory?: boolean; + readonly?: boolean; +} + +interface RegistrationOptions { + name?: string; + varargs?: boolean; + deterministic?: boolean; + safeIntegers?: boolean; +} + +interface Database { + memory: boolean; + readonly: boolean; + name: string; + open: boolean; + inTransaction: boolean; + + prepare(source: string): Statement; + transaction(sources: string[]): Transaction; + exec(source: string): this; + pragma(source: string, simplify?: boolean): any; + checkpoint(databaseName?: string): this; + register(cb: (...params: any[]) => any): this; + register(options: RegistrationOptions, cb: (...params: any[]) => any): this; + close(): this; + defaultSafeIntegers(toggleState?: boolean): this; +} + +declare class SqliteError implements Error { + name: string; + message: string; + code: string; + constructor(message: string, code: string); +} + +interface DatabaseConstructor { + new(filename: string, options?: DatabaseOptions): Database; + (filename: string, options?: DatabaseOptions): Database; + prototype: Database; + + Integer: typeof Integer; + SqliteError: typeof SqliteError; +} + +declare const Database: DatabaseConstructor; +export = Database; diff --git a/types/better-sqlite3/tsconfig.json b/types/better-sqlite3/tsconfig.json new file mode 100644 index 0000000000..fa406408e4 --- /dev/null +++ b/types/better-sqlite3/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "better-sqlite3-tests.ts" + ] +} diff --git a/types/better-sqlite3/tslint.json b/types/better-sqlite3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/better-sqlite3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bezier-easing/index.d.ts b/types/bezier-easing/index.d.ts index 2a742daf1e..e714e55535 100644 --- a/types/bezier-easing/index.d.ts +++ b/types/bezier-easing/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bezier-easing // Project: https://github.com/gre/bezier-easing -// Definitions by: brian ridley +// Definitions by: brian ridley // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare interface Easing { diff --git a/types/big.js/index.d.ts b/types/big.js/index.d.ts index e08ee7bc57..92eb845b98 100644 --- a/types/big.js/index.d.ts +++ b/types/big.js/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for big.js // Project: https://github.com/MikeMcl/big.js/ -// Definitions by: Steve Ognibene +// Definitions by: Steve Ognibene // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/bignumber.js/bignumber.js-tests.ts b/types/bignumber.js/bignumber.js-tests.ts index 8ea0775dba..424665d8ba 100644 --- a/types/bignumber.js/bignumber.js-tests.ts +++ b/types/bignumber.js/bignumber.js-tests.ts @@ -182,7 +182,7 @@ x.floor(); y = new BigNumber(-1.3); y.floor(); -0.1 > (0.3 - 0.2); +0.1 > (0.3 - 0.2); // tslint:disable-line binary-expression-operand-order x = new BigNumber(0.1); x.greaterThan(BigNumber(0.3).minus(0.2)); BigNumber(0).gt(x); diff --git a/types/bignumber.js/index.d.ts b/types/bignumber.js/index.d.ts index d627ad136c..ae7ec5b6f7 100644 --- a/types/bignumber.js/index.d.ts +++ b/types/bignumber.js/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bignumber.js 4.0 // Project: https://github.com/MikeMcl/bignumber.js/ -// Definitions by: Viktor Smirnov +// Definitions by: Viktor Smirnov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 diff --git a/types/bigscreen/index.d.ts b/types/bigscreen/index.d.ts index 6d240729c5..0807cc61e5 100644 --- a/types/bigscreen/index.d.ts +++ b/types/bigscreen/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for BigScreen 2.0.4 // Project: http://brad.is/coding/BigScreen/ -// Definitions by: Douglas Eichelberger +// Definitions by: Douglas Eichelberger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace BigScreen; diff --git a/types/bingmaps/Autosuggest.d.ts b/types/bingmaps/Autosuggest.d.ts new file mode 100644 index 0000000000..4ccfcc9270 --- /dev/null +++ b/types/bingmaps/Autosuggest.d.ts @@ -0,0 +1,119 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module Microsoft.Maps { + /** Options used to customize the autosuggest functionality. */ + export interface IAutosuggestOptions { + /** Specifies if street address suggestions should be returned. Default: true */ + addressSuggestions?: boolean; + + /** + * Specifies if the user’s location should be auto detected using their IP address, if no location information is provided + * in the userLocation property. Default: true + */ + autoDetectLocation?: boolean; + + /** + * A bounding box that is used to help influence the results such that locations that are in or near this bounding box + * are given more weight than they would normally. + */ + bounds?: LocationRect; + + /** + * A reference to a map instance. If the useMapView property is set to true, the bounding box of the map view will be used + * to influence the weight of suggestions. + */ + map?: Map; + + /** The maximum number of results to return. Can be any value between 1 and 10. Default: 5 */ + maxResults?: number; + + /** Specifies if place suggestions (city, landmark, etc.) should be returned. Default: true */ + placeSuggestions?: boolean; + + /** + * Indicates if the maps bounding box should be used to influence the suggested results. Ignored if the bounds property is + * set. Default: true + */ + useMapView?: boolean; + + /** A coordinate indicating where the user is located. This will influence the results to be more relevant to the user. */ + userLocation?: Location; + } + + /** Represents the suggestion result from the Autosuggest manager. */ + export interface ISuggestionResult { + /** A structured address object for the result. */ + address: IAddress; + + /** A LocationRect that can be used to set the map view over the result. */ + bestView: LocationRect; + + /** Unique entity id to be used for searching the entity. */ + entityId: string; + + /** The type of the result; Address, Place */ + entityType: string; + + /** The sub type of result; Address, RoadBlock, PopulatedPlace, CountryRegion, etc. */ + entitySubType: string; + + /** A nicely formatted suggestion string for the result based on market. */ + formattedSuggestion: string; + + /** + * The coordinate of the result. This value is only returned for place (city, landmarks) results and not for addresses. + * Street addresses will need to be geocoded to get their location. + */ + location: Location; + + /** A secondary title that provides additional context to the title value of the suggestion. **/ + subtitle: string; + + /** The display title for the result (i.e. “Redmond”). */ + title: string; + } + + /** + * The AutosuggestManager is the primary class in the Autosuggest module that powers the autosuggest functionality. + * @requires The Microsoft.Maps.Autosuggest module. + */ + export class AutosuggestManager { + /** + * @constructor + * @requires The Microsoft.Maps.Autosuggest module. + * @param options The options to use with the autosuggest manager. + */ + constructor(options?: IAutosuggestOptions); + + /** + * Attaches the Autosuggest functionality to an input box. + * @param suggestionBoxId The HTML element identifier of the input box. + * @param suggestionContainerId The Id of container where suggestions will be displayed. + * @param selectedSuggestionCallback A reference to a callback function that will be called when a user selects a suggestion from the Autosuggest UI. + */ + public attachAutosuggest(suggestionBoxId: string, suggestionContainerId: string, selectedSuggestionCallback: (result: ISuggestionResult) => void) : void; + + /** Detaches the autosuggest functionality from the input box, freeing any resources it has or events it has tied to. */ + public detachAutosuggest(): void; + + /** Disposes the Autosuggest object, freeing any resources it has or events it has tied to. */ + public dispose(): void; + + /** + * Gets the options currently used by the autosuggest manager. + * @returns The options currently used by the autosuggest manager. + */ + public getOptions(): IAutosuggestOptions; + + /** + * Sets the options currently used by the autosuggest manager. + * @param options The options to use with the autosuggest manager. + */ + public setOptions(options?: IAutosuggestOptions): void; + } +} \ No newline at end of file diff --git a/types/bingmaps/Clustering.d.ts b/types/bingmaps/Clustering.d.ts new file mode 100644 index 0000000000..a936653d3b --- /dev/null +++ b/types/bingmaps/Clustering.d.ts @@ -0,0 +1,149 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module Microsoft.Maps { + /** The options used to customize how the ClusterLayer functions. */ + export interface IClusterLayerOptions { + /** + * A callback function that is fired after the clustering for a map view has completed. This is useful if you want to generate a list of locations based on what is in the current view. + */ + callback?: () => void; + + /** + * A callback function that allows you to process a clustered pushpin before it is added to a layer. This is useful if you want to add events or set style options on the clustered pushpin. + */ + clusteredPinCallback?: (pin: ClusterPushpin) => void; + + /** + * Indicates if the layer should cluster the locations or not. Default: true + */ + clusteringEnabled?: boolean; + + /** + * Defines how clusters are positioned on the map. Default: MeanAverage + */ + clusterPlacementType?: ClusterPlacementType; + + /** + * The width and height of the gird cells used for clustering in pixels. Default: 45 + */ + gridSize?: number; + + /** + * Offsets the placement of clustered pushpins by a set number of pixels. This option is only available when the placement type is set to GridCenter. + * This is useful if you have multiple cluster layers on the map and you want to offset the clustered pushpins between the layers so that they are visible, + * otherwise the clusters from the different layers would overlap completely. + */ + layerOffset?: Point; + + /** + * A boolean indicating if the layer is visible or not. + */ + visible?: boolean; + + /** + * The z-index of the layer. + */ + zIndex?: number; + } + + /** + * Used to specify how a clustered pushpin should be positioned relative to the pushpins it contains. + * @requires The Microsoft.Maps.Clustering module. + */ + export enum ClusterPlacementType { + /** + * Mean Average placement calculates the average position of a group of coordinates. This method creates a more realistic representation of the data, + * however requires more processing power and increases the chances of pushpins overlapping. + */ + MeanAverage, + + /** + * This method is the simplest way to represent a cluster. It places the cluster at the first location in the cluster. This method may not accurately + * represent the data but requires little processing power. + */ + FirstLocation + } + + /** + * This class extends the Pushpin class and has all the same methods and properties plus the following properties. + * @requires The Microsoft.Maps.Clustering module. + */ + export class ClusterPushpin extends Pushpin { + /** An array of all the pushpins that are in the cluster. */ + containedPushpins: Pushpin[]; + + /** + * The grid cell key that can be used retrieve the clustered pushpin(s) from the clustering layer. This is useful when creating a clickable list that + * link items in the list to clusters or pushpins on the map. Your list just needs to store the gridKey value. + */ + gridKey: number; + } + + /** + * This class allows you to easily add in client side clustering to your application. Client Side Clustering is a method where pushpins that are close + * together are grouped and represented as a single pushpin, often using a different icon to indicate the cluster. This is a great way to improve both + * the user experience and performance of the map. + * @requires The Microsoft.Maps.Clustering module. + */ + export class ClusterLayer implements IDataLayer { + /** + * @constructor + * @requires The Microsoft.Maps.Clustering module. + * @param pushpins An array of pushpins to cluster in the layer. + * @param options The options used to customize how the ClusterLayer functions. + */ + constructor(pushpins: Pushpin[], options?: IClusterLayerOptions); + + /** Clears all the data in the cluster layer. */ + public clear(): void; + + /** + * Gets all the pushpins that are in the current map view. If clustering is disabled, all pushpins in the clustering layer are returned. + * @returns All the pushpins that are in the current map view. If clustering is disabled, all pushpins in the clustering layer are returned. + */ + public getDisplayedPushpins(): Pushpin[]; + + /** + * Gets the current options used by the cluster layer. + * @returns The current options used by the cluster layer. + */ + public getOptions(): IClusterLayerOptions; + + /** + * Gets all pushpins that are in the layers. + * @returns An array of all the pushpins that are in the layers. + */ + public getPushpins(): Pushpin[]; + + /** + * Gets the original pushpins that are in the specified grid cell. + * @param The gridKey index to retrieve the pushpins for. + * @returns The original pushpins that are in the specified grid cell. + */ + public getPushpinsByGridKey(gridKey: number): Pushpin[]; + + /** + * Gets the pushpin in the specified cluster grid cell which can be either a ClusterPushpin if there are multiple pushpins in a cell or a single Pushpin. + * @param The gridKey index to retrieve the pushpins for. + * @returns The pushpin in the specified cluster grid cell which can be either a ClusterPushpin if there are multiple pushpins in a cell or a single Pushpin. + */ + public getClusterPushpinByGridKey(gridKey: number): ClusterPushpin | Pushpin; + + /** + * Sets the clustering options to use in the layer. + * @params options The clustering options to use in the layer. + */ + public setOptions(options: IClusterLayerOptions): void; + + /** + * Sets the array of pushpins that are used in the clustering layer. + * @param pushpins An array of pushpins that are to be used by the clustering layer. + */ + public setPushpins(pushpins: Pushpin[]): void; + } +} \ No newline at end of file diff --git a/types/bingmaps/Contour.d.ts b/types/bingmaps/Contour.d.ts new file mode 100644 index 0000000000..8bc80e70b9 --- /dev/null +++ b/types/bingmaps/Contour.d.ts @@ -0,0 +1,94 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module Microsoft.Maps { + + /** + * The contour layer options + */ + interface IContourLayerOptions { + /** The z-index of this layer */ + zIndex?: number; + + /** Whether the layer is visible */ + visible?: boolean; + + /** A callback function which defines the color of the contour line fill. */ + colorCallback?: (contourValue: number | string) => string | Color; + + /** The polygon options that apply to all contour lines of this layer */ + polygonOptions?: IPolygonOptions; + } + + /** + * The contour line of a contour layer + */ + export class ContourLine extends Polygon { + /** The contour lines that are directly nested inside this contour line */ + public innerContourLines: ContourLine[]; + + /** The outer/parent contour line of this contour */ + public outerContourLine: ContourLine; + + /** The data value associated with this contour line */ + public contourValue: number | string; + + /** + * @constructor + * @param boundary The boundary of this contour line + * @param contourValue The value associated with this contour line + */ + constructor(boundary: Location[], contourValue?: number | string); + } + + /** + * The contour layer class. + */ + export class ContourLayer extends Layer { + /** + * @constructor + * @param contourLines The contour lines that compose this layer. + * @param options The contour layer options. + */ + constructor(contourLines: ContourLine[], options?: IContourLayerOptions); + + /** + * Clears all data on the contour layer. + */ + public clear(): void; + + /** + * Gets the contour lines of this layer. + * @returns The contour lines of this layer. + */ + public getContourLines(): ContourLine[]; + + /** + * Gets the polygons that were generated from the contour lines in this layer. + * @returns The polygons that were generated from the contour lines in this layer. + */ + public getContourPolygons(): Polygon[]; + + /** + * Retrieves the options of this contour layer. + * @returns The options of this contour layer. + */ + public getOptions(): IContourLayerOptions; + + /** + * Sets the contour lines used to calculate the polygon areas of this layer. + * @param contourLines The contour lines used to calculate the polygon areas of this layer. + */ + public setContourLines(contourLines: ContourLine[]): void; + + /** + * Sets the options of the contour layer. + * @param options The new options to update the layer. + */ + public setOptions(options: IContourLayerOptions): void; + } +} \ No newline at end of file diff --git a/types/bingmaps/DataBinning.d.ts b/types/bingmaps/DataBinning.d.ts new file mode 100644 index 0000000000..548a9cc681 --- /dev/null +++ b/types/bingmaps/DataBinning.d.ts @@ -0,0 +1,154 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module Microsoft.Maps { + + /** + * Specifies the shape of data bin rendered in the layer. + */ + export enum DataBinType { + /* Renders data bins as circles in a square grid. */ + circle, + + /* Renders data bins as hexagons with a flat top edge. */ + hexagon, + + /* Renders data bins as circles in a hexagonal grid. */ + hexCircle, + + /* Renders data bins as hexagons with a pointy top corner. */ + pointyHexagon, + + /* Renders data bins as a square grid. */ + square + } + + /** + * A set options the define how a data binning layer is rendered. + */ + export interface IDataBinningOptions { + /* The name of a property in the Pushpin.metadata object on which to perform calculations (average, count, sum) against the pushpins in each data bin. */ + aggregationProperty?: string; + + /* + * A callback function which defines the color a data bin polygon should be. This callback recieves data bin information + * along with the min and max calculated metrics for the data set. If set, this callback function must return a color value. + */ + colorCallback?: (binInfo: IDataBinInfo, min: IDataBinMetrics, max: IDataBinMetrics) => string | Color; + + /* The shape of the data bin to generate. Default: hexagon */ + dataBinType?: DataBinType; + + /* The distance units of the radius option. Default: meters */ + distanceUnits?: SpatialMath.DistanceUnits; + + /* The default options used for rendering the data bin polygons. */ + polygonOptions?: IPolygonOptions; + + /* + * A spatial distance which will be converted into a pixel distance at the equater and used to generate symetrically sized data bins + * that have the apprimate spatial distance radius. Default: 1000 + */ + radius?: number; + + /* + * A callback function which defines how much to scale a data bins size. This callback recieves data bin information + * along with the min and max calculated metrics for the data set. If set, this callback function must return a number between 0 and 1. + */ + scaleCallback?: (binInfo: IDataBinInfo, min: IDataBinMetrics, max: IDataBinMetrics) => number; + } + + /** + * A set of values calculated from the pushpins in a data bin. + */ + export interface IDataBinMetrics { + + /* The average value of the aggregation property of the pushpins in a data bin. */ + average?: number; + + /* The number of pushpins in a data bin. */ + count?: number; + + /* The number of pushpins in the data bin who's aggregation property has a value. */ + countNotBlank?: number; + + /* The number of pushpins in the data bin who's aggregation property is a valid number. */ + countNumbers?: number; + + /* The sum of the aggregation property of the pushpins in a data bin. */ + sum?: number; + } + + /** + * The result of a calculated data bin. + */ + export interface IDataBinInfo { + /* An array of all the pushpins that are in the data bin. */ + containedPushpins: Microsoft.Maps.Pushpin[]; + + /* A set of calculated metric values determined using the aggregationProperty value of all the pushpins contained in the data bin. */ + metrics: IDataBinMetrics; + } + + /** + * A polygon which represents a data bin on the map and contains the data bin information. + */ + + export class DataBinPolygon extends Polygon { + /* Information about the data bin; the contained pushpins and calculated metrics. */ + public dataBinInfo: IDataBinInfo; + } + + /** + * This class provides a data binning visualization for the map. It takes in an array of pushpins, groups them into + * symmetrical shapes that fit together in a grid such as hexagons. Aggregation of data values are done and can be + * used to customize how the data bins are rendered on the map (i.e. scale / color) . + */ + export class DataBinningLayer extends Layer { + /** + * Initializes the data binning layer. + * @param pushpins The array of pushpins that are used to generate the data bins. + * @param options The options used for calculating and rendering the data bins. + */ + constructor(pushpins?: Pushpin[], options?: IDataBinningOptions); + + /** + * Gets the options used for calculating and rendering the data bins. + * @returns The options used for calculating and rendering the data bins. + */ + public getOptions(): IDataBinningOptions; + + /** + * Gets all pushpins that are in the layers. + * @returns All pushpins that are in the layers. + */ + public getPushpins(): Pushpin[]; + + /** + * Sets the array of pushpins that are used to generate the data bins. + * @param pushpins The array of pushpins that are used to generate the data bins. + */ + public setPushpins(pushpins: Pushpin[]): void; + + /** + * Clears all the data in the data binning layer. + */ + public clear(): void; + + /** + * Cleans up any resources this object is consuming. + */ + public dispose(): void; + + /** + * Sets the options used for calculating and rendering the data bins. + * @param options The options used for calculating and rendering the data bins. + */ + public setOptions(options: IDataBinningOptions): void; + } +} \ No newline at end of file diff --git a/types/bingmaps/Directions.d.ts b/types/bingmaps/Directions.d.ts new file mode 100644 index 0000000000..80a3bd5a07 --- /dev/null +++ b/types/bingmaps/Directions.d.ts @@ -0,0 +1,618 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module Microsoft.Maps.Directions { + ///////////////////////////////////// + /// Enumerations + //////////////////////////////////// + + /** Distance units for calculating the directions in. */ + export enum DistanceUnit { + + /** A distance in Kilometers. */ + km, + + /** A distance in Miles. */ + miles + } + + /** Defines the type of route to calculate. */ + export enum RouteMode { + /** Driving directions are calculated. */ + driving, + + /** Transit directions are calculated. */ + transit, + + /** Walking directions are calculated. */ + walking + } + + /** Defines features to avoid when calculating the route. */ + export enum RouteAvoidance { + /** Calculate the best route using any travel option available. */ + none = 0, + + /** Reduce the use of limited access highways when calculating the route. */ + minimizeHighways = 1, + + /** Reduce the use of roads with tolls when calculating the route. */ + minimizeToll = 2, + + /** Avoid using limited access highways when calculating the route. */ + avoidHighways = 4, + + /** Avoid using roads with tolls when calculating the route. */ + avoidToll = 8, + + /** Avoid using express trains when calculating the route. This option only affects routes with a transitRouteMode that have the culture set to ja-jp. */ + avoidExpressTrain = 16, + + /** Avoid using airlines when calculating the route. This option only affects routes with a transitRouteMode that have the culture set to ja-jp. */ + avoidAirline = 32, + + /** Avoid using bullet trains when calculating the route. This option only affects routes with a transitRouteMode that have the culture set to ja-jp. */ + avoidBulletTrain = 64 + } + + /** Response codes for a route calculation request. */ + export enum RouteResponseCode { + /** The route was successfully calculated. */ + success = 0, + + /** An unknown error has occurred. */ + unknownError = 1, + + /** A nearby road cannot be found for one or more of the route waypoints. */ + cannotFindNearbyRoad = 2, + + /** + * The distance between two route waypoints, or the total length of the route exceeds the limit of the route mode. + * Modify the waypoint locations so that they are closer together. + */ + tooFar = 3, + + /** + * A route cannot be calculated for the specified waypoints. For example, this code is returned when a route between + * “Seattle, WA” and “Honolulu, HI” is requested. + */ + noSolution = 4, + + /** There is no route data for the specified waypoints. */ + dataSourceNotFound = 5, + + /** There are no transit options available for the specified time. */ + noAvailableTransitTrip = 7, + + /** The transit stops are so close that walking is always a better option. */ + transitStopsTooClose = 8, + + /** The transit stops are so close that walking is a better option. */ + walkingBestAlternative = 9, + + /** + * There is no transit data available for the route or for one or more of the specified waypoints, + * or the waypoints are in different transit areas that do not overlap. + */ + outOfTransitBounds = 10, + + /** The directions calculation request has timed out. */ + timeOut = 11, + + /** + * One or more waypoints need to be disambiguated. This error does not occur if the + * autoDisplayDisambiguation directions render option is set to true. + */ + waypointDisambiguation = 12, + + /** One or more waypoints do not have an address or location specified. */ + hasEmptyWaypoint = 13, + + /** The maximum number of waypoints, which is 25, has been exceeded. */ + exceedMaxWaypointLimit = 14, + + /** At least two waypoints are required to calculate a route. */ + atleastTwoWaypointRequired = 15, + + /** The first or last waypoint is a via point, which is not allowed. */ + firstOrLastStoppointIsVia = 16, + + /** The search service failed to return results. */ + searchServiceFailed = 17, + + /** The credentials passed to the Directions module are invalid. */ + invalidCredentials = 18 + } + + /** Defines optimization options for calculating directions. */ + export enum RouteOptimization { + /** Calculate a route the shortest time. */ + shortestTime = 0, + + /** Calculate a route with the shortest distance. */ + shortestDistance = 1, + + /** The route is calculated to minimize the time and uses current traffic information. */ + timeWithTraffic = 2, + + /** The route is calculated to minimize the time and avoid road closures. Traffic information is not used in the calculation. */ + timeAvoidClosure = 3, + + /** Minimize the cost when calculating directions. This option only affects routes with a transitRouteMode that have the culture set to ja-jp.*/ + minimizeMoney = 4, + + /** Minimize transit transfers when calculating directions. This option only affects routes with a transitRouteMode that have the culture set to ja-jp.*/ + minimizeTransfers = 5, + + /** Minimize the amount of walking when calculating directions. This option only affects routes with a transitRouteMode that have the culture set to ja-jp.*/ + minimizeWalking = 6 + } + + /** An enumeration that specifies the releance of a dateTime when calculating a route. */ + export enum TimeType { + /** The dateTime parameter contains the desired arrival time for a transit request. */ + arrival, + + /** The dateTime parameter contains the desired departure time for a transit request. */ + departure, + + /** The dateTime parameter should be ignored and the first available transit taken. */ + firstAvailable, + + /** The dateTime parameter contains the latest departure time available for a transit request. */ + lastAvailable + } + + ///////////////////////////////////// + /// Interfaces + //////////////////////////////////// + + /** Contains the arguments for directions events. */ + export interface IDirectionsEventArgs { + /** The calculated route (or routes, if the route mode is transit). */ + route: IRoute[]; + + /** The route summary (or summaries) of the route(s) defined in the route property. */ + routeSummary: IRouteSummary[]; + } + + /** Contains arguments for directions error events. */ + export interface IDirectionsErrorEventArgs { + /** The code which identifies the error that occurred. */ + responseCode: RouteResponseCode; + + /** The error message. */ + message: string; + } + + /** Represents one direction in a set of route directions. */ + export interface IDirectionsStep { + /** The child direction items for this directions step. */ + childItineraryItems: IDirectionsStep[]; + + /** The location of the start of the direction. */ + coordinate: Location; + + /** The total distance of the step in the unit specified in the distanceUnit property of the DirectionsRequestOptions. */ + distance: string; + + /** The total time, in seconds, of the direction step. */ + durationInSeconds: number; + + /** The HTML formatted route instruction associated with the step. */ + formattedText: string; + + /** A boolean indicating whether the maneuver image is a road shield image. */ + isImageRoadShield: boolean; + + /** The name of the maneuver image. */ + maneuverImageName: string; + + /** An array of strings, where each string is a hint to help determine when to move to the next direction step. Not all direction steps have hints. */ + postIntersectionHints: string[]; + + /** An array of strings, where each string is a hint to help determine when you have arrived at this direction step. Not all direction steps have hints. */ + preIntersectionHints: string[]; + + /** The name of the transit stop where this step originates. */ + startStopName: string; + + /** The transit line associated with this step. */ + transitLine: ITransitLine; + + /** The URL of the image to use for transit direction steps. */ + transitStepIcon: string; + + /** The ID of the transit stop. */ + transitStopId: string; + + /** The name of the transit line end. */ + transitTerminus: string; + } + + /** Represents a route. */ + export interface IRoute { + /** The legs of the route. Each route leg represents the route between two waypoints. */ + routeLegs: IRouteLeg[]; + + /** An array of locations that makes up the path of the route. */ + routePath: Location[]; + } + + /** Represents a leg of a route. A route leg is the part of the route between two stop waypoints. */ + export interface IRouteLeg { + /** The end time of the route leg. This property only applies when the routeMode of the DirectionsRequestOptions is set to transit. */ + endTime: Date; + + /** The location of the last waypoint of this leg. */ + endWaypointLocation: Location; + + /** The directions steps associated with this route leg. */ + itineraryItems: IDirectionsStep[]; + + /** The index of the route to which this route leg belongs. */ + originalRouteIndex: number; + + /** The start time of the route leg. This property only applies when the routeMode of the DirectionsRequestOptions is set to transit. */ + startTime: Date; + + /** The location of the first waypoint of this route leg. */ + startWaypointLocation: Location; + + /** The sub legs of this route leg. A sub leg of a route is the part of the route between a stop point and a via point or between two via points.*/ + subLegs: IRouteSubLeg[]; + + /** The summary which describes this route leg. */ + summary: IRouteSummary; + } + + /** Represents a route sub leg. A route sub leg is the part of the route between a stop point and a via point or between two via points. */ + export interface IRouteSubLeg { + /** The location of the last waypoint of the sub leg. */ + actualEnd: Location; + + /** The location of the first waypoint of the sub leg. */ + actualStart: Location; + + /** The description of the last waypoint of the sub leg. */ + endDescription: string; + + /** The description of the first waypoint of the sub leg. */ + startDescription: string; + } + + /** Represents a route summary. */ + export interface IRouteSummary { + /** The total travel distance of the route */ + distance: number; + + /** The cost of the route. This property is only returned if the routeMode of the IDirectionsRequestOptions is set to transit and the map culture is set to ja-jp. */ + monetaryCost: number; + + /** The location of the northeast corner of bounding box that defines the best map view of the route. */ + northEast: Location; + + /** The location of the southwest corner of bounding box that defines the best map view of the route. */ + southWest: Location; + + /** The total travel time, in seconds, for the route. */ + time: number; + + /** + * The total travel time, in seconds, taking into account traffic delays, for the route. + * This property is 0 if the avoidTraffic property of the IDirectionsRequestOptions is set to false. + */ + timeWithTraffic: number; + } + + /** Contains information about a transit line. */ + export interface ITransitLine { + /** The short name for the transit line. */ + abbreviatedName: string; + + /** The ID of the agency that owns the transit line. */ + agencyId: number; + + /** The name of the agency that owns the transit line. */ + agencyName: string; + + /** The URL of the website of the agency that owns the transit line. */ + agencyUrl: string; + + /** Phone number for the transit agency. */ + phoneNumber: string; + + /** Information about the provider of this transit line data. */ + providerInfo: string; + + /** The uri for the transit agencies website. */ + uri: string; + + /** The full name of this transit line. */ + verboseName: string; + } + + /** Options that can be used to define a waypoint. */ + export interface IWaypointOptions { + /** + * The address string of the waypoint. For example, the following strings are valid for this parameter: "Seattle", "1 Microsoft Way, Redmond, WA". Either the address or location property must be specified. + */ + address?: string; + + /** + * A boolean indicating whether the waypoint is a via point. A via point is a point along the route that is not a stop point. Set this property to + * true if you just want the route to pass through this location. Default: false + */ + isViaPoint?: boolean; + + /** The location of the waypoint. Either the address or location property must be specified. */ + location?: Location; + } + + /** Contains options for the directions to calculate. */ + export interface IDirectionsRequestOptions { + /** The unit to use when displaying direction distances. */ + distanceUnit?: DistanceUnit; + + /** The number of routes to calculate. */ + maxRoutes?: number; + + /** The features to avoid when calculating the route. */ + routeAvoidance?: RouteAvoidance[]; + + /** A boolean indicating whether the route line on the map can be dragged with the mouse cursor. */ + routeDraggable?: boolean; + + /** If multiple routes are returned, the index of the route and directions to display. */ + routeIndex?: number; + + /** The type of directions to calculate. */ + routeMode?: RouteMode; + + /** The optimization setting for the route calculation. */ + routeOptimization?: RouteOptimization; + + /** The type of the time specified. The default value is departure. */ + timeType?: TimeType; + + /** The time to use when calculating the route. If this property is set to null, the current time is used */ + time?: Date; + } + + /** Represents render options for a route. */ + export interface IDirectionsRenderOptions { + /** A boolean indicating whether to automatically set the map view to the best map view of the calculated route. Default: true */ + autoUpdateMapView?: boolean; + + /** A boolean indicating whether to display the disclaimer about the accuracy of the directions. Default: true */ + displayDisclaimer?: boolean; + + /** A boolean indicating whether to display the icons for each direction maneuver. Default: true */ + displayManeuverIcons?: boolean; + + /** A boolean indicating whether to display direction hints that describe when a direction step was missed. Default: true */ + displayPostItineraryItemHints?: boolean; + + /** + * A boolean indicating whether to display direction hints that describe what to look for before you come to the next + * direction step. The default value is true. + */ + displayPreItineraryItemHints?: boolean; + + /** A boolean indicating whether to display the route selector control. Default: true */ + displayRouteSelector?: boolean; + + /** A boolean indicating whether to display direction warnings. Default: true */ + displayStepWarnings?: boolean; + + /** A boolean indicating whether to display a warning about walking directions. Default: true */ + displayWalkingWarning?: boolean; + + /** The polyline options that define how to draw the route line on the map, if the RouteMode is driving. */ + drivingPolylineOptions?: IPolylineOptions; + + /** The pushpin options that define how the first waypoint should be rendered. */ + firstWaypointPushpinOptions?: IPushpinOptions; + + /** The DOM element inside which the directions itinerary will be rendered. */ + itineraryContainer?: HTMLElement; + + /** The pushpin options that define how the last waypoint should be rendered. */ + lastWaypointPushpinOptions?: IPushpinOptions; + + /** A boolean indicating whether to show the input panel. Default: false */ + showInputPanel?: boolean; + + /** The options that define how to draw the route line on the map, if the RouteMode is transit. */ + transitPolylineOptions?: IPolylineOptions; + + /** The options that define how to draw the route line on the map, if the RouteMode is walking. */ + walkingPolylineOptions?: IPolylineOptions; + + /** The options that define the pushpin to use for all route waypoints by default. The first and last waypoints in the route will be overriden by firstWaypointPushpinOptions and lastWaypointPushpinOptions if set. */ + waypointPushpinOptions?: IPushpinOptions; + } + + ///////////////////////////////////// + /// Classes + //////////////////////////////////// + + /** An object used to define a start, end or stop location along a route. */ + export class Waypoint { + /** + * @constructor + * @param options: Options used to define the Waypoint. + */ + constructor(options: IWaypointOptions); + + /** Releases any resources associated with the waypoint. */ + public dispose(): void; + + /** + * Gets the address associated with the waypoint. + * @returns The address associated with the waypoint. + */ + public getAddress(): string; + + /** + * Gets the location of the waypoint. + * @returns The location of the waypoint. + */ + public getLocation(): Location; + + /** + * Gets a boolean value indicating whether the waypoint is a via point. + * @returns A boolean value indicating whether the waypoint is a via point. + */ + public isViapoint(): boolean; + + /** + * Sets options for the waypoint. For these options to take effect, you must recalculate the route. + * @param options Options used to define the Waypoint. + */ + public setOptions(options: IWaypointOptions): void; + } + + /** The main class in the Directions module that process direction calculations and rendering. */ + export class DirectionsManager { + + /** + * @constructor + * @param map A map to calculate directions for. + * @param waypoints An array of waypoints to be added to the route. + */ + constructor(map: Map, waypoints?: Waypoint[]); + + /** + * Adds a waypoint to the route at the given index, if specified. If an index is not specified, the waypoint is added as the last waypoint in the route. The maximum number of walking or driving waypoints is 25. The maximum number of transit waypoints is 2. Up to 10 via points are allowed between two stop waypoints. To recalculate the route, use calculateDirections. + * @param waypoint The waypoint to be added to the directions manager. + * @param index An index at which the waypoint is to be added. + */ + public addWaypoint(waypoint: Waypoint, index?: number): void; + + /** + * Calculates directions based on request and render options set + */ + public calculateDirections(): void; + + /** Clears the directions request and render options and removes all waypoints */ + public clearAll(): void; + + /** + * Clears the directions displayed and removes the route line from the map. + * This method does not remove waypoints from the route and retains all calculated direction information and option settings. + */ + public clearDisplay(): void; + + /** Deletes the DirectionsManager object and releases any associated resources. */ + public dispose(): void; + + /** + * Gets all the waypoints in the directions manager. + * @returns All the waypoints in the directions manager. + */ + public getAllWaypoints(): Waypoint[]; + + /** + * Gets the currently displayed route information. + * @returns The currently displayed route information. + */ + public getCurrentRoute(): IRoute; + + /** + * Gets the route render options. + * @returns The route render options + */ + public getRenderOptions(): IDirectionsRenderOptions; + + /** + * Gets the directions request options. + * @returns The directions request options. + */ + public getRequestOptions(): IDirectionsRequestOptions; + + /** + * Gets the current calculated route(s) + * @returns The current calculated route(s). If the route was not successfully calculated, null is returned. + */ + public getRouteResult(): IRoute[]; + + /** + * Removes the given waypoint or the waypoint identified by the given index from the route. + * @param waypointOrIndex A Waypoint object to be removed or the index of the waypoint to be removed + */ + public removeWaypoint(waypointOrIndex: Waypoint | number): void; + + /** + * Sets the specified render options for the route. + * @param options The options that customize the rendering of the calculated route. + */ + public setRenderOptions(options: IDirectionsRenderOptions): void; + + /** + * Sets the specified route calculation options. + * @param options The route calculation options. + */ + public setRequestOptions(options: IDirectionsRequestOptions): void; + + /** + * Displays an input panel for calculating directions in the specified container. Provides autosuggest for location inputs. + * @param inputContainerId The id name of the HTML container in which to render the directions input panel. + */ + public showInputPanel(inputContainerId: string): void; + } +} + +declare module Microsoft.Maps { + /** A static class that manages events within the map SDK. */ + module Events { + ///////////////////////////////////// + /// addHandler Definitions + //////////////////////////////////// + + /** + * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * • directionsError + * • directionsUpdated + * @param handler The callback function to handle the event when triggered. + * @returns The handler id. + */ + export function addHandler(target: Directions.DirectionsManager, eventName: string, handler: (eventArg?: Directions.IDirectionsEventArgs | Directions.IDirectionsErrorEventArgs) => void): IHandlerId; + + ///////////////////////////////////// + /// addOne Definitions + //////////////////////////////////// + + /** + * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * • directionsError + * • directionsUpdated + * @param handler The callback function to handle the event when triggered. + */ + export function addOne(target: Directions.DirectionsManager, eventName: string, handler: (eventArg?: Directions.IDirectionsEventArgs | Directions.IDirectionsErrorEventArgs) => void): void; + + ///////////////////////////////////// + /// addThrottledHandler Definitions + //////////////////////////////////// + + /** + * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * • directionsError + * • directionsUpdated + * @param handler The callback function to handle the event when triggered. + * @param throttleInterval throttle interval (in ms) + * @returns The handler id. + */ + export function addThrottledHandler(target: Directions.DirectionsManager, eventName: string, handler: (eventArg?: Directions.IDirectionsEventArgs | Directions.IDirectionsErrorEventArgs) => void, throttleInterval: number): IHandlerId; + } +} diff --git a/types/bingmaps/DrawingTools.d.ts b/types/bingmaps/DrawingTools.d.ts new file mode 100644 index 0000000000..8bdc7e8b21 --- /dev/null +++ b/types/bingmaps/DrawingTools.d.ts @@ -0,0 +1,241 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module Microsoft.Maps { + /** An object that contains the event arguments for when the drawing mode changes in the drawing tools. **/ + export interface IDrawingModeChangedData { + + /** The shape being modified by the drawing tools. **/ + shape: IPrimitive; + + /** The new drawing mode. **/ + mode: DrawingTools.DrawingMode; + } + + /** + * The DrawingManager class manages the ability to draw and edit multiple shapes on the map. Shapes managed by this class are rendered on a separate drawing layer. + * User can use a mouse or a touch screen to draw on the map. When they are done, pressing the escape button or any button on the toolbar will exit the current drawing mode. + * This class does not have a publicly accessible constructor and can only be accessed using the showDrawingManager of the DrawingTools class. + */ + export interface DrawingManager { + /** + * Adds a shapes to the layer, at the specified index if specified. + • @param data The shape(s) to be added to the layer. + • @param index The index at which to insert the shape into the layer. + */ + add(data: IPrimitive | IPrimitive[], index?: number): void; + + /** + * Disposes the drawing manager instance. + */ + dispose(): void; + + /** + * Resets the drawing manager and clears all shapes in the drawing layer. + */ + clear(): void; + + /** + * Gets the current drawing mode of the drawing manager. + * @returns The current drawing mode of the drawing manager. + */ + getDrawingMode(): DrawingTools.DrawingMode; + + /** + * Gets an array of shapes that are in the layer. This can be used to iterate over the individual shapes. + * @returns An array of shapes that are in the layer. This can be used to iterate over the individual shapes. + */ + getPrimitives(): IPrimitive[]; + + /** + * Returns the index of the shape in the drawing layer. + * @param primitive The shape to find the index of. + * @param fromIndex The index to start the search from. + * @returns The index of the shape in the drawing layer. Returns -1 if shape is not found. + */ + indexOf(primitive: IPrimitive, fromIndex?: number): number; + + /** + * Removes a shape from the layer and returns it. + * @param primitive The shape to remove from the layer. + * @returns The shape that was removed from the layer. + */ + remove(primitive: IPrimitive): IPrimitive; + + /** + * Removes a shape from the layer at the specified index. + * @param index The index of the shape to remove from the layer. + * @returns The shape that was removed from the layer. + */ + removeAt(index: number): IPrimitive; + + /** + * Sets the drawing mode of the drawing manager. + * @param mode The drawing mode to set the DrawingManager to. + */ + setDrawingMode(mode: DrawingTools.DrawingMode): void; + + /** + * Replaces all shapes in the layer with the new array of shapes that have been provided. + * @param primitives An array of shapes to add to the drawing layer. + */ + setPrimitives(primitives: IPrimitive[]): void; + } + + /** + * Provides a set of tools for drawing and editing shapes on top of the map. + * @requires The Microsoft.Maps.DrawingTools module. + */ + export class DrawingTools { + /** + * @constructor + * @requires The Microsoft.Maps.DrawingTools module. + * @param map A map instanct to attach the drawing tools to. + */ + constructor(map: Map); + + /** + * Initializes the drawing layer and instructs it to create a new shape of a given type. + * @param shapeType The type of new shape to create. + * @param created A callback function that is fired after the initial shape is created. + */ + public create(shapeType: DrawingTools.ShapeType, created?: (shape: IPrimitive) => void): void; + + /** Disposes the instance of the DrawingTools class. */ + public dispose(): void; + + /** + * Adds a shape to the drawing layer and puts it into edit mode. + * @param shape A shape to put into editting mode. + */ + public edit(shape: IPrimitive): void; + + /** + * Finishes any shape create / edit operation currently in progress, and returns the shape that was created or editted through a specified callback function. + * @param finished A callback function to return the completed shape with. + */ + public finish(finished?: (shape: IPrimitive) => void): void; + + /** + * Creates a drawing manager which allows multi-shape editing and displays the toolbar. + * @param callback A callback function that is triggered after the DrawingTools have loaded. + */ + public showDrawingManager(callback?: (manager: DrawingManager) => void): void; + } + + export module Events { + ///////////////////////////////////// + /// addHandler Definitions + //////////////////////////////////// + + /** + * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * drawingChanged, drawingChanging, drawingEnded, drawingModeChanged, drawingStarted + * @param handler The callback function to handle the event when triggered. + * @returns The handler id. + */ + export function addHandler(target: DrawingTools, eventName: string, handler: (eventArg?: IPrimitive | IDrawingModeChangedData) => void): IHandlerId; + + /** + * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * disposed, drawingChanged, drawingChanging, drawingEnded, drawingErased, drawingModeChanged, drawingStarted + * @param handler The callback function to handle the event when triggered. + * @returns The handler id. + */ + export function addHandler(target: DrawingManager, eventName: string, handler: (eventArg?: IPrimitive | DrawingTools.DrawingMode) => void): IHandlerId; + + ///////////////////////////////////// + /// addOne Definitions + //////////////////////////////////// + + /** + * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * drawingChanged, drawingChanging, drawingEnded, drawingModeChanged, drawingStarted + * @param handler The callback function to handle the event when triggered. + */ + export function addOne(target: DrawingTools, eventName: string, handler: (eventArg?: IPrimitive | IDrawingModeChangedData) => void): void; + + /** + * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * disposed, drawingChanged, drawingChanging, drawingEnded, drawingErased, drawingModeChanged, drawingStarted + * @param handler The callback function to handle the event when triggered. + */ + export function addOne(target: DrawingManager, eventName: string, handler: (eventArg?: IPrimitive | DrawingTools.DrawingMode) => void): void; + + ///////////////////////////////////// + /// addThrottledHandler Definitions + //////////////////////////////////// + + /** + * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * drawingChanged, drawingChanging, drawingEnded, drawingModeChanged, drawingStarted + * @param handler The callback function to handle the event when triggered. + * @returns The handler id. + */ + export function addThrottledHandler(target: DrawingTools, eventName: string, handler: (eventArg?: IPrimitive | IDrawingModeChangedData) => void): IHandlerId; + + /** + * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * disposed, drawingChanged, drawingChanging, drawingEnded, drawingErased, drawingModeChanged, drawingStarted + * @param handler The callback function to handle the event when triggered. + * @param throttleInterval throttle interval (in ms) + * @returns The handler id. + */ + export function addThrottledHandler(target: DrawingManager, eventName: string, handler: (eventArg?: IPrimitive | DrawingTools.DrawingMode) => void, throttleInterval: number): IHandlerId; + } + +} + +declare module Microsoft.Maps.DrawingTools { + /** + * The different drawing modes that the drawing manager can be set to. + * @requires The Microsoft.Maps.DrawingTools module. + */ + export enum DrawingMode { + /** Edit an existing shape. Click on a shape to edit it. */ + edit, + + /** Erase and existing shape. Click on the shapes to erase them. */ + erase, + + /** Sets the drawing manager into an idle mode. */ + none, + + /** Allow the user to draw a polygon. */ + polygon, + + /** Allow the user to draw a polyline. */ + polyline, + + /** Allow the user to draw a pushpin. */ + pushpin + } + + /** + * The different types of shapes that are created or edited by the drawing tools. + * @requires The Microsoft.Maps.DrawingTools module. + */ + export enum ShapeType { + /** A polygon shape type. */ + polygon, + + /** A polyline shape type. */ + polyline + } +} \ No newline at end of file diff --git a/types/bingmaps/GeoJson.d.ts b/types/bingmaps/GeoJson.d.ts new file mode 100644 index 0000000000..c68ce2e80f --- /dev/null +++ b/types/bingmaps/GeoJson.d.ts @@ -0,0 +1,75 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module Microsoft.Maps { + + /** GeoJSON object definition */ + export interface IGeoJsonObject { + /** + * Type of the object + * could be one of the following: + * Point + * LineString + * Polygon + * MultiPoint + * MultiLineString + * MultiPolygon + * GeometryCollection + * Feature + * FeatureCollection + */ + type: string; + + /** Geometric coordinates of the object */ + coordinates?: number[] | number[][] | number[][][] | number[][][][]; + + /** Additional properties of the object as a key,value pair */ + properties?: any; + + /** Set of features (only applicable if the type is 'featurecollection') */ + features?: IGeoJsonObject[]; + + /** Set of geometries (only applicable if the type is 'geometrycollection') */ + geometries?: IGeoJsonObject[]; + + /** Geometry (only applicable if the type is 'feature') */ + geometry?: IGeoJsonObject; + + /** identifier of a feature (only applicable if the type is 'feature') */ + id?: any; + } + + /** + * Class responsible for reading/writing geo data in GeoJson format + * @requires The Microsoft.Maps.GeoJson module. + */ + export module GeoJson { + /** + * Reads the data from a given url and returns the shapes. + * @param url GeoJson download url. + * @param callback Callback function that needs to be called once the data is downloaded and parsed. + * @param jsonpQueryParam The name of the url query param to make a jsonp request. + * @param styles Styles that needs to be applied. + */ + export function readFromUrl(url: string, callback: (data: IPrimitive | IPrimitive[]) => void, jsonpQueryParam?: string, styles?: IStylesOptions): void; + + /** + * Reads the data in geoJson format and returns the shapes. + * @param geoJson GeoJson data object that needs to be parsed into shapes. + * @param styles Styles that needs to be applied. + * @returns An array of shapes. + */ + export function read(geoJson: IGeoJsonObject | string, styles?: IStylesOptions): IPrimitive | IPrimitive[]; + + /** + * Writes the data into geoJson format. + * @param data Data that needs to be serialized. + * @returns A geoJson formatted string. + */ + export function write(data: IPrimitive | IPrimitive[]): IGeoJsonObject; + } +} \ No newline at end of file diff --git a/types/bingmaps/HeatMapLayer.d.ts b/types/bingmaps/HeatMapLayer.d.ts new file mode 100644 index 0000000000..c012e06422 --- /dev/null +++ b/types/bingmaps/HeatMapLayer.d.ts @@ -0,0 +1,113 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module Microsoft.Maps { + /** A standard dictionary object (associative array). */ + export interface IDictionary { + [K: string]: T; + } + + /** Options for customizing how the heat map is rendered. */ + export interface IHeatMapLayerOptions { + /** + * The temperature gradient that is used to colorize the map. Default gradient: + * { + * '0.00': 'rgb(255,0,255)', // Magenta + * '0.25': 'rgb(0,0,255)', // Blue + * '0.50': 'rgb(0,255,0)', // Green + * '0.75': 'rgb(255,255,0)', // Yellow + * '1.00': 'rgb(255,0,0)' // Red + * } + */ + colorGradient?: IDictionary; + + /** + * The intensity of each heat point. This is a decimal value between 0 and 1. This is used to specify how "hot" a single data point should be. Default: 0.5 + */ + intensity?: number; + + /** + * The opacity of the HeatMapLayer canvas. Value should be a decimal between 0 and 1. Default: 1 + */ + opacity?: number; + + /** + * The radius to draw each data point on the map. Default: 10 + */ + radius?: number; + + /** + * The distance units of the radius. Possible values are: + * + * • 'pixels' (defualt) + * • 'meters' + * + * When set to pixels the size of each data point will always be the same radius, regardless of zoom level. When set to meters, the size of the data points + * will scale based on zoom level so as to ensure that the radius is spatially accurate. + */ + unit?: 'meters' | 'pixel'; + + /** A boolean indicating if the heat map layer is visible or not. **/ + visible?: boolean; + } + + /** + * Class for rendering data as a heat map layer. + * @requires The Microsoft.Maps.Heatmap module. + */ + export class HeatMapLayer implements IDataLayer { + /** + * @constructor + * @requires The Microsoft.Maps.Heatmap module. + * @param locations Set of locations to visualize as a heat map. + * @param options Options for customizing how the heat map is rendered. + */ + constructor(locations: (Location | Pushpin)[], options?: IHeatMapLayerOptions); + + /** Clears all data in the heat map layer. */ + public clear(): void; + + /** Disposes the heat map layer. */ + public dispose(): void; + + /** + * Gets a boolean indicating if the heat map layer is visible or not. + * @returns A boolean indicating if the heat map layer is visible or not. + */ + public getVisible(): boolean; + + /** + * @deprecated + * Hides the heat map layer. + */ + public hide(): void; + + /** + * Specifies the locations to use when generating the heat map. + * @param locations Set of locations. + */ + public setLocations(locations: (Location | Pushpin)[]): void; + + /** + * Sets the options to use with the heat map layer. + * @param options Set of heat map layer options. + */ + public setOptions(options: IHeatMapLayerOptions): void; + + /** + * Sets the visibility of the heat map layer. + * @param visible A boolean indicating if the heat map layer is visible or not. + */ + public setVisible(visible: boolean): void; + + /** + * @deprecated + * Shows the heat map layer. + */ + public show(): void; + } +} \ No newline at end of file diff --git a/types/bingmaps/Microsoft.Maps.AdvancedShapes.d.ts b/types/bingmaps/Microsoft.Maps.AdvancedShapes.d.ts deleted file mode 100644 index e261e1d0ce..0000000000 --- a/types/bingmaps/Microsoft.Maps.AdvancedShapes.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -// Type definitions for Microsoft.Maps.AdvancedShapes 7.0 -// Project: http://msdn.microsoft.com/en-us/library/hh921952.aspx -// Definitions by: Eric Todd -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Microsoft.Maps.AdvancedShapes { - - export class EntityCollection { - - constructor(options?: EntityCollectionOptions); - - clear(): void; - get(index: number): Entity; - getLength(): number; - getVisible(): boolean; - getZIndex(): number; - indexOf(entity: Entity): number; - insert(entity: Entity, index: number): void; - pop(): Entity; - push(entity: Entity): void; - remove(entity: Entity): Entity; - removeAt(index: number): Entity; - setOptions(options: EntityCollectionOptions): void; - toString(): string; - } - - export class Polygon implements Entity { - - constructor(locations: Array, options?: PolygonOptions); - - getFillColor(): Color; - getLocations(): Array; - getStrokeColor(): Color; - getStrokeDashArray(): string; - getStrokeThickness(): number; - getVisible(): boolean; - setLocations(locations: Location[]): void; - setOptions(options: PolylineOptions): void; - toString(): string; - } - -} diff --git a/types/bingmaps/Microsoft.Maps.Directions.d.ts b/types/bingmaps/Microsoft.Maps.Directions.d.ts deleted file mode 100644 index 710efd7b02..0000000000 --- a/types/bingmaps/Microsoft.Maps.Directions.d.ts +++ /dev/null @@ -1,434 +0,0 @@ -// Type definitions for Microsoft.Maps.Directions 7.0 -// Project: http://msdn.microsoft.com/en-us/library/hh312813.aspx -// Definitions by: Eric Todd -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Microsoft.Maps.Directions { - - export interface BusinessDetails { - - businessName?: string; - entityId?: string; - phoneNumber?: string; - website?: string; - } - - export interface WaypointOptions { - - address?: string; - businessDetails?: BusinessDetails; - disambiguationContainer?: HTMLElement; - exactLocation?: string; - isViapoint?: boolean; - location?: Location; - pushpin?: Pushpin; - shortAddress?: string; - } - - export interface BusinessDisambiguationSuggestion { - - address?: string; - distance?: number; - entityId?: number; - index?: number; - isApproximate?: boolean; - location?: Location; - name?: string; - phoneNumber?: string; - photoUrl?: string; - rooftopLocation?: Location; - website?: string; - } - - export interface LocationDisambiguationSuggestion { - - formattedSuggestion?: string; - location?: Location; - rooftopLocation?: Location; - suggestion?: string; - } - - export interface Disambiguation { - - businessSuggestions?: Array; - hasMoreSuggestions?: boolean; - headerText?: string; - locationSuggestions?: Array; - } - - export interface WaypointEventArgs { - - waypoint: Waypoint; - } - - export class Waypoint { - - constructor(options: WaypointOptions); - - clear(): void; - dispose(): void; - getAddress(): string; - getBusinessDetails(): BusinessDetails; - getDisambiguationContainer(): HTMLElement; - getDisambiguationResult(): Disambiguation; - getLocation(): Location; - getPushpin(): Pushpin; - getShortAddress(): string; - isExactLocation(): boolean; - isViapoint(): boolean; - setOptions(options: WaypointOptions): void; - } - - export interface DirectionsRenderOptions { - - autoDisplayDisambiguation?: boolean; - autoUpdateMapView?: boolean; - disambiguationPushpinOptions?: PushpinOptions; - displayDisclaimer?: boolean; - displayManeuverIcons?: boolean; - displayPostItineraryItemHints?: boolean; - displayPreItineraryItemHints?: boolean; - displayRouteSelector?: boolean; - displayStepWarnings?: boolean; - displayTrafficAvoidanceOption?: boolean; - displayWalkingWarning?: boolean; - drivingPolylineOptions?: PolylineOptions; - itineraryContainer?: HTMLElement; - lastWaypointIcon?: string; - middleWaypointIcon?: string; - stepPushpinOptions?: PushpinOptions; - transitPolylineOptions?: PolylineOptions; - viapointPushpinsOptions?: PushpinOptions; - walkingPolylineOptions?: PolylineOptions; - waypointPushpinOptions?: PushpinOptions; - } - - export enum DistanceUnit { - kilometers= 0, - miles= 1 - } - - export enum RouteAvoidance { - none= 0, - minimizeLimitedAccessHighway= 1, - minimizeToll= 2, - avoidLimitedAccessHighway= 4, - avoidToll= 8, - avoidExpressTrain= 16, - avoidAirline= 32, - avoidBulletTrain= 64 - } - - export enum RouteMode { - driving, - transit, - walking - } - - export enum RouteOptimization { - shortestTime= 0, - shortestDistance= 1, - minimizeMoney= 3, - minimizeTransfers= 4, - minimizeWalking= 5 - } - - export enum TimeType { - arrival, - departure, - lastAvailable - } - - export interface TransitOptions { - timeType?: TimeType; - transitTime?: Date; - } - - export interface DirectionsRequestOptions { - - avoidTraffic?: boolean; - distanceUnit?: DistanceUnit; - maxRoutes?: number; - routeAvoidance?: Array; - routeDraggable?: boolean; - routeIndex?: boolean; - routeMode?: RouteMode; - routeOptimization?: RouteOptimization; - transitOptions?: TransitOptions; - } - - export class DirectionsManager { - - constructor(map: Microsoft.Maps.Map); - - resetDirections(): void; - addWaypoint(waypoint: Waypoint, index?: number): void; - calculateDirections(): void; - clearDisplay(): void; - dispose(): void; - getAllWaypoints(): Array; - getMap(): Map; - getNearbyMajorRoads(location: Location, callback: any, errorCallback: any, userData: any): void; - getRenderOptions(): DirectionsRenderOptions; - getRequestOptions(): DirectionsRequestOptions; - getRouteResult(): Array; - removeWaypoint(waypoint: Waypoint): void; - removeWaypoint(index: number): void; - resetDirections(options: ResetDirectionsOptions): void; - reverseGeocode(location: Location, callback: any, errorCallback: any, userData: any): void; - setMapView(): void; - setRenderOptions(options: DirectionsRenderOptions): void; - setRequestOptions(options: DirectionsRequestOptions): void; - } - - export interface DirectionsStepEventArgs { - handled: boolean; - location: Location; - routeIndex: number; - routeLegIndex: number; - step: DirectionsStep; - stepIndex: number; - stepNumber: number; - } - - export interface DirectionsErrorEventArgs { - responseCode: RouteResponseCode; - message: string; - } - - export interface DirectionsEventArgs { - routeSummary: Array; - route: Array; - } - - export interface DisambiguationRenderEventArgs { - containerElement: HTMLElement; - handled: boolean; - waypoint: Waypoint; - } - - export interface DirectionsStepRenderEventArgs { - containerElement: HTMLElement; - handled: boolean; - lastStep: boolean; - routeIndex: number; - routeLegIndex: number; - step: DirectionsStep; - stepIndex: number; - } - - export interface RouteSummaryRenderEventArgs { - containerElement: HTMLElement; - handled: boolean; - routeLegIndex: number; - summary: RouteSummary; - } - - export interface WaypointRenderEventArgs { - containerElement: HTMLElement; - handled: boolean; - waypoint: Waypoint; - } - - export interface DirectionsStep { - - childItineraryItems: Array; - coordinate: Location; - distance: string; - durationInSeconds: number; - formattedText: string; - iconType: IconType; - isImageRoadShield: boolean; - maneuver: Maneuver; - maneuverImageName: string; - monetaryCost: number; - postIntersectionHints: Array; - preIntersectionHings: Array; - startStopName: string; - transitLine: TransitLine; - transitStepIcon: string; - transitStopId: string; - transitTerminus: string; - warnings: Array; - } - - export enum IconType { - none, - other, - auto, - ferry, - walk, - bus, - train, - airline - } - - export enum Maneuver { - none= 0, - unknown= 1, - departStart= 2, - departIntermediateStop= 3, - departIntermediateStopReturning= 4, - arriveFinish= 5, - arriveIntermediateStop= 6, - turnLeft= 7, - turnRight= 8, - turnBack= 9, - uTurn= 10, - turnToStayLeft= 11, - turnToStayRight= 12, - bearLeft= 13, - bearRight= 14, - keepToStayLeft= 15, - keepToStayRight= 16, - keepToStayStraight= 17, - keepLeft= 18, - keepRight= 19, - keepStraight= 20, - take= 21, - takeRampLeft= 22, - takeRampRight= 23, - takeRampStraight= 24, - keepOnRampLeft= 25, - keepOnRampRight= 26, - keepOnRampStraight= 27, - merge= 28, - continueRoute= 29, - roadNameChange= 30, - enterRoundabout= 31, - exitRoundabout= 32, - turnRightThenTurnRight= 33, - turnRightThenTurnLeft= 34, - turnRightThenBearRight= 35, - turnRightThenBearLeft= 36, - turnLeftThenTurnLeft= 37, - turnLeftThenTurnRight= 38, - turnLeftThenBearLeft= 39, - turnLeftThenBearRight= 40, - bearRightThenTurnRight= 41, - bearRightThenTurnLeft= 42, - bearRightThenBearRight= 43, - bearRightThenBearLeft= 44, - bearLeftThenTurnLeft= 45, - bearLeftThenTurnRight= 46, - bearLeftThenBearRight= 47, - bearLeftThenBearLeft= 48, - rampThenHighwayRight= 49, - rampThenHighwayLeft= 50, - rampToHighwayStraight= 51, - enterThenExitRoundabout= 52, - bearThenMerge= 53, - turnThenMerge= 54, - bearThenKeep= 55, - transfer= 56, - wait = 57, - takeTransit= 58, - walk = 59, - transitDepart = 60, - transitArrive= 61, - } - - export interface TransitLine { - abbreviatedName: string; - agencyId: number; - agencyName: string; - agencyUrl: string; - lineColor: Color; - lineTextColor: Color; - providerInfo: string; - verboseName: string; - } - - export interface DirectionsStepWarning { - style: StepWarningStyle; - text: string; - } - - export enum StepWarningStyle { - info= 0, - minor= 1, - moderate= 2, - major= 3, - ccZoneEnter= 4, - ccZoneExit= 5 - } - - export interface ResetDirectionsOptions { - removeAllWaypoints?: boolean; - resetRenderOptions?: boolean; - resetRequestOptions?: boolean; - } - - export interface Route { - routeLegs: Array; - } - - export interface RouteLeg { - endTime: Date; - endWaypointLocation: Location; - itineraryItems: Array; - originalRouteIndex: number; - startTime: Date; - startWaypointLocation: Location; - subLegs: Array; - summary: RouteSummary; - } - - export interface RouteSubLeg { - actualEnd: Location; - actualStart: Location; - endDescription: string; - routePath: RoutePath; - startDescription: string; - summary: RouteSummary; - } - - export interface RoutePath { - decodedLatitudes: Array; - decodedLongitudes: Array; - decodedRegions: Array; - } - - export interface RouteSummary { - distance: number; - monetaryCost: number; - northEast: Location; - southWest: Location; - time: number; - timeWithTraffic: number; - } - - export enum RouteResponseCode { - success= 0, - unknownError= 1, - cannotFindNearbyRoad= 2, - tooFar= 3, - noSolution= 4, - dataSourceNotFound= 5, - noAvailableTransitTrip= 7, - transitStopsTooClose= 8, - walkingBestAlternative= 9, - outOfTransitBounds= 10, - timeout= 11, - waypointDisambiguation= 12, - hasEmptyWaypoint= 13, - exceedMaxWaypointLimit= 14, - atleastTwoWaypointRequired= 15, - firstOrLastStoppointsIsVia= 16, - searchServiceFailed= 17, - invalidCredentials= 18 - } - - export interface RouteSelectorEventArgs { - handled: boolean; - routeIndex: number; - } - - export interface RouteSelectorRenderEventArgs { - containerElement: HTMLElement; - handled: boolean; - routeIndex: number; - routeLeg: RouteLeg; - } - -} diff --git a/types/bingmaps/Microsoft.Maps.Search.d.ts b/types/bingmaps/Microsoft.Maps.Search.d.ts deleted file mode 100644 index d5fcb3e255..0000000000 --- a/types/bingmaps/Microsoft.Maps.Search.d.ts +++ /dev/null @@ -1,150 +0,0 @@ -// Type definitions for Microsoft.Maps.Search 7.0 -// Project: http://msdn.microsoft.com/en-us/library/hh868061.aspx -// Definitions by: Eric Todd -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Microsoft.Maps.Search { - - export interface Address { - addressLine: string; - adminDistrict: string; - countryRegion: string; - district: string; - formattedAddress: string; - locality: string; - postalCode: string; - postalTown:string; - } - - export interface GeocodeLocation { - location: Location; - name: string; - precision:LocationPrecision; - } - - export interface GeocodeRequestOptions { - bounds?: LocationRect; - callback?: (result: GeocodeResult, userData: any) => any; - count: number; - errorCallback?: (options: GeocodeRequestOptions) => any; - timeout?: number; - userData?: any; - where:string; - } - - export interface GeocodeResult { - parsedAddress: Address; - parsedKeyword: string; - parsedSeparator: string; - results:Array; - } - - export enum LocationPrecision { - interpolated, - rooftop, - } - - export enum MatchCode { - none, - good, - ambiguous, - upHierarchy, - modified, - } - - export enum MatchConfidence { - high, - medium, - low, - unknown, - } - - export interface PlaceResult { - bestView: LocationRect; - location: GeocodeLocation; - locations: Array; - matchCode: MatchCode; - matchConfidence: MatchConfidence; - name:string; - } - - export interface ReverseGeocodeRequestOptions { - callback?: (result: PlaceResult, userData: any) => any; - errorCallback?: (options: ReverseGeocodeRequestOptions) => any; - location?: Location; - timeout?: number; - userData?:any; - } - - export class SearchManager { - - constructor(map: Map); - - geocode(request: GeocodeRequestOptions): void; - reverseGeocode(request: ReverseGeocodeRequestOptions): void; - search(request:SearchRequestOptions):void; - } - - export interface SearchParseResult { - keyword: string; - location: GeocodeLocation; - matchConfidence:MatchConfidence; - } - - export interface SearchRegion { - address: Address; - geocodeLocations: Array; - explicitLocation: GeocodeLocation; - mapBounds: LocationRect; - matchCode: MatchCode; - matchConfidence: MatchConfidence; - source:string; - } - - export interface SearchRequestOptions { - callback?:(result: SearchResponse, userData: any)=>any; - count: number; - errorCallback?:(options: SearchRequestOptions)=>any; - query?: string; - startIndex?: number; - timeout?: number; - entityType?: string; - userData?: any; - what?: string; - where?:string; - } - - export interface SearchResponse { - alternateSearchRegions: Array; - hasMore: boolean; - parseResults: Array; - responseSummary: SearchResponseSummary; - searchRegion: SearchRegion; - searchResults:Array; - } - - export interface SearchResponseSummary { - authResultCode: number; - copyright: string; - errorMessage: string; - statusCode: number; - traceId:number; - } - - export interface SearchResult { - address: Address; - city: string; - country: string; - entityType: string; - hoursOfOperation: string; - id: number; - location: Location; - name: string; - phone: string; - postalCode: string; - reviewCount: number; - userRating: number; - website:string; - } - - } diff --git a/types/bingmaps/Microsoft.Maps.Themes.BingTheme.d.ts b/types/bingmaps/Microsoft.Maps.Themes.BingTheme.d.ts deleted file mode 100644 index 43faf0bd71..0000000000 --- a/types/bingmaps/Microsoft.Maps.Themes.BingTheme.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Type definitions for Microsoft.Maps.Themes 7.0 -// Project: http://msdn.microsoft.com/en-us/library/hh868061.aspx -// Definitions by: Eric Todd -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Microsoft.Maps.Themes { - - export class BingTheme { - constructor(); - } - -} diff --git a/types/bingmaps/Microsoft.Maps.Traffic.d.ts b/types/bingmaps/Microsoft.Maps.Traffic.d.ts deleted file mode 100644 index 003f874cd1..0000000000 --- a/types/bingmaps/Microsoft.Maps.Traffic.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -// Type definitions for Microsoft.Maps.Traffic 7.0 -// Project: http://msdn.microsoft.com/en-us/library/hh312840.aspx -// Definitions by: Eric Todd -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Microsoft.Maps.Traffic { - - export class TrafficManager { - - constructor(map: Map); - - hide(): void; - hideFlow(): void; - hideIncidents(): void; - hideLegend(): void; - show(): void; - showFlow(): void; - showIncidents(): void; - showLegend():void; - } - -} diff --git a/types/bingmaps/Microsoft.Maps.VenueMaps.d.ts b/types/bingmaps/Microsoft.Maps.VenueMaps.d.ts deleted file mode 100644 index 79076d30ea..0000000000 --- a/types/bingmaps/Microsoft.Maps.VenueMaps.d.ts +++ /dev/null @@ -1,136 +0,0 @@ -// Type definitions for Microsoft.Maps.VenueMaps 7.0 -// Project: http://msdn.microsoft.com/en-us/library/hh312797.aspx -// Definitions by: Eric Todd -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Microsoft.Maps.VenueMaps { - - export interface MouseResponse { - eventArgs: MouseEventArgs; - } - - export interface PrimitiveResponse { - eventArgs: Primitive; - } - - export interface Directory { - - addToDOM(div: HTMLElement, sortOrder: DirectorySortOrder, to_group_or_not: DirectoryGrouping): void; - createUIElements(): void; - handleMouseClick(e: (response: MouseResponse) => void): void; - handleMouseClick(e: (response: PrimitiveResponse) => void): void; - handleMouseOut(e: (response: MouseResponse) => void): void; - handleMouseOut(e: (response: PrimitiveResponse) => void): void; - handleMouseOver(e: (response: MouseResponse) => void): void; - handleMouseOver(e: (response: PrimitiveResponse) => void): void; - isInDOM(): boolean; - removeFromDOM(): void; - setHeight(height: number): void; - } - - export enum DirectoryGrouping { - byCategory, - none, - } - - export enum DirectorySortOrder { - alphabetical, - byFloor, - } - - export interface Floor { - name: string; - primitives: Array; - zoomRange: Array; - } - - export interface Footprint { - polygons: Array; - zoomRange: Array; - } - - export interface Metadata { - CenterLatitude: number; - CenterLongitude: number; - DefaultFloor: string; - FloorHeader: string; - Floors: Array; - Footprint: Footprint; - MapId: string; - MapType: string; - Name: string; - YpId: string; - } - - export interface NearbyVenue { - distance: number; - metadata: Metadata; - } - - export interface NearbyVenueOptions { - callback?: (maps: Array) => any; - location?: Location; - map?: Map; - radius?: number; - } - - export interface Polygon { - bounds: LocationRect; - center: Location; - locations: Array; - } - - export interface Primitive { - - bounds: LocationRect; - businessId: string; - categoryId: string; - categoryName: string; - center: Location; - floor: Floor; - id: string; - locations: Array; - name: string; - - highlight(): void; - unhighlight(): void; - } - - export interface VenueMap { - - address: string; - bestMapView: ViewOptions; - businessId: string; - center: Location; - defaultFloor: string; - directory: Directory; - floorHeader: string; - floors: Array; - footprint: Footprint; - id: string; - name: string; - phoneNumber: string; - type: string; - - dispose(): void; - getActiveFloor(): string; - hide(): void; - setActiveFloor(floor: string): void; - show(): void; - } - - export interface VenueMapCreationOptions { - error: (errorCode: number, args: any) => any; - success: (venueMap: VenueMap, args: any) => any; - venueMapId: string; - } - - export class VenueMapFactory { - - constructor(map: Map); - - create(options: VenueMapCreationOptions): void; - getNearbyVenues(options: NearbyVenueOptions): void; - } - -} diff --git a/types/bingmaps/Search.d.ts b/types/bingmaps/Search.d.ts new file mode 100644 index 0000000000..eea087480c --- /dev/null +++ b/types/bingmaps/Search.d.ts @@ -0,0 +1,235 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * Provides an easy method for geocoding address and searching for points of interest from JavaScript. + * @requires The Microsoft.Maps.Search module. + */ +declare module Microsoft.Maps.Search { + /** + * Defines the match precision of a geocdoed result. + * @requires The Microsoft.Maps.Search module. + */ + export enum LocationPrecision { + /** The geocode result was matched to a point on a road using interpolation. */ + interpolated, + + /** + * The geocode result was matched to a point on a road using interpolation with an additional offset to shift the + * Location to the side of the street. + */ + InterpolatedOffset, + + /** The geocode result was matched to the center of a parcel (property boundary). */ + parcel, + + /** The geocode result was matched to the rooftop of a building. */ + rooftop + } + + /** + * Defines the geocoding level of the location match found by the geocoder. + * @requires The Microsoft.Maps.Search module. + */ + export enum MatchCode { + /** No match was found. */ + none, + + /** The match was good. */ + good, + + /** The match was ambiguous. Multiple results were returned. */ + ambiguous, + + /** The match was found by a broader search. */ + upHierarchy, + + /** The match was found, but possibly using a modified query. */ + modified + } + + /** + * Defines the confidence of the location match found by the geocoding service. + * @requires The Microsoft.Maps.Search module. + */ + export enum MatchConfidence { + /** The confidence of the match is high. */ + high, + + /** The confidence of the match is medium. */ + medium, + + /** The confidence of the match is low. */ + low, + + /** The confidence of the match is unknown. */ + unknown + } + + /** A object that represents a geocoded location. */ + export interface IGeocodeLocation { + /** The map location of this geocode location match. */ + location: Location; + + /** The name of this geocode location match. */ + name: string; + + /** The precision of this geocode location match. */ + precision: string | LocationPrecision; + } + + /** An object that represents an place result. */ + export interface IPlaceResult { + /** The geocoded address of the place result. */ + address: IAddress; + + /** The location rectangle that defines the boundaries of the best map view of the place result. */ + bestView: LocationRect; + + /** The classification of the geographic entity returned, such as PopulatedPlace. */ + entityType: string; + + /** The geocoded location of the best result. */ + location: Location; + + /** The geocoded locations. */ + locations: IGeocodeLocation[]; + + /** The match code of the best result. */ + matchCode: string | MatchCode; + + /** The match confidence of the best result. */ + matchConfidence: string | MatchConfidence; + + /** The name of the place result, if one exists. */ + name: string; + } + + /** An object that represents a geocode result returned by REST service. */ + export interface IGeocodeResult { + /** An array of geocode results. */ + results: IPlaceResult[]; + } + + /** The options for a geocode request. */ + export interface IGeocodeRequestOptions { + /** + * A location rectangle that defines the boundaries of the area in which to search for + * location results. The default is the bounds of the map view associated with this + * instance of the SearchManager, which is usually the current map view. + */ + bounds?: LocationRect; + + /** + * The name of the function to call when a successful result is returned from the + * geocode request. The callback function must accept two parameters: result, which is + * a GeocodeResult type, and a userData object. + */ + callback: (geocodeResult: IGeocodeResult, userData: any) => void; + + /** The maximum number of results to return. Required. The maximum number than can be returned is 20. */ + count?: number; + + /** + * The name of the function to call when the request is returned with an error. The + * error callback function must accept an IGeocodeRequestOptions object. + */ + errorCallback?: (geocodeRequestOptions: IGeocodeRequestOptions) => void; + + /** Specifies to include the two-letter ISO country code. */ + includeCountryIso2?: boolean; + + /** Specifies to include the neighborhood in the response when it is available. */ + includeNeighborhood?: boolean; + + /** A number indicating how long to wait, in seconds, for the geocode request to return. The default value is 5 seconds. */ + timeout?: number; + + /** An object containing any data that needs to be passed to the callback when the request is completed. */ + userData?: any; + + /** A string containing the address or place to be matched to a location on the map. */ + where: string; + } + + /** The options for a reverse geocode request. */ + export interface ReverseGeocodeRequestOptions { + /** + * A reference to a function to call when a successful result is returned from the geocode request. The callback function + * will receive a PlaceResult object as an argument. + */ + callback: (placeResult: IPlaceResult, userData: any) => void; + + /** + * A reference to a function to call when the request is returned with an error. The error callback function will receive + * an object containing the geocode request options used in the request. + */ + errorCallback?: (reverseGeocodeRequestOptions: ReverseGeocodeRequestOptions) => void; + + /** Specifies to include the two-letter ISO country code. Default: false */ + includeCountryIso2?: boolean; + + /** + * An array of entity types selected from the following options. + * • Address + * • Neighborhood + * • PopulatedPlace + * • Postcode1 + * • AdminDivision1 + * • AdminDivision2 + * • CountryRegion + * These entity types are ordered from the most specific entity to the least specific entity. When entities of more than one entity type are found, only the most specific + * entity is returned. For example, if you specify Address and AdminDistrict1 as entity types and entities were found for both types, only the Address entity information is + * returned in the response. One exception to this rule is when both PopulatedPlace and Neighborhood entity types are specified and information is found for both. In this case, + * the information for both entity types is returned. Also, more than one Neighborhood may be returned because the area covered by two different neighborhoods can overlap. + */ + includeEntityTypes?: string[]; + + /** + * Specifies to include the neighborhood in the response when it is available. Note: This feature isn’t + * available in all locations. + */ + includeNeighborhood?: boolean; + + /** The location to use to match to geographic entities and addresses. */ + location: Location; + + /** A number indicating how long to wait, in seconds, for the reverse geocode request to return. The default value is 5 seconds. */ + timeout?: number; + + /** An object containing any data that needs to be passed to the callback when the request is completed. */ + userData?: any; + } + + /** + * A class that contains methods for returning search and location results. + * @requires The Microsoft.Maps.Search module. + */ + export class SearchManager { + /** + * @constructor + * @requires The Microsoft.Maps.Search module. + * @param map A Map object + */ + constructor(map: Map); + + /** + * Matches the address or place query in the specified request + * options to a location and returns the results to the request + * options callback function. + * @param request Options for sending geocode request + */ + public geocode(request: IGeocodeRequestOptions): void; + + /** + * Matches the specified location to an address and returns the + * address results to the specified request options callback function. + * @param request Options for sending reverse geocode request + */ + public reverseGeocode(request: ReverseGeocodeRequestOptions): void; + } +} \ No newline at end of file diff --git a/types/bingmaps/SpatialDataService.d.ts b/types/bingmaps/SpatialDataService.d.ts new file mode 100644 index 0000000000..f31642cc04 --- /dev/null +++ b/types/bingmaps/SpatialDataService.d.ts @@ -0,0 +1,447 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * This module wraps the Query and GeoData REST API’s in the Bing Spatial Dara Services and expose them as an easy to use JavaScript library. + * @requires The Microsoft.Maps.SpatialDataService module. + */ +declare module Microsoft.Maps.SpatialDataService { + + ////////////////////////////////////////////// + /// GeoData API + ////////////////////////////////////////////// + + /** Represents the options for requests boundary data from the GeoData API in the Bing Spatial Data Services. */ + export interface IGetBoundaryRequestOptions { + /** + * The level of detail for the boundary polygons returned. An integer between 0 and 3, where 0 specifies the coarsest level of boundary detail and 3 + * specifies the best. Default: 0 + */ + lod?: number; + + /** + * The entity type to return. Default: CountryRegion + * Supported entity types: + * AdminDivision1, AdminDivision2, CountryRegion, eighborhood, PopulatedPlace, Postcode1, Postcode2, Postcode3, Postcode4 + * Note: Not all entity types are available in all areas. + */ + entityType?: string; + + /** + * Specifies the preferred language to use for any metadata text about the entity or polygons. Defaults to the culture used by the map control, which + * usually automatically detected based on user's browser settings. Setting this property will override the default value. + */ + culture?: string; + + /** + * Specifies whether the response should include all of the boundary polygons for the requested entity or just return a single polygon that represents + * the main outline of the entity. Default: false + */ + getAllPolygons?: boolean; + + /** + * Specifies whether the response should include metadata about the entity, such as AreaSqKm and others. Default: false + */ + getEntityMetadata?: boolean; + + /** + * Specifies the user’s home country or region.Defaults to the region setting of the user who loads the map. + * Warning: Setting this property will override the default value, which is the region the user is actually in, and will allow the user to see boundaries + * which may not align with the views of their region.This could result in geopolitically sensitive borders being returned. + */ + userRegion?: string; + } + + /** Represents the primitive object for a boundary returned by the GeoData API. */ + export interface IGeoDataPrimitive { + /** A unique ID associated with this polygon primitive. */ + PrimitiveID: string; + + /** + * A comma-delimited sequence starting with the version number of the polygon set followed by a list of compressed polygon + * "rings" (closed paths represented by sequences of latitude and-longitude points). + */ + Shape: string; + + /** The number of vertex points used to define the polygon. */ + NumPoints: string; + + /** + * An ID identifying the data provider that supplied the data. This ID number will reference one of the sources listed in the + * array of CopyrightSources in the Copyright property of the GeoDataResultSet object. + */ + SourceID: string; + } + + /** Represents the copyright source object for a boundary returned by the GeoData API. */ + export interface ICopyrightSource { + /** The copyright string from the source. */ + Copyright: string; + + /** An ID identifying the data provider that supplied the data. */ + SourceID: string; + + /** The name of the data provider represented by this Source element. */ + SourceName: string; + } + + /** Represents the copyright object for a boundary returned by the GeoData API. */ + export interface ICopyright { + /** The copyright URL for the GeoData service. */ + CopyrightURL: string; + + /** A collection of CopyrightSource objects that give information about the sources of the polygon data that is returned. */ + Sources: ICopyrightSource[]; + } + + /** Represents the name object for a boundary returned by the GeoData API. */ + export interface IName { + /** The name of boundary. Example: "United States" */ + EntityName: string; + + /** The culture of the region. */ + Culture: string; + + /** An ID identifying the data provider that supplied the data. */ + SourceID: string; + } + + /** Represents the metadata object for a boundary returned by the GeoData API. Not all properties will be returned for all results. */ + export interface IMetadata { + /** The approximate total surface area (in square kilometers) covered by all the polygons that comprise this entity. */ + AreaSqKm: string; + + /** + * An area on the Earth that provides the best map view for this entity. This area is defined as a bounding box in the format of a + * “MULTIPOINT ((WestLongitude SouthLatitude), (EastLongitude NorthLatitude))”. + */ + BestMapViewBox: string; + + /** The culture associated with this entity. Example: en */ + OfficialCulture: string; + + /** The approximate population within this entity. Example: PopClass20000to99999 */ + PopulationClass: string; + + /** The regional culture associated with this entity. */ + RegionalCulture: string; + } + + /** Represents a single result object returned by the GeoData API. */ + export interface IGeoDataResult { + /** Copyright information for the returned boundary data. */ + Copyright: ICopyright; + + /** A unique ID number associated with this entity. */ + EntityID: string; + + /** + * A collection of metadata information associated with the entity. The getEntityMetadata option of the request must be set + * to true. Note, not all boundaries will return this metadata. + */ + EntityMetadata: IMetadata; + + /** Information about the name of the boundary location. */ + Name: IName; + + /** A Polygon object that has been generated from the data in the Primitives property. */ + Polygons: Polygon[]; + + /** An array of objects that contain the polygon information for the boundary. */ + Primitives: IGeoDataPrimitive[]; + } + + /** Represents the set of results returned by the GeoData API. */ + export interface IGeoDataResultSet { + /** Copyright information for the GeoData API. */ + Copyright: string; + + /** The location provided in the query that generated this result. */ + location: string |  Location; + + /** Results of the boundary data. */ + results: IGeoDataResult[]; + } + + /** + * This is a static class that provides the ability to request polygons that describe the boundaries of a geographic entities, such as an AdminDivision1 + * (such as a state or province) or a Postcode1 (such as a zip code) that contain a given point (latitude and longitude) or address. This uses the GeoData + * API in the Bing Spatial Data Services. + * @requires The Microsoft.Maps.SpatialDataService module. + */ + export module GeoDataAPIManager { + /** + * Gets a boundary for the specified request. If the specified location value is a string, it will be geocoded and the coordinates of the result will + * be used to find a boundary of the specified entityType that intersects with this coordinate. + * @requires The Microsoft.Maps.SpatialDataService module. + * @param locations The locations to retrieve boundaries for. If the specified location value is a string, it will be geocoded and the coordinates of + * the result will be used to find a boundary of the specified entityType that intersects with this coordinate. + * @param request The request options for retrieving a boundary. + * @param credentials A bing maps key or a map instance which can be used to provide credentials to access the data source. Note that the map will need + * to be loaded with a bing maps key that has access to the data source. + * @param callback A callback function to return the results to. If an array of locations are specified the callback function will be triggered for each location in the array. + */ + export function getBoundary(locations: string | Location | (string | Location)[], request: IGetBoundaryRequestOptions, credentials: string | Map, callback: (results: IGeoDataResultSet) => void): void; + } + + ////////////////////////////////////////////// + /// Query API + ////////////////////////////////////////////// + + /** + * An enumeration that defines how to compare the filters value against the corresponding property value. + * @requires The Microsoft.Maps.SpatialDataService module. + */ + export enum FilterCompareOperator { + /** Determines if a string value ends with a specified string value. */ + endsWith, + + /** Determines if two values are equal. */ + equals, + + /** Determines if a first value is greater than a second value. */ + greaterThan, + + /** Determines if a first value is greater than or equal to a second value. */ + greaterThanOrEqual, + + /** Determines if a value is within an array. */ + isIn, + + /** Determines if a first value is less than a second value. */ + lessThan, + + /** Determines if a first value is less than or equal a second value. */ + lessThanOrEqual, + + /** Determines if a string value does not end with a specified string value. */ + notEndsWith, + + /** Determines if two values are not equal. */ + notEquals, + + /** Determines if a string value does not start with a specified string value. */ + notStartsWith, + + /** Determines if a string value starts with a specified string value. */ + startsWith + } + + /** + * An enumeration that defines how two or more filters are linked together. + * @requires The Microsoft.Maps.SpatialDataService module. + */ + export enum FilterLogicalOperator { + /** Connects two or more filters that both must be true. */ + and, + + /** Connects two or more filters where one of them must be true. */ + or + } + + /** + * A Fitler object that defines the logic behind a filter expression that can be executed against a JSON object or generate + * a filter string that can be used with the Bing Spatial Data Services. + */ + export interface IFilter { + /** + * Executes the filter logic against a JSON object and returns a boolean indicating if the object meets the requirements of the Filter. + * @returns A boolean indicating if the specified object meets the requirements of the Filter. + */ + execute(object: any): boolean; + + /** + * Converts the filter logic into a string format that is compatible with the Bing Spatial Data Services. + * @returns A filter string that is formatted such that it is compatible with the Bing Spatial Data Services. + */ + toString(): string; + } + + /** + * The Fitler class defines the logic behind a filter expression that can be executed against a JSON object or generate + * a filter string that can be used with the Bing Spatial Data Services. + * @requires The Microsoft.Maps.SpatialDataService module. + */ + export class Filter implements IFilter { + /** + * @constructor + * @requires The Microsoft.Maps.SpatialDataService module. + * @param propertyName The name of the property in the object to test against. Can also provide child properties i.e. 'root.child'. + * @param operator The operator to use when comparing the specified property to value to the provided value. + * @param value A value to compare against. + */ + constructor(propertyName: string, operator: string | FilterCompareOperator, value: any); + + /** + * Executes the filter logic against a JSON object and returns a boolean indicating if the object meets the requirements of the Filter. + * @returns A boolean indicating if the specified object meets the requirements of the Filter. + */ + public execute(object: any): boolean; + + /** + * Converts the filter logic into a string format that is compatible with the Bing Spatial Data Services. + * @returns A filter string that is formatted such that it is compatible with the Bing Spatial Data Services. + */ + public toString(): string; + } + + /** + * A class that groups two or more logical filters or filter groups together. It can be executed against a JSON or generate + * a filter string that can be used with the Bing Spatial Data Services. + * @requires The Microsoft.Maps.SpatialDataService module. + */ + export class FilterGroup implements IFilter { + /** + * @constructor + * @requires The Microsoft.Maps.SpatialDataService module. + * @param filters An array consisting of Filter or FilterGroup objects to combine. + * @param operator The logical operator for combining the filters together. + * @param not A boolean is the logical inverse should of the filter should be used. + */ + constructor(filters: IFilter[], operator: FilterLogicalOperator, not?: boolean) + + /** + * Executes the filter logic against a JSON object and returns a boolean indicating if the object meets the requirements of the Filter. + * @returns A boolean indicating if the specified object meets the requirements of the Filter. + */ + public execute(object: any): boolean; + + /** + * Converts the filter logic into a string format that is compatible with the Bing Spatial Data Services. + * @returns A filter string that is formatted such that it is compatible with the Bing Spatial Data Services. + */ + public toString(): string; + } + + /** Options for find near route query API. */ + export interface ISpatialFilterOptions { + /** + * One of the following values: + * • nearby – Searches in a radius around a location. + * • nearRoute – Searches for results that are within 1 mile of a route. + * • intersects – Searches for results that intersect with the specified geometry. + * Note: Note that the NavteqNA and NavteqEU data sources only support nearby queries. + */ + spatialFilterType: string; + + /** Location at which the filter should be applied (only for nearby filter). */ + location?: string | Location; + + /** + * Radius to use when performing a nearby search. The distance in kilometers and must be between 0.16 and 1000 kilometers + * (only for nearby filter). + */ + radius?: number; + + /** Start location of the route (only for nearroute filter). */ + start?: string | Location; + + /** End location of the route (only for nearroute filter). */ + end?: string | Location; + + /** Intersection object. Can be a well known text string or a LocationRect object (only for intersects filter). */ + intersects?: string | LocationRect | IPrimitive; + } + + /** Options for find near route query API. */ + export interface IFindNearRouteOptions extends ISpatialFilterOptions { + /** + * One of the following values: + * • Driving [default] + * • Walking + */ + travelMode?: string; + + /** + * An integer value between 0 and 359 that represents degrees from north + * where north is 0 degrees and the heading is specified clockwise from north. + * For example, setting the heading of 270 degrees creates a route that initially heads west + */ + heading?: number; + + /** + * An integer distance specified in meters. + * Use this parameter to make sure that the moving vehicle has enough distance + * to make the first turn + */ + distanceBeforeFirstTurn?: number; + + /** + * A list of values that limit the use of highways and toll roads in the route. + * Use one of the following values: + * • highways - Avoids the use of highways in the route. + * • tolls - Avoids the use of toll roads in the route. + * • minimizeHighways - Minimizes (tries to avoid) the use of highways in the route. + * • minimizeTolls - Minimizes (tries to avoid) the use of toll roads in the route. + */ + avoid?: string[]; + + /** + * One of the following values: + * • distance - The route is calculated to minimize the distance.Traffic information is not used. + * • time[default] - The route is calculated to minimize the time.Traffic information is not used. + * • timeWithTraffic - The route is calculated to minimize the time and uses current traffic information. + */ + optimize?: string; + } + + /** Set of options that can be specified for query APIs. */ + export interface IQueryAPIOptions { + /** A queryurl containing the access id, data source name and the entity type name. */ + queryUrl: string; + + /** Specifies a conditional expression for a list of properties and values. */ + filter?: IFilter; + + /** Specifies whether or not to return a count of the results in the response. Default: false */ + inlineCount?: boolean; + + /** Specifies to query the staged version of the data source instead of the published version. Default: false */ + isStaging?: boolean; + + /** + * Specifies one or more properties to use to sort the results of a query. + * You can specify up to three (3) properties. Results are sorted in ascending order. + * Note: You cannot use the latitude and longitude properties to sort results. You can use the elevation property. + */ + orderBy?: string[]; + + /** + * Specifies the data source properties to return in the response. If the $select query option is not specified or + * if it is set to "" ($select=), all data source properties are returned. Default: "*,_distance" + */ + select?: string[]; + + /** Specifies to not return a specified number of query results. */ + skip?: number; + + /** Spatial filter options to apply. */ + spatialFilter?: ISpatialFilterOptions | IFindNearRouteOptions; + + /** Specifies the maximum number of results to return in the query response. Default: 25 */ + top?: number; + } + + /** + * This is a static class that provides that ability to query data sources that are hosted by the Bing Spatial Data Services using the Query API. + * @requires The Microsoft.Maps.SpatialDataService module. + */ + export module QueryAPIManager { + /** + * Perform a search + * @requires The Microsoft.Maps.SpatialDataService module. + * @param queryOptions - Options for the query + * @param credentials - Credentials for the query + * @param callback - The function to call once the results are retrieved + * @param styles - (Optional) Styles of the data that needs to be rendered on map + */ + export function search(queryOptions: IQueryAPIOptions, + credentials: string | Map, + callback: (data: IPrimitive[], inlineCount?: number) => void, + styles?: IStylesOptions): void; + } +} \ No newline at end of file diff --git a/types/bingmaps/SpatialMath.d.ts b/types/bingmaps/SpatialMath.d.ts new file mode 100644 index 0000000000..94c4ceab61 --- /dev/null +++ b/types/bingmaps/SpatialMath.d.ts @@ -0,0 +1,537 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +////////////////////////////////////////////// +/// Core Library +////////////////////////////////////////////// + +/** + * This module provides a bunch of useful spatial math calculations. + * @requires The Microsoft.Maps.SpatialMath module. + */ +declare module Microsoft.Maps.SpatialMath { + + /** + * Distance Unit enumerator + * @requires The Microsoft.Maps.SpatialMath module. + **/ + export enum DistanceUnits { + /** A distance in meters */ + Meters, + + /** A distance in kilometers */ + Kilometers, + + /** A distance in miles */ + Miles, + + /** A distance in Feet */ + Feet, + + /** A distance in Yards */ + Yards, + + /** A distance in Nautical Miles */ + NauticalMiles + } + + /** + * Area units enumerator + * @requires The Microsoft.Maps.SpatialMath module. + **/ + export enum AreaUnits { + /** Area in square meters */ + SquareMeters, + + /** Area in square kilometers */ + SquareKilometers, + + /** Area in square miles */ + SquareMiles, + + /** Area in square Feet */ + SquareFeet, + + /** Area in square Yards */ + SquareYards, + + /** Area in Acres */ + Acres, + + /** Area in Hectares */ + Hectares + } + + ////////////////////////////////////////////// + /// Core Calculations + ////////////////////////////////////////////// + + /** + * Converts an area from one area units to another. + * @param area A number that represents an area to convert. + * @param fromUnits The area units the original area is in. + * @param toUnits The area units to convert to. + * @returns An area in the new units. + **/ + export function convertArea(area: number, fromUnits: AreaUnits, toUnits: AreaUnits): number; + + /** + * Converts a distance from one distance units to another. + * @param distance A number that represents a distance to convert. + * @param fromUnits The distance units the original distance is in. + * @param toUnits The disired distance units to convert to. + * @returns A distance in the new units. + **/ + export function convertDistance(distance: number, fromUnits: DistanceUnits, toUnits: DistanceUnits): number; + + /** + * Calculates an array of locations that form a cardinal spline between the specified array of locations. + * @param locations The array of locations to calculate the spline through. + * @param tension A number that indicates the tightness of the curve. Can be any number, although a value between 0 and 1 is usually used. Default: 0.5 + * @param nodeSize Number of nodes to insert between each Location. Default: 15 + * @param close A boolean indicating if the spline should be a closed ring or not. Default: false + * @returns An array of locations that form a cardinal spline between the specified array of locations. + */ + export function getCardinalSpline(locations: Location[], tension ?: number, nodeSize ?: number, close ?: boolean): Location[]; + + /** + * Calculates a destination Location based on a starting Location, a heading, a distance, and a distance unit type. + * @param origin Location that the destination is relative to. + * @param bearing A heading angle between 0 - 360 degrees. 0 - North, 90 - East, 180 - South, 270 - West. + * @param distance Distance that destination is away. + * @param units Unit of distance measurement. Default is Meters. + * @returns A Location that is the specified distance away from the origin. + **/ + export function getDestination(origin: Location, bearing: number, distance: number, units?: DistanceUnits): Location; + + /** + * Calculate the distance between two Location objects on the surface of the earth using the Haversine formula. + * @param origin First Location to calculate distance between. + * @param destination Second Location to calculate distance between. + * @param units Unit of distance measurement. Default is Meters. + * @param highAccuracy When set enabled, will use the slower but more accurate Vincenty formula for calculating distances, rather than the Haversine formula. + * @returns The shortest distance between two Locations in the specifed units. + **/ + export function getDistanceTo(origin: Location, destination: Location, units?: DistanceUnits, highAccuracy?: boolean): number; + + /** + * Retrieves the radius of the earth in a specific distance unit for WGS84. + * @param units Unit of distance measurement. Default: Meters + * @returns A number that represents the radius of the earth in a specific distance unit. + **/ + export function getEarthRadius(units?: DistanceUnits): number; + + /** + * Takes an array of Locations objects and fills in the space between them with accurately positioned Locations to form an approximated Geodesic path. + * @param path Array of Location objects that form a path to fill in. + * @param nodeSize Number of nodes to insert between each Location. Default: 15 + * @returns An array of Location objects that form a geodesic paths. + **/ + export function getGeodesicPath(path: Location[], nodeSize?: number): Location[]; + + /** + * Calculates the heading from one Location object to another. + * @param origin Point of origin. + * @param destination Destination to calculate relative heading to. + * @returns A heading in degrees between 0 and 360. 0 degrees points due North. + **/ + export function getHeading(origin: Location, destination: Location): number; + + /** + * Calculates the distance between all Location objects in an array. + * @param path The array of Location objects that make up the path to calculate the length of. + * @param units Unit of distance measurement. Default: Meters + * @param highAccuracy If set to true, uses the more accurate Vincenty algorithm for calcuating distances. Otherwise the faster Haversine formula is used. + * @returns The distance between all Locations in between all Location objects in an array on the surface of a earth in the specifed units. + **/ + export function getLengthOfPath(path: Location[], units?: DistanceUnits, highAccuracy?: boolean): number; + + /** + * Calculates the Location object on a path that is a specified distance away from the start of the path. If the specified distance is longer + * than the length of the path, the last Location of the path will be returned. + * @param path A polyline or array of Location coordinates that form a path. + * @param distance The distance along the path (from the start) to calculate the location for. + * @param units Unit of distance measurement. Default is Meters. + * @returns A Location object that is the specified distance away from the start of the path when following the path. + **/ + export function getLocationAlongPath(path: Polyline | Location[], distance: number, units?: DistanceUnits): Location; + + /** + * Calculates an array of Location objects that are an equal distance away from a central point to create a regular polygon. + * @param origin Center of the regular polygon. + * @param radius Radius of the regular polygon. + * @param numberOfPoints Number of points the polygon should have. + * @param units Unit of distance measurement for radius. Default is Meters. + * @param offset An offset to rotate the polygon clockwise in degrees. When 0 the first Location will align with North. + * @returns An array of Location objects that form a regular polygon. + **/ + export function getRegularPolygon(origin: Location, radius: number, numberOfPoints: number, units?: DistanceUnits, offset?: number): Location[]; + + /** + * Calculates a Location object that is a fractional distance between two Location objects. + * @param origin First Location to calculate mid-point between. + * @param destination Second Location to calculate mid-point between. + * @param fraction The fractional parameter to calculate a mid-point for. Default 0.5. + * @returns A Location that lies a fraction of the distance between two Location objects, relative to the first Location object. + **/ + export function interpolate(origin: Location, destination: Location, fraction?: number): Location; + + /** + * Takes a LocationRect and converts it to a polygon. + * @param bounds The LocationRect to convert to a Polygon. + * @returns A polygon representation of the LocationRect. + **/ + export function locationRectToPolygon(bounds: LocationRect): Polygon; + + /** + * Takes a Location object and converts it into a Degree Minute Seconds string in the format. For example: 40° 26′ 46″ N 79° 58′ 56″ W + * @param loc The Location object to convert into a Degree Minute Seconds string. + * @returns A string in Degree Minute Seconds format or null if invalid Location object is provided. + */ + export function toDegMinSec(loc: Location): string; + + /** + * Tries to parse the given string that is in Degree Minute Seconds format. For Example: 35° 26′ 31″ E or 40° 26′ 46″ N 79° 58′ 56″ W + * @param input A string in Degree Minute Seconds format to parse. + * @returns Returns a decimal degree value if only a single angle is provided. If two angles provided in the string, then a + * Location object is returned. If string is in an invalid format, null is returned. + */ + export function tryParseDegMinSec(input: string): number | Location; +} + + +////////////////////////////////////////////// +/// Tile Calculations +////////////////////////////////////////////// + +/** +* A colleciton of mathematical algorithms based on the tile pyramid used by Bign Maps. +* @requires The Microsoft.Maps.SpatialMath module. +*/ +declare module Microsoft.Maps.SpatialMath.Tiles { + //Based on https://msdn.microsoft.com/en-us/library/bb259689.aspx + + /** + * Calculates the full width of the map in pixels at a specific zoom level from -180 degrees to 180 degrees. + * @param zoom Zoom level to calculate width at. + * @param tileWidth Width of tile. + * @returns Width of map in pixels. + **/ + export function mapSize(zoom: number): number; + + /** + * Calculates the Ground resolution at a specific degree of latitude in the specified units per pixel. + * @param latitude Degree of latitude to calculate resolution at. + * @param zoom Zoom level to calculate resolution at. + * @param units Distance unit type to calculate resolution in. + * @returns Ground resolution in distance unit per pixels. + **/ + export function groundResolution(latitude: number, zoom: number, units?: SpatialMath.DistanceUnits): number; + + /** + * Converts a Pixel coordinate into a Geospatial Location at a specified zoom level. + * Global Pixel coordinates are relative to the top left corner of the map (90, -180) + * @param point Pixel coordinate. + * @param zoom Zoom level. + * @returns A Location that is at the specified pixel location at a specified zoom level. + **/ + export function globalPixelToLocation(point: Point, zoom: number): Location; + + /** + * Converts a point from latitude/longitude WGS-84 Location (in degrees) + * into pixel XY coordinates at a specified level of detail. + * @param loc Location to convert to a global pixel. + * @param zoom Level of detail, from 1 (lowest detail) to 23 (highest detail). + * @returns Point object containing the the global pixel location of a Location. + **/ + export function locationToGlobalPixel(loc: Location, zoom: number): Point; + + /** + * Calculates the PyramidTileId that a global pixel intersects with at a specific zoom level. + * @param pixel The pixel coordinate to calculate the tile for. + * @param zoom The zoom level to calculate the tile for. + * @returns A PyramidTileId that a global pixel intersects with at a specific zoom level. + **/ + export function globalPixelToTile(pixel: Point, zoom: number): PyramidTileId; + + /** + * Converts a PyramidTileId into a global pixel coordinates of the upper-left pixel of the specified tile. + * @param tile A PyramidTileId to calculate the upper-left pixel for. + * @returns Global pixel coordinate of the top left corner of a tile. + **/ + export function tileToGlobalPixel(tile: PyramidTileId): Point; + + /** + * Calculates the PyramidTileId that a Location object intersects with at a specific zoom level. + * @param loc The location to calulate the tile for. + * @param zoom The zoom level to use to calculate the tile. + * @returns A PyramidTileId that a Location object intersects with at a specific zoom level. + **/ + export function locationToTile(loc: Location, zoom: number): PyramidTileId; + + /** + * Calculates all the PyramidTileId's that are within a LocationRect at a specific zoom level. + * @param bounds A LocationRect to search for tiles in. + * @param zoom The zoom level to calculate tiles for. + * @returns A list of PyramidTileId's that are within the specified LocationRect and zoom level. + **/ + export function getTilesInBounds(bounds: LocationRect, zoom: number): PyramidTileId[]; + + /** + * Calculates the LocationRect (bounding box) of a PyramidTileId. + * @param tile A PyramidTileId to calculate the LocationRect of. + * @returns The bounding box of a tile. + **/ + export function tileToLocationRect(tile: PyramidTileId): LocationRect; +} + + +////////////////////////////////////////////// +/// Geometry Calculations +////////////////////////////////////////////// + +/** +* A colleciton of geometry calculations that can be performed against Bing Maps shapes. +* @requires The Microsoft.Maps.SpatialMath module. +*/ +declare module Microsoft.Maps.SpatialMath.Geometry { + + /** Defines how the end of a line should be buffered. */ + export enum BufferEndCap { + /** Adds a rounded end to a buffered line. */ + Round, + + /** Adds a flat end to a buffered line that touches the end of the line. */ + Flat, + + /** Adds a square end to a buffered line that has a buffer area at the end of the line. */ + Square + } + + /** + * Calculates the area of a shape. + * @param shape The shape to calculate the area of. + * @param areaUnits The unit of measurement to calculate the area in. + * @returns The area of a shape in the specified unit of measurement. + */ + export function area(shape: IPrimitive | IPrimitive[], areaUnits?: AreaUnits): number; + + /** + * Calculates a bounding box that encloses a set of shapes and/or locations. + * @param shapes The shape(s) to calculate the bounding box for. + * @returns A location rect that encloses the shapes and/or locations. + */ + export function bounds(shapes: Location | IPrimitive | (Location | IPrimitive)[]): LocationRect; + + /** + * Calcuates a shape with an updated boundary that has been inflated/deflated by a speicifed distance. + * @param shape The shape to buffer. + * @param distance The distance to buffer the shape by. + * @param units The distance units to buffer the shape by. + * @param endCapType The type of end cap to use for the joints of the buffer, default value is round. + * @param options A set of polygon options to apply to the generated shape. + * @returns A buffered version of the shape. + */ + export function buffer(shape: Location | IPrimitive | (Location | IPrimitive)[], distance: number, units?: DistanceUnits, endCapType?: BufferEndCap, options?: IPolygonOptions): IPrimitive | IPrimitive[]; + + /** + * Calculates the center of a shape. + * @param shape The shape to calculate the center of. + * @returns The center of the specified shape. + */ + export function centroid(shape: IPrimitive | IPrimitive[]): Location; + + /** + * Calculates an approximate concave hull that best fits the data. + * A concave hull is a shape that represents that a possible concave geometry that encloses all shapes in the specified data set. + * If a single unique Location is in the data set, a Pushpin is returned. If only two unique Locations are provided, or if all Locations form a line, a Polyline is returned. + * If 3 or more unique Locations are in the data set a Polygon, or array of Polygons will be returned. + * @param shapes Shape(s) whose Location(s) or Location(s) are to be used to generate a concave hull. + * @param allowMultiPolygons A boolean indicating if the resulting concave hull can be a MultiPolygon. Default: false + * @param allowHoles A boolean indicating if the polygons in the resulting concave hull can have holes in them. Default: false + * @param options A set of polygon options to apply to the generated shape. + * @returns An approximate concave hull that best fits the data. + * If a single unique Location is in the data set, a Pushpin is returned. If only two unique Locations are provided, or if all Locations form a line, a Polyline is returned. + * If 3 or more unique Locations are in the data set a Polygon, or array of Polygons will be returned. + */ + export function concaveHull(shapes: Location | IPrimitive | (Location | IPrimitive)[], allowMultiPolygons?: boolean, allowHoles?: boolean, options?: IPolygonOptions): IPrimitive | IPrimitive[]; + + /** + * Given two shapes, determines if the first one contains the second one + * (or, the second shape is a subset of the first shape) or not. + * @param shapeA The first shape to test against the second. + * @param shapeB The second shape to test against the first. + * @returns A boolean indicating if the first shape contains the second shape. + */ + export function contains(shapeA: Location | IPrimitive | (Location | IPrimitive)[], shapeB: Location | IPrimitive | (Location | IPrimitive)[]): boolean; + + /** + * Calculates a convex hull. A convex hull is a shape that represents that minimum convex geometry that encloses all shapes in the specified data set. + * @param shapes Shape(s) whose Location(s) or Location(s) are to be used to generate a convex hull. + * @param options A set of polygon options to apply to the generated shape. + * @returns An array of locations that form a convex hull that encloses all locations of the shapes provided in an array. + */ + export function convexHull(shapes: Location | IPrimitive | (Location | IPrimitive)[], options?: IPolygonOptions): IPrimitive | IPrimitive[]; + + /** + * Creates Delaunay Triangles from the Location objects of the provided shapes. + * @param shapes Location(s) of shape(s) or Location(s) to generate a Delaunay Triangles from. + * @param options A set of polyline or polygon options to apply to the generated shape. + * @returns An array of shapes that form the polygon triangles of the delaunay triangles. + */ + export function delaunayTriangles(shapes: Location | IPrimitive | (Location | IPrimitive)[], options?: IPolygonOptions): Polygon[]; + + /** + * Returns an object that represents area of an initial shape subtracted by the overlapping area of a second shape. + * @param shapeA The first shape. + * @param shapeB The second shape to subtract from the first. + * @returns A set of shapes that represent the area of the first shape that is not overlapped by the second shape. + */ + export function difference(shapeA: IPrimitive | IPrimitive[], shapeB: IPrimitive | IPrimitive[]): IPrimitive | IPrimitive[]; + + /** + * Calculates the approximate shortest distance between any two shapes. + * @param shapeA The first shape to calculate the distance from. + * @param shapeB The second shape to calculate the distance to. + * @param units Unit of distance measurement. Default: Meters + * @param highAccuracy If set to true, uses the more accurate Vincenty algorithm for calcuating distances. Otherwise the faster Haversine formula is used. + * @returns The shorested distance between the shapes in the specified units. + */ + export function distance(shapeA: Location | IPrimitive | (Location | IPrimitive)[], shapeB: Location | IPrimitive | (Location | IPrimitive)[], units?: DistanceUnits, highAccuracy?: boolean): number; + + /** + * Returns an object that represents the area where two shapes intersect. + * @param shapeA The first shape. + * @param shapeB The second shape. + * @returns A set of shapes that represents the area where two shapes intersect. + */ + export function intersection(shapeA: IPrimitive | IPrimitive[], shapeB: IPrimitive | IPrimitive[]): IPrimitive | IPrimitive[]; + + /** + * Determines if two shapes intersect or not. + * @param shapeA The first shape to test against the second. + * @param shapeB The second shape to test against the first. + * @returns A boolean indicating if the two shapes intersect. + */ + export function intersects(shapeA: Location | IPrimitive | (Location | IPrimitive)[], shapeB: Location | IPrimitive | (Location | IPrimitive)[]): boolean; + + /** + * Tests to see if the shape is valid and meets the requirements of an SQL Geography type and other OGC compliant systems. Polylines & Polygons can't be self intersecting. For Polygons, + * coordinates in an exterior rings have a counter-clockwise orientation, while holes have a clockwise orientation. + * @param shape The shape to test for validity. + * @returns Returns a boolean indicting if the specified shape(s) is valid or not. + */ + export function isValid(shape: IPrimitive | IPrimitive[]): boolean; + + /** + * Calculates the distance between all Locations in a shape. If the shape is a polygon, the length of the perimeter of all rings is calculated. + * @param shape The shape to calculate the length of. + * @param units Unit of distance measurement. Default: Meters + * @param highAccuracy If set to true, uses the more accurate Vincenty algorithm for calcuating distances. Otherwise the faster Haversine formula is used. + * @returns The distance between all Locations in a polyline or the perimeter of a ploygon on the surface of a earth in the specifed units. + */ + export function calculateLength(shape: IPrimitive | IPrimitive[], units ?: DistanceUnits, highAccuracy ?: boolean): number; + + /** + * Takes a shape and returns a copy of it that meets the requirements of an SQL Geography type and other OGC compliant systems. Polylines & Polygons can't be self intersecting. For Polygons, + * coordinates in an exterior rings have a counter-clockwise orientation, while holes have a clockwise orientation. + * @param shape The shape to make valid. + * @returns Valiated version of the provided shape. May be a different shape type than what was provided. i.e. A polygon may be broken up into an array of polygons (MultiPolygon). + */ + export function makeValid(shape: IPrimitive | IPrimitive[]): IPrimitive | IPrimitive[]; + + /** + * Calculates the nearest Location objects between to shapes that lie on the shapes. + * If the shapes do not overlap, this calculates a location on each shape that is closest to the other shape. + * If the shapes overlap, a location that is within the intersection area of the shapes will be added twice to an array, once for each shape, and returned. + * @param shapeA The first shape. + * @param shapeB The second shape. + * @returns An array of two Location objects that represent the nearest points between two shapes. + * The Location objects are in the same order as the input shapes. + * Returns null if nearest points were unable to be computed. + */ + export function nearestLocations(shapeA: Location | IPrimitive | (Location | IPrimitive)[], shapeB: Location | IPrimitive | (Location | IPrimitive)[]): Location[]; + + /** + * Reduces the resolution of a shape using the Douglas-Peucker algorithm. + * @param shape The shape to reduce the resolution of. + * @param tolerance A tolerance distance in meters used by the reduction algorithms. + * @returns A version of the specified shape that has been reduced. + */ + export function reduce(shape: IPrimitive | IPrimitive[], tolerance: number): IPrimitive | IPrimitive[]; + + /** + * Rotates a shape around a given Location for the specified angle of rotation. If an origin is not provided, the centroid of the shape is used. + * @param shape The shape to be rotated. + * @param angle The amount to rotate the shape in degrees. + * @param origin The location to rotate the shape around. Defaults to the centroid of the shape. + */ + export function rotate(shape: IPrimitive | IPrimitive[], angle: number, origin?: Location): void; + + /** + * Calculates the shortest path that between two shapes and returns a Polyline. + * @param shapeA The first shape. + * @param shapeB The second shape. + * @param options A set of polyline options to apply to the generated polyline. + * @returns A polyline that represents the shortest path between two shapes. + */ + export function shortestLineTo(shapeA: Location | IPrimitive | (Location | IPrimitive)[], shapeB: Location | IPrimitive | (Location | IPrimitive)[], options?: IPolylineOptions): Polyline; + + /** + * Snaps the locations of one shape that are within the specified tolerance distance away from another shape. + * @param locs The locations to snap to the shape. + * @param shape The shape to snap the locations to. + * @param tolerance A maximum distance (in the specified units) that the snapped location can be from the input location. Default: Infinity + * @param toleranceUnits The distance units of the tolerance value. Default: Meters + * @returns A snapped location if only one location is provided, otherwise returns an array of snapped locations. + */ + export function snapLocationsToShape(locs: Location | Location[], shape: IPrimitive | IPrimitive[], tolerance?: number, toleranceUnits?: DistanceUnits): Location | Location[]; + + /** + * Snaps the locations of one shape that are within the specified tolerance distance away from another shape. + * @param shapeToSnap The shape to snap the locations of. + * @param shape The shape to snap the locations to. + * @param tolerance A maximum distance (in the specified units) that the snapped location can be from the input location. Default: Infinity + * @param toleranceUnits The distance units of the tolerance value. Default: Meters + */ + export function snapShapeToShape(shapeToSnap: IPrimitive | IPrimitive[], shape: IPrimitive | IPrimitive[], tolerance?: number, toleranceUnits?: DistanceUnits): void; + + /** + * Returns an object that represents all points that are either in one shape instance or another, but not those points that lie in both instances. + * "Sym" stands for Symmetric. symDifference is an OGC standard name for this calculation used in most spatial math libraries, including SQL. + * @param shapeA The first shape. + * @param shapeB The second shape. + * @returns A shape that represents the symetric difference between two shapes. + */ + export function symDifference(shapeA: IPrimitive | IPrimitive[], shapeB: IPrimitive | IPrimitive[]): IPrimitive | IPrimitive[]; + + /** + * Returns an object that represents the union of two shapes. If shapes don't overlap, an array of each individual shapes will be returned. + * @param shapeA The first shape. + * @param shapeB The second shape. + * @returns A shape that represents the union of two shapes. + */ + export function union(shapeA: IPrimitive | IPrimitive[], shapeB: IPrimitive | IPrimitive[]): IPrimitive | IPrimitive[]; + + /** + * Performs a union operation on a set of shapes. + * If a shape doesn't overlap with the rest, the returned result will be an array of shapes containing this shape and the union of the rest. + * @param shapes An array of shapes to union together. + * @returns A shape that represents the union of all specified shapes. + */ + export function unionAggregate(shapes: IPrimitive[]): IPrimitive | IPrimitive[]; + + /** + * Creates a Voronoi diagram from the Location objects of the provided shapes. The diagram is returned as an array of Polygons. + * If a clip region is specified, the diagram will be clipped accordingly. + * @param shapes Location(s) of shape(s) or Location(s) to generate a Voronoi diagram. + * @param clipRegion A region to clip the voronoi diagram to. + * @param options A set of polygon options to apply to the generated shape. + * @returns An array of polygons that form a Voronoi diagram. + */ + export function voronoiDiagram(shapes: Location | IPrimitive | (Location | IPrimitive)[], clipRegion?: LocationRect | Polygon, options?: IPolygonOptions): Polygon[]; +} \ No newline at end of file diff --git a/types/bingmaps/Traffic.d.ts b/types/bingmaps/Traffic.d.ts new file mode 100644 index 0000000000..46f508128f --- /dev/null +++ b/types/bingmaps/Traffic.d.ts @@ -0,0 +1,75 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * Adds a traffic incident and flow data to the map. + * @requires The Microsoft.Maps.Traffic module. + */ +declare module Microsoft.Maps.Traffic { + /** Options that can be customized in the Traffic manager. */ + export interface ITrafficOptions { + /** Displays the traffic flow layer. */ + flowVisible?: boolean; + + /** Displays all traffic incidents. */ + incidentsVisible?: boolean; + + /** Displays the traffic legend. */ + legendVisible?: boolean; + + /** + * Sets the opacity of the traffic flow tile layer. Must be a number between 0 and 1. The default is 1 unless the map + * mode is set to lite, in which case the default is set to 0.7. + */ + opacity?: number; + } + + /** + * The TrafficManager class provides the ability to show traffic flow and incident data on top of the map. When creating an + * instance of the TrafficManager class the map must be passed as an argument to the constructor. + * @requires The Microsoft.Maps.Traffic module. + */ + export class TrafficManager { + /** + * @constructor + * @requires The Microsoft.Maps.Traffic module. + * @param map A map instnce to attach the traffic manager to. + */ + constructor(map: Map); + + /** Hides all traffic data. */ + public hide(): void; + + /** Hides the traffic flow layer. */ + public hideFlow(): void; + + /** Hides all traffic incidents. */ + public hideIncidents(): void; + + /** Hides the traffic legend. */ + public hideLegend(): void; + + /** + * Sets the options for the traffic manager. + * @param options The options for the traffic manager. + */ + public setOptions(options: ITrafficOptions): void; + + /** Displays all traffic data. */ + public show(): void; + + /** Displays the traffic flow layer. */ + public showFlow(): void; + + /** Displays all traffic incidents. */ + public showIncidents(): void; + + /** Displays the traffic legend. */ + public showLegend(): void; + + } +} \ No newline at end of file diff --git a/types/bingmaps/UNUSED_FILES.txt b/types/bingmaps/UNUSED_FILES.txt index edf324bfcc..b0c81f8c63 100644 --- a/types/bingmaps/UNUSED_FILES.txt +++ b/types/bingmaps/UNUSED_FILES.txt @@ -1,6 +1,13 @@ -Microsoft.Maps.AdvancedShapes.d.ts -Microsoft.Maps.Directions.d.ts -Microsoft.Maps.Search.d.ts -Microsoft.Maps.Themes.BingTheme.d.ts -Microsoft.Maps.Traffic.d.ts -Microsoft.Maps.VenueMaps.d.ts \ No newline at end of file +Autosuggest.d.ts +Clustering.d.ts +Contour.d.ts +DataBinning.d.ts +Directions.d.ts +DrawingTools.d.ts +GeoJson.d.ts +HeatMapLayer.d.ts +Search.d.ts +SpatialDataService.d.ts +SpatialMath.d.ts +Traffic.d.ts +WellKnownText.d.ts \ No newline at end of file diff --git a/types/bingmaps/WellKnownText.d.ts b/types/bingmaps/WellKnownText.d.ts new file mode 100644 index 0000000000..1a0670ae1c --- /dev/null +++ b/types/bingmaps/WellKnownText.d.ts @@ -0,0 +1,29 @@ +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module Microsoft.Maps { + /** + * Class responsible for readon/writing geo data in well known text format + * @requires The Microsoft.Maps.WellKnownText module. + */ + export module WellKnownText { + /** + * Reads the data in wellknowntext format and returns the shapes. Multi-Geometry type shapes are returned as an array of shapes. + * @param wkt The well known text string that needs to be parsed into shapes. + * @param styles Styles to apply to the shapes. + * @returns One of more shapes. + */ + export function read(wkt: string, styles?: IStylesOptions): IPrimitive | IPrimitive[]; + + /** + * Writes the data into wellknowntext format. + * @param data The data that needs to be serialized. + * @returns Well known text formatted string. + */ + export function write(data: IPrimitive | IPrimitive[]): string; + } +} \ No newline at end of file diff --git a/types/bingmaps/bingmaps-tests.ts b/types/bingmaps/bingmaps-tests.ts index e83ff89aba..962c3047fa 100644 --- a/types/bingmaps/bingmaps-tests.ts +++ b/types/bingmaps/bingmaps-tests.ts @@ -1,5 +1,5 @@ namespace BingMapsTests { - + // An interactive set of Bing Maps AJAX control usages can be found at http://www.bingmapsportal.com/isdk/ajaxv7 // A full API description can be found at http://msdn.microsoft.com/en-us/library/gg427610.aspx export class TestFixture { @@ -13,27 +13,25 @@ namespace BingMapsTests { mapPositions: Array, // This will fire if the geolocation fails and will pass the original target (parameter 2) onFailure: (element: HTMLElement) => any) { - + var self = this; var map: Microsoft.Maps.Map; navigator.geolocation.getCurrentPosition((position: Position) => { var locations: Array = new Array(); - var options: Microsoft.Maps.MapOptions; + var options: Microsoft.Maps.IMapLoadOptions; function loadMap() { - options = {}; - options.credentials = bingMapsApiKey; - options.enableClickableLogo = false; - options.enableSearchLogo = false; - options.showDashboard = false; - options.showScalebar = false; - options.center = self.toLocation(position); - options.zoom = 16; - options.mapTypeId = Microsoft.Maps.MapTypeId.road; - options.height = target.clientHeight; - options.width = target.clientWidth; + options = { + credentials: bingMapsApiKey, + enableClickableLogo: false, + showDashboard: false, + showScalebar: false, + center: self.toLocation(position), + zoom: 16, + mapTypeId: Microsoft.Maps.MapTypeId.road + }; target.innerHTML = ""; diff --git a/types/bingmaps/index.d.ts b/types/bingmaps/index.d.ts index 95644801c5..919b7df62f 100644 --- a/types/bingmaps/index.d.ts +++ b/types/bingmaps/index.d.ts @@ -1,553 +1,2836 @@ -// Type definitions for Microsoft.Maps 7.0 -// Project: http://msdn.microsoft.com/en-us/library/gg427611.aspx -// Definitions by: Eric Todd +// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4) +// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions +// Definitions by: Ricky Brundritt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace Microsoft.Maps { +/** + * The Bing Maps V8 developer API. + */ +declare module Microsoft.Maps { + + ////////////////////////////////////////////// + /// Custom Map Styles + ////////////////////////////////////////////// + + /** The styles options that can be applied to map elements. */ + export interface IMapElementStyle { + /** + * Hex color used for filling polygons, the background of point icons, and for the center of lines if they have split. + */ + fillColor?: string; - export enum AltitudeReference { - ground, - ellipsoid + /** + * The hex color of a map label. + */ + labelColor?: string; + + /** + * The outline hex color of a map label. + */ + labelOutlineColor?: string; + + /** + * Species if a map label type is visible or not. + */ + labelVisible?: boolean; + + /** + * Hex color used for the outline around polygons, the outline around point icons, and the color of lines. + */ + strokeColor?: string; + + /** + * Specifies if the map element is visible or not. + */ + visible?: boolean; } - export class Location { + /** The style options that can be appliction to bordered map elements. */ + export interface IBorderedMapElementStyle extends IMapElementStyle { + /** + * Secondary/casing line hex color of the border of a filled polygon. + */ + borderOutlineColor?: string; - constructor(latitude: number, longitude: number, altitude?: number, altitudeReference?: AltitudeReference); + /** + * Primary line hex color of the border of a filled polygon. + */ + borderStrokeColor?: string; - altitude: number; - altitudeReference: AltitudeReference; - latitude: number; - longitude: number; - - static areEqual(location1: Location, location2: Location): boolean; - static normalizeLongitude(longitude: number): number; - - clone(): Location; - toString(): string; + /** + * Specifies if a border is visible or not. + */ + borderVisible?: boolean; } - export class LocationRect { - - constructor(center: Location, width: number, height: number); - - center: Location; - height: number; - width: number; - - static fromCorners(northwest: Location, southeast: Location): LocationRect; - static fromEdges(north: number, west: number, south: number, east: number, altitude: number, altitudeReference: AltitudeReference): LocationRect; - static fromLocations(locations: Array): LocationRect; - static fromString(value: string): LocationRect; - - clone(): LocationRect; - contains(location: Location): boolean; - getEast(): number; - getNorth(): number; - getNorthwest(): Location; - getSouth(): number; - getSoutheast(): Location; - getWest(): number; - intersects(rect: LocationRect): boolean; - toString(): string; + /** Global style settings */ + export interface ISettingsStyle { + /** A hex color value that all land is first flushed to before things are drawn on it. */ + landColor?: string; + + /** Specifies whether or not to draw elevation shading on the map. */ + shadedReliefVisible?: boolean; } - export class Point { + /** Map Elements which can be styled. */ + export interface IMapElements { - constructor(x: number, y: number); + /** Admin1, state, province, etc. */ + adminDistrict?: IBorderedMapElementStyle; - x: number; - y: number; + /** Icon representing the capital of a state/province. */ + adminDistrictCapital?: IMapElementStyle; - static areEqual(p1: Point, p2: Point): boolean; - static clone(p: Point): Point; + /** Area of land encompassing an airport. */ + airport?: IMapElementStyle; - clone(): Point; - toString(): string; + /** Area of land use, not to be confused with Structure */ + area?: IMapElementStyle; + + /** An arterial road is a high-capacity urban road. Its primary function is to deliver traffic from collector roads to freeways or expressways, and between urban centers efficiently. */ + arterialRoad?: IMapElementStyle; + + /** A structure such as a house, store, factory. */ + building?: IMapElementStyle; + + /** Restaurant, hospital, school, etc. */ + business?: IMapElementStyle; + + /** Icon representing the capital populated place. */ + capital?: IMapElementStyle; + + /** Area of a cemetery */ + cemetery?: IMapElementStyle; + + /** Area of a whole continent */ + continent?: IMapElementStyle; + + /** A controlled-access highway is a type of road which has been designed for high-speed vehicular traffic, with all traffic flow and ingress/egress regulated. Also known as a highway, freeway, motorway, expressway, interstate, parkway. */ + controlledAccessHighway?: IMapElementStyle; + + /** A country or independent sovereign state. */ + countryRegion?: IBorderedMapElementStyle; + + /** Icon representing the capital of a country/region. */ + countryRegionCapital?: IMapElementStyle; + + /** Admin2, county, etc. */ + district?: IBorderedMapElementStyle; + + /** An area of land used for educational purposes such as a school campus. */ + education?: IMapElementStyle; + + /** A school or other educational building. */ + educationBuilding?: IMapElementStyle; + + /** Restaurant, café, etc. */ + foodPoint?: IMapElementStyle; + + /** Area of forest land. */ + forest?: IMapElementStyle; + + /** An area of land where the game of golf is played. */ + golfCourse?: IMapElementStyle; + + /** Lines representing ramps typically alongside ControlledAccessHighways */ + highSpeedRamp?: IMapElementStyle; + + /** A highway. */ + highway?: IMapElementStyle; + + /** An area of land reserved for Indigenous people. */ + indigenousPeoplesReserve?: IMapElementStyle; + + /** Labeling of area of an island. */ + island?: IMapElementStyle; + + /** Major roads. */ + majorRoad?: IMapElementStyle; + + /** The base map element in which all other map elements inherit from. */ + mapElement?: IMapElementStyle; + + /** Area of land used for medical purposes. Generally, hospital campuses. */ + medical?: IMapElementStyle; + + /** A building which provides medical services. */ + medicalBuilding?: IMapElementStyle; + + /** A military area. */ + military?: IMapElementStyle; + + /** A natural point of interest. */ + naturalPoint?: IMapElementStyle; + + /** Area of land used for nautical purposes. */ + nautical?: IMapElementStyle; + + /** Area defined as a neighborhood. Labels only. */ + neighborhood?: IMapElementStyle; + + /** Area of any kind of park. */ + park?: IMapElementStyle; + + /** Icon representing the peak of a mountain. */ + peak?: IMapElementStyle; + + /** All point features that are rendered with an icon of some sort */ + point?: IMapElementStyle; + + /** Restaurant, hospital, school, marina, ski area, etc. */ + pointOfInterest?: IMapElementStyle; + + /** A political border. */ + political?: IBorderedMapElementStyle; + + /** Icon representing size of populated place (city, town, etc). */ + populatedPlace?: IMapElementStyle; + + /** Railway lines */ + railway?: IMapElementStyle; + + /** Line representing the connecting entrance/exit to a highway. */ + ramp?: IMapElementStyle; + + /** Area of nature reserve. */ + reserve?: IMapElementStyle; + + /** River, stream, or other passage. Note that this may be a line or polygon and may connect to non-river water bodies. */ + river?: IMapElementStyle; + + /** Lines that represent all roads */ + road?: IMapElementStyle; + + /** Icon representing the exit, typically from a controlled access highway. */ + roadExit?: IMapElementStyle; + + /** Sign representing a compact name for a road. For example, I-5. */ + //roadShield?: IMapElementStyle; + + /** Land area covered by a runway. See also Airport for the land area of the whole airport. */ + runway?: IMapElementStyle; + + /** Area generally used for beaches, but could be used for sandy areas/golf bunkers in the future. */ + sand?: IMapElementStyle; + + /** A shopping center or mall. */ + shoppingCenter?: IMapElementStyle; + + /** Area of a stadium. */ + stadium?: IMapElementStyle; + + /** A street. */ + street?: IMapElementStyle; + + /** Buildings and other building-like structures */ + structure?: IMapElementStyle; + + /** A toll road. */ + tollRoad?: IMapElementStyle; + + /** Walking trail, either through park or hiking trail */ + trail?: IMapElementStyle; + + /** Icon representing a bus stop, train stop, airport, etc. */ + transit?: IMapElementStyle; + + /** A transit building. */ + transitBuilding?: IMapElementStyle; + + /** Lines that are part of the transportation network (roads, trains, ferries, etc) */ + transportation?: IMapElementStyle; + + /** An unpaved street. */ + unpavedStreet?: IMapElementStyle; + + /** Forests, grassy areas, etc. */ + vegetation?: IMapElementStyle; + + /** Icon representing the peak of a volcano. */ + volcanicPeak?: IMapElementStyle; + + /** Anything that looks like water */ + water?: IMapElementStyle; + + /** Icon representing a water feature location such as a waterfall. */ + waterPoint?: IMapElementStyle; + + /** Ferry route lines */ + waterRoute?: IMapElementStyle; } - export class Events { + /** Defines a custom map style. */ + export interface ICustomMapStyle { + /** A list of map elements to be styled. */ + elements?: IMapElements; - static addHandler(target: any, eventName: string, handler: (e: any) => void): any; - static addThrottledHandler(target: any, eventName: string, handler: (e: any) => void, throttleInterval: number): any; - static hasHandler(target: any, eventName: string): boolean; - static invoke(target: any, eventName: string, args: any): void; - static removeHandler(handlerId: any): void; - } + /** Global Settings. */ + settings?: ISettingsStyle; - export interface KeyEventArgs { - altKey: boolean; - ctrlKey: boolean; - eventName: boolean; - handled: boolean; - keyCode: string; - originalEvent: any; - shiftKey: boolean; + /** The version of the style syntax used. */ + version: string; } + + ////////////////////////////////////////////// + /// Enumerations + ////////////////////////////////////////////// + /** This enumeration defines how the map labels are displayed. */ export enum LabelOverlay { + /** + * Map labels are hidden. Note that this will have no effect on road maps unless the allowHidingLabelsOfRoad map option + * is set to true. + */ hidden, + + /** Map labels are visible. */ visible } - export interface ZoomRange { - min: number; - max: number; - } - - export class Map { - - constructor(containerElement: HTMLElement, options?: MapOptions); - constructor(containerElement: HTMLElement, options?: ViewOptions); - - entities: EntityCollection; - - static getVersion(): string; - - blur(): void; - dispose(): void; - focus(): void; - getBounds(): LocationRect; - getCenter(): Location; - getCopyrights(callback: (copyrights: Array) => void): void; - getCredentials(callback: (credentials: Array) => void): void; - getHeading(): string; - getHeight(): number; - getImageryId: string; - getMapTypeId(): string; - getMetersPerPixel(): number; - getMode(): MapMode; - getModeLayer(): HTMLElement; - getOptions(): MapOptions; - getPageX(): number; - getPageY(): number; - getRootElement(): HTMLElement; - getTargetBounds(): LocationRect; - getTargetCenter(): Location; - getTargetHeading(): number; - getTargetMetersPerPixel(): number; - getTargetZoom(): number; - getUserLayer(): HTMLElement; - getViewportX(): number; - getViewportY(): number; - getWidth(): number; - getZoom(): number; - getZoomRange(): ZoomRange; - isDownloadingTiles(): boolean; - isMercator(): boolean; - isRotationEnabled(): boolean; - setMapType(mapTypeId: MapTypeId): void; - setOptions(options: MapOptions): void; - setView(options: ViewOptions): void; - tryLocationToPixel(locations: Location, reference?: PixelReference): Point; - tryLocationToPixel(locations: Array, reference?: PixelReference): Array; - tryPixelToLocation(points: Point, reference?: PixelReference): Location; - tryPixelToLocation(points: Array, reference?: PixelReference): Array; - } - - export class MapMode { - - getDrawShapesInSingleLayer(): boolean; - getShouldClipPolygons(): boolean; - setOptions(options: MapModeOptions): void; - setViewChangeEndDelay(delay: number): void; - } - - export interface MapModeOptions { - shouldClipPolygons?: boolean; - drawShapesInSingleLayer?:boolean; - } - - export interface MapOptions { - - backgroundColor?: Color; - credentials?: string; - customizeOverlays?: boolean; - disableBirdseye?: boolean; - disableKeyboardInput?: boolean; - disableMouseInput?: boolean; - disablePanning?: boolean; - disableTouchInput?: boolean; - disableUserInput?: boolean; - disableZooming?: boolean; - enableClickableLogo?: boolean; - enableSearchLogo?: boolean; - fixedMapPosition?: boolean; - height?: number; - inertiaIntensity?: number; - navigationBarMode?: number; - showBreadcrumb?: boolean; - showCopyright?: boolean; - showDashboard?: boolean; - showMapTypeSelector?: boolean; - showScalebar?: boolean; - theme?: any; - tileBuffer?: number; - useInertia?: boolean; - width?: number; - center?: Location; - zoom?: number; - mapTypeId?: MapTypeId; - } - + /** This enumeration is used to specify the type of map style that should be displayed by the map. */ export enum MapTypeId { + /** The aerial map type which uses top-down satellite & airplane imagery. */ aerial, - auto, + + /** High resolution aerial imagery taken at 45 degrees to the ground, from 4 different directions. */ birdseye, - collinsBart, + + /** A darker version of the road maps. */ + canvasDark, + + /** A lighter version of the road maps which also has some of the details such as hill shading disabled. */ + canvasLight, + + /** A grayscale version of the road maps. */ + grayscale, + + /** Displays a blank canvas that uses the mercator map project. It basically removed the base maps layer. */ mercator, + + /** Ordnance survey map type (en-gb only). */ ordnanceSurvey, - road - } - export class MouseEventArgs { + /** Road map type. */ + road, - eventName: string; - handled: boolean; - isPrimary: boolean; - isSecondary: boolean; - isTouchEvent: boolean; - originalEvent: any; - pageX: number; - pageY: number; - target: any; - targetType: string; - wheelDelta: number; - - getX(): number; - getY(): number; + /** Provides streetside panoramas from the street level. */ + streetside } + /** The NavigationBarMode can be used to customize the layout and style of the navigation bar. */ export enum NavigationBarMode { - default, + /** + * A compact navigation bar that includes a smaller drop down for the map type and zoom buttons. Recommended for small + * maps or screen such as a mobile device. + */ compact, + + /** + * The default navigation bar that has a drop down for the map type, a locate me button, and zoom buttons. Recommended for + * medium to large maps in desktop browsers. + */ + default, + + /** + * A minified navigation bar that has a button to toggle between road and aerial maps, zoom buttons, and a button to turn + * traffic information on and off. Recommended for small maps or screen such as a mobile device. + */ minified } + /** The NavigationBarOrientation enumeration is used to define how the navigation bar controls are laid out. */ + export enum NavigationBarOrientation { + /** Repositions the buttons in the navigation bar such that they are aligned horizontally. */ + horizontal, + + /** Repositions the buttons in the navigation bar such that they are aligned vertically. */ + vertical + } + + /** This enumeration is used to specify how the overview map for the streetside map mode should be displayed. */ + export enum OverviewMapMode { + /** Shows the overview map in an expanded state. */ + expanded, + + /** Hides the overview map. */ + hidden, + + /** Shows the overview map in a minimized state. */ + minimized + } + + /** Contains enum to show how pixels are defined. */ export enum PixelReference { + /** The pixel is defined relative to the map control’s root element, where the top left corner of the map control is (0, 0). */ control, + + /** The pixel is defined relative to the page, where the top left corner of the HTML page is (0, 0). */ page, + + /** The pixel is defined in viewport coordinates, relative to the center of the map, where the center of the map is (0, 0). */ viewport } - export interface ViewOptions { + ////////////////////////////////////////////// + /// Interfaces + ////////////////////////////////////////////// - animate?: boolean; + /** Represents a structured address object. */ + export interface IAddress { + /** + * The street line of an address. The addressLine property is the most precise, official line for an address relative to the postal agency + * servicing the area specified by the locality or postalCode properties. + */ + addressLine: string; + + /** + * The subdivision name within the country or region for an address. This element is also commonly treated as the first order administrative + * subdivision. An example is a US state, such as “Oregon”. + */ + adminDistrict: string; + + /** The country or region name of the address. */ + countryRegion: string; + + /** A string specifying the two-letter ISO country code. */ + countryRegionISO2: string; + + /** The second, third, or fourth order subdivision within a country, dependency, or region. An example is a US county, such as “King”. */ + district: string; + + /** A nicely formatted address string for the result. */ + formattedAddress: string; + + /** The locality, such as the primary city, that corresponds to an address. An example is “Seattle”. */ + locality: string; + + /** The post code, postal code, or ZIP code of an address. An example is a US ZIP code, such as “98152”. */ + postalCode: string; + } + + /** The event args for when a layer frame is being loaded in an AnimtedTileLayer. **/ + export interface IAnimatedFrameEventArgs { + /** The animated tile layer that the frame belongs to. **/ + animatedTileLayer: AnimatedTileLayer; + + /** The index of the frame being loaded. **/ + index: number; + } + + /** An object that defines the options for an AnimatedTileLayer. **/ + export interface IAnimatedTileLayerOptions { + /** A boolean that specifies whether the animation should auto-start when it is added to the map or not. Default: true **/ + autoPlay?: boolean; + + /** The number of miliseconds between two layer frames. Default: 1000 **/ + frameRate?: number; + + /** A custom loading screen to show on the map when the map tiles are being fetched. **/ + loadingScreen?: CustomOverlay; + + /** The max amount of total loading time of all tiles in a viewport in milliseconds. Default: 15000 **/ + maxTotalLoadTime?: number; + + /** The array of tile layer sources to animate through. **/ + mercator: TileSource[]; + + /** A boolean specifying if the animated tile layer is visible or not. **/ + visible?: boolean; + } + + /** Represents the options that can be used when initializing a custom overlay. **/ + export interface ICustomOverlayOptions { + /** + * Specifies if the custom overlay should eb rendered above or below the label layer of the map. When above, + * elements in the overlay can be clickable. Default: True + */ + beneathLabels?: boolean; + } + + /** Base data layer interface. */ + export interface IDataLayer extends ILayer { + /** Clears all data in the layer. */ + clear(): void; + } + + /** Event args included in entity collection events. */ + export interface IEntityCollectionChangedEventArgs { + /** The entity collection the event was triggered from. */ + collection: EntityCollection; + + /** The IPrimitive object that the event occurred for. */ + data: IPrimitive; + } + + /** An object the identifies an event that has been attached to an object. */ + export interface IHandlerId { + } + + /** Base layer interface. */ + export interface ILayer { + } + + /** + * @deprecated use IMouseEventArgs + * A LayerMouseEventArgs object is returned by many the mouse event handlers attached to a Layer. + */ + export interface ILayerMouseEventArgs { + /** + * @deprecated use target + * The IPrimitive shape (pushpin, polyline, polygon) that the event occurred on. + */ + primitive: IPrimitive; + } + + /** The options that can be used to customize an infobox. */ + export interface IInfoboxOptions { + /** + * @deprecated Use HTML buttons and links in description instead. + */ + actions?: IInfoboxActions[]; + + /** The string displayed inside the infobox. */ + description?: string; + + /** + * The HTML that represents the infobox. Note that infobox options are ignored if custom HTML is set. Also, if custom HTML is used to represent the + * infobox, the infobox is anchored at the top-left corner. + */ + htmlContent?: string; + + /** The location on the map where the infobox’s anchor is attached. */ + location?: Location; + + /** The maximium size that the infobox height can expand to based on it’s content. Default: 126 **/ + maxHeight?: number; + + /** The maximium size that the infobox width can expand to based on it’s content. Default: 256 **/ + maxWidth?: number; + + /** + * The amount the infobox pointer is shifted from the location of the infobox, or if showPointer is false, then it is the amount the info box bottom + * left edge is shifted from the location of the infobox. If custom HTML is set, it is the amount the top-left corner of the infobox is shifted from + * its location. The default offset value is (0,0), which means there is no offset. + */ + offset?: Point; + + /** + * A boolean indicating whether to show the close dialog button on the infobox. The default value is true. By default, the close button is displayed + * as an X in the top right corner of the infobox. This property is ignored if custom HTML is used to represent the infobox. + */ + showCloseButton?: boolean; + + /** + * A boolean indicating whether to display the infobox with a pointer. The default value is true. In this case the infobox is anchored at the bottom + * point of the pointer. If this property is set to false, the infobox is anchored at the bottom left corner. This property is ignored if custom HTML + * is used to represent the infobox. + */ + showPointer?: boolean; + + /** The title of the infobox. */ + title?: string; + + /** + * A boolean indicating whether to show or hide the infobox. The default value is true. A value of false indicates that the infobox is hidden, + * although it is still an entity on the map. + */ + visible?: boolean; + + /** The z-index of the infobox with respect to other items on the map. */ + zIndex?: number; + } + + /** + * @deprecated Use HTML buttons and links in description instead. + */ + export interface IInfoboxActions { + /** The text to display for the action. */ + label: string; + + /** The function to call when the label is clicked. */ + eventHandler: (eventArg?: MouseEvent) => void; + } + + /** An object that contains information about an infobox event. **/ + export interface IInfoboxEventArgs { + /** The event that occurred. **/ + eventName: string; + + /** The x-value of the pixel coordinate on the page of the mouse cursor. **/ + pageX: number; + + /** The y-value of the pixel coordinate on the page of the mouse cursor. **/ + pageY: number; + + /** The infobox object that fired the event. **/ + target: Infobox; + + /** The type of the object that fired the event.This will always be 'infobox'. **/ + targetType: string; + + /** Original mouse event from the browser. */ + originalEvent?: MouseEvent; + } + + /** Map or View options */ + export interface IMapLoadOptions extends IMapOptions, IViewOptions { + /** The Bing Maps Key used to authenticate the application. This property can only be set when using the Map constructor. */ + credentials: string; + } + + /** + * An object that can be used to customize the map. Some of the map options can be changed after the map has loaded by using + * the setOptions function on the map. + */ + export interface IMapOptions { + + /** + * A boolean that, when set to true, allows the road labels to be hidden. Default: false + * This property can only be set when using the Map constructor. This property can only be set when using the Map constructor. + */ + allowHidingLabelsOfRoad?: boolean; + + /** A boolean indicating if the infobox is allowed to overflow outside the bounds of the map. Default: false. */ + allowInfoboxOverflow?: boolean; + + /** The color to use for the map control background. The default color is #EAE8E1. This property can only be set when using the Map constructor. */ + backgroundColor?: string | Color; + + /** Custom map styles used to modify the look and feel of the base map. */ + customMapStyle?: ICustomMapStyle; + + /** A boolean value indicating whether to disable the user’s ability to control the using the keyboard. Default: false */ + disableKeyboardInput?: boolean; + + /** A boolean value indicating if mousing over the map type selector should open it or not. Default: true */ + disableMapTypeSelectorMouseOver?: boolean; + + /** A boolean value indicating whether to disable the user's ability to pan the map. Default: false */ + disablePanning?: boolean; + + /** + * Scrolling the mouse wheel over the map will zoom it in or out, but will not scroll the page. + * Setting this property to true disables the zooming of the map and instead reverts back to scrolling the page instea. + * Default: false + */ + disableScrollWheelZoom?: boolean; + + /** + * A boolean indicating whether to disable streetside mode.If this property is set to true, streetside will be removed from + * the navigation bar, and the automatic coverage overlay will be disabled when zoomed in at lower zoom levels. Default false + * This property can only be set when using the Map constructor. + */ + disableStreetside?: boolean; + + /** + * A boolean indicating whether to disable the automatic streetside coverage layer that appears when zoomed in at lower zoom + * levels. Default false + * This property can only be set when using the Map constructor. + **/ + disableStreetsideAutoCoverage?: boolean; + + /** A boolean value indicating whether to disable the user's ability to zoom in or out. Default: false */ + disableZooming?: boolean; + + /** + * A boolean value indicating whether the Bing(TM) logo on the map is clickable. Default: true. + * This property can only be set when using the Map constructor. + */ + enableClickableLogo?: boolean; + + /** + * A boolean value indicating whether to use the inertia animation effect during map navigation. Default: true + * This property can only be set when using the Map constructor. + */ + enableInertia?: boolean; + + /** + * A boolean that indicates if the map should be rendered using lite mode. When set to true vector map labels are + * disabled and map labels are rendered directly into the map tiles. This offers improved performance, but will result + * in the labels being rendered behind data on the map and the labels will also not use collision dection with pushpins. + * If this property is not set, the map set this value based on the target device and browser as vector labels perform + * better in some scenrarios than others. + * This property can only be set when using the Map constructor. + */ + liteMode?: boolean; + + /** A bounding area that restricts the map view. */ + maxBounds?: LocationRect; + + /** The maximum zoom level that the map can be zoomed into. */ + maxZoom?: number; + + /** The minimum zoom level that the map cab be zoomed out to. */ + minZoom?: number; + + /** Specifies how the navigation bar should be rendered on the map. */ + navigationBarMode?: NavigationBarMode; + + /** A boolean whether what orientation should be used when laying out the navigation controls. */ + navigationBarOrientation?: NavigationBarOrientation; + + /** + * A boolean value indicating whether to display the “breadcrumb control”. The breadcrumb control shows the current center location’s geography hierarchy. + * The default value is false. Requires the showLocateMeButton map option to be set to true. The breadcrumb control displays best when the width of the map + * is at least 400 pixels. + */ + showBreadcrumb?: boolean; + + /** + * A boolean value indicating whether to show the map navigation control. Default: true This property can only be set when using the Map constructor. + */ + showDashboard?: boolean; + + /** + * A boolean value indicating whether to show a button that centers the map over the user's location in the map navigation control. Default: true + * This property can only be set when using the Map constructor. + */ + showLocateMeButton?: boolean; + + /** + * A boolean value indicating whether or not to show the map Bing logo. The default value is true. + * This property can only be set when using the Map constructor. + */ + showLogo?: boolean; + + /** + * A boolean value indicating whether to show the map type selector in the map navigation control. Default: true + * This property can only be set when using the Map constructor. + */ + showMapTypeSelector?: boolean; + + /** + * A boolean value indicating whether to show the scale bar. Default: true + * This property can only be set when using the Map constructor. + */ + showScalebar?: boolean; + + /** When using the minified navigation bar, a traffic button is displayed. Setting this option to false will hide this button. */ + showTrafficButton?: boolean; + + /** + * A boolean value indicating whether to show a link to the End User Terms of Use, which appears to the right of the copyrights, or not. Default: true + * This property can only be set when using the Map constructor. + */ + showTermsLink?: boolean; + + /** + * A boolean value indicating whether to show the zoom buttons in the map navigation control. Default: true + * This property can only be set when using the Map constructor. + */ + showZoomButtons?: boolean; + + /** A set of properties for the streetside mode of the map. */ + streetsideOptions?: IStreetsideOptions; + + /** Additional support map types that should be added to the navigaiton bar such as canvasDark, canvasLight, and grayscale.*/ + supportedMapTypes?: MapTypeId[]; + } + + /** A MapTypeChangeEventArgs object is returned by the map when using the mapTypeChanged event. */ + export interface IMapTypeChangeEventArgs { + /** The map type that map has changed to. */ + newMapTypeId: MapTypeId; + + /** The map type that the map has changed from. */ + oldMapTypeId: MapTypeId; + + /** The map instance the event occured on */ + target: Map; + + /** The type of object the event was attached to. Should always be "map" */ + targetType: string; + } + + /** Interface for module options. */ + export interface IModuleOptions { + /** A callback function that is fired after the module has loaded. */ + callback?: () => void; + + /** A function that is called if there is an error loading the module. */ + errorCallback?: () => void; + + /** A Bing Maps key that is used with the module when the module is loaded without a map. */ + credentials?: string; + } + + /** A MouseEventArgs object is returned by many the mouse event handlers. */ + export interface IMouseEventArgs extends ILayerMouseEventArgs { + /** The event that occurred. */ + eventName: string; + + /** A boolean indicating if the primary button, such as the left mouse button or a tap on a touch screen, was used during a mouse down or up event. */ + isPrimary: boolean; + + /** A boolean indicating if the secondary mouse button, such as the right mouse button, was used during a mouse down or up event. */ + isSecondary: boolean; + + /** If the target is a shape, this will be the layer that the shape is in. */ + layer: Layer; + + /** The map location of where the event occurred. */ + location: Location; + + /** The x-value of the pixel coordinate on the page of the mouse cursor. */ + pageX: number; + + /** The y-value of the pixel coordinate on the page of the mouse cursor. */ + pageY: number; + + /** The pixel coordinate of the mouse cusrsor relative to the top left corner of the map div. */ + point: Point; + + /** The object that triggered the event. */ + target: Map | IPrimitive; + + /** The type of the object that the event is attached to. Valid values include the following: ‘map’, 'layer', ‘polygon’, ‘polyline’, or ‘pushpin’ */ + targetType: string; + + /** + * Returns the x-value of the pixel coordinate, relative to the map, of the mouse. + * @returns The x-value of the pixel coordinate, relative to the map, of the mouse. + */ + getX(): number; + + /** + * Returns the y-value of the pixel coordinate, relative to the map, of the mouse. + * @returns The y-value of the pixel coordinate, relative to the map, of the mouse. + */ + getY(): number; + } + + /** + * An object tthat contains information about a streetside scene. + */ + export interface IPanoramaInfo { + /** The capture date of the streetside scene. */ + cd?: string; + } + + /** + * All shapes; Pushpins, Polylines and Polygons, derive from the IPrimitive interface. This means that they can be + * passed into any function that takes in an IPrimitive object. Also, any function that returns an IPrimitive is capable + * of returning any of these shapes. + */ + export interface IPrimitive { + /** Optional property to store any additional metadata for this primitive. */ + metadata?: any; + + /** + * Gets the css cursor value when the primitive has events on it. + * @returns css cursor string when primitive has events on it. + */ + getCursor(): string; + + /** + * Gets whether the primitive is visible. + * @returns A boolean indicating whether the primitive is visible or not. + */ + getVisible(): boolean; + + /** + * Sets the options for customizing the IPrimitive. + * @param options The options for customizing the IPrimitive. + */ + setOptions(options: IPrimitiveOptions): void; + } + + /** A IPrimitiveChangedEventArgs object is returned by the changed event on IPrimitive shapes. */ + export interface IPrimitiveChangedEventArgs { + /** The IPrimitive shape the event occured on. */ + sender: IPrimitive; + + /** The name of the change that occured; 'locations' or 'options'. */ + name: string; + } + + /** Options used for customizing IPrimitive objects. */ + export interface IPrimitiveOptions { + /** The css cursor to show when the IPrimitive has mouse events on it. Default value is pointer (hand). */ + cursor?: string; + + /** Boolean indicating whether the IPrimitive is visible. */ + visible?: boolean; + } + + /** Options used for customizing Polylines. */ + export interface IPolylineOptions extends IPrimitiveOptions { + /** Indicates if drawn shape should be generalized based on the zoom level to improve rendering performance. Default true **/ + generalizable?: boolean; + + /** CSS string or Color object as the poly's color. */ + strokeColor?: string | Color; + + /** An array of numbers separated by spaces, or a string separated by spaces/commas specifying the repetitive stroke pattern. */ + strokeDashArray?: number[] | string; + + /** The thickness of the poly stroke. */ + strokeThickness?: number; + } + + /** Options used for customizing Polygons. */ + export interface IPolygonOptions extends IPolylineOptions { + /** CSS string or Color object as the polygon's filling color. */ + fillColor?: string | Color; + } + + /** Options used for customizing Pushpins. */ + export interface IPushpinOptions extends IPrimitiveOptions { + /** The point on the pushpin icon, in pixels, which is anchored to the pushpin location. An anchor of (0,0) is the top left corner of the icon. */ + anchor?: Point; + + /** Specifies what color to make the default pushpin. */ + color?: string | Color; + + /** A boolean indicating whether the pushpin can be dragged to a new position with the mouse or by touch. */ + draggable?: boolean; + + /** Specifies whether to enable the clicked style on the pushpin. */ + enableClickedStyle?: boolean; + + /** Specifies whether to enable the hover style on the pushpin. */ + enableHoverStyle?: boolean; + + /** + * Defines the the icon to use for the pushpin.This can be a URL to an Image or SVG file, an image data URI, or an inline SVG string. + * Tip: When using inline SVG, you can pass in placeholders `{color}` and `{text}` in your SVG string. This placeholder will be replaced by the pushpins color or text property value when rendered. + */ + icon?: string; + + /** Whether the clickable area of pushpin should be an ellipse instead of a rectangle. */ + roundClickableArea?: boolean; + + /** + * A secondary title label value to display under the pushpin. Uses label collision detection. This label automatically changes color between white + * and dark grey depending on which map style is selected. Requires the title label to be set. + */ + subTitle?: string; + + /** + * The title label value to display under the pushpin. This label automatically changes color between white and dark grey depending on which map + * style is selected. Pushpin Titles support label collision detection, as described below. + */ + title?: string; + + /** A short string of text that is overlaid on top of the pushpin. */ + text?: string; + + /** The amount the text is shifted from the pushpin icon. The default value is (0,5). */ + textOffset?: Point; + } + + /** An object that represents a min and max value range. */ + export interface IRange { + /** The minimum value. */ + min: number; + + /** The maximum value. */ + max: number; + } + + /** The options that can be used to customize how the streetside map mode is displayed to the user. */ + export interface IStreetsideOptions { + /** A boolean indicating if the ability to navigate between image bubbles should be disabled in streetside map mode. Default: false */ + disablePanoramaNavigation?: boolean; + + /** The location that the streetside panorama should be looking towards. This can be used instead of a heading. */ + locationToLookAt?: Location; + + /** A callback function that is triggered after the streetside view has not loaded successfully. */ + onErrorLoading?: () => void; + + /** A callback function that is triggered after the streetside view has loaded successfully. */ + onSuccessLoading?: () => void; + + /** + * Specifies how to render the overview map when in streetside mode. + * Default: Microsoft.Maps.OverviewMapMode.expanded + */ + overviewMapMode?: OverviewMapMode; + + /** + * Information for a streetside panorama scene to load. + */ + panoramaInfo?: IPanoramaInfo; + + /** The radius to search in for available streetside panoramas. */ + panoramaLookupRadius?: number; + + /** A boolean indicating if the current address being viewed should be hidden when in streetside map mode. Default: true */ + showCurrentAddress?: boolean; + + /** A boolean indicating if the exit button should be hidden when in streetside map mode. Default: true */ + showExitButton?: boolean; + + /** A boolean indicating if the heading compass button is hidden when in streetside map mode. Default: true */ + showHeadingCompass?: boolean; + + /** A boolean indicating if the link to report a problem with a streetside image is hidden when in streetside map mode. Default: true */ + showProblemReporting?: boolean; + + /** A boolean indicating if the zoom buttons should be displayed when in streetside map mode. Default: true */ + showZoomButtons?: boolean; + } + + /** Defines a set of styles for pushpins, polylines, and polygons. */ + export interface IStylesOptions { + /** Sets the options for all pushpins. */ + pushpinOptions?: IPushpinOptions; + + /** Sets the options for all polylines. */ + polylineOptions?: IPolylineOptions; + + /** Sets the options for all polygons. */ + polygonOptions?: IPolygonOptions; + } + + /** Interface to specify style css while registering a module */ + export interface IStyleUrl { + /** List of style css urls o be downloaded */ + styleURLs: string[]; + } + + /** Represents options that can be used to customize a tile layer. */ + export interface ITileLayerOptions { + + /** + * The number of milliseconds allowed for the tile layer image download. If the timeout occurs before the image is fully + * downloaded, the map control considers the download a failure. The default value is 10000. + */ + downloadTimeout?: number; + + /** The tile source for the tile layer. */ + mercator: TileSource; + + /** The opacity of the tile layer, defined by a number between 0 (not visible) and 1. */ + opacity?: number; + + /** + * A boolean indicating whether to show or hide the tile layer. The default value is true. A value of false indicates that + * the tile layer is hidden, although it is still an entity on the map. + */ + visible?: boolean; + + /** The z-index of the tile layer. */ + zIndex?: number; + } + + /** Represents options that can be used to define a tile source. */ + export interface ITileSourceOptions { + /** + * A bounding box that specifies where tiles are available. + * Note: This will not crop tiles to the specific bounding box, it limits the tiles it loads to those that intersect this bounding box. + */ bounds?: LocationRect; + + /** The maximum zoom level tiles that tiles should be rendered at. */ + maxZoom?: number; + + /** The minimum zoom level tiles that tiles should be rendered at. */ + minZoom?: number; + + /** + * Required. This can be a string or a callback function that constructs the URLs used to retrieve tiles from the tile source. + * When using a string, the uriConstructor will allow you to specify placeholders that will be replaced with the tiles value (i.e. {quadkey}). + * See the Tile URL Parameters section for a list of supported parameters. + * Besides using formatted tile URLs, you can also specify a callback function as the uriConstructor. This is useful if you need to be able to + * build custom tile URL’s that may require some additional calculations for a tile. + */ + uriConstructor: string | ((tile: PyramidTileId) => string); + } + + /** Represents options that can be used to set the view of the map. */ + export interface IViewOptions { + /** The bounding rectangle of the map view. If both bounds and center are specified, bounds takes precedence over center. */ + bounds?: LocationRect; + + /** The location of the center of the map view. If both bounds and center are specified, bounds takes precedence over center. */ center?: Location; - centerOffset?: Point; + + /** + * The directional heading of the map. The heading is represented in geometric degrees with 0 or 360 = North, 90 = East, + * 180 = South, and 270 = West. + */ heading?: number; + + /** Indicates how the map labels are displayed. */ labelOverlay?: LabelOverlay; - mapTypeId?: string; + + /** The map type of the view. */ + mapTypeId?: MapTypeId; + + /** The amount of padding in pixels to be added to each side of the bounds of the map view. */ padding?: number; + + /** The angle relative to the horizon to tilt a streetside panorama image. */ + pitch?: number; + + /** The zoom level of the map view. */ zoom?: number; } + ////////////////////////////////////////////// + /// Modular Framework + ////////////////////////////////////////////// + + /** + * Loads the specified registered module, making its functionality available. You can provide the name of a single module or an array of names in. + * Options or a callback function that is called when the module is loaded can be specified. + * @param moduleName Name of the module to load. Can be the name of a custom module or a built in module name. Built in modules: + * Microsoft.Maps.Autosuggest, Microsoft.Maps.Clustering, Microsoft.Maps.Directions, Microsoft.Maps.DrawingTools, Microsoft.Maps.GeoJSON, + * Microsoft.Maps.HeatMap, Microsoft.Maps.Search, Microsoft.Maps.SpatialDataService, Microsoft.Maps.SpatialMath, Microsoft.Maps.Traffic, + * Microsoft.Maps.WellKnownText + * @param options A callback function or options containing additional information and a callback to call once a module is loaded + */ + export function loadModule(moduleName: string | string[], options?: (() => void) | IModuleOptions): void; + + /** + * Registers a module with the map control. The name of the module is specified in moduleKey, the module script is defined in scriptURL, and the + * options provides the location of a *.css file to load with the module. + * @param moduleName Name of the module to load. + * @param url Url to where the module code is located. + * @param styles List of css files to download. + */ + export function registerModule(moduleName: string, url: string, styles?: IStyleUrl): void; + + /** + * Signals that the specified module has been loaded and if specified, calls the callback function in loadModule. Call this method at the end of your custom module script. + * @param moduleName Name of the module that is loaded. + */ + export function moduleLoaded(moduleName: string): void; + + ////////////////////////////////////////////// + /// Classes + ////////////////////////////////////////////// + + /** + * Provides a layer which can smoothly animate through an array of tile layer sources. + */ + export class AnimatedTileLayer { + /** + * @contstructor + * @param options Options that define how to animate between the specified tile layers. + */ + constructor(options?: IAnimatedTileLayerOptions); + + /** + * Gets the frame rate of this animated tile layer. + * @returns The frame rate of this animated tile layer. + **/ + public getFrameRate(): number; + + /** + * Gets the loading screen overlay when tiles are being fetched. + * @returns The loading screen overlay when tiles are being fetched. + **/ + public getLoadingScreen(): CustomOverlay; + + /** + * Gets the maximum total tile fetching time of this animated tile layer. + * @returns The maximum total tile fetching time of this animated tile layer + **/ + public getMaxTotalLoadTime(): number; + + /** + * Gets the tile sources associated with this layer. + * @returns The tile sources associated with this layer. + **/ + public getTileSources(): TileSource[]; + + /** + * Gets the visibility of this animated tile layer. + * @returns The visibility of this animated tile layer. + **/ + public getVisible(): boolean; + + /** Pause the tile layer animation. **/ + public pause(): void; + + /** Play the animation either from start or where it was paused. **/ + public play(): void; + + /** + * Sets the options for the animated tile layer. + * @params Options that define how to animate between the specified tile layers. + **/ + public setOptions(options: IAnimatedTileLayerOptions): void; + + /** Stop the layer animation, hide layer, and reset frame to the beginning. **/ + public stop(): void; + } + + /** Class that represents a color */ export class Color { + /** The opacity of the color. The range of valid values are an interger between 0 and 255, or a decimal between 0 and 1. */ + public a: number; - constructor(alpha: number, red: number, green: number, blue: number); + /** The red value of the color. The range of valid values is 0 to 255 */ + public r: number; - a: number; - r: number; - g: number; - b: number; + /** The green value of the color. The range of valid values is 0 to 255 */ + public g: number; - static clone(color: Color): Color; - static fromHex(hex: string): Color; + /** The blue value of the color. The range of valid values is 0 to 255 */ + public b: number; - clone(): Color; - getOpacity(): number; - toHex(): string; - toString(): string; + /** + * @constructor + * @param a The alpha value in argb format + * @param r The r value in argb format + * @param g The g value in argb format + * @param b The b value in argb format + */ + constructor(a: number, r: number, g: number, b: number); + + /** + * Clones the color. + * @param color The color class that needs to be clones. + * @returns The colne of the color. + */ + public static clone(color: Color): Color; + + /** + * Creates the color from a hex string. + * @param hex The color represented as '#rrggbb' format. + * @returns The color object. + */ + public static fromHex(hex: string): Color; + + /** + * Clones the color. + * @returns The clone of the color. + */ + public clone(): Color; + + /** + * Gets the opacity of this color. + * @returns The opacity between 0 and 1 of this color. + */ + public getOpacity(): number; + + /** + * Converts the color to hex notation. + * @returns The hex notation as '#rrggbb' (ignores a). + */ + public toHex(): string; + + /** + * Converts the color to rgba notation. + * @returns The rgba notation as rgba(rr, gg, bb, aa) + */ + public toRgba(): string; } - export interface EntityChangeArgs { - collection: EntityCollection; - entity: Entity; + /** + * You can use this class to create custom overlays on top of the map. These can be static overlays such as custom + * navigation bars, or dynamic overlays such as custom visualization layers. CustomOverlays can be added to the map + * just like any other layer using the map.layers property. + */ + export class CustomOverlay implements ILayer { + /** A reference the the map instance that the overlay was added to. This will be null until the onLoad function has fired. **/ + _map: Map; + + /** + * @constructor + * @param options The options to use when initializing the custom overlay. + */ + constructor(options?: ICustomOverlayOptions); + + /** + * Gets the html element of this custom overlay. + * @returns The htmlElement of this overlay. + */ + public getHtmlElement(): HTMLElement; + + /** + * Gets the map that this overlay is attached to. + * @returns The map that this overlay is attached to. + */ + public getMap(): Map; + + /** + * Updates the html element of this custom overlay. + * @param htmlElement The new htmlElement to set for the overlay. + */ + public setHtmlElement(htmlElement: HTMLElement): void; + + /** + * Implement this method to perform any task that should be done when the overlay is added to the map. + */ + public onAdd(): void; + + /** + * Implement this methof to perform any task that should be done after the overlay has been added to the map. + */ + public onRemove(): void; + + /** + * Implement this method to perform any tasks that should be done when the overlay is removed from the map. + */ + public onLoad(): void; } - export interface EntityCollectionOptions { - bubble?: boolean; - visible?: boolean; - zIndex?: number; + /** + * Use the Layer class. + * @deprecated in V8 + */ + export class EntityCollection extends Layer { + /** + * @constructor Deprecated. Use the Layer class. + * @deprecated in V8 + */ + constructor(); + + /** + * Removes all shapes from the collection. + */ + public clear(): void; + + /** + * Gets the item at a specified index. + * @param index Index of the item to get. + * @returns The item at a specified index. + */ + public get(index: number): IPrimitive; + + /** + * Gets the number of items in this collection. + * @returns The count of the items. + */ + public getLength(): number; + + /** + * Gets the index of the item in the list. + * @param primitive The item to get the index of. + * @returns The index of the item in the list. + */ + public indexOf(primitive: IPrimitive): number; + + /** + * Inserts the item into the list at a specific index. + * @param primitive The item to insert. + * @param index Index of the item to be inserted. + */ + public insert(primitive: IPrimitive, index: number): void; + + /** + * Returns the last element in the list after removing it. + * @returns The last element in the list after removing it. + */ + public pop(): IPrimitive; + + /** + * Adds the item to the end of the list. + * @param primitive Item to be added. + */ + public push(primitive: IPrimitive | IPrimitive[]): void; + + /** + * Removes the item from the list. + * @param primitive Item to be removed. + * @returns The item to be removed. + */ + public remove(primitive: IPrimitive): IPrimitive; + + /** + * Removes the item from the list at a specified index. + * @param index Index of the item that needs to be removed. + * @returns The item to be removed at a specified index. + */ + public removeAt(index: number): IPrimitive; } - export class EntityCollection { + /** A static class that manages events within the map SDK. */ + export module Events { + ///////////////////////////////////// + /// addHandler Definitions + //////////////////////////////////// - constructor(options?: EntityCollectionOptions); + /** + * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported events: + * click, dblclick, maptypechanged, mousedown, mousemove, mouseout, mouseover, mouseup, mousewheel, rightclick, viewchange, viewchangeend, viewchangestart + * @param handler The callback function to handle the event when triggered. + * @returns The handler id. + */ + export function addHandler(target: Map, eventName: string, handler: (eventArg?: IMouseEventArgs | IMapTypeChangeEventArgs) => void): IHandlerId; - clear(): void; - get(index: number): Entity; - getLength(): number; - getVisible(): boolean; - getZIndex(): number; - indexOf(entity: Entity): number; - insert(entity: Entity, index: number): void; - pop(): Entity; - push(entity: Entity): void; - remove(entity: Entity): Entity; - removeAt(index: number): Entity; - setOptions(options: EntityCollectionOptions): void; - toString(): string; + /** + * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * changed, click, dblclick, drag, dragend, dragstart, mousedown, mouseout, mouseover, mouseup + * @param handler The callback function to handle the event when triggered. + * @returns The handler id. + */ + export function addHandler(target: Pushpin, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void): IHandlerId; + /** + * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * changed, click, dblclick, mousedown, mouseout, mouseover, mouseup + * @param handler The callback function to handle the event when triggered. + * @returns The handler id. + */ + export function addHandler(target: Polyline | Polygon, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void): IHandlerId; + + /** + * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * click, infoboxChanged, mouseenter, mouseleave + * @param handler The callback function to handle the event when triggered. + * @returns The handler id. + */ + export function addHandler(target: Infobox, eventName: string, handler: (eventArg?: IInfoboxEventArgs) => void): IHandlerId; + + /** + * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * click, dblclick, mousedown, mouseout, mouseover, mouseup, rightclick + * @param handler The callback function to handle the event when triggered. + * @returns The handler id. + */ + export function addHandler(target: Layer, eventName: string, handler: (eventArg?: IMouseEventArgs) => void): IHandlerId; + + /** + * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * • entityadded + * • entityremoved + * @param handler The callback function to handle the event when triggered. + * @returns The handler id. + */ + export function addHandler(target: EntityCollection, eventName: string, handler: (eventArg?: IEntityCollectionChangedEventArgs) => void): IHandlerId; + + /** + * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. + * @param handler The callback function to handle the event when triggered. + * @returns The handler id. + */ + export function addHandler(target: any, eventName: string, handler: (eventArg?: any) => void): IHandlerId; + + ///////////////////////////////////// + /// addOne Definitions + //////////////////////////////////// + + /** + * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported events: + * click, dblclick, maptypechanged, mousedown, mousemove, mouseout, mouseover, mouseup, mousewheel, rightclick, viewchange, viewchangeend, viewchangestart + * @param handler The callback function to handle the event when triggered. + */ + export function addOne(target: Map, eventName: string, handler: (eventArg?: IMouseEventArgs | IMapTypeChangeEventArgs) => void): void; + + /** + * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * changed, click, dblclick, drag, dragend, dragstart, mousedown, mouseout, mouseover, mouseup + * @param handler The callback function to handle the event when triggered. + */ + export function addOne(target: Pushpin, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void): void; + + /** + * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * changed, click, dblclick, mousedown, mouseout, mouseover, mouseup + * @param handler The callback function to handle the event when triggered. + */ + export function addOne(target: Polyline | Polygon, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void): void; + + /** + * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * click, infoboxChanged, mouseenter, mouseleave + * @param handler The callback function to handle the event when triggered. + */ + export function addOne(target: Infobox, eventName: string, handler: (eventArg?: IInfoboxEventArgs) => void): void; + + /** + * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * click, dblclick, mousedown, mouseout, mouseover, mouseup, rightclick + * @param handler The callback function to handle the event when triggered. + */ + export function addOne(target: Layer, eventName: string, handler: (eventArg?: IMouseEventArgs) => void): void; + + /** + * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * • entityadded + * • entityremoved + * @param handler The callback function to handle the event when triggered. + */ + export function addOne(target: EntityCollection, eventName: string, handler: (eventArg?: IEntityCollectionChangedEventArgs) => void): void; + + /** + * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. + * @param handler The callback function to handle the event when triggered. + */ + export function addOne(target: any, eventName: string, handler: (eventArg?: any) => void): void; + + ///////////////////////////////////// + /// addThrottledHandler Definitions + //////////////////////////////////// + + /** + * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported events: + * click, dblclick, maptypechanged, mousedown, mousemove, mouseout, mouseover, mouseup, mousewheel, rightclick, viewchange, viewchangeend, viewchangestart + * @param handler The callback function to handle the event when triggered. + * @param throttleInterval throttle interval (in ms) + * @returns The handler id. + */ + export function addThrottledHandler(target: Map, eventName: string, handler: (eventArg?: IMouseEventArgs | IMapTypeChangeEventArgs) => void, throttleInterval: number): IHandlerId; + + /** + * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * changed, click, dblclick, drag, dragend, dragstart, mousedown, mouseout, mouseover, mouseup + * @param handler The callback function to handle the event when triggered. + * @param throttleInterval throttle interval (in ms) + * @returns The handler id. + */ + export function addThrottledHandler(target: Pushpin, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void, throttleInterval: number): IHandlerId; + + /** + * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * changed, click, dblclick, mousedown, mouseout, mouseover, mouseup + * @param handler The callback function to handle the event when triggered. + * @param throttleInterval throttle interval (in ms) + * @returns The handler id. + */ + export function addThrottledHandler(target: Polyline | Polygon, eventName: string, handler: (eventArg?: IMouseEventArgs | IPrimitiveChangedEventArgs) => void, throttleInterval: number): IHandlerId; + + /** + * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * click, infoboxChanged, mouseenter, mouseleave + * @param handler The callback function to handle the event when triggered. + * @returns The handler id. + */ + export function addThrottledHandler(target: Infobox, eventName: string, handler: (eventArg?: IInfoboxEventArgs) => void): IHandlerId; + + /** + * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * click, dblclick, mousedown, mouseout, mouseover, mouseup, rightclick + * @param handler The callback function to handle the event when triggered. + * @param throttleInterval throttle interval (in ms) + * @returns The handler id. + */ + export function addThrottledHandler(target: Layer, eventName: string, handler: (eventArg?: IMouseEventArgs) => void, throttleInterval: number): IHandlerId; + + /** + * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. Supported Events: + * • entityadded + * • entityremoved + * @param handler The callback function to handle the event when triggered. + * @param throttleInterval throttle interval (in ms) + * @returns The handler id. + */ + export function addThrottledHandler(target: EntityCollection, eventName: string, handler: (eventArg?: IEntityCollectionChangedEventArgs) => void, throttleInterval: number): IHandlerId; + + /** + * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. + * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. + * @param eventName The type of event to attach. + * @param handler The callback function to handle the event when triggered. + * @param throttleInterval throttle interval (in ms) + * @returns The handler id. + */ + export function addThrottledHandler(target: any, eventName: string, handler: (eventArg?: any) => void, throttleInterval: number): IHandlerId; + + ///////////////////////////////////// + /// All other definitions + //////////////////////////////////// + + /** + * Checks if the target has any attached event handler. + * @param target The object to check if an event is attached to it. + * @param eventName The name of the event to check to see is attached. + * @returns A boolean indicating if the specified event type is attached to the object. + */ + export function hasHandler(target: any, eventName: string): boolean; + + /** + * Invokes an event on the target. This causes all handlers for the specified event name to be called. + * @param target The object to invoke the event on. + * @param eventName The name of the event to invoke. + * @param args Arguments for the event handler. + */ + export function invoke(target: any, evenName: string, args: any): void; + + /** + * Detaches the specified handler from the event. The handlerId is returned by the addHandler and addThrottledHandler methods. + * @param handlerId The handler id of the event to remove. + */ + export function removeHandler(handlerId: IHandlerId): void; } + /** + * Standard compass headings; north, south, east, west. + */ + export class Heading { + /** A heading pointing north, 0 degrees. */ + static North: number; + + /** A heading pointing south, 180 degrees. */ + static South: number; + + /** A heading pointing east, 90 degrees. */ + static East: number; + + /** A heading pointing west, 270 degrees. */ + static West: number; + } + + /** + * An infobox, also sometimes refer to as an info window or popup, is a simple panel that displays information over top the map. This is + * often used to display information linked to a location after clicking on a pushpin. + */ export class Infobox { - constructor(location: Location, options?: InfoboxOptions); + /** + * @constructor + * @param location The location to display the infobox at. + * @param options Options for rendering the infobox. + */ + constructor(location: Location, options?: IInfoboxOptions); - getActions(): any; - getAnchor(): Point; - getDescription(): string; - getHeight(): number; - getHtmlContent(): string; - getId(): string; - getLocation(): Location; - getOffset(): Point; - getOptions(): InfoboxOptions; - getShowCloseButton(): boolean; - getShowPointer(): boolean; - getTitle(): string; - getTitleAction(): any; - getTitleClickHandler(): (mouseEvent?: MouseEvent) => void; - getVisible(): boolean; - getWidth(): number; - getZIndex(): number; - setHtmlContent(content: string): void; - setLocation(location: Location): void; - setMap(map: Map): void; - setOptions(options: InfoboxOptions): void; - toString(): string; + /** + * @deprecated Use HTML buttons and links in description instead. + */ + public getActions(): IInfoboxActions[]; + + /** + * Gets the point on the infobox which is anchored to the map. An anchor of (0,0) is the top left corner of the infobox. + * @returns The anchor point of the infobox. + */ + public getAnchor(): Point; + + /** + * Gets the string that is printed inside the infobox. + * @returns The description value of the infobox options. + */ + public getDescription(): string; + + /** + * Gets the height of the infobox. + * @returns The height of the infobox. + */ + public getHeight(): number; + + /** + * Gets the infobox as HTML. + * @returns The HTML string used to create a custom infobox. + */ + public getHtmlContent(): string; + + /** + * Gets the location on the map where the infobox’s anchor is attached. + * @returns The location of the infobox. + */ + public getLocation(): Location; + + /** + * Gets the maximium height setting for the infobox. + * @returns the maximium height setting for the infobox. + */ + public getMaxHeight(): number; + + /** + * Gets the maximium width setting for the infobox. + * @returns the maximium width setting for the infobox. + */ + public getMaxWidth(): number; + + /** + * Gets the amount the infobox pointer is shifted from the location of the infobox, or if showPointer is false, then it is the amount the infobox + * bottom left edge is shifted from the location of the infobox. The default value is (0,0), which means there is no offset. + * @returns The offset of the infobox. + */ + public getOffset(): Point; + + /** + * Gets the infobox options. + * @returns The infobox options currently used by the infobox. + */ + public getOptions(): IInfoboxOptions; + + /** + * Gets a boolean indicating whether the infobox close button is shown. + * @returns A boolean indicating if the close button is shown or not. + */ + public getShowCloseButton(): boolean; + + /** + * Gets a boolean indicating whether the infobox is drawn with a pointer. + * @returns A boolean indicating if the pointer of the infobox is shown or not. + */ + public getShowPointer(): boolean; + + /** + * Gets a string that is the title of the infobox. + * @returns The title property of the infobox. + */ + public getTitle(): string; + + /** + * Gets whether the infobox is visible. A value of false indicates that the infobox is hidden, although it is still an entity on the map. + * @returns A boolean indicating if the infobox is visible or not. + */ + public getVisible(): boolean; + + /** + * Gets the width of the infobox. + * @returns The width of the infobox. + */ + public getWidth(): number; + + /** + * Gets the z-index of the infobox. + * @returns The z-index of the infobox. + */ + public getZIndex(): number; + + /** + * Sets the HTML content of the infobox. You can use this method to change the look of the infobox. Note that infobox options are ignored if + * custom HTML is set. Also, when custom HTML is used to represent the infobox, the infobox is anchored at the bottom-left corner. + * @param content The HTML string to use to generate the infobox. + */ + public setHtmlContent(content: string): void; + + /** + * Sets the location on the map where the anchor of the infobox is attached. + * @param loc The location to display the infobox at. + */ + public setLocation(loc: Location): void; + + /** + * Adds the infobox to the map. To remove an Infobox from the map, simply pass null into this function. + * @param map A map instance to display the infoboox on, or null if removing infobox from map. + */ + public setMap(map: Map): void; + + /** + * Sets options for the infobox. + * @param options The options to assign to the infobox. + */ + public setOptions(options: IInfoboxOptions): void; } - export interface Action { - label?: string; - icon?: string; - eventHandler: (args?: any) => void; + /** + * The Layer class makes it easy to organize groups of data by storing them in separate layers on the map. Grouping your data into layers + * provides a number of benefits such as the ability to hide or attach events to all IPrimitive shapes in a layer with a single line of code, + * while also providing providing a performance benefit over manually looping through each shape and performing these tasks. + */ + export class Layer implements IDataLayer { + + /** Optional property to store any additional metadata for this layer. */ + public metadata: any; + + /** + * @constructor + * @param id Unique string identifier for the layer. + */ + constructor(id?: string); + + /** + * Adds a shapes to the layer, at the specified index if specified. + * @param primitive The shape(s) to be added to the layer. + * @param index The index at which to insert the shape into the layer. + */ + public add(primitive: IPrimitive | IPrimitive[], index?: number): void; + + /** + * Clears all the data + */ + public clear(): void; + + /** + * Cleans up any resources this object is consuming + */ + public dispose(): void; + + /** + * Gets the id of the layer. + * @returns The id assigned to the layer. + */ + public getId(): string; + + /** + * Gets an array of shapes that are in the layer. This can be used to iterate over the individual shapes. + * @returns An array of shapes that are in the layer. + */ + public getPrimitives(): IPrimitive[]; + + /** + * Gets a value indicating whether the layer is visible or not. + * @returns A boolean indicating if the layer is visible or not. + */ + public getVisible(): boolean; + + /** + * Gets the zIndex of the layer. + * @returns The zIndex of the layer. + */ + public getZIndex(): number; + + /** + * Removes a primitive + * @param primitive primitive that needs to be removed + * @returns The primitive that needs to be removed + */ + public remove(primitive: IPrimitive): IPrimitive; + + /** + * Removes a primitive at a specified index + * @param index index of the primitive that needs to be removed + * @returns The primitive that needs to be removed at this index + */ + public removeAt(index: number): IPrimitive; + + /** + * Replaces all shapes in the layer with the new array of shapes that have been provided. + * @param primitives The array of shapes to add to the layer. + */ + public setPrimitives(primitives: IPrimitive[]): void; + + /** + * Sets whether the layer is visible or not. + * @param value A value indicating if the layer should be displayed or not. + */ + public setVisible(value: boolean): void; + + /** + * Sets the zIndex of the layer. + * @param zIndex The zIndex value to assign to the layer. + */ + public setZIndex(zIndex: number): void; } - export interface InfoboxOptions { + /** + * The layers property of the map is a LayerCollection object and contains all the layers that have been added to the map. + * Note: This class is only exposed in the map.layers property. No other instance of this class can be created. + */ + export class LayerCollection extends Array { + /** The number of layers in the collection. */ + public length: number; - actions?: Array; - description?: string; - htmlContent?: string; - id?: string; - location?: Location; - offset?: Point; - showCloseButton?: boolean; - showPointer?: boolean; - pushpin?: Pushpin; - title?: string; - titleAction?: { label?: string; eventHandler: (mouseEvent?: MouseEvent) => void; }; - titleClickHandler?: (mouseEvent?: MouseEvent) => void; - typeName?: InfoboxType; - visible?: boolean; - width?: number; - height?: number; + /** + * Removes all layers from the map. + */ + public clear(): void; + + /** + * Gets the index of a layer in the collection. + * @param layer The layer to get the index of. + * @returns The index of the specified layer. + */ + public indexOf(layer: ILayer): number; + + /** + * Adds a layer to the map. + * @param layer The layer to insert into the collection. + */ + public insert(layer: ILayer): void; + + /** + * Adds an array of layers to the map. + * @param layers The layers to insert into the collection. + */ + public insertAll(layers: ILayer[]): void; + + /** + * Removes a layer from the map. + * @param layer The layer to remove from the collection. + */ + public remove(layer: ILayer): void; + + /** + * Removes a layer from the map at the specified index in the collection. + * @param idx The index of the layer to remove. + */ + public removeAt(idx: number): void; } - export enum InfoboxType { - mini, - standard + /** + * This class stores the coordinate information needed to mark locations on a map. The Location class consists of two properties: + * latitude and longitude. + */ + export class Location { + /** The location north or south of the equator from +90 to -90 */ + public latitude: number; + + /** The location east or west of the prime meridian +180 to -180 */ + public longitude: number; + + /** + * @constructor + * @param latitude The location north or south of the equator from +90 to -90 + * @param longitude The location east or west of the prime meridian +180 to -180 + */ + constructor(latitude: any, longitude: any); + + /** + * Determines if two locations are equal. + * @param location1 The first location to test. + * @param location2 The second location to test. + * @returns True if both locations are equivalent. + */ + static areEqual(location1: Location, location2: Location): boolean; + + /** + * Creates a deep copy of the map location. + * @returns A deep copy of the map location. + */ + public clone(): Location; + + /** + * Creates a proper Location from an object that has the same signature. + * @param source A Location or Location-like object that contains the same properties. + * @returns A copy of the map location. + */ + static cloneFrom(source: Location): Location; + + /** + * Normalizes the longitude by wrapping it around the earth. + * @param longitude The input longitude. + * @returns The longitude normalized to within -180 and +180. + */ + static normalizeLongitude(longitude: number): number; + + /** + * Parses a location string of the form "lat,long". + * @param str The location string. + * @returns The parsed location or null otherwise. + */ + static parseLatLong(str: string): Location; + + /** + * Converts the Location to a string representation. + * @returns A string representation of the location. + */ + public toString(): string; } - export interface Entity { + /** + * The LocationRect class, also known as a bounding box, consists of a set of coordinates that are used to represent rectangular area on the map. + */ + export class LocationRect { + /** The location that defines the center of the rectangle. */ + public center: Location; + + /** The height, in degrees, of the rectangle. */ + public height: number; + + /** The width, in degrees, of the rectangle. */ + public width: number; + + /** + * @constructor + * @param center The center of the LocationRect. + * @param width The width of the LocationRect in degrees. + * @param height The height of the LocationRect in degrees. + */ + constructor(center: Location, width: number, height: number); + + /** + * Gets a LocationRect using the specified locations for the northwest and southeast corners. + * @param northwest The north west corner of the LocationRect. + * @param southeast The south east corner of the LocationRect. + * @returns A LocationRect using the specified locations for the northwest and southeast corners. + */ + static fromCorners(northwest: Location, southeast: Location): LocationRect; + + /** + * Gets a LocationRect using the specified northern and southern latitudes and western and eastern longitudes for the rectangle boundaries. + * @param north The northern latitude of the LocationRect. + * @param west The western longitude of the LocationRect. + * @param south The southern latitude of the LocationRect. + * @param east The eastern longitude of the LocationRect. + * @returns A LocationRect defined by the specified northern and southern latitudes and western and eastern longitudes for the rectangle boundaries. + */ + static fromEdges(north: number, west: number, south: number, east: number): LocationRect; + + /** + * Gets a LocationRect using a list of locations. + * @param locations A list of locations. + * @returns A LocationRect that encloses all the specified locations. + */ + static fromLocations(...locations: Location[]): LocationRect; + + /** + * Gets a LocationRect using an array of locations. + * @param locations An array of locations. + * @returns A LocationRect that encloses all the specified locations. + */ + static fromLocations(locations: Location[]): LocationRect; + + /** + * Creates a LocationRect from a string with the following format: "north,west,south,east". North, west, south and east specify the coordinate number values. + * @param str A string that repsents a LocationRect with the format "north,west,south,east". + * @returns A LocationRect defined by the specified northern and southern latitudes and western and eastern longitudes for the rectangle boundaries that have been parsed by the string. + */ + static fromString(str: string): LocationRect; + + /** + * Gets a copy of the LocationRect object. + * @retruns A copy of the LocationRect object. + */ + public clone(): LocationRect; + + /** + * Gets whether the specified Location is within the LocationRect. + * @returns A boolean indicating if a location is within a LocationRect. + */ + public contains(location: Location): boolean; + + /** + * Determines if the LocationRect crosses the 180th meridian. + * @returns A boolean indicating if the LocationRect crosses the international date line (-180/180 degrees longitude). + */ + public crossesInternationalDateLine(): boolean; + + /** + * Gets the longitude that defines the eastern edge of the LocationRect. + * @returns The eastern longitude value of the LocationRect. + */ + public getEast(): number; + + /** + * Gets the latitude that defines the northern edge of the LocationRect. + * @returns The northern latitude value of the LocationRect. + */ + public getNorth(): number; + + /** + * Gets the Location that defines the northwest corner of the LocationRect. + * @returns The northwest corner location of the LocationRect. + */ + public getNorthwest(): Location; + + /** + * Gets the latitude that defines the southern edge of the LocationRect. + * @returns The southern latitude value of the LocationRect. + */ + public getSouth(): number; + + /** + * Gets the Location that defines the southeast corner of the LocationRect. + * @returns The southeast corner location of the LocationRect. + */ + public getSoutheast(): Location; + + /** + * Gets the latitude that defines the western edge of the LocationRect. + * @returns The western longitude value of the LocationRect. + */ + public getWest(): number; + + /** + * Gets whether the specified LocationRect intersects with this LocationRect. + * @param rect A second LocationRect to test for intersection with. + * @returns A boolean indicating if a second LocationRect interests with this LocationRect. + */ + public intersects(rect: LocationRect): boolean; + + /** + * Scales the size of a LocationRect by multiplying the width and height properties by a percentage. + * @param percentage A percentage value to increase the size of the LocationRect by. + */ + public inflate(percentage: number): void; + + /** + * If a LocationRect crosses the international date line, this method splits it into two LocationRect objects and returns them as an array. + * @returns An array of LocationRects, that are split by the international date line (-180/180 degrees longitude) + */ + public splitByInternationalDateLine(): LocationRect[]; + + /** + * Converts the LocationRect object to a string. + * @returns A string version of the LocationRect. + */ + public toString(): string; } - export class Polyline implements Entity { + /** The map object generates an interactive map within a specified DOM element. */ + export class Map { + /** Entities of the map */ + public entities: EntityCollection; - constructor(locations: Array, options?: PolylineOptions); + /** Set of map layers */ + public layers: LayerCollection; - getLocations(): Array; - getStrokeColor(): Color; - getStrokeDashArray(): string; - getStrokeThickness(): number; - getVisible(): boolean; - setLocations(locations: Array): void; - setOptions(options: PolylineOptions): void; - toString(): string; + /** + * @constructor + * @param parentElement The parent element of the map as a CSS selector string or HTMLElement. + * @param options Options used when creating the map. + */ + constructor(parentElement: string | HTMLElement, options: IMapLoadOptions); + + /** + * Gets the streetside panorama information closest to the specified bounding box and returns using a success callback function. + * This information can then be used to set the map view to that streetside panorama. + */ + public static getClosestPanorama(bounds: LocationRect, success: (panoramaInfo: IPanoramaInfo) => void, missingCoverage: () => void): void; + + /** Returns the branch name; release, experimental, frozen. */ + public static getVersion(): string; + + + /** Deletes the Map object and releases any associated resources. */ + public dispose(): void; + + /** + * Gets the location rectangle that defines the boundaries of the current map view. + * @returns The location rectangle that defines the boundaries of the current map view. + */ + public getBounds(): LocationRect; + + /** + * Gets the location of the center of the current map view. + * @returns The location of the center of the current map view. + */ + public getCenter(): Location; + + /** + * Gets to the specified callback an array of strings representing the attributions of the imagery currently displayed on the map. + * @param callback The callback function that needs to be called after retrieving the copyright information. + */ + public getCopyrights(callback: (copyrights: string[]) => void): void; + + /** + * Gets the session ID. This method calls the callback function with the session ID as the first parameter + * @param callback The callback function that needs to be called with the session id. + */ + public getCredentials(callback: (creds: string) => void): void; + + /** + * Gets the current culture. + * @returns The current culture. + */ + public getCulture(): string; + + /** + * Gets the height of the map control. + * @returns The height of the map control. + */ + public getHeight(): number; + + /** + * Returns the heading of the current map view. + * @returns Returns the heading of the current map view. + */ + public getHeading(): number; + + /** + * Gets the string that represents the imagery currently displayed on the map. + * @returns The string that represents the imagery currently displayed on the map. + */ + public getImageryId(): string; + + /** + * Gets a string that represents the current map type displayed on the map. + * @returns A string that represents the current map type displayed on the map. + */ + public getMapTypeId(): MapTypeId; + + /** + * Gets the current scale in meters per pixel of the center of the map. + * @returns The current scale in meters per pixel of the center of the map. + */ + public getMetersPerPixel(): number; + + /** + * Gets the map options that have been set. + * @returns the map options that have been set. + */ + public getOptions(): IMapOptions; + + /** + * Gets the x coordinate of the top left corner of the map control, relative to the page. + * @returns The x coordinate of the top left corner of the map control, relative to the page. + */ + public getPageX(): number; + + /** + * Gets the y coordinate of the top left corner of the map control, relative to the page. + * @returns The y coordinate of the top left corner of the map control, relative to the page. + */ + public getPageY(): number; + + /** + * Returns the pitch of the current streetside map view. + * @returns Returns the pitch of the current streetside map view. + */ + public getPitch(): number; + + /** + * Gets the map root node. + * @returns the map root node. + */ + public getRootElement(): HTMLElement; + + /** + * Gets the user region. + * @returns The user region. + */ + public getUserRegion(): string; + + /** + * Gets the width of the map control. + * @returns the width of the map control. + */ + public getWidth(): number; + + /** + * Gets the zoom level of the current map view. + * @returns Returns the zoom level of the current map view. + */ + public getZoom(): number; + + /** + * Gets the range of valid zoom levels for the current map view. + * @returns The range of valid zoom levels for the current map view. + */ + public getZoomRange(): IRange; + + /** + * Gets a boolean indicating whether the map is in a regular Mercator nadir mode. + * @returns A boolean indicating whether the map is in a regular Mercator nadir mode. + */ + public isMercator(): boolean; + + /** + * Gets a boolean indicating if the current map type allows the heading to change; false if the display heading is fixed. + * @returns true if the current map type allows the heading to change; false if the display heading is fixed. + */ + public isRotationEnabled(): boolean; + + /** + * Sets the current map type. + * @param mapTypeId The map imagery type of the map to set. + */ + public setMapType(mapTypeId: MapTypeId): void; + + /** + * Sets the map options. + * @param options The map options to be set. + */ + public setOptions(options: IMapOptions): void; + + /** + * Sets the view of the map. + * @param viewOptions The view options to be set. + */ + public setView(viewOptions: IViewOptions): void; + + /** + * Converts a specified Location or a Location array to a Point or Point array on the map + * relative to the specified PixelReference. If no reference is specified, PixelReference.viewport + * is taken. + * @param location The given Location or Location[] to convert. + * @param reference The PixelReference to specify the reference point. + * @returns The converted Point or Point[], or null if the conversion fails. + */ + public tryLocationToPixel(location: Location | Location[], reference?: any): Point | Point[]; + + /** + * Converts a specified Point or a Point array to a Location or Location array on the map + * relative to the specified PixelReference. If no reference is specified, PixelReference.viewport + * is taken. + * @param point The given Point or Point[] to convert. + * @param reference The PixelReference to specify the reference point. + * @returns The converted Location or Location[], or null if the conversion fails. + */ + public tryPixelToLocation(point: Point | Point[], reference?: any): Location | Location[]; } - export class Position { - coords: Coordinates; - timestamp: string; + /** + * This class is used to represent a pixel coordinate or offset. This is often used by pushpin anchors, and map location to pixel conversion calculations. + */ + export class Point { + /** The x coordinate */ + public x: number; + + /** The y coordinate */ + public y: number; + + /** + * @constructor + * @param x The x coordinate. + * @param y The y coordinate. + */ + constructor(x: number, y: number); + + /** + * Adds the x and y values of two points and returns a new Point. + * @param point The point to add. + * @returns A new point created by the sum of two points. + */ + public add(point: Point): Point; + + /** + * Creates a copy of the current point. + * @returns A new instance of the current point. + */ + public clone(): Point; + + /** + * Compares the x and y values of two points to see if they are equal. If a tolerance value is specified, it checks to see if the linear distance between the points is less than or equal to the tolerance value. + * @param point The point to compare to. + * @param tolerance Optional, tolerance (>= 0) to avoid false result because of floating point errors. + * @returns true if this point equals point, false otherwise + */ + public equals(point: Point, tolerance?: number): boolean; + + /** + * Subtracts the x and y values of a points and returns a new Point. + * @param point The point to subtract. + * @returns A new point created by the subtraction of two points. + */ + public subtract(point: Point): Point; + + /** + * Converts the Point to a string representation. + * @returns A string representation of the point. + */ + public toString(): string; } - export interface PolylineOptions { - strokeColor?: Color; - strokeDashArray?: string; - strokeThickness?: number; - visible?: boolean; + /** + * This compression algorithm encodes/decodes an array of locations into a string. + * This algorithm is used for generating a compressed collection of locations for use + * with the Bing Maps REST Elevation Service. This algorithm is also used for decoding + * the compressed coordinates returned by the GeoData API. + * + * These algorithms come from the following documentation: + * http://msdn.microsoft.com/en-us/library/jj158958.aspx + * http://msdn.microsoft.com/en-us/library/dn306801.aspx + */ + export class PointCompression { + /** + * Decodes a collection of locations from a compressed string. + * @param value Compressed string to decode. + * @returns An array of locations that have been decoded from the compressed string. + */ + public static decode(value: string): Location[]; + + /** + * Compresses an array of locations into a string. + * @param locations Collection of coordinates to compress. + * @returns A compressed string representing an array of locations. + */ + public static encode(locations: Location[]): string; } - export class Polygon implements Entity { + /** + * A polygon is an area defined by a closed ring of locations. A simple polygon consists of an array of Location objects that form a boundary. + * A complex polygon consists of several arrays of Locations, where the first array is the outline of the polygon, and the subsequent arrays are holes in the polygon. + * The Polygon class derives from the IPrimitive interface. + */ + export class Polygon implements IPrimitive { + /** + * Information that is linked to the polygon. + * Some modules such as the GeoJSON, and Spatial Data Service modules will also often add information to this property. + */ + public metadata: any; - constructor(locations: Array, options?: PolygonOptions); + /** + * @constructor + * @param rings A Location array for basic polygon with single outer perimeter, + * or an array of Location arrays for advanced polygon (multi-polygon, polygon with holes, or combination of polygons). + * @param options Options used to customize polygon. + */ + constructor(rings: Location[] | Location[][], options?: IPolygonOptions); - getFillColor(): Color; - getLocations(): Array; - getStrokeColor(): Color; - getStrokeDashArray(): string; - getStrokeThickness(): number; - getVisible(): boolean; - setLocations(locations: Location[]): void; - setOptions(options: PolylineOptions): void; - toString(): string; + /** + * Gets the css cursor value when polygon has events on it. + * @returns CSS cursor string when polygon has events on it. + */ + public getCursor(): string; + + /** + * Gets the fill color of the inside of the polygon. Will be string or Color object depending on the the what method was used in the pushpin options. + * @returns The fill color of the inside of the polygon. + */ + public getFillColor(): string | Color; + + /** + * Returns whether the polygon is generalizable based on zoom level or not. + * @returns whether the polygon is generalizable based on zoom level or not. + */ + public getGeneralizable(): boolean; + + /** + * Gets the first ring of the polygon (for V7 compatability). + * @returns An array of Locations that is the first ring of the polygon; or an empty array if the polygon has no ring at all. + */ + public getLocations(): Location[]; + + /** + * Gets an array of location arrays, where each location array defines a ring of the polygon. + * @returns An array of location arrays, where each location array defines a ring of the polygon. + */ + public getRings(): Location[][]; + + /** + * Gets the color of the border stroke of the polygon. Will be string or Color object depending on the the what method was used in the pushpin options. + * @returns The color of the border stroke of the polygon. + */ + public getStrokeColor(): string | Color; + + /** + * Gets the stroke dash array of the polygon, in format of either array or string, whichever user provides. + * @returns The stroke dash array of the polygon. + */ + public getStrokeDashArray(): number[] | string; + + /** + * Gets the thickness of the border stroke of the polygon. + * @returns The thickness of the border stroke of the polygon as a number. + */ + public getStrokeThickness(): number; + + /** + * Gets whether the polygon is visible. + * @returns A boolean indicating whether the polygon is visible or not. + */ + public getVisible(): boolean; + + /** + * Sets locations (single ring) of the polygon. (for V7 compatability) + * @param locations A Location[] that defines the only ring of the polygon + */ + public setLocations(locations: Location[]): void; + + /** + * Sets the properties for the polygon. + * @param options The IPolygonOptions object containing the options to customize the polygon. + */ + public setOptions(options: IPolygonOptions): void; + + /** + * Sets rings of the polygon. + * @param rings A Location[][] where each Location[] defines a ring of the polygon. + */ + public setRings(rings: Location[] | Location[][]): void; } - export interface PolygonOptions { - fillColor?: Color; - infobox?: Infobox; - strokeColor?: Color; - strokeDashArray?: string; - strokeThickness?: number; - visible?: boolean; + /** + * Polylines allow you to draw connected lines on a map. In many spatial database systems, this is also known as a LineString. + * The Polyline class derives from the IPrimitive interface. + */ + export class Polyline implements IPrimitive { + /** + * Information that is linked to the polyline. + * Some modules such as the GeoJSON, and Spatial Data Service modules will also often add information to this property. + */ + public metadata: any; + + /** + * @constructor + * @param locations An array of locations that make up the path of the polyine. + * @param options Options used to customize polyline. + */ + constructor(locations: Location[], options?: IPolylineOptions); + + /** + * Gets the css cursor value when polyline has events on it. + * @returns CSS cursor string when polyline has events on it. + */ + public getCursor(): string; + + /** + * Returns whether the polyline is generalizable based on zoom level or not. + * @returns whether the polyline is generalizable based on zoom level or not. + */ + public getGeneralizable(): boolean; + + /** + * Gets the locations that make up the polyline. + * @returns An array that defines the path of the polyline. + */ + public getLocations(): Location[]; + + /** + * Gets the color of the border stroke of the polyline. Will be string or Color object depending on the the what method was used in the polyline options. + * @returns The stroke color of the polyline. + */ + public getStrokeColor(): string | Color; + + /** + * Gets the stroke dash array of the polyline, in format of either array or string, whichever user provides. + * @returns The stroke dash array of the polyline. + */ + public getStrokeDashArray(): number[] | string; + + /** + * Gets the thickness of the border stroke of the polyline. + * @returns The thickness of the border stroke of the polyline as a number. + */ + public getStrokeThickness(): number; + + /** + * Gets whether the polyline is visible. + * @returns A boolean indicating whether the polyline is visible or not. + */ + public getVisible(): boolean; + + /** + * Sets locations of the polyline. + * @param locations A Location[] that defines path of the polyline + */ + public setLocations(locations: Location[]): void; + + /** + * Sets the properties for the polyline. + * @param options The IPolylineOptions object containing the options to customize the polyline. + */ + public setOptions(options: IPolylineOptions): void; } - export class Pushpin implements Entity { + /** + * Pushpins, sometimes also referred to as markers or MapIcons on other mapping platforms, are one of the primary ways of marking a location on a map. + * The Pushpin class derives from the IPrimitive interface. + */ + export class Pushpin implements IPrimitive { - constructor(location: Location, options?: PushpinOptions); + /** + * Information that is linked to the pushpin. + * Some modules such as the GeoJSON, and Spatial Data Service modules will also often add information to this property. + */ + public metadata: any; - getAnchor(): Point; - getIcon(): string; - getHeight(): number; - getLocation(): Location; - getText(): string; - getTextOffset(): Point; - getTypeName(): string; - getVisible(): boolean; - getWidth(): number; - getZIndex(): number; - setLocation(location: Location): void; - setOptions(options: PushpinOptions): void; - toString(): string; + /** + * @constructor + * @param location A Location object that specifies where to display the pushpin. + * @param options Options used when creating the Pushpin. + */ + constructor(location: Location, options?: IPushpinOptions); + + /** + * Gets the point on the Pushpin icon which is anchored to the pushpin location. + * An anchor of (0,0) is the top left corner of the icon. + * @returns The point on the Pushpin icon which is anchored to the pushpin location. + */ + public getAnchor(): Point; + + /** + * Gets whether the pushpin clicked style is enabled + * @returns Whether the pushpin clicked style is enabled. + */ + public getClickedStyleEnabled(): boolean; + + /** + * Gets the color option of the pushpin. + * @returns The color option of the pushpin. + */ + public getColor(): string | Color; + + /** + * Gets the css cursor value when pushpin has events on it. + * @returns CSS cursor string when pushpin has events on it. + */ + public getCursor(): string; + + /** + * Gets a boolean indicating if the pushpin is draggable or not. + * @returns A boolean indicating if the pushpin is draggable or not. + */ + public getDraggable(): boolean; + + /** + * Gets whether the pushpin hover style is enabled + * @returns Whether the pushpin hover style is enabled. + */ + public getHoverStyleEnabled(): boolean; + + /** + * Gets the custom Pushpin source icon string which can be a url to an image or SVG, inline SVG string, or data URI. + * @returns the custom Pushpin icon source string, which can be a url to an image or SVG, inline SVG string, or data URI. + */ + public getIcon(): string; + + /** + * Returns the location of the pushpin. + * @returns The location of the pushpin. + */ + public getLocation(): Location; + + /** + * Returns whether the clickable area of the pushpin is an ellipse. + * @returns A boolean indicating whether the clickable area of the pushpin is an ellipse. + */ + public getRoundClickableArea(): boolean; + + /** + * Gets the subtitle label of the Pushpin. + * @returns The subtitle label of the Pushpin. + */ + public getSubTitle(): string; + + /** + * Gets the text within the Pushpin icon. + * @returns The text within the Pushpin icon. + */ + public getText(): string; + + /** + * Gets the amount the text is shifted from the Pushpin icon. + * @returns the amount the text is shifted from the Pushpin icon. + */ + public getTextOffset(): Point; + + /** + * Gets the title label of the Pushpin. + * @returns the title label of the Pushpin. + */ + public getTitle(): string; + + /** + * Gets whether the pushpin is visible. + * @returns A boolean indicating whether the pushpin is visible or not. + */ + public getVisible(): boolean; + + /** + * Sets the location of the Pushpin. + * @param location The location of the Pushpin. + */ + public setLocation(location: Location): void; + + /** + * Sets the properties for the pushpin. + * @param options The IPushpinOptions object containing the options to customize the pushpin. + */ + public setOptions(options: IPushpinOptions): void; } - export enum EntityState { - highlighted, - none, - selected + /** + * Used to represent the location of a map tile in the quadkey tile pyramid system used by the map. + * If using a tile source where the uriConstructor property is set to a callback function, that callback function will recieve + * an instance of the PyramidTileId class. + */ + export class PyramidTileId { + /** The height of the tile. */ + public pixelHeight: number; + + /** The width of the tile. */ + public pixelWidth: number; + + /** The quadkey ID of the tile. */ + public quadKey: string; + + /** The x tile coordinate. */ + public x: number; + + /** The y tile coordinate. */ + public y: number; + + /** The zoom level of the tile. */ + public zoom: number; + + /** + * @constructor + * @param x The integer x position of the tile within the tile layer at the specified zoom level. + * @param y The integer y position of the tile within the tile layer at the specified zoom level. + * @param zoom The zoom level of the tile. + * @param width The tile's width in pixels. Default value: 256 + * @param height The tile's height in pixels. Default value: 256 + */ + constructor(x: number, y: number, zoom: number, width?: number, height?: number) + + /** + * Compares two PyramidTileId objects and returns a boolean indicating if the two PyramidTileId are equal. + * @param tileId1 The first PyramidTileId to compare to the second. + * @param tileId2 The second PyramidTileId to compare to the first. + * @returns A boolean indicating if the two PyramidTileId are equal. + */ + public static areEqual(tileId1: PyramidTileId, tileId2: PyramidTileId): boolean; + + /** + * Generates a PyramidTileId from a quadkey tile id string. + * @param quadkey The quadkey tile id string to convert into a PyramidTileId object. + * @param width The tile's width in pixels. Default value: 256 + * @param height The tile's height in pixels. Default value: 256 + */ + public static fromQuadKey(quadkey: string, width?: number, height?: number): PyramidTileId; } - export interface PushpinOptions { + /** Provides static functions for generating random test data. */ + export class TestDataGenerator { + /** + * Generates a random hex or rgba color string. + * @param withAlpha A boolean indicating if the color should have an alpha value or not. if set to true, a rgba value will be returned with an alpha value of 0.5. + * @returns A css color string, hex or rgba. + */ + public static getColor(withAlpha?: boolean): string; - anchor?: Point; - draggable?: boolean; - height?: number; - htmlContent?: string; - icon?: string; - infobox?: Infobox; - state?: EntityState; - text?: string; - textOffset?: Point; - typeName?: string; - visible?: boolean; - width?: number; - zIndex?: number; + /** + * Generates random Location objects. + * @param num The number of locations to generate. If set to one a single Location will be returned. If greater than one and array will be returned. + * @param bounds The bounding box in which all the locations should fall within. + * @returns One or more random Locations. + */ + public static getLocations(num?: number, bounds?: LocationRect): Location | Location[]; + + /** + * Generates random pushpins. + * @param num The number of pushpins to generate. If set to one a single Pushpin will be returned. If greater than one and array will be returned. + * @param bounds The bounding box in which all the pushpins should fall within. + * @param options The options to use for rendering the pushpins. Default is random. + * @returns One or more random Pushpins. + */ + public static getPushpins(num?: number, bounds?: LocationRect, options?: IPushpinOptions): Pushpin | Pushpin[]; + + /** + * Generates random polylines. + * @param num The number of polylines to generate. If set to one a single Polyline will be returned. If greater than one and array will be returned. + * @param bounds The bounding box in which all the locations of the polylines should fall within. + * @param size The number of locations each polylines should have. Default: random between 3 and 10. + * @param scaleFactor A number that scales the size of the polylines based on size of the bounding box. A value of 0.1 would generate polylines that are no larger than 10% of the width/height of the map. Default: 0.1 + * @param options The options to use for rendering the polylines. Default is random. + * @returns One or more random Polylines. + */ + public static getPolylines(num?: number, bounds?: LocationRect, size?: number, scaleFactor?: number, options?: IPolylineOptions): Polyline | Polyline[]; + + /** + * Generates random polygons. + * @param num The number of polygons to generate. If set to one a single Polygon will be returned. If greater than one and array will be returned. + * @param bounds The bounding box in which all the locations of the polygon should fall within. + * @param size The number of locations each polygon should have. Default: random between 3 and 10. + * @param scaleFactor A number that scales the size of the polygons based on the size of the bounding box. A value of 0.1 would generate polygons that are no larger than 10% of the width/height of the map. Default: 0.1 + * @param options The options to use for rendering the polygons. Default is random. + * @param addHole A boolean indicating if the generated polygon should have a hole or not. Note that this will double the number of Location objects that are in the Polygon. Default: false + * @returns One or more random polygons. + */ + public static getPolygons(num?: number, bounds?: LocationRect, size?: number, scaleFactor?: number, options?: IPolygonOptions, addHole?: boolean): Polygon | Polygon[]; } - export class TileLayer implements Entity { + /** Represents a tile layer that can be overlaid on top of the map. */ + export class TileLayer implements ILayer { + /** + * @constructor + * @param options The options to use to define the tile layer. + */ + constructor(options: ITileLayerOptions); - constructor(options: TileLayerOptions); + /** + * Gets the opacity of the tile layer, defined as a double between 0 (not visible) and 1. + * @returns The opacity of the tile layer, defined as a double between 0 (not visible) and 1. + */ + public getOpacity(): number; - getOpacity(): number; - getTileSource(projection: string): TileSource; - getZIndex(): number; - setOptions(options: TileLayerOptions): void; - toString(): string; + /** + * Gets the tile source of the tile layer. + * @returns The tile source of the tile layer. + */ + public getTileSource(): TileSource; + + /** + * Gets a boolean that indicates if the tile layer is visible or not. + * @returns A boolean that indicates if the tile layer is visible or not. + */ + public getVisible(): boolean; + + /** + * Gets the zIndex of the tile layer. + * @returns The zIndex of the tile layer. + */ + public getZIndex(): number; + + /** + * Sets the opacity of the tile layer. Value must be a number between 0 and 1. + * @param opacity The opacity of the tile layer. Value must be a number between 0 and 1. + */ + public setOpacity(opacity: number): void; + + /** + * Sets options for the tile layer. + * @param options The options for the tile layer. + */ + public setOptions(options: ITileLayerOptions): void; + + /** + * Sets the visibility of the tile layer. + * @param show A boolean indicating if the tile layer should be visible or not. + */ + public setVisible(show: boolean): void; + + /** + * Sets the zIndex of the tile layer. + * @param idx The zIndex of the tile layer. + */ + public setZIndex(idx: number): void; } + /** Defines the data source for a tile layer. */ export class TileSource { + /** + * @constructor + * @param options The options to use to define the tile source. + */ + constructor(options: ITileSourceOptions); - constructor(options: TileSourceOptions); + /** + * Gets the specified bounding box of the of the tile source. + * @returns The specified bounding box of the of the tile source. + */ + public getBounds(): LocationRect; - getHeight(): number; - getUriConstructor(): string; - getWidth(): string; - toString(): string; + /** + * Gets the pixel height of each tile in the tile source. + * @returns The pixel height of each tile in the tile source. + */ + public getHeight(): number; + + /** + * Gets the maximum zoom level specified for the tile source. + * @returns The maximum zoom level specified for the tile source. + */ + public getMaxZoom(): number; + + /** + * Gets the minimum zoom level specified for the tile source. + * @returns The minimum zoom level specified for the tile source. + */ + public getMinZoom(): number; + + /** + * Gets a string that constructs tile URLs used to retrieve tiles for the tile layer. + * @returns A string that constructs tile URLs used to retrieve tiles for the tile layer. + */ + public getUriConstructor(): string | ((tile: PyramidTileId) => string); + + /** + * Gets the pixel width of each tile in the tile source. + * @returns The pixel width of each tile in the tile source. + */ + public getWidth(): number; } - - export interface TileSourceOptions { - - height?: number; - uriConstructor: any; - width?: number; - } - - - export interface TileLayerOptions { - - animationDisplay?: AnimationVisibility; - downloadTimeout?: number; - mercator?: TileSource; - opacity?: number; - visible?: boolean; - zIndex?: number; - } - - export enum AnimationVisibility { - auto, - hide, - show - } - - export class Coordinates { - - accuracy: number; - altitude: number; - altitudeAccuracy: number; - heading: number; - latitude: number; - longitude: number; - } - - export class GeoLocationProvider { - - constructor(map: Map); - - addAccuracyCircle(center: Location, radiusInMeters: number, segments: number, options: PositionCircleOptions): void; - cancelCurrentRequest(): void; - getCurrentPosition(options?: PositionOptions): void; - removeAccuracyCircle(): void; - } - - export interface PositionOptionsErrorCallbackResult { - internalError: PositionError; - errorCode:number; - } - - export interface PositionOptionsSuccessCallbackResult { - center: Location; - position: Position; - } - - export interface PositionOptions { - enableHighAccuracy?: boolean; - errorCallback?: (result: PositionOptionsErrorCallbackResult) => void; - showAccuracyCircle?: boolean; - timeout?: number; - updateMapView?: boolean; - maximumAge?: number; - successCallback?: (result: PositionOptionsSuccessCallbackResult) => void; - } - - export interface PositionCircleOptions { - polygonOptions: PolygonOptions; - showOnMap?: boolean; - } - - export class PositionError { - errorCode: number; - internalError: string; - } - - export interface ModuleOptions { - callback?: () => void; - styleURLS?: Array; - culture?: string; - homeRegion?: string; - } - - export function loadModule(moduleKey: string, options?: ModuleOptions): void; - export function moduleLoaded(moduleKey: string): void; - export function registerModule(moduleKey: string, scriptUrl: string, options?: ModuleOptions): void; } diff --git a/types/bingmaps/tsconfig.json b/types/bingmaps/tsconfig.json index 8fa709cf83..b552120da3 100644 --- a/types/bingmaps/tsconfig.json +++ b/types/bingmaps/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "bingmaps-tests.ts" ] -} \ No newline at end of file +} \ No newline at end of file diff --git a/types/bintrees/bintrees-tests.ts b/types/bintrees/bintrees-tests.ts index 707d8e0adf..fb4a22a3d8 100644 --- a/types/bintrees/bintrees-tests.ts +++ b/types/bintrees/bintrees-tests.ts @@ -1,14 +1,50 @@ +/// +/// +import assert = require('assert'); import { BinTree, RBTree } from 'bintrees'; -let treeA = new RBTree((a:number, b:number) => a - b); +describe('bintrees', () => { + it('builds a simple tree', () => { + let treeA = new RBTree((a: number, b: number) => a - b); -treeA.insert(5); -treeA.insert(3); -treeA.remove(3); + treeA.insert(5); + treeA.insert(3); + treeA.remove(3); -let treeB = new BinTree((a:string, b:string) => a.length - b.length); + assert.equal(treeA.size, 1); + }); + + it('builds a tree of strings', () => { + let treeB = new BinTree((a:string, b:string) => a.length - b.length); + + treeB.insert('hi'); + treeB.insert('there'); + treeB.insert('how'); + treeB.insert('are'); // ignored + treeB.remove('how'); + + assert.equal(treeB.size, 2); + assert.equal(treeB.min(), 'hi'); + }); + + it('maintains a tree of objects', () => { + + interface C { + id: number + } + + let treeC = new BinTree((a: C, b: C) => a.id - b.id); + + treeC.insert({ id: 100 }); + treeC.insert({ id: 110 }); + treeC.insert({ id: 105 }); + + let ids: number[] = []; + treeC.each((val: C) => { + ids.push(val.id); + }); + + assert.deepEqual(ids, [100, 105, 110]); + }); +}); -treeB.insert('hi'); -treeB.insert('there'); -treeB.insert('how'); -treeB.insert('are'); diff --git a/types/bintrees/index.d.ts b/types/bintrees/index.d.ts index 7a7b2c233e..743997dc03 100644 --- a/types/bintrees/index.d.ts +++ b/types/bintrees/index.d.ts @@ -5,8 +5,8 @@ declare module 'bintrees' { - type Callback = (item: T) => void; - type Comparator = (a: T, b: T) => number; + type Callback = (item: T) => void; + type Comparator = (a: T, b: T) => number; class Iterator { constructor(tree: TreeBase); @@ -37,14 +37,14 @@ declare module 'bintrees' { iterator(): Iterator; - each(cb: Callback): void; + each(cb: Callback): void; - reach(cb: Callback): void; + reach(cb: Callback): void; } export class RBTree extends TreeBase { - constructor(comparator: Comparator); + constructor(comparator: Comparator); insert(item: T): boolean; @@ -52,7 +52,7 @@ declare module 'bintrees' { } export class BinTree extends TreeBase { - constructor(comparator: Comparator); + constructor(comparator: Comparator); insert(item: T): boolean; diff --git a/types/bip21/index.d.ts b/types/bip21/index.d.ts index 06e61a6944..7561551e7a 100644 --- a/types/bip21/index.d.ts +++ b/types/bip21/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bip21 v1.1.2 // Project: https://github.com/bitcoinjs/bip21 -// Definitions by: Stefan Huber +// Definitions by: Stefan Huber // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace bip21 { diff --git a/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts index 7267fe5d26..549de76507 100644 --- a/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts +++ b/types/bitcoinjs-lib/bitcoinjs-lib-tests.ts @@ -1,5 +1,3 @@ -/// - import bigi = require('bigi'); import bitcoin = require('bitcoinjs-lib'); @@ -8,57 +6,57 @@ declare const describe: any; declare const assert: any; describe('bitcoinjs-lib (basic)', () => { - it('can generate a random bitcoin address', () => { - // for testing only - function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } + it('can generate a random bitcoin address', () => { + // for testing only + function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } - // generate random keyPair - const keyPair = bitcoin.ECPair.makeRandom({ rng }); - const address = keyPair.getAddress(); + // generate random keyPair + const keyPair = bitcoin.ECPair.makeRandom({ rng }); + const address = keyPair.getAddress(); - assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64'); - }); + assert.strictEqual(address, '1F5VhMHukdnUES9kfXqzPzMeF1GPHKiF64'); + }); - it('can generate an address from a SHA256 hash', () => { - const hash = bitcoin.crypto.sha256('correct horse battery staple'); - const d = bigi.fromBuffer(hash); + it('can generate an address from a SHA256 hash', () => { + const hash = bitcoin.crypto.sha256(Buffer.from('correct horse battery staple', 'utf8')); + const d = bigi.fromBuffer(hash); - const keyPair = new bitcoin.ECPair(d); - const address = keyPair.getAddress(); + const keyPair = new bitcoin.ECPair(d); + const address = keyPair.getAddress(); - assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8'); - }); + assert.strictEqual(address, '1C7zdTfnkzmr13HfA2vNm5SJYRK6nEKyq8'); + }); - it('can generate a random keypair for alternative networks', () => { - // for testing only - function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } + it('can generate a random keypair for alternative networks', () => { + // for testing only + function rng() { return new Buffer('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'); } - const litecoin = bitcoin.networks.litecoin; + const litecoin = bitcoin.networks.litecoin; - const keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng }); - const wif = keyPair.toWIF(); - const address = keyPair.getAddress(); + const keyPair = bitcoin.ECPair.makeRandom({ network: litecoin, rng }); + const wif = keyPair.toWIF(); + const address = keyPair.getAddress(); - assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn'); - assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS'); - }); + assert.strictEqual(address, 'LZJSxZbjqJ2XVEquqfqHg1RQTDdfST5PTn'); + assert.strictEqual(wif, 'T7A4PUSgTDHecBxW1ZiYFrDNRih2o7M8Gf9xpoCgudPF9gDiNvuS'); + }); - it('can import an address via WIF', () => { - const keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct'); - const address = keyPair.getAddress(); + it('can import an address via WIF', () => { + const keyPair = bitcoin.ECPair.fromWIF('Kxr9tQED9H44gCmp6HAdmemAzU3n84H3dGkuWTKvE23JgHMW8gct', bitcoin.networks.testnet); + const address = keyPair.getAddress(); - assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31'); - }); + assert.strictEqual(address, '19AAjaTUbRjQCMuVczepkoPswiZRhjtg31'); + }); - it('can create a Transaction', () => { - const keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy'); - const tx = new bitcoin.TransactionBuilder(); + it('can create a Transaction', () => { + const keyPair = bitcoin.ECPair.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy', bitcoin.networks.testnet); + const tx = new bitcoin.TransactionBuilder(); - tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0); - tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000); - tx.sign(0, keyPair); + tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0); + tx.addOutput(Buffer.from('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK'), 15000); + tx.sign(0, keyPair); - // tslint:disable-next-line:max-line-length - assert.strictEqual(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000'); - }); + // tslint:disable-next-line:max-line-length + assert.strictEqual(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000'); + }); }); diff --git a/types/bitcoinjs-lib/index.d.ts b/types/bitcoinjs-lib/index.d.ts index 600edda000..986bb75e0b 100644 --- a/types/bitcoinjs-lib/index.d.ts +++ b/types/bitcoinjs-lib/index.d.ts @@ -1,114 +1,230 @@ -// Type definitions for bitcoinjs-lib 2.3 -// Project: https://github.com/bitcoinjs/bitcoinjs-lib#readme -// Definitions by: Mohamed Hegazy +// Type definitions for bitcoinjs-lib 3.0 +// Project: https://github.com/bitcoinjs/bitcoinjs-lib +// Definitions by: Mohamed Hegazy +// Daniel +// Ron Buckton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Declaration file initially generated by dts-gen for bitcoinjs-lib 3.0.3 +// based on the flow version found at https://github.com/flowtype/flow-typed/blob/master/definitions/npm/bitcoinjs-lib_v2.x.x/flow_v0.17.x-/bitcoinjs-lib_v2.x.x.js -export class Block { - constructor(); - checkMerkleRoot(): any; - checkProofOfWork(): any; - getHash(): any; - getId(): any; - getUTCDate(): any; - toBuffer(headersOnly: any): any; - toHex(headersOnly: any): any; - static calculateMerkleRoot(transactions: any): any; - static calculateTarget(bits: any): any; - static fromBuffer(buffer: any): any; - static fromHex(hex: any): any; +/// +import BigInteger = require("bigi"); + +export interface Output { + script: Buffer; + value: number; } -export class ECPair { - constructor(d: any, Q?: any, options?: any); - getAddress(): string; - getNetwork(): Network; - getPublicKeyBuffer(): any; - sign(hash: any): any; - toWIF(): string; - verify(hash: any, signature: any): boolean; - static fromPublicKeyBuffer(buffer: any, network: Network): ECPair; - static fromWIF(string: any, network?: Network): ECPair; - static makeRandom(options: any): ECPair; -} -export class ECSignature { - constructor(r: any, s: any, ...args: any[]); - toCompact(i: any, compressed: any): any; - toDER(): any; - toScriptSignature(hashType: any): any; - static fromDER(buffer: any): ECSignature; - static parseCompact(buffer: any): ECSignature; - static parseScriptSignature(buffer: any): ECSignature; -} -export class HDNode { - constructor(keyPair: any, chainCode: any, ...args: any[]); - derive(index: any): any; - deriveHardened(index: any): any; - derivePath(path: any): any; - getAddress(): string; - getFingerprint(): any; - getIdentifier(): any; - getNetwork(): Network; - getPublicKeyBuffer(): any; - isNeutered(): any; - neutered(): any; - sign(hash: any): any; - toBase58(__isPrivate: any): any; - toString(__isPrivate: any): any; - verify(hash: any, signature: any): any; - static HIGHEST_BIT: number; - static LENGTH: number; - static fromBase58(string: any, networks: Network[]): HDNode; - static fromSeedBuffer(seed: any, network: Network, ...args: any[]): HDNode; - static fromSeedHex(hex: any, network: Network): HDNode; -} -export class Transaction { - constructor(); - addInput(hash: any, index: any, sequence: any, scriptSig: any, ...args: any[]): any; - addOutput(scriptPubKey: any, value: any, ...args: any[]): any; - byteLength(): number; - clone(): Transaction; - getHash(): any; - getId(): any; - hashForSignature(inIndex: any, prevOutScript: any, hashType: any, ...args: any[]): any; - isCoinbase(): boolean; - setInputScript(index: any, scriptSig: any, ...args: any[]): void; - toBuffer(buffer?: any, initialOffset?: any): Buffer; - toHex(): string; - static DEFAULT_SEQUENCE: number; - static SIGHASH_ALL: number; - static SIGHASH_ANYONECANPAY: number; - static SIGHASH_NONE: number; - static SIGHASH_SINGLE: number; - static fromBuffer(buffer: any, __noStrict: any): Transaction; - static fromHex(hex: any): Transaction; - static isCoinbaseHash(buffer: any): Transaction; -} -export class TransactionBuilder { - constructor(network?: Network); - addInput(txHash: any, vout: any, sequence?: any, prevOutScript?: any): any; - addOutput(scriptPubKey: any, value: any): any; - build(): Transaction; - buildIncomplete(): Transaction; - setLockTime(locktime: number): any; - setVersion(version: number): void; - sign(index: any, keyPair: any, redeemScript?: any, hashType?: any): any; - static fromTransaction(transaction: Transaction, network: Network): TransactionBuilder; + +export interface Input { + script: Buffer; + hash: Buffer; + index: number; + sequence: number; } export interface Network { - bitcoin: { - private: number; + bip32: { public: number; + private: number; }; - dustThreshold: number; messagePrefix: string; pubKeyHash: number; scriptHash: number; wif: number; } +export class Block { + constructor(); + + byteLength(headersOnly?: boolean): number; + + checkMerkleRoot(): any; + + checkProofOfWork(): any; + + getHash(): Buffer; + + getId(): string; + + getUTCDate(): any; + + toBuffer(headersOnly?: boolean): Buffer; + + toHex(headersOnly?: boolean): string; + + static calculateMerkleRoot(transactions: Transaction[] | Array<{ getHash(): Buffer; }>): Buffer; + + static calculateTarget(bits: number): Buffer; + + static fromBuffer(buffer: Buffer): Block; + + static fromHex(hex: string): Block; +} + +export class ECPair { + constructor(d: BigInteger, Q?: null | undefined, options?: { compressed?: boolean, network?: Network }); + + constructor(d: null | undefined, Q: any, options?: { compressed?: boolean, network?: Network }); // Q should be ECPoint, but not sure how to define such type + + getAddress(): string; + + getNetwork(): Network; + + getPublicKeyBuffer(): Buffer; + + sign(hash: Buffer): ECSignature; + + toWIF(): string; + + verify(hash: Buffer, signature: ECSignature): boolean; + + static fromPublicKeyBuffer(buffer: Buffer, network: Network): ECPair; + + static fromWIF(string: string, network: Network): ECPair; + + static makeRandom(options?: { compressed?: boolean, network?: Network, rng?: Rng }): ECPair; +} + +export type Rng = (size: number) => Buffer; + +export class ECSignature { + constructor(r: BigInteger, s: BigInteger); + + toCompact(i: number, compressed: boolean): Buffer; + + toDER(): Buffer; + + toScriptSignature(hashType: number): Buffer; + + static fromDER(buffer: Buffer): ECSignature; + + static parseCompact(buffer: Buffer): { compressed: boolean, i: number, signature: ECSignature }; + + static parseScriptSignature(buffer: Buffer): { signature: ECSignature, hashType: number }; +} + +export class HDNode { + constructor(keyPair: ECPair, chainCode: Buffer); + + keyPair: ECPair; + + derive(index: number): HDNode; + + deriveHardened(index: number): HDNode; + + derivePath(path: string): HDNode; + + getAddress(): string; + + getFingerprint(): Buffer; + + getIdentifier(): Buffer; + + getNetwork(): Network; + + getPublicKeyBuffer(): Buffer; + + isNeutered(): boolean; + + neutered(): HDNode; + + sign(hash: Buffer): ECSignature; + + toBase58(): string; + + verify(hash: Buffer, signature: ECSignature): Buffer; + + static HIGHEST_BIT: number; + + static LENGTH: number; + + static fromBase58(string: string, networks?: Network[] | Network): HDNode; + + static fromSeedBuffer(seed: Buffer, network?: Network): HDNode; + + static fromSeedHex(hex: string, network?: Network): HDNode; + + static MASTER_SECRET: Buffer; +} + +export class Transaction { + version: number; + locktime: number; + ins: Input[]; + outs: Output[]; + constructor(); + + addInput(hash: Buffer, index: number, sequence?: number, scriptSig?: Buffer): number; + + addOutput(scriptPubKey: Buffer | string, value: number): number; + + byteLength(): number; + + clone(): Transaction; + + getHash(): Buffer; + + getId(): string; + + hasWitnesses(): boolean; + + hashForSignature(inIndex: number, prevOutScript: Buffer, hashType: number): Buffer; + + hashForWitnessV0(inIndex: number, prevOutScript: Buffer, value: number, hashType: number): Buffer; + + isCoinbase(): boolean; + + setInputScript(index: number, scriptSig: Buffer): void; + + setWitness(index: number, witness: any, ...args: any[]): void; + + toBuffer(buffer?: Buffer, initialOffset?: number): Buffer; + + toHex(): string; + + static ADVANCED_TRANSACTION_FLAG: number; + + static ADVANCED_TRANSACTION_MARKER: number; + + static DEFAULT_SEQUENCE: number; + + static SIGHASH_ALL: number; + + static SIGHASH_ANYONECANPAY: number; + + static SIGHASH_NONE: number; + + static SIGHASH_SINGLE: number; + + static fromBuffer(buffer: Buffer, __noStrict?: boolean): Transaction; + + static fromHex(hex: string): Transaction; + + static isCoinbaseHash(buffer: Buffer): boolean; +} + +export class TransactionBuilder { + constructor(network?: Network, maximumFeeRate?: number); + + addInput(txhash: Buffer | string | Transaction, vout: number, sequence?: number, prevOutScript?: Buffer): number; + + addOutput(scriptPubKey: Buffer, value: number): number; + + build(): Transaction; + + buildIncomplete(): Transaction; + + setLockTime(locktime: number): void; + + setVersion(version: number): void; + + sign(vin: number, keyPair: ECPair, redeemScript?: Buffer, hashType?: number, witnessValue?: number, witnessScript?: Buffer): void; + + static fromTransaction(transaction: Transaction, network: Network): TransactionBuilder; +} + export const networks: { bitcoin: Network; - dogecoin: Network; litecoin: Network; testnet: Network; }; @@ -232,172 +348,185 @@ export const opcodes: { OP_WITHIN: number; OP_XOR: number; }; -export namespace HDNode { - namespace MASTER_SECRET { - const BYTES_PER_ELEMENT: number; - const byteLength: number; - const byteOffset: number; - const length: number; - const offset: number; - function asciiSlice(): any; - function asciiWrite(): any; - function base64Slice(): any; - function base64Write(): any; - function compare(target: any, start: any, end: any, thisStart: any, thisEnd: any): any; - function copy(): any; - function copyWithin(p0: any, p1: any): any; - function entries(): any; - function equals(b: any): any; - function every(p0: any): any; - function fill(val: any, start: any, end: any, encoding: any): any; - function filter(p0: any): any; - function find(p0: any): any; - function findIndex(p0: any): any; - function forEach(p0: any): any; - function hexSlice(): any; - function hexWrite(): any; - function includes(val: any, byteOffset: any, encoding: any): any; - function indexOf(val: any, byteOffset: any, encoding: any): any; - function inspect(): any; - function join(p0: any): any; - function keys(): any; - function lastIndexOf(val: any, byteOffset: any, encoding: any): any; - function latin1Slice(): any; - function latin1Write(): any; - function map(p0: any): any; - function readDoubleBE(offset: any, noAssert: any): any; - function readDoubleLE(offset: any, noAssert: any): any; - function readFloatBE(offset: any, noAssert: any): any; - function readFloatLE(offset: any, noAssert: any): any; - function readInt16BE(offset: any, noAssert: any): any; - function readInt16LE(offset: any, noAssert: any): any; - function readInt32BE(offset: any, noAssert: any): any; - function readInt32LE(offset: any, noAssert: any): any; - function readInt8(offset: any, noAssert: any): any; - function readIntBE(offset: any, byteLength: any, noAssert: any): any; - function readIntLE(offset: any, byteLength: any, noAssert: any): any; - function readUInt16BE(offset: any, noAssert: any): any; - function readUInt16LE(offset: any, noAssert: any): any; - function readUInt32BE(offset: any, noAssert: any): any; - function readUInt32LE(offset: any, noAssert: any): any; - function readUInt8(offset: any, noAssert: any): any; - function readUIntBE(offset: any, byteLength: any, noAssert: any): any; - function readUIntLE(offset: any, byteLength: any, noAssert: any): any; - function reduce(p0: any): any; - function reduceRight(p0: any): any; - function reverse(): any; - function set(p0: any): any; - function slice(start: any, end: any): any; - function some(p0: any): any; - function sort(p0: any): any; - function subarray(p0: any, p1: any): any; - function swap16(): any; - function swap32(): any; - function swap64(): any; - function toJSON(): any; - function toLocaleString(): any; - function toString(...args: any[]): any; - function ucs2Slice(): any; - function ucs2Write(): any; - function undefined(): any; - function utf8Slice(): any; - function utf8Write(): any; - function values(): any; - function write(string: any, offset: any, length: any, encoding: any): any; - function writeDoubleBE(val: any, offset: any, noAssert: any): any; - function writeDoubleLE(val: any, offset: any, noAssert: any): any; - function writeFloatBE(val: any, offset: any, noAssert: any): any; - function writeFloatLE(val: any, offset: any, noAssert: any): any; - function writeInt16BE(value: any, offset: any, noAssert: any): any; - function writeInt16LE(value: any, offset: any, noAssert: any): any; - function writeInt32BE(value: any, offset: any, noAssert: any): any; - function writeInt32LE(value: any, offset: any, noAssert: any): any; - function writeInt8(value: any, offset: any, noAssert: any): any; - function writeIntBE(value: any, offset: any, byteLength: any, noAssert: any): any; - function writeIntLE(value: any, offset: any, byteLength: any, noAssert: any): any; - function writeUInt16BE(value: any, offset: any, noAssert: any): any; - function writeUInt16LE(value: any, offset: any, noAssert: any): any; - function writeUInt32BE(value: any, offset: any, noAssert: any): any; - function writeUInt32LE(value: any, offset: any, noAssert: any): any; - function writeUInt8(value: any, offset: any, noAssert: any): any; - function writeUIntBE(value: any, offset: any, byteLength: any, noAssert: any): any; - function writeUIntLE(value: any, offset: any, byteLength: any, noAssert: any): any; - namespace buffer { - const byteLength: number; - function slice(p0: any, p1: any): any; - } - namespace parent { - const byteLength: number; - function slice(p0: any, p1: any): any; - } - } -} + export namespace address { - function fromBase58Check(address: any): any; - function fromOutputScript(scriptPubKey: any, network?: Network): any; - function toBase58Check(hash: any, version: any, ...args: any[]): any; - function toOutputScript(address: any, network?: Network): any; + function fromBase58Check(address: string): { hash: Buffer, version: number }; + + function fromOutputScript(outputScript: Buffer, network?: Network): Buffer; + + function toBase58Check(hash: Buffer, version: number): string; + + function toOutputScript(address: string, network?: Network): Buffer; } + export namespace bufferutils { - function equal(a: any, b: any): any; - function pushDataSize(i: any): any; - function readPushDataInt(buffer: any, offset: any): any; - function readUInt64LE(buffer: any, offset: any): any; - function readVarInt(buffer: any, offset: any): any; - function reverse(src: any): any; - function varIntBuffer(i: any): any; - function varIntSize(i: any): any; - function writePushDataInt(buffer: any, number: any, offset: any): any; - function writeUInt64LE(buffer: any, value: any, offset: any): void; - function writeVarInt(buffer: any, number: any, offset: any): any; + function pushDataSize(i: number): number; + + function readPushDataInt(buffer: Buffer, offset: number): { opcode: number, number: number, size: number }; + + function readUInt64LE(buffer: Buffer, offset: number): number; + + function readVarInt(buffer: Buffer, offset: number): { number: number, size: number }; + + function varIntBuffer(number: number, buffer: Buffer, offset: number): Buffer; + + function varIntSize(number: number): number; + + function writePushDataInt(buffer: Buffer, number: number, offset: number): number; + + function writeUInt64LE(buffer: Buffer, value: number, offset: number): number; + + function writeVarInt(buffer: Buffer, number: number, offset: number): number; } + export namespace crypto { - function hash160(buffer: any): any; - function hash256(buffer: any): any; - function ripemd160(buffer: any): any; - function sha1(buffer: any): any; - function sha256(buffer: any): any; -} -export namespace message { - function magicHash(message: any, network: any): any; - function sign(keyPair: any, message: any, network: any): any; - function verify(address: any, signature: any, message: any, network: any): any; + function hash160(buffer: Buffer): Buffer; + + function hash256(buffer: Buffer): Buffer; + + function ripemd160(buffer: Buffer): Buffer; + + function sha1(buffer: Buffer): Buffer; + + function sha256(buffer: Buffer): Buffer; } + export namespace script { - function classifyInput(script: any, allowIncomplete: any): any; - function classifyOutput(script: any): any; - function compile(chunks: any): any; - function decompile(buffer: any): any; - function fromASM(asm: any): any; - function isCanonicalPubKey(buffer: any): any; - function isCanonicalSignature(buffer: any): any; - function isDefinedHashType(hashType: any): any; - function isMultisigInput(script: any, allowIncomplete: any): any; - function isMultisigOutput(script: any): any; - function isNullDataOutput(script: any): any; - function isPubKeyHashInput(script: any): any; - function isPubKeyHashOutput(script: any): any; - function isPubKeyInput(script: any): any; - function isPubKeyOutput(script: any): any; - function isScriptHashInput(script: any, allowIncomplete: any): any; - function isScriptHashOutput(script: any): any; - function isWitnessPubKeyHashOutput(script: any): any; - function isWitnessScriptHashOutput(script: any): any; - function multisigInput(signatures: any, scriptPubKey: any): any; - function multisigOutput(m: any, pubKeys: any, ...args: any[]): any; - function nullDataOutput(data: any): any; - function pubKeyHashInput(signature: any, pubKey: any, ...args: any[]): any; - function pubKeyHashOutput(pubKeyHash: any): any; - function pubKeyInput(signature: any): any; - function pubKeyOutput(pubKey: any): any; - function scriptHashInput(scriptSig: any, scriptPubKey: any): any; - function scriptHashOutput(scriptHash: any): any; - function toASM(chunks: any): any; - function witnessPubKeyHashOutput(pubKeyHash: any): any; - function witnessScriptHashInput(scriptSig: any, scriptPubKey: any): any; - function witnessScriptHashOutput(scriptHash: any): any; + function classifyInput(script: Buffer | Array, allowIncomplete?: boolean): "pubkeyhash" | "scripthash" | "multisig" | "pubkey" | "nonstandard"; + + function classifyOutput(script: Buffer | Array): "witnesspubkeyhash" | "witnessscripthash" | "pubkeyhash" + | "scripthash" | "multisig" | "pubkey" | "witnesscommitment" | "nulldata" | "nonstandard"; + + function classifyWitness(script: Buffer | Array, allowIncomplete: boolean): "witnesspubkeyhash" | "witnessscripthash" | "nonstandard"; + + function compile(chunks: Array): Buffer; + + function decompile(buffer: Buffer): Array; + + function fromASM(asm: string): Buffer; + + function isCanonicalPubKey(buffer: Buffer): boolean; + + function isCanonicalSignature(buffer: Buffer): boolean; + + function isDefinedHashType(hashType: any): boolean; + + function isPushOnly(value: any): boolean; + + function toASM(chunks: Buffer | Array): string; + + function toStack(chunks: Buffer | Array): Buffer[]; + namespace number { - function decode(buffer: any, maxLength: any, minimal: any): any; - function encode(number: any): any; + function decode(buffer: Buffer, maxLength: number, minimal: boolean): number; + + function encode(number: number): Buffer; } + + const multisig: { + input: { + check(script: Buffer, allowIncomplete: boolean): boolean; + decode(buffer: Buffer): Array; + decodeStack(stack: Buffer[], allowIncomplete: boolean): Array; + encode(signatures: ECSignature[], scriptPubKey: Buffer): Buffer; + encodeStack(signatures: ECSignature[], scriptPubKey: Buffer): ECSignature[]; + }; + output: { + check(script: Buffer, allowIncomplete: boolean): boolean; + decode(buffer: Buffer, allowIncomplete: boolean): { m: number; pubKeys: Array }; + encode(m: number, pubKeys: Array): Buffer; + }; + }; + + const pubKey: { + input: { + check(script: Buffer): boolean; + decode(buffer: Buffer): Array; + decodeStack(stack: Buffer[]): Array; + encode(signature: ECSignature): Buffer; + encodeStack(signature: ECSignature): ECSignature[]; + }; + + output: { + check(script: Buffer): boolean; + decode(buffer: Buffer): Buffer | number; + encode(pubKey: Buffer): Buffer; + }; + }; + + const pubKeyHash: { + input: { + check(script: Buffer): boolean; + decode(buffer: Buffer): { signature: ECSignature; pubKey: Buffer }; + decodeStack(stack: Buffer[]): { signature: ECSignature; pubKey: Buffer }; + encode(signature: ECSignature, pubKey: Buffer): Buffer; + encodeStack(signature: ECSignature, pubKey: Buffer): [ECSignature, Buffer]; + }; + + output: { + check(script: Buffer): boolean; + decode(buffer: Buffer): Buffer; + encode(pubKeyHash: Buffer): Buffer; + }; + }; + + const scriptHash: { + input: { + check(script: Buffer, allowIncomplete: boolean): boolean; + decode(buffer: Buffer): { redeemScriptStack: Buffer[]; redeemScript: Buffer }; + decodeStack(stack: Buffer[]): { redeemScriptStack: Buffer[]; redeemScript: Buffer }; + encode(redeemScriptSig: Array, redeemScript: Buffer): Buffer; + encodeStack(redeemScriptStack: Buffer[], redeemScript: Buffer): Buffer; + }; + + output: { + check(script: Buffer): boolean; + decode(buffer: Buffer): Buffer; + encode(scriptHash: Buffer): Buffer; + }; + }; + + const witnessCommitment: { + output: { + check(script: Buffer): boolean; + decode(buffer: Buffer): Buffer[]; + encode(commitment: Buffer): Buffer; + }; + }; + + const witnessPubKeyHash: { + input: { + check(script: Buffer): boolean; + decodeStack(stack: Buffer[]): { signature: ECSignature; pubKey: Buffer }; + encodeStack(signature: ECSignature, pubKey: Buffer): [ECSignature, Buffer]; + }; + + output: { + check(script: Buffer): boolean; + decode(buffer: Buffer): Buffer; + encode(pubKeyHash: Buffer): Buffer; + }; + }; + + const witnessScriptHash: { + input: { + check(script: Buffer, allowIncomplete: boolean): boolean; + decodeStack(stack: Buffer[]): { redeemScriptStack: Buffer[]; redeemScript: Buffer }; + encodeStack(redeemScriptStack: Buffer[], redeemScript: Buffer): Buffer; + }; + + output: { + check(script: Buffer): boolean; + decode(buffer: Buffer): Buffer; + encode(scriptHash: Buffer): Buffer; + }; + }; + + const nullData: { + output: { + check(script: Buffer): boolean; + decode(buffer: Buffer): Buffer; + encode(data: Buffer[]): Buffer; + }; + }; } diff --git a/types/bitcoinjs-lib/tsconfig.json b/types/bitcoinjs-lib/tsconfig.json index 7a9a4cf261..d1f5ec75b6 100644 --- a/types/bitcoinjs-lib/tsconfig.json +++ b/types/bitcoinjs-lib/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "bitcoinjs-lib-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/bl/index.d.ts b/types/bl/index.d.ts index 12bbf0bec5..5d34052b80 100644 --- a/types/bl/index.d.ts +++ b/types/bl/index.d.ts @@ -9,7 +9,7 @@ import stream = require('stream'); declare class BufferList extends stream.Duplex { - new(callback?: (err: Error, buffer: Buffer) => void): void; + constructor(callback?: (err: Error, buffer: Buffer) => void); append(buffer: Buffer): void; get(index: number): number; diff --git a/types/bleno/bleno-tests.ts b/types/bleno/bleno-tests.ts index 7dcb47ff35..bd4b6971ee 100644 --- a/types/bleno/bleno-tests.ts +++ b/types/bleno/bleno-tests.ts @@ -45,7 +45,7 @@ Bleno.on('stateChange', (state: string) => { } }); -let characteristic = new EchoCharacteristic(); +const characteristic = new EchoCharacteristic(); Bleno.on('advertisingStart', (error: string) => { if (!error) { Bleno.setServices( diff --git a/types/bleno/tslint.json b/types/bleno/tslint.json index 377cc837d4..26bcea6634 100644 --- a/types/bleno/tslint.json +++ b/types/bleno/tslint.json @@ -1 +1,6 @@ -{ "extends": "../tslint.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "dt-header": false + } +} diff --git a/types/blessed/index.d.ts b/types/blessed/index.d.ts index b08f77b3b1..abbc31d295 100644 --- a/types/blessed/index.d.ts +++ b/types/blessed/index.d.ts @@ -5,7 +5,7 @@ /// -import {EventEmitter} from 'events'; +import { EventEmitter } from 'events'; import * as stream from "stream"; import * as child_process from "child_process"; diff --git a/types/bloomfilter/bloomfilter-tests.ts b/types/bloomfilter/bloomfilter-tests.ts index 650cc97eb4..96ee0443b6 100644 --- a/types/bloomfilter/bloomfilter-tests.ts +++ b/types/bloomfilter/bloomfilter-tests.ts @@ -1,7 +1,7 @@ import { BloomFilter } from 'bloomfilter'; function test_bloomfilter() { - const m: number = 10; - const k: number = 2; + const m = 10; + const k = 2; const bloomFilter = new BloomFilter(m, k); const array: Int32Array[] = bloomFilter.buckets; diff --git a/types/body-parser/index.d.ts b/types/body-parser/index.d.ts index be10668973..2056c89b22 100644 --- a/types/body-parser/index.d.ts +++ b/types/body-parser/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for body-parser 1.16 // Project: https://github.com/expressjs/body-parser -// Definitions by: Santi Albo , Vilic Vane , Jonathan Häberle , Gevik Babakhani , Tomasz Łaziuk +// Definitions by: Santi Albo , Vilic Vane , Jonathan Häberle , Gevik Babakhani , Tomasz Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/bonjour/index.d.ts b/types/bonjour/index.d.ts index 0c2578121e..61b97e4ee8 100644 --- a/types/bonjour/index.d.ts +++ b/types/bonjour/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bonjour 3.5 // Project: https://github.com/watson/bonjour -// Definitions by: Quentin Lampin , Nicolas Voigt +// Definitions by: Quentin Lampin , Nicolas Voigt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/bookshelf/bookshelf-tests.ts b/types/bookshelf/bookshelf-tests.ts index f42a1bf784..77af31461b 100644 --- a/types/bookshelf/bookshelf-tests.ts +++ b/types/bookshelf/bookshelf-tests.ts @@ -182,10 +182,10 @@ exports.down = (knex: Knex) => { { class Site extends bookshelf.Model { - get tableName() { return 'sites'; } - photo(): Photo { - return this.morphOne(Photo, 'imageable'); - } + get tableName() { return 'sites'; } + photo(): Photo { + return this.morphOne(Photo, 'imageable'); + } } class Post extends bookshelf.Model { @@ -867,6 +867,10 @@ model.where('favorite_color', 'red').fetch().then(() => { model.where({favorite_color: 'red', shoe_size: 12}).fetch().then(() => { //... }); +// or +model.where('favorite_color', 'in', ['red', 'green']).fetch().then(() => { + // ... +}); /* Lodash methods, see http://bookshelfjs.org/#Model-subsection-lodash-methods */ @@ -1197,6 +1201,13 @@ ships.trigger('fetched'); /* collection.where(), see http://bookshelfjs.org/#Collection-instance-where */ +(new Author()) + .where('first_name', 'in', ['User', 'Resu']) + .fetchAll() + .then(() => { + // ... + }) + /* collection.withPivot(), see http://bookshelfjs.org/#Collection-instance-withPivot */ { diff --git a/types/bookshelf/index.d.ts b/types/bookshelf/index.d.ts index 55be61ba9e..bb817d3074 100644 --- a/types/bookshelf/index.d.ts +++ b/types/bookshelf/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bookshelfjs v0.9.3 // Project: http://bookshelfjs.org/ -// Definitions by: Andrew Schurman , Vesa Poikajärvi +// Definitions by: Andrew Schurman , Vesa Poikajärvi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -84,6 +84,10 @@ declare namespace Bookshelf { values(): any[]; } + interface ModelSubclass { + new(): Model; + } + class Model> extends ModelBase { static collection>(models?: T[], options?: CollectionOptions): Collection; static count(column?: string, options?: SyncOptions): BlueBird; @@ -93,10 +97,10 @@ declare namespace Bookshelf { /** @deprecated should use `new` objects instead. */ static forge(attributes?: any, options?: ModelOptions): T; static where(properties: { [key: string]: any }): T; - static where(key: string, operatorOrValue: string | number | boolean, valueIfOperator?: string | number | boolean): T; + static where(key: string, operatorOrValue: string | number | boolean, valueIfOperator?: string | string[] | number | number[] | boolean): T; belongsTo>(target: { new (...args: any[]): R }, foreignKey?: string, foreignKeyTarget?: string): R; - belongsToMany>(target: { new (...args: any[]): R }, table?: string, foreignKey?: string, otherKey?: string): Collection; + belongsToMany>(target: { new (...args: any[]): R }, table?: string, foreignKey?: string, otherKey?: string, foreignKeyTarget?: string, otherKeyTarget?: string): Collection; count(column?: string, options?: SyncOptions): BlueBird; destroy(options?: DestroyOptions): BlueBird; fetch(options?: FetchOptions): BlueBird; @@ -106,8 +110,8 @@ declare namespace Bookshelf { load(relations: string | string[], options?: LoadOptions): BlueBird; 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; + morphTo(name: string, columnNames?: string[], ...target: ModelSubclass[]): T; + morphTo(name: string, ...target: ModelSubclass[]): T; orderBy(column: string, order?: SortOrder): T; // Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[]) @@ -120,9 +124,9 @@ declare namespace Bookshelf { resetQuery(): T; save(key?: string, val?: any, options?: SaveOptions): BlueBird; save(attrs?: { [key: string]: any }, options?: SaveOptions): BlueBird; - through>(interim: typeof Model, throughForeignKey?: string, otherKey?: string): R; + through>(interim: ModelSubclass, throughForeignKey?: string, otherKey?: string): R; where(properties: { [key: string]: any }): T; - where(key: string, operatorOrValue: string | number | boolean, valueIfOperator?: string | number | boolean): T; + where(key: string, operatorOrValue: string | number | boolean, valueIfOperator?: string | string[] | number | number[] | boolean): T; // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/errors.js // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/model.js#L1280 @@ -255,7 +259,7 @@ declare namespace Bookshelf { query(query: { [key: string]: any }): Collection; resetQuery(): Collection; - through>(interim: typeof Model, throughForeignKey?: string, otherKey?: string): Collection; + through>(interim: ModelSubclass, throughForeignKey?: string, otherKey?: string): Collection; updatePivot(attributes: any, options?: PivotOptions): BlueBird; withPivot(columns: string[]): Collection; diff --git a/types/boom/boom-tests.ts b/types/boom/boom-tests.ts index 38dc39058f..1819be25cb 100644 --- a/types/boom/boom-tests.ts +++ b/types/boom/boom-tests.ts @@ -136,7 +136,8 @@ const gatewayTimeoutError = Boom.gatewayTimeout('message', {some: 'data'}); gatewayTimeoutError.data.some; const gatewayTimeoutError2: Boom.BoomError = Boom.gatewayTimeout('message'); -// wrap and create +// boomify, wrap, and create +const boomifiedError = Boom.boomify(new Error('test'), { statusCode: 400, message: 'some message' }) const wrappedError = Boom.wrap(new Error('test'), 400, 'some message'); diff --git a/types/boom/index.d.ts b/types/boom/index.d.ts index b8f41a85be..8025a7ddab 100644 --- a/types/boom/index.d.ts +++ b/types/boom/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for boom 4.3 -// Project: http://github.com/hapijs/boom -// Definitions by: Igor Rogatty , AJP +// Project: https://github.com/hapijs/boom +// Definitions by: Igor Rogatty +// AJP +// Jinesh Shah // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -53,6 +55,14 @@ declare namespace Boom { // Excluded this to aid typing of the other values. See tests for example casting to a custom interface to manipulate the payload // [anyContent: string]: any; } + + /** + * Decorates an error with the boom properties + * @param error the error object to wrap. If error is already a boom object, it defaults to overriding the object with the new status code and message. + * @param options optional additional options + * @see {@link https://github.com/hapijs/boom#boomifyerror-options} + */ + export function boomify(error: Error, options?: { statusCode?: number, message?: string, override?: boolean }): BoomError; /** * Decorates an error with the boom properties diff --git a/types/boom/v3/index.d.ts b/types/boom/v3/index.d.ts index 2c0a3ce21d..adf433c9f4 100644 --- a/types/boom/v3/index.d.ts +++ b/types/boom/v3/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for boom 3.2 -// Project: http://github.com/hapijs/boom -// Definitions by: Igor Rogatty +// Project: https://github.com/hapijs/boom +// Definitions by: Igor Rogatty // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/bootbox/index.d.ts b/types/bootbox/index.d.ts index 7007d80feb..ba5cc8c23b 100644 --- a/types/bootbox/index.d.ts +++ b/types/bootbox/index.d.ts @@ -1,6 +1,6 @@ // 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 , Stanny Nuytkens +// Definitions by: Vincent Bortone , Kon Pik , Anup Kattel , Dominik Schroeter , Troy McKinnon , Stanny Nuytkens // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/bootpag/index.d.ts b/types/bootpag/index.d.ts index 20fee59ff2..af47cc3219 100644 --- a/types/bootpag/index.d.ts +++ b/types/bootpag/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for jQuery-Bootpag 1.0.7 // Project: http://botmonster.com/jquery-bootpag/ -// Definitions by: MAF.DAP / Romain Deneau +// Definitions by: MAF.DAP / Romain Deneau // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/bootstrap-datepicker/index.d.ts b/types/bootstrap-datepicker/index.d.ts index 9287ee1ba3..02eda0fba8 100644 --- a/types/bootstrap-datepicker/index.d.ts +++ b/types/bootstrap-datepicker/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bootstrap-datepicker // Project: https://github.com/eternicode/bootstrap-datepicker -// Definitions by: Boris Yankov +// Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -36,6 +36,7 @@ interface DatepickerOptions { forceParse?: boolean; inputs?: any[]; minViewMode?: 0|"days"|1|"months"|2|"years"|3|"decades"|4|"centuries"|"millenium"; + maxViewMode?: 0|"days"|1|"months"|2|"years"|3|"decades"|4|"centuries"|"millenium"; multidate?: boolean|number; multidateSeparator?: string; orientation?: "auto"|"left top"|"left bottom"|"right top"|"right bottom"; diff --git a/types/bootstrap-notify/index.d.ts b/types/bootstrap-notify/index.d.ts index 441bb33c39..0517b62cf8 100644 --- a/types/bootstrap-notify/index.d.ts +++ b/types/bootstrap-notify/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bootstrap-notify v3.1.3 // Project: http://bootstrap-notify.remabledesigns.com/ -// Definitions by: Blake Niemyjski , Robert McIntosh , Robert Voica +// Definitions by: Blake Niemyjski , Robert McIntosh , Robert Voica // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/bootstrap-slider/bootstrap-slider-tests.ts b/types/bootstrap-slider/bootstrap-slider-tests.ts index 8b59a25a36..2073a3de9d 100644 --- a/types/bootstrap-slider/bootstrap-slider-tests.ts +++ b/types/bootstrap-slider/bootstrap-slider-tests.ts @@ -12,7 +12,7 @@ $(() => { $('#ex2').slider({}); const RGBChange = () => { - $('#RGB').css('background', 'rgb(' + r.getValue() + ',' + g.getValue() + ',' + b.getValue() + ')'); + $('#RGB').css('background', `rgb(${r.getValue()},${g.getValue()},${b.getValue()})`); }; const r = $('#R').slider() diff --git a/types/bootstrap-table/index.d.ts b/types/bootstrap-table/index.d.ts index e70ada9e38..8f29583e56 100644 --- a/types/bootstrap-table/index.d.ts +++ b/types/bootstrap-table/index.d.ts @@ -1,13 +1,14 @@ // Type definitions for Bootstrap Table v1.11.0 // Project: http://bootstrap-table.wenzhixin.net.cn/ -// Definitions by: Talat Baig +// Definitions by: Talat Baig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// interface JQuery { - bootstrapTable(options?: any): JQuery; + bootstrapTable(options?: any): JQuery; + bootstrapTable(method: string, parameter?: any): JQuery; } declare var bootstrapTable: JQueryStatic; diff --git a/types/bootstrap-treeview/bootstrap-treeview-tests.ts b/types/bootstrap-treeview/bootstrap-treeview-tests.ts new file mode 100644 index 0000000000..421df3b9dc --- /dev/null +++ b/types/bootstrap-treeview/bootstrap-treeview-tests.ts @@ -0,0 +1,105 @@ +// A example tree structure + +let data: BootstrapTreeViewNodeData[] = [ + { + text: "Parent 1", + nodes: [ + { + text: "Child 1", + nodes: [ + { + text: "Grandchild 1" + }, + { + text: "Node 1", + icon: "glyphicon glyphicon-stop", + selectedIcon: "glyphicon glyphicon-stop", + color: "#000000", + backColor: "#FFFFFF", + href: "#node-1", + selectable: true, + state: { + checked: true, + disabled: true, + expanded: true, + selected: true + }, + tags: ['available'] + } + ] + }, + { + text: "Child 2" + } + ] + }, + { + text: "Parent 2" + }, + { + text: "Parent 3" + }, + { + text: "Parent 4" + }, + { + text: "Parent 5" + } +]; + +// Example for treeview init with options + +$('#tree').treeview({ + data, + levels: 5, + backColor: 'green' +}); + +// Treeview functions. + +let nodeId = 5; + +let node: BootstrapTreeViewNodeData = data[0]; + +$('#tree').treeview('checkAll', { silent: true }); +$('#tree').treeview('checkNode', [ nodeId, { silent: true } ]); +$('#tree').treeview('clearSearch'); +$('#tree').treeview('collapseAll', { silent: true }); +$('#tree').treeview('collapseNode', [ nodeId, { silent: true, ignoreChildren: false } ]); +$('#tree').treeview('disableAll', { silent: true }); +$('#tree').treeview('disableNode', [ nodeId, { silent: true } ]); +$('#tree').treeview('enableAll', { silent: true }); +$('#tree').treeview('enableNode', [ nodeId, { silent: true } ]); +$('#tree').treeview('expandAll', { levels: 2, silent: true }); +$('#tree').treeview('expandNode', [ nodeId, { levels: 2, silent: true } ]); +$('#tree').treeview('getCollapsed', nodeId); +$('#tree').treeview('getDisabled', nodeId); +$('#tree').treeview('getEnabled', nodeId); +$('#tree').treeview('getExpanded', nodeId); +$('#tree').treeview('getExpanded', nodeId); +$('#tree').treeview('getParent', node); +$('#tree').treeview('getSelected', nodeId); +$('#tree').treeview('getSiblings', node); +$('#tree').treeview('getUnselected', nodeId); +$('#tree').treeview('remove'); +$('#tree').treeview('revealNode', [ nodeId, { silent: true } ]); +$('#tree').treeview('search', [ 'Parent', { + ignoreCase: true, // case insensitive + exactMatch: false, // like or equals + revealResults: true, // reveal matching nodes +}]); +$('#tree').treeview('selectNode', [ nodeId, { silent: true } ]); +$('#tree').treeview('toggleNodeChecked', [ nodeId, { silent: true } ]); +$('#tree').treeview('toggleNodeDisabled', [ nodeId, { silent: true } ]); +$('#tree').treeview('toggleNodeExpanded', [ nodeId, { silent: true } ]); +$('#tree').treeview('toggleNodeSelected', [ nodeId, { silent: true } ]); +$('#tree').treeview('uncheckAll', { silent: true }); +$('#tree').treeview('uncheckNode', [ nodeId, { silent: true } ]); +$('#tree').treeview('unselectNode', [ nodeId, { silent: true } ]); + +// Test events +$('#tree').treeview({ + onNodeSelected: (event: any, data: BootstrapTreeViewNodeData) => void { + // Event handler + } +}); diff --git a/types/bootstrap-treeview/index.d.ts b/types/bootstrap-treeview/index.d.ts new file mode 100644 index 0000000000..fa771a6043 --- /dev/null +++ b/types/bootstrap-treeview/index.d.ts @@ -0,0 +1,70 @@ +// Type definitions for bootstrap-treeview.js 1.20 +// Project: https://github.com/jonmiles/bootstrap-treeview +// Definitions by: Jan Böhmer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +interface BootstrapTreeViewNodeData { + text?: string; + icon?: string; + selectedIcon?: string; + color?: string; + backColor?: string; + href?: string; + selectable?: boolean; + nodeId?: number; + state?: { + checked: boolean; + disabled: boolean; + expanded: boolean; + selected: boolean; + }; + tags?: string[]; + nodes?: BootstrapTreeViewNodeData[]; +} + +interface BootstrapTreeViewOptions { + data?: BootstrapTreeViewNodeData[]; + backColor?: string; + borderColor?: string; + checkedIcon?: string; + collapseIcon?: string; + color?: string; + emptyIcon?: string; + enableLinks?: boolean; + expandIcon?: string; + highlightSearchResults?: boolean; + highlightSelected?: boolean; + levels?: number; + multiSelect?: boolean; + nodeIcon?: string; + onhoverColor?: string; + selectedIcon?: string; + searchResultBackColor?: string; + searchResultColor?: string; + selectedBackColor?: string; + selectedColor?: string; + showBorder?: boolean; + showCheckbox?: boolean; + showIcon?: boolean; + showTags?: boolean; + uncheckedIcon?: boolean; + + onNodeSelected?(event: any, node: BootstrapTreeViewNodeData): void; + onNodeChecked?(event: any, node: BootstrapTreeViewNodeData): void; + onNodeCollapsed?(event: any, node: BootstrapTreeViewNodeData): void; + onNodeDisabled?(event: any, node: BootstrapTreeViewNodeData): void; + onNodeEnabled?(event: any, node: BootstrapTreeViewNodeData): void; + onNodeExpanded?(event: any, node: BootstrapTreeViewNodeData): void; + onNodeUnchecked?(event: any, node: BootstrapTreeViewNodeData): void; + onNodeUnselected?(event: any, node: BootstrapTreeViewNodeData): void; + onSearchComplete?(event: any, node: BootstrapTreeViewNodeData): void; + onSearchCleared?(event: any, node: BootstrapTreeViewNodeData): void; +} + +interface JQuery { + treeview(options: BootstrapTreeViewOptions): JQuery; + treeview(method: string, ...args: any[]): JQuery; +} diff --git a/types/bootstrap-treeview/tsconfig.json b/types/bootstrap-treeview/tsconfig.json new file mode 100644 index 0000000000..0dce7ab41a --- /dev/null +++ b/types/bootstrap-treeview/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bootstrap-treeview-tests.ts" + ] +} diff --git a/types/bootstrap-treeview/tslint.json b/types/bootstrap-treeview/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bootstrap-treeview/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bootstrap-validator/index.d.ts b/types/bootstrap-validator/index.d.ts index e9f2073d70..9a0c700fc4 100644 --- a/types/bootstrap-validator/index.d.ts +++ b/types/bootstrap-validator/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bootstrap-validator 0.11 // Project: https://github.com/1000hz/bootstrap-validator -// Definitions by: Brady Liles +// Definitions by: Brady Liles // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/bootstrap.paginator/index.d.ts b/types/bootstrap.paginator/index.d.ts index b79e7bca0a..55ee536378 100644 --- a/types/bootstrap.paginator/index.d.ts +++ b/types/bootstrap.paginator/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bootstrap.paginator // Project: https://github.com/lyonlai/bootstrap-paginator -// Definitions by: derikwhittaker +// Definitions by: derikwhittaker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/bootstrap.timepicker/index.d.ts b/types/bootstrap.timepicker/index.d.ts index f0cc7f472b..384d550e57 100644 --- a/types/bootstrap.timepicker/index.d.ts +++ b/types/bootstrap.timepicker/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bootstrap.timepicker // Project: https://github.com/jdewit/bootstrap-timepicker -// Definitions by: derikwhittaker +// Definitions by: derikwhittaker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts b/types/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts index 9f2b780f44..fe985e229f 100644 --- a/types/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts +++ b/types/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker-tests.ts @@ -118,7 +118,7 @@ function test_timeZone() { function test_widgetParent() { let nullW: null = null; - let str: string = "myId"; + let str = "myId"; let jquery = $("#element"); $("#picker").datetimepicker({ diff --git a/types/bootstrap.v3.datetimepicker/index.d.ts b/types/bootstrap.v3.datetimepicker/index.d.ts index 0dee893fc5..7b1d3877ba 100644 --- a/types/bootstrap.v3.datetimepicker/index.d.ts +++ b/types/bootstrap.v3.datetimepicker/index.d.ts @@ -328,6 +328,18 @@ export interface Datetimepicker { * Usually you should not override those options unless you have a special need in your layout. */ widgetPositioning(value: WidgetPositioningOptions): void; + + /** + * JQuery plugin function. + * @param {DatetimepickerOptions} options + */ + (options?: DatetimepickerOptions): JQuery; + + /** + * Default options that will be used for all instances. + * To change: `$.fn.datetimepicker.defaults` + */ + defaults: DatetimepickerOptions; } export interface DatetimepickerOptions { @@ -577,11 +589,11 @@ export interface UpdateEvent extends JQueryEventObject { viewDate: moment.Moment; } -export type EventName = "dp.show" | "dp.hide" | "dp.error"; +export type EventName = "dp.show" | "dp.hide" | "dp.error"; declare global { interface JQuery { - datetimepicker(options?: DatetimepickerOptions): JQuery; + datetimepicker: Datetimepicker; data(key: "DateTimePicker"): Datetimepicker; diff --git a/types/bootstrap/index.d.ts b/types/bootstrap/index.d.ts index 53d9b45b37..9fa10bcdbb 100644 --- a/types/bootstrap/index.d.ts +++ b/types/bootstrap/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Bootstrap 3.3.5 // Project: http://twitter.github.com/bootstrap/ -// Definitions by: Boris Yankov +// Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -119,6 +119,7 @@ interface JQuery { typeahead(options?: TypeaheadOptions): JQuery; affix(options?: AffixOptions): JQuery; + affix(command: string): JQuery; emulateTransitionEnd(duration: number): JQuery; } diff --git a/types/bounce.js/index.d.ts b/types/bounce.js/index.d.ts index 0db872fb30..c90f709a97 100644 --- a/types/bounce.js/index.d.ts +++ b/types/bounce.js/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Bounce.js v0.8.2 -// Project: http://github.com/tictail/bounce.js -// Definitions by: Cherry +// Project: https://github.com/tictail/bounce.js +// Definitions by: Cherry // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/box2d/README.md b/types/box2d/README.md index 9a775a1962..e16b327ee1 100644 --- a/types/box2d/README.md +++ b/types/box2d/README.md @@ -73,7 +73,7 @@ Change Log License ======= -Box2DWeb-2.1.d.ts Copyright (c) 2012 Josh Baldwin http://github.com/jbaldwin/box2dweb.d.ts +Box2DWeb-2.1.d.ts Copyright (c) 2012 Josh Baldwin https://github.com/jbaldwin/box2dweb.d.ts There are a few competing javascript Box2D ports. This definitions file is for Box2dWeb.js -> http://code.google.com/p/box2dweb/ diff --git a/types/box2d/index.d.ts b/types/box2d/index.d.ts index 26411b2198..77a132592e 100644 --- a/types/box2d/index.d.ts +++ b/types/box2d/index.d.ts @@ -1,10 +1,10 @@ // Type definitions for bootstrap.timepicker // Project: http://code.google.com/p/box2dweb/ -// Definitions by: jbaldwin +// Definitions by: jbaldwin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** -* Box2DWeb-2.1.d.ts Copyright (c) 2012-2013 Josh Baldwin http://github.com/jbaldwin/box2dweb.d.ts +* Box2DWeb-2.1.d.ts Copyright (c) 2012-2013 Josh Baldwin https://github.com/jbaldwin/box2dweb.d.ts * There are a few competing javascript Box2D ports. * This definitions file is for Box2dWeb.js -> * http://code.google.com/p/box2dweb/ diff --git a/types/brace-expansion/brace-expansion-tests.ts b/types/brace-expansion/brace-expansion-tests.ts new file mode 100644 index 0000000000..a9b0955cd7 --- /dev/null +++ b/types/brace-expansion/brace-expansion-tests.ts @@ -0,0 +1,13 @@ +import expand = require('brace-expansion'); + +// $ExpectType string[] +expand('file-{a,b,c}.jpg'); +expand('-v{,,}'); +expand('file{0..2}.jpg'); +expand('file-{a..c}.jpg'); +expand('file{2..0}.jpg'); +expand('file{0..4..2}.jpg'); +expand('file-{a..e..2}.jpg'); +expand('file{00..10..5}.jpg'); +expand('{{A..C},{a..c}}'); +expand('ppp{,config,oe{,conf}}'); diff --git a/types/brace-expansion/index.d.ts b/types/brace-expansion/index.d.ts new file mode 100644 index 0000000000..0c1894fd8c --- /dev/null +++ b/types/brace-expansion/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for brace-expansion 1.1 +// Project: https://github.com/juliangruber/brace-expansion +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = expand; + +declare function expand(input: string): string[]; diff --git a/types/brace-expansion/tsconfig.json b/types/brace-expansion/tsconfig.json new file mode 100644 index 0000000000..ef79d3729f --- /dev/null +++ b/types/brace-expansion/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "brace-expansion-tests.ts" + ] +} diff --git a/types/brace-expansion/tslint.json b/types/brace-expansion/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/brace-expansion/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/breeze/index.d.ts b/types/breeze/index.d.ts index bfd3479d3c..3094f3452d 100644 --- a/types/breeze/index.d.ts +++ b/types/breeze/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Breeze 1.6.3 // Project: http://www.breezejs.com/ -// Definitions by: Boris Yankov , IdeaBlade +// Definitions by: Boris Yankov , IdeaBlade // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Updated Jan 14 2011 - Jay Traband ( www.ideablade.com). diff --git a/types/browser-bunyan/browser-bunyan-tests.ts b/types/browser-bunyan/browser-bunyan-tests.ts index 47f439a07e..6cf1bf926b 100644 --- a/types/browser-bunyan/browser-bunyan-tests.ts +++ b/types/browser-bunyan/browser-bunyan-tests.ts @@ -1,8 +1,25 @@ import * as bunyan from "browser-bunyan"; const log = bunyan.createLogger({ - name: 'play', - serializers: bunyan.stdSerializers + name: 'myLogger', + streams: [ + { + level: 'info', + stream: new bunyan.ConsoleFormattedStream() + } + ], + serializers: bunyan.stdSerializers, + src: true }); -log.debug({foo: 'bar'}, 'hi at debug'); -log.trace('hi at trace'); + +log.info('hi on info'); + +const log2 = bunyan.createLogger({ + name: 'myLogger', + stream: new bunyan.ConsoleRawStream() +}); + +const myObject = { x: 1, y: 2 }; +log.info({ obj: myObject }, 'This is my object:'); + +new bunyan.ConsoleFormattedStream({ logByLevel: true }); diff --git a/types/browser-bunyan/index.d.ts b/types/browser-bunyan/index.d.ts index bb243e4324..7edabdca26 100644 --- a/types/browser-bunyan/index.d.ts +++ b/types/browser-bunyan/index.d.ts @@ -1,12 +1,31 @@ // Type definitions for browser-bunyan 0.4 // Project: https://github.com/philmander/browser-bunyan // Definitions by: Paul Lockwood +// Michael Strobel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import bunyan = require("bunyan"); +/// -declare module "bunyan" { - function ConsoleFormattedStream(): void; +import * as bunyan from 'bunyan'; + +declare namespace BrowserBunyan { + interface ConsoleFormattedStreamOptions { + logByLevel?: boolean; + } + + interface ConsoleFormattedStream { + new(options?: ConsoleFormattedStreamOptions): NodeJS.WritableStream; + } + + interface ConsoleRawStream { + new(options?: ConsoleFormattedStreamOptions): NodeJS.WritableStream; + } } -export = bunyan; +type BrowserBunyan = typeof bunyan & { + ConsoleFormattedStream: BrowserBunyan.ConsoleFormattedStream + ConsoleRawStream: BrowserBunyan.ConsoleRawStream +}; + +declare const browserBunyan: BrowserBunyan; +export = browserBunyan; diff --git a/types/browser-resolve/index.d.ts b/types/browser-resolve/index.d.ts index 30f3875541..22b45dd8d2 100644 --- a/types/browser-resolve/index.d.ts +++ b/types/browser-resolve/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for browser-resolve // Project: https://github.com/defunctzombie/node-browser-resolve -// Definitions by: Mario Nebl +// Definitions by: Mario Nebl // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/browser-sync/index.d.ts b/types/browser-sync/index.d.ts index 449063192d..ade12d3cb6 100644 --- a/types/browser-sync/index.d.ts +++ b/types/browser-sync/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for browser-sync // Project: http://www.browsersync.io/ -// Definitions by: Asana , Joe Skeen +// Definitions by: Asana , Joe Skeen // Thomas "Thasmo" Deinhamer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/browserify/index.d.ts b/types/browserify/index.d.ts index 8b51a34dd5..e419fa2ceb 100644 --- a/types/browserify/index.d.ts +++ b/types/browserify/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Browserify 12.0 // Project: http://browserify.org/ -// Definitions by: Andrew Gaspar , John Vilk , Leonard Thieu +// Definitions by: Andrew Gaspar , John Vilk , Leonard Thieu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/bson/index.d.ts b/types/bson/index.d.ts index 67df319bf6..2b6a636e89 100644 --- a/types/bson/index.d.ts +++ b/types/bson/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bson 1.0.4 // Project: https://github.com/mongodb/js-bson -// Definitions by: Hiroki Horiuchi +// Definitions by: Hiroki Horiuchi // Federico Caselli // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/buffers/index.d.ts b/types/buffers/index.d.ts index ec8be5a493..3f83813146 100644 --- a/types/buffers/index.d.ts +++ b/types/buffers/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for buffers 0.1.1 // Project: https://github.com/substack/node-buffers -// Definitions by: Robert Hencke +// Definitions by: Robert Hencke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/bunyan-config/index.d.ts b/types/bunyan-config/index.d.ts index 0ff84fd9d2..ebcddcd50d 100644 --- a/types/bunyan-config/index.d.ts +++ b/types/bunyan-config/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/LSEducation/bunyan-config // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/types/bunyan-logentries/index.d.ts b/types/bunyan-logentries/index.d.ts index 9a2a5c3fb9..33057d768b 100644 --- a/types/bunyan-logentries/index.d.ts +++ b/types/bunyan-logentries/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/nemtsov/node-bunyan-logentries // Definitions by: Aymeric Beaumet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/types/bunyan-prettystream/index.d.ts b/types/bunyan-prettystream/index.d.ts index c82d444f76..f4c5efb948 100644 --- a/types/bunyan-prettystream/index.d.ts +++ b/types/bunyan-prettystream/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bunyan-prettystream 0.1.3 // Project: https://www.npmjs.com/package/bunyan-prettystream -// Definitions by: Jason Swearingen , Vadim Macagon +// Definitions by: Jason Swearingen , Vadim Macagon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/bunyan/bunyan-tests.ts b/types/bunyan/bunyan-tests.ts index 657a59c3a8..3c093c0270 100644 --- a/types/bunyan/bunyan-tests.ts +++ b/types/bunyan/bunyan-tests.ts @@ -1,13 +1,10 @@ import Logger = require('bunyan'); -let ringBufferOptions: Logger.RingBufferOptions = { +const ringBufferOptions: Logger.RingBufferOptions = { limit: 100 }; -let ringBuffer: Logger.RingBuffer = new Logger.RingBuffer(ringBufferOptions); +const ringBuffer: Logger.RingBuffer = new Logger.RingBuffer(ringBufferOptions); ringBuffer.write("hello"); -ringBuffer.end(); -ringBuffer.destroy(); -ringBuffer.destroySoon(); let level: number; level = Logger.resolveLevel("trace"); @@ -23,13 +20,14 @@ level = Logger.resolveLevel(Logger.WARN); level = Logger.resolveLevel(Logger.ERROR); level = Logger.resolveLevel(Logger.FATAL); -let options: Logger.LoggerOptions = { +const options: Logger.LoggerOptions = { name: 'test-logger', serializers: Logger.stdSerializers, streams: [{ type: 'stream', stream: process.stdout, - level: Logger.TRACE + level: Logger.TRACE, + name: 'foo' }, { type: 'file', path: '/tmp/test.log', @@ -45,7 +43,7 @@ let options: Logger.LoggerOptions = { }, { type: 'raw', stream: process.stderr, - level: Logger.WARN + level: Logger.FATAL + 1, // disabled, as stderr explodes when given raw streams }, { type: 'raw', stream: ringBuffer, @@ -53,9 +51,9 @@ let options: Logger.LoggerOptions = { }] }; -let log = Logger.createLogger(options); +const log = Logger.createLogger(options); -let customSerializer = (anything: any) => { +const customSerializer = (anything: any) => { return { obj: anything }; }; @@ -69,19 +67,17 @@ log.addSerializers( } ); -let child = log.child({ name: 'child' }); -child.reopenFileStreams(); -log.addStream({ path: '/dev/null' }); -child.level(Logger.DEBUG); -child.level('debug'); -child.levels(0, Logger.ERROR); -child.levels(0, 'error'); -child.levels('stream1', Logger.FATAL); -child.levels('stream1', 'fatal'); +const levels: number[] = log.levels(); +level = log.levels(0); +log.levels('foo'); -let buffer = new Buffer(0); -let error = new Error(''); -let object = { +log.levels(0, Logger.INFO); +log.levels(0, 'info'); +log.levels('foo', Logger.WARN); + +const buffer = new Buffer(0); +const error = new Error(''); +const object = { test: 123 }; @@ -116,7 +112,7 @@ log.fatal(error); log.fatal(object); log.fatal('Hello, %s', 'world!'); -let recursive: any = { +const recursive: any = { hello: 'world', whats: {} }; @@ -129,3 +125,22 @@ class MyLogger extends Logger { super(options); } } + +const child = log.child({ widget_type: 'wuzzle' }); +child.reopenFileStreams(); +log.addStream({ path: '/dev/null' }); +child.level(Logger.DEBUG); +child.level('debug'); +child.levels(0, Logger.ERROR); +child.levels(0, 'error'); +child.levels('foo', Logger.FATAL); +child.levels('foo', 'fatal'); + +ringBuffer.end(); +ringBuffer.destroy(); +ringBuffer.destroySoon(); + +const logLevelString: Logger.LogLevelString = 'warn'; +const nameLevel: number = Logger.levelFromName[logLevelString]; +const nameLevel2: number = Logger.levelFromName['warn']; +const levelName: string = Logger.nameFromLevel[10]; diff --git a/types/bunyan/index.d.ts b/types/bunyan/index.d.ts index bc1dca298d..055c64deb8 100644 --- a/types/bunyan/index.d.ts +++ b/types/bunyan/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/trentm/node-bunyan // Definitions by: Alex Mikhalev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// @@ -210,7 +211,11 @@ declare namespace Logger { const ERROR: number; const FATAL: number; - type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | number; + type LogLevelString = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'; + type LogLevel = LogLevelString | number; + + const levelFromName: { [name in LogLevelString]: number }; + const nameFromLevel: { [level: number]: string }; const stdSerializers: StdSerializers; @@ -228,6 +233,7 @@ declare namespace Logger { closeOnExit?: boolean; period?: string; count?: number; + name?: string; } interface LoggerOptions { diff --git a/types/bwip-js/index.d.ts b/types/bwip-js/index.d.ts index 9c37fa6e44..401cc9dbc8 100644 --- a/types/bwip-js/index.d.ts +++ b/types/bwip-js/index.d.ts @@ -1,11 +1,11 @@ // Type definitions for bwip-js 1.1.1 // Project: https://github.com/metafloor/bwip-js -// Definitions by: TANAKA Koichi +// Definitions by: TANAKA Koichi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -import {IncomingMessage as Request, ServerResponse as Response} from 'http'; +import { IncomingMessage as Request, ServerResponse as Response } from 'http'; declare namespace BwipJs { export function loadFont(fontName:string, sizeMulti: number, fontFile: string): void; diff --git a/types/bytebuffer/index.d.ts b/types/bytebuffer/index.d.ts index 1cf7142592..8456f28182 100644 --- a/types/bytebuffer/index.d.ts +++ b/types/bytebuffer/index.d.ts @@ -1,8 +1,8 @@ // Type definitions for bytebuffer.js 5.0.0 // Project: https://github.com/dcodeIO/bytebuffer.js -// Definitions by: Denis Cappellin +// Definitions by: Denis Cappellin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Definitions by: SINTEF-9012 +// Definitions by: SINTEF-9012 import Long = require("long"); diff --git a/types/bytes/index.d.ts b/types/bytes/index.d.ts index ae9e8f2d87..0f438052e3 100644 --- a/types/bytes/index.d.ts +++ b/types/bytes/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for bytes v2.5.0 // Project: https://github.com/visionmedia/bytes.js -// Definitions by: Zhiyuan Wang +// Definitions by: Zhiyuan Wang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface BytesOptions { diff --git a/types/c3/c3-tests.ts b/types/c3/c3-tests.ts index 029946c710..509678636b 100644 --- a/types/c3/c3-tests.ts +++ b/types/c3/c3-tests.ts @@ -3,7 +3,7 @@ ////////////////// function chart_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, bindto: "#myContainer", size: { @@ -30,19 +30,19 @@ function chart_examples() { onresized: () => { /* code*/ } }); - let chart2 = c3.generate({ + const chart2 = c3.generate({ bindto: document.getElementById("myContainer"), data: {} }); - let chart3 = c3.generate({ + const chart3 = c3.generate({ bindto: d3.select("#myContainer"), data: {} }); } function data_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: { url: "/data/c3_test.csv", json: [ @@ -126,7 +126,7 @@ function data_examples() { } }); - let chart2 = c3.generate({ + const chart2 = c3.generate({ data: { labels: { format: (v, id, i, j) => { /* code */ } }, hide: ["data1"] @@ -135,7 +135,7 @@ function data_examples() { } function axis_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, axis: { rotated: true, @@ -207,7 +207,7 @@ function axis_examples() { } }); - let chart2 = c3.generate({ + const chart2 = c3.generate({ data: {}, axis: { x: { @@ -241,7 +241,7 @@ function axis_examples() { } function grid_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, grid: { x: { @@ -265,7 +265,7 @@ function grid_examples() { } function region_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, regions: [ { axis: "x", start: 1, end: 4, class: "region-1-4" }, @@ -274,7 +274,7 @@ function region_examples() { } function legend_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, legend: { show: true, @@ -294,7 +294,7 @@ function legend_examples() { } }); - let chart2 = c3.generate({ + const chart2 = c3.generate({ data: {}, legend: { hide: "data1", @@ -307,7 +307,7 @@ function legend_examples() { } }); - let chart3 = c3.generate({ + const chart3 = c3.generate({ data: {}, legend: { hide: ["data1", "data2"] @@ -316,7 +316,7 @@ function legend_examples() { } function subchart_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, subchart: { show: true, @@ -329,7 +329,7 @@ function subchart_examples() { } function zoom_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, zoom: { enabled: false, @@ -343,7 +343,7 @@ function zoom_examples() { } function point_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, point: { show: false, @@ -362,7 +362,7 @@ function point_examples() { } function line_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, line: { connectNull: true, @@ -374,7 +374,7 @@ function line_examples() { } function area_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, area: { zerobased: false @@ -383,7 +383,7 @@ function area_examples() { } function bar_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, bar: { width: 10, @@ -391,7 +391,7 @@ function bar_examples() { } }); - let chart2 = c3.generate({ + const chart2 = c3.generate({ data: {}, bar: { width: { @@ -403,7 +403,7 @@ function bar_examples() { } function pie_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, pie: { label: { @@ -419,7 +419,7 @@ function pie_examples() { } function donut_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, donut: { label: { @@ -437,7 +437,7 @@ function donut_examples() { } function gauge_examples() { - let chart = c3.generate({ + const chart = c3.generate({ data: {}, gauge: { label: { @@ -460,7 +460,7 @@ function gauge_examples() { ///////////////// function simple_multiple() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -481,7 +481,7 @@ function simple_multiple() { } function timeseries() { - let chart = c3.generate({ + const chart = c3.generate({ data: { x: "x", xFormat: "%Y%m%d", // 'xFormat' can be used as custom format of 'x' @@ -503,7 +503,7 @@ function timeseries() { } function chart_spline() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -515,7 +515,7 @@ function chart_spline() { } function simple_xy() { - let chart = c3.generate({ + const chart = c3.generate({ data: { x: "x", columns: [ @@ -528,7 +528,7 @@ function simple_xy() { } function simple_xy_multiple() { - let chart = c3.generate({ + const chart = c3.generate({ data: { xs: { data1: "x1", @@ -545,7 +545,7 @@ function simple_xy_multiple() { } function simple_regions() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -560,7 +560,7 @@ function simple_regions() { } function chart_step() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 300, 350, 300, 0, 0, 100], @@ -575,7 +575,7 @@ function chart_step() { } function area_chart() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 300, 350, 300, 0, 0, 0], @@ -590,7 +590,7 @@ function area_chart() { } function chart_area_stacked() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 300, 350, 300, 0, 0, 120], @@ -607,7 +607,7 @@ function chart_area_stacked() { } function chart_bar() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -627,7 +627,7 @@ function chart_bar() { } function chart_bar_stacked() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", -30, 200, 200, 400, -150, 250], @@ -648,7 +648,7 @@ function chart_bar_stacked() { } function chart_scatter() { - let chart = c3.generate({ + const chart = c3.generate({ data: { xs: { setosa: "setosa_x", @@ -682,7 +682,7 @@ function chart_scatter() { } function chart_pie() { - let chart = c3.generate({ + const chart = c3.generate({ data: { // iris data from R columns: [ @@ -698,7 +698,7 @@ function chart_pie() { } function chart_donut() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30], @@ -716,7 +716,7 @@ function chart_donut() { } function gauge_chart() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data", 91.4] @@ -753,7 +753,7 @@ function gauge_chart() { } function chart_combination() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 20, 50, 40, 60, 50], @@ -781,7 +781,7 @@ function chart_combination() { //////////////////// function categorized() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250, 50, 100, 250] @@ -797,7 +797,7 @@ function categorized() { } function axes_rotated() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -814,7 +814,7 @@ function axes_rotated() { } function axes_y2() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -834,7 +834,7 @@ function axes_y2() { } function axes_x_tick_format() { - let chart = c3.generate({ + const chart = c3.generate({ data: { x: "x", columns: [ @@ -855,7 +855,7 @@ function axes_x_tick_format() { } function axes_x_tick_count() { - let chart = c3.generate({ + const chart = c3.generate({ data: { x: "x", columns: [ @@ -876,7 +876,7 @@ function axes_x_tick_count() { } function axes_x_tick_values() { - let chart = c3.generate({ + const chart = c3.generate({ data: { x: "x", columns: [ @@ -897,7 +897,7 @@ function axes_x_tick_values() { } function axes_x_tick_culling() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["sample", 30, 200, 100, 400, 150, 250, 30, 200, 100, 400, 150, 250, 30, 200, 100, 400, 150, 250, 200, 100, 400, 150, 250] @@ -919,7 +919,7 @@ function axes_x_tick_culling() { } function axes_x_tick_fit() { - let chart = c3.generate({ + const chart = c3.generate({ data: { x: "x", columns: [ @@ -940,7 +940,7 @@ function axes_x_tick_fit() { } function axes_x_localtime() { - let chart = c3.generate({ + const chart = c3.generate({ data: { x: "x", xFormat: "%Y", @@ -966,7 +966,7 @@ function axes_x_localtime() { } function axes_x_tick_rotate() { - let chart = c3.generate({ + const chart = c3.generate({ data: { x: "x", columns: [ @@ -990,7 +990,7 @@ function axes_x_tick_rotate() { } function axes_y_tick_format() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["sample", 30, 200, 100, 400, 150, 2500] @@ -1008,7 +1008,7 @@ function axes_y_tick_format() { } function axes_y_padding() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -1032,7 +1032,7 @@ function axes_y_padding() { } function axes_y_range() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["sample", 30, 200, 100, 400, 150, 250] @@ -1050,7 +1050,7 @@ function axes_y_range() { } function axes_label() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["sample", 30, 200, 100, 400, 150, 250], @@ -1076,7 +1076,7 @@ function axes_label() { } function axes_label_position() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["sample1", 30, 200, 100, 400, 150, 250], @@ -1134,7 +1134,7 @@ function axes_label_position() { /////////////////// function data_columned() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 20, 50, 40, 60, 50], @@ -1146,7 +1146,7 @@ function data_columned() { } function data_rowed() { - let chart = c3.generate({ + const chart = c3.generate({ data: { rows: [ ["data1", "data2", "data3"], @@ -1210,7 +1210,7 @@ function data_json() { } function data_url() { - let chart = c3.generate({ + const chart = c3.generate({ data: { url: "/data/c3_test.csv" } @@ -1227,7 +1227,7 @@ function data_url() { } function data_stringx() { - let chart = c3.generate({ + const chart = c3.generate({ data: { x: "x", columns: [ @@ -1294,7 +1294,7 @@ function data_stringx() { } function data_load() { - let chart = c3.generate({ + const chart = c3.generate({ data: { url: "/data/c3_test.csv", type: "line" @@ -1397,7 +1397,7 @@ function data_load() { } function data_name() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -1412,7 +1412,7 @@ function data_name() { } function data_color() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 20, 50, 40, 60, 50], @@ -1434,7 +1434,7 @@ function data_color() { } function data_order() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 130, 200, 320, 400, 530, 750], @@ -1478,7 +1478,7 @@ function data_order() { } function data_label() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, -200, -100, 400, 150, 250], @@ -1500,7 +1500,7 @@ function data_label() { } function data_label_format() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, -200, -100, 400, 150, 250], @@ -1532,7 +1532,7 @@ function data_label_format() { /////////////////// function options_gridline() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["sample", 30, 200, 100, 400, 150, 250, 120, 200] @@ -1550,7 +1550,7 @@ function options_gridline() { } function grid_x_lines() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["sample", 30, 200, 100, 400, 150, 250] @@ -1569,7 +1569,7 @@ function grid_x_lines() { } function grid_y_lines() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["sample", 30, 200, 100, 400, 150, 250], @@ -1601,7 +1601,7 @@ function grid_y_lines() { /////////////////// function region() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250, 400], @@ -1631,7 +1631,7 @@ function region() { } function region_timeseries() { - let chart = c3.generate({ + const chart = c3.generate({ data: { x: "date", columns: [ @@ -1657,7 +1657,7 @@ function region_timeseries() { ///////////////////// function options_subchart() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["sample", 30, 200, 100, 400, 150, 250] @@ -1670,7 +1670,7 @@ function options_subchart() { } function interaction_zoom() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["sample", 30, 200, 100, 400, 150, 250, 150, 200, 170, 240, 350, 150, 100, 400, 150, 250, 150, 200, 170, 240, 100, 150, 250, 150, 200, 170, 240, 30, 200, 100, 400, 150, 250, 150, @@ -1688,7 +1688,7 @@ function interaction_zoom() { ///////////////////// function options_legend() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["sample", 30, 200, 100, 400, 150, 250] @@ -1701,7 +1701,7 @@ function options_legend() { } function legend_position() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -1737,7 +1737,7 @@ function legend_position() { } function legend_custom() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 100], @@ -1781,7 +1781,7 @@ function legend_custom() { ///////////////////// function tooltip_show() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -1795,7 +1795,7 @@ function tooltip_show() { } function tooltip_grouped() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -1810,7 +1810,7 @@ function tooltip_grouped() { } function tooltip_format() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30000, 20000, 10000, 40000, 15000, 250000], @@ -1837,7 +1837,7 @@ function tooltip_format() { format: { title: (d: any) => "Data " + d, value: (value: any, ratio: any, id: any) => { - let format = id === "data1" ? d3.format(",") : d3.format("$"); + const format = id === "data1" ? d3.format(",") : d3.format("$"); return format(value); } // value: d3.format(",") // apply this format to both y and y2 @@ -1851,7 +1851,7 @@ function tooltip_format() { //////////////////////// function options_size() { - let chart = c3.generate({ + const chart = c3.generate({ size: { height: 240, width: 480 @@ -1865,7 +1865,7 @@ function options_size() { } function options_padding() { - let chart = c3.generate({ + const chart = c3.generate({ padding: { top: 40, right: 100, @@ -1881,7 +1881,7 @@ function options_padding() { } function options_color() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -1900,7 +1900,7 @@ function options_color() { } function transition_duration() { - let chart = c3.generate({ + const chart = c3.generate({ data: { url: "/data/c3_test.csv" }, @@ -1953,7 +1953,7 @@ function transition_duration() { ///////////////////////////// function point_show() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -1971,7 +1971,7 @@ function point_show() { //////////////////////////// function pie_label_format() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30], @@ -1994,7 +1994,7 @@ function pie_label_format() { ///////////////////// function api_flow() { - let chart = c3.generate({ + const chart = c3.generate({ data: { x: "x", columns: [ @@ -2064,7 +2064,7 @@ function api_flow() { } function api_data_name() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -2087,7 +2087,7 @@ function api_data_name() { } function api_data_color() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 20, 50, 40, 60, 50], @@ -2122,7 +2122,7 @@ function api_data_color() { } function api_axis_label() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -2154,7 +2154,7 @@ function api_axis_label() { } function api_axis_range() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -2210,7 +2210,7 @@ function api_axis_range() { } function api_resize() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -2233,7 +2233,7 @@ function api_resize() { } function api_grid_x() { - let chart = c3.generate({ + const chart = c3.generate({ bindto: "#chart", data: { columns: [ @@ -2276,7 +2276,7 @@ function api_grid_x() { ///////////////////// function transform_line() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -2304,7 +2304,7 @@ function transform_line() { } function transform_spline() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -2332,7 +2332,7 @@ function transform_spline() { } function transform_bar() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -2360,7 +2360,7 @@ function transform_bar() { } function transform_area() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -2388,7 +2388,7 @@ function transform_area() { } function transform_areaspline() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -2416,7 +2416,7 @@ function transform_areaspline() { } function transform_scatter() { - let chart = c3.generate({ + const chart = c3.generate({ data: { xs: { setosa: "setosa_x", @@ -2462,7 +2462,7 @@ function transform_scatter() { } function transform_pie() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -2485,7 +2485,7 @@ function transform_pie() { } function transform_donut() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 30, 200, 100, 400, 150, 250], @@ -2516,7 +2516,7 @@ function transform_donut() { ///////////////////// function style_region() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["sample", 30, 200, 100, 400, 150, 250] @@ -2530,7 +2530,7 @@ function style_region() { } function style_grid() { - let chart = c3.generate({ + const chart = c3.generate({ data: { columns: [ ["data1", 100, 200, 1000, 900, 500] diff --git a/types/c3/index.d.ts b/types/c3/index.d.ts index 2d0c4381d6..00d1cf1840 100644 --- a/types/c3/index.d.ts +++ b/types/c3/index.d.ts @@ -863,6 +863,7 @@ declare namespace c3 { keys?: { x?: string; value: string[]; } rows?: PrimitiveArray[]; columns?: PrimitiveArray[]; + names?: { [key: string]: string }; classes?: { [key: string]: string }; categories?: string[]; axes?: { [key: string]: string }; diff --git a/types/cache-manager/index.d.ts b/types/cache-manager/index.d.ts index 37af0b8374..40d644b546 100644 --- a/types/cache-manager/index.d.ts +++ b/types/cache-manager/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for cache-manager v1.2.0 // Project: https://github.com/BryanDonovan/node-cache-manager -// Definitions by: Simon Gausmann +// Definitions by: Simon Gausmann // Definitions: https://github.com/borisyankov/DefinitelyTyped interface CachingConfig { diff --git a/types/cal-heatmap/index.d.ts b/types/cal-heatmap/index.d.ts index f4b9f4df4f..affde185e2 100644 --- a/types/cal-heatmap/index.d.ts +++ b/types/cal-heatmap/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for cal-heatmap v3.5.4 // Project: https://github.com/wa0x6e/cal-heatmap -// Definitions by: Chris Baker +// Definitions by: Chris Baker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/callsites/callsites-tests.ts b/types/callsites/callsites-tests.ts new file mode 100644 index 0000000000..abe174537d --- /dev/null +++ b/types/callsites/callsites-tests.ts @@ -0,0 +1,20 @@ +import callsites = require('callsites'); + +function unicorn() { + callsites(); // $ExpectType CallSite[] + callsites()[0].getThis(); // $ExpectType object | undefined + callsites()[0].getTypeName(); // $ExpectType string + callsites()[0].getFunction(); // $ExpectType Function | undefined + callsites()[0].getFunctionName(); // $ExpectType string + callsites()[0].getMethodName(); // $ExpectType string | null + callsites()[0].getFileName(); // $ExpectType string | undefined + callsites()[0].getLineNumber(); // $ExpectType number + callsites()[0].getColumnNumber(); // $ExpectType number + callsites()[0].getEvalOrigin(); // $ExpectType string | CallSite + callsites()[0].isToplevel(); // $ExpectType boolean + callsites()[0].isEval(); // $ExpectType boolean + callsites()[0].isNative(); // $ExpectType boolean + callsites()[0].isConstructor(); // $ExpectType boolean +} + +unicorn(); diff --git a/types/callsites/index.d.ts b/types/callsites/index.d.ts new file mode 100644 index 0000000000..aea96c767f --- /dev/null +++ b/types/callsites/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for callsites 2.0 +// Project: https://github.com/sindresorhus/callsites#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = callsites; + +declare function callsites(): callsites.CallSite[]; + +declare namespace callsites { + interface CallSite { + getThis(): object | undefined; + getTypeName(): string; + getFunction(): Function | undefined; // tslint:disable-line ban-types + getFunctionName(): string; + getMethodName(): string | null; + getFileName(): string | undefined; + getLineNumber(): number; + getColumnNumber(): number; + getEvalOrigin(): CallSite | string; + isToplevel(): boolean; + isEval(): boolean; + isNative(): boolean; + isConstructor(): boolean; + } +} diff --git a/types/callsites/tsconfig.json b/types/callsites/tsconfig.json new file mode 100644 index 0000000000..68aca90ea3 --- /dev/null +++ b/types/callsites/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "callsites-tests.ts" + ] +} diff --git a/types/callsites/tslint.json b/types/callsites/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/callsites/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/camelcase/camelcase-tests.ts b/types/camelcase/camelcase-tests.ts index aacb29481a..871ec5c3b2 100644 --- a/types/camelcase/camelcase-tests.ts +++ b/types/camelcase/camelcase-tests.ts @@ -1,4 +1,3 @@ - import camelCase = require('camelcase'); camelCase('foo-bar'); diff --git a/types/camelcase/index.d.ts b/types/camelcase/index.d.ts index 79705dd423..83abf5a8a5 100644 --- a/types/camelcase/index.d.ts +++ b/types/camelcase/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for camelcase +// Type definitions for camelcase 4.1 // Project: https://github.com/sindresorhus/camelcase // Definitions by: Sam Verschueren // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = camelcase; declare function camelcase(...args: string[]): string; -declare namespace camelcase { } -export = camelcase; +declare namespace camelcase {} diff --git a/types/camelcase/tsconfig.json b/types/camelcase/tsconfig.json index 872bd51e96..a3fc596eb6 100644 --- a/types/camelcase/tsconfig.json +++ b/types/camelcase/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "camelcase-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/camelcase/tslint.json b/types/camelcase/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/camelcase/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/canvasjs/canvasjs-tests.ts b/types/canvasjs/canvasjs-tests.ts index e9120ec9c3..281cea0e51 100644 --- a/types/canvasjs/canvasjs-tests.ts +++ b/types/canvasjs/canvasjs-tests.ts @@ -1,248 +1,243 @@ +import * as CanvasJS from "canvasjs"; - -namespace CanvasJS.Tests { - // Column Chart - var columnChart = new CanvasJS.Chart("chartContainer", - { - title: { - text: "Top Oil Reserves", - }, - axisY: { - title: "Reserves(MMbbl)" - }, - legend: { - verticalAlign: "bottom", - horizontalAlign: "center" - }, - theme: "theme2", - data: [ - { - type: "column", - showInLegend: true, - legendMarkerColor: "grey", - legendText: "MMbbl = one million barrels", - dataPoints: [ - { y: 297571, label: "Venezuela" }, - { y: 267017, label: "Saudi" }, - { y: 175200, label: "Canada" }, - { y: 154580, label: "Iran" }, - { y: 116000, label: "Russia" }, - { y: 97800, label: "UAE" }, - { y: 20682, label: "US" }, - { y: 20350, label: "China" } - ] - } - ] - }); - columnChart.render(); - - // Line Chart - var lineChart = new CanvasJS.Chart("chartContainer", - { - theme: "theme2", - title: { - text: "Earthquakes - per month" - }, - axisX: { - valueFormatString: "MMM", - interval: 1, - intervalType: "month" - - }, - axisY: { - includeZero: false - - }, - data: [ - { - type: "line", - //lineThickness: 3, - dataPoints: [ - { x: new Date(2012, 0, 1), y: 450 }, - { x: new Date(2012, 1, 1), y: 414 }, - { x: new Date(2012, 2, 1), y: 520, indexLabel: "highest", markerColor: "red", markerType: "triangle" }, - { x: new Date(2012, 3, 1), y: 460 }, - { x: new Date(2012, 4, 1), y: 450 }, - { x: new Date(2012, 5, 1), y: 500 }, - { x: new Date(2012, 6, 1), y: 480 }, - { x: new Date(2012, 7, 1), y: 480 }, - { x: new Date(2012, 8, 1), y: 410, indexLabel: "lowest", markerColor: "DarkSlateGrey", markerType: "cross" }, - { x: new Date(2012, 9, 1), y: 500 }, - { x: new Date(2012, 10, 1), y: 480 }, - { x: new Date(2012, 11, 1), y: 510 } - - ] - } - - - ] - }); - lineChart.render(); - - // Spline Chart - var splineChart = new CanvasJS.Chart("chartContainer", - { - theme: "theme2", - title: { - text: "Game of Thrones, Viewers of the first airing on HBO" - }, - axisY: { - includeZero: false, - // suffix: " k", - valueFormatString: "#,,.", - suffix: " mn" - }, - toolTip: { - shared: true - }, - data: [ - { - type: "spline", - showInLegend: true, - name: "Season 2", - // markerSize: 0, - // color: "rgba(54,158,173,.6)", - dataPoints: [ - { label: "Ep. 1", y: 3858000 }, - { label: "Ep. 2", y: 3759000 }, - { label: "Ep. 3", y: 3766000 }, - { label: "Ep. 4", y: 3654000 }, - { label: "Ep. 5", y: 3903000 }, - { label: "Ep. 6", y: 3879000 }, - { label: "Ep. 7", y: 3694000 }, - { label: "Ep. 8", y: 3864000 }, - { label: "Ep. 9", y: 3384000 }, - { label: "Ep. 10", y: 4200000 } - - ] - }, - { - type: "spline", - showInLegend: true, - // markerSize: 0, - name: "Season 1", - dataPoints: [ - { label: "Ep. 1", y: 2220000 }, - { label: "Ep. 2", y: 2200000 }, - { label: "Ep. 3", y: 2440000 }, - { label: "Ep. 4", y: 2450000 }, - { label: "Ep. 5", y: 2580000 }, - { label: "Ep. 6", y: 2440000 }, - { label: "Ep. 7", y: 2400000 }, - { label: "Ep. 8", y: 2720000 }, - { label: "Ep. 9", y: 2660000 }, - { label: "Ep. 10", y: 3040000 } - - ] - } - ], - legend: { - cursor: "pointer", - itemclick: function (e) { - if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) { - e.dataSeries.visible = false; - } - else { - e.dataSeries.visible = true; - } - splineChart.render(); - } - - }, - }); - splineChart.render(); - - // Bar Chart - var barChart = new CanvasJS.Chart("chartContainer", { - +// Column Chart +const columnChart = new CanvasJS.Chart("chartContainer", + { title: { - text: "Fortune Global 500 Companies by Country" - }, - axisX: { - interval: 1, - gridThickness: 0, - labelFontSize: 10, - labelFontStyle: "normal", - labelFontWeight: "normal", - labelFontFamily: "Lucida Sans Unicode" + text: "Top Oil Reserves", }, axisY: { - interlacedColor: "rgba(1,77,101,.2)", - gridColor: "rgba(1,77,101,.1)" + title: "Reserves(MMbbl)" }, + legend: { + verticalAlign: "bottom", + horizontalAlign: "center" + }, + theme: "theme2", data: [ { - type: "bar", - name: "companies", - axisYType: "secondary", - color: "#014D65", + type: "column", + lineDashType: "longDash", + showInLegend: true, + legendMarkerColor: "grey", + legendText: "MMbbl = one million barrels", dataPoints: [ - { y: 5, label: "Sweden" }, - { y: 6, label: "Taiwan" }, - { y: 7, label: "Russia" }, - { y: 8, label: "Spain" }, - { y: 8, label: "Brazil" }, - { y: 8, label: "India" }, - { y: 9, label: "Italy" }, - { y: 9, label: "Australia" }, - { y: 12, label: "Canada" }, - { y: 13, label: "South Korea" }, - { y: 13, label: "Netherlands" }, - { y: 15, label: "Switzerland" }, - { y: 28, label: "Britain" }, - { y: 32, label: "Germany" }, - { y: 32, label: "France" }, - { y: 68, label: "Japan" }, - { y: 73, label: "China" }, - { y: 132, label: "US" } + { y: 297571, label: "Venezuela" }, + { y: 267017, label: "Saudi" }, + { y: 175200, label: "Canada" }, + { y: 154580, label: "Iran" }, + { y: 116000, label: "Russia" }, + { y: 97800, label: "UAE" }, + { y: 20682, label: "US" }, + { y: 20350, label: "China" } ] } ] }); - barChart.render(); +columnChart.render(); +const option = columnChart.get("title"); +columnChart.print(); +columnChart.exportChart({ format: "jpg" }); +columnChart.destroy(); +columnChart.axisX[0].convertPixelToValue(20); +columnChart.toolTip.get("text"); - // Pie Chart - var pieChart = new CanvasJS.Chart("chartContainer", - { - title: { - text: "Desktop Search Engine Market Share, Dec-2012" - }, - legend: { - verticalAlign: "center", - horizontalAlign: "left", - fontSize: 20, - fontFamily: "Helvetica" - }, - theme: "theme2", - data: [ - { - type: "pie", - indexLabelFontFamily: "Garamond", - indexLabelFontSize: 20, - indexLabel: "{label} {y}%", - startAngle: -20, - showInLegend: true, - toolTipContent: "{legendText} {y}%", - dataPoints: [ - { y: 83.24, legendText: "Google", label: "Google" }, - { y: 8.16, legendText: "Yahoo!", label: "Yahoo!" }, - { y: 4.67, legendText: "Bing", label: "Bing" }, - { y: 1.67, legendText: "Baidu", label: "Baidu" }, - { y: 0.98, legendText: "Others", label: "Others" } - ] - } - ] - }); - pieChart.render(); - - addColorSet("MyColorSet", [ - "123456", - "blue", - "red", - "orange" - ]); - - addCultureInfo("js", { - days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] +// Line Chart +const lineChart = new CanvasJS.Chart("chartContainer", + { + theme: "theme2", + title: { + text: "Earthquakes - per month" + }, + axisX: { + valueFormatString: "MMM", + interval: 1, + intervalType: "month" + }, + axisY: { + includeZero: false + }, + data: [ + { + type: "line", + // lineThickness: 3, + dataPoints: [ + { x: new Date(2012, 0, 1), y: 450 }, + { x: new Date(2012, 1, 1), y: 414 }, + { x: new Date(2012, 2, 1), y: 520, indexLabel: "highest", markerColor: "red", markerType: "triangle" }, + { x: new Date(2012, 3, 1), y: 460 }, + { x: new Date(2012, 4, 1), y: 450 }, + { x: new Date(2012, 5, 1), y: 500 }, + { x: new Date(2012, 6, 1), y: 480 }, + { x: new Date(2012, 7, 1), y: 480 }, + { x: new Date(2012, 8, 1), y: 410, indexLabel: "lowest", markerColor: "DarkSlateGrey", markerType: "cross" }, + { x: new Date(2012, 9, 1), y: 500 }, + { x: new Date(2012, 10, 1), y: 480 }, + { x: new Date(2012, 11, 1), y: 510 } + ] + } + ] }); -} +lineChart.render(); + +// Spline Chart +const splineChart = new CanvasJS.Chart("chartContainer", + { + theme: "theme2", + title: { + text: "Game of Thrones, Viewers of the first airing on HBO" + }, + axisY: { + includeZero: false, + // suffix: " k", + valueFormatString: "#,,.", + suffix: " mn" + }, + toolTip: { + shared: true + }, + data: [ + { + type: "spline", + showInLegend: true, + name: "Season 2", + // markerSize: 0, + // color: "rgba(54,158,173,.6)", + dataPoints: [ + { label: "Ep. 1", y: 3858000 }, + { label: "Ep. 2", y: 3759000 }, + { label: "Ep. 3", y: 3766000 }, + { label: "Ep. 4", y: 3654000 }, + { label: "Ep. 5", y: 3903000 }, + { label: "Ep. 6", y: 3879000 }, + { label: "Ep. 7", y: 3694000 }, + { label: "Ep. 8", y: 3864000 }, + { label: "Ep. 9", y: 3384000 }, + { label: "Ep. 10", y: 4200000 } + ] + }, + { + type: "spline", + showInLegend: true, + // markerSize: 0, + name: "Season 1", + dataPoints: [ + { label: "Ep. 1", y: 2220000 }, + { label: "Ep. 2", y: 2200000 }, + { label: "Ep. 3", y: 2440000 }, + { label: "Ep. 4", y: 2450000 }, + { label: "Ep. 5", y: 2580000 }, + { label: "Ep. 6", y: 2440000 }, + { label: "Ep. 7", y: 2400000 }, + { label: "Ep. 8", y: 2720000 }, + { label: "Ep. 9", y: 2660000 }, + { label: "Ep. 10", y: 3040000 } + ] + } + ], + legend: { + cursor: "pointer", + itemclick: (e) => { + e.dataSeries.visible = !(typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible); + splineChart.render(); + } + }, + }); +splineChart.render(); + +// Bar Chart +const barChart = new CanvasJS.Chart("chartContainer", { + title: { + text: "Fortune Global 500 Companies by Country" + }, + axisX: { + interval: 1, + gridThickness: 0, + labelFontSize: 10, + labelFontStyle: "normal", + labelFontWeight: "normal", + labelFontFamily: "Lucida Sans Unicode" + }, + axisY: { + interlacedColor: "rgba(1,77,101,.2)", + gridColor: "rgba(1,77,101,.1)" + }, + data: [ + { + type: "bar", + name: "companies", + axisYType: "secondary", + color: "#014D65", + dataPoints: [ + { y: 5, label: "Sweden" }, + { y: 6, label: "Taiwan" }, + { y: 7, label: "Russia" }, + { y: 8, label: "Spain" }, + { y: 8, label: "Brazil" }, + { y: 8, label: "India" }, + { y: 9, label: "Italy" }, + { y: 9, label: "Australia" }, + { y: 12, label: "Canada" }, + { y: 13, label: "South Korea" }, + { y: 13, label: "Netherlands" }, + { y: 15, label: "Switzerland" }, + { y: 28, label: "Britain" }, + { y: 32, label: "Germany" }, + { y: 32, label: "France" }, + { y: 68, label: "Japan" }, + { y: 73, label: "China" }, + { y: 132, label: "US" } + ] + } + ] +}); +barChart.render(); + +// Pie Chart +const pieChart = new CanvasJS.Chart("chartContainer", + { + title: { + text: "Desktop Search Engine Market Share, Dec-2012" + }, + legend: { + verticalAlign: "center", + horizontalAlign: "left", + fontSize: 20, + fontFamily: "Helvetica" + }, + theme: "theme2", + data: [ + { + type: "pie", + indexLabelFontFamily: "Garamond", + indexLabelFontSize: 20, + indexLabel: "{label} {y}%", + startAngle: -20, + showInLegend: true, + toolTipContent: "{legendText} {y}%", + dataPoints: [ + { y: 83.24, legendText: "Google", label: "Google" }, + { y: 8.16, legendText: "Yahoo!", label: "Yahoo!" }, + { y: 4.67, legendText: "Bing", label: "Bing" }, + { y: 1.67, legendText: "Baidu", label: "Baidu" }, + { y: 0.98, legendText: "Others", label: "Others" } + ] + } + ] + }); +pieChart.render(); + +CanvasJS.addColorSet("MyColorSet", [ + "123456", + "blue", + "red", + "orange" +]); + +CanvasJS.addCultureInfo("js", { + days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] +}); + +CanvasJS.formatNumber(20); + +CanvasJS.formatDate(new Date()); diff --git a/types/canvasjs/index.d.ts b/types/canvasjs/index.d.ts index 79a168f2d0..e1b74a7606 100644 --- a/types/canvasjs/index.d.ts +++ b/types/canvasjs/index.d.ts @@ -1,992 +1,1673 @@ -// Type definitions for CanvasJS v1.5.1 +// Type definitions for CanvasJS 1.9 // Project: http://canvasjs.com/ -// Definitions by: Mark Overholt +// Definitions by: ShuYin Zhang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +type DashType = "solid" | "shortDash" | "shortDot" | "shortDashDot" | "shortDashDotDot" | "dot" | "dash" | "dashDot" | "longDash" | "longDashDot" | "longDashDotDot"; + declare namespace CanvasJS { class Chart { - /** - * The current options of the chart. - */ + * The current options of the chart. + */ options: ChartOptions; - /** - * Initializes a new instance of CanvasJS Chart. - * @param containerId the DOM ID of the location where the chart is to be rendered - * @param options the options used to render the chart - */ + * All Title options become available as properties after Chart Render. You can access them either via get method or dot notation. But you can change / set those values only via set method. + */ + readonly title: ChartTitle; + /** + * The subtitles of the chart. + * You can access them either via get method or dot notation. But you can change / set those values only via set method. + */ + readonly subtitles: ChartTitle[]; + /** + * The toolTip of the chart. + */ + readonly toolTip: ChartToolTip; + readonly axisX: ChartAxisX[]; + readonly axisX2: ChartAxisX[]; + readonly axisY: ChartAxisY[]; + readonly axisY2: ChartAxisY[]; + readonly stripLines: ChartStrip[]; + readonly data: ChartDataSeries[]; + /** + * Initializes a new instance of CanvasJS Chart. + * @param containerId the DOM ID of the location where the chart is to be rendered + * @param options the options used to render the chart + */ constructor(containerId: string, options?: ChartOptions); /** - * Renders the chart. - * @param options an optional set of options that will override the constructed values. - */ - render(options?: ChartOptions): void; + * Renders the chart. + */ + render(): void; + /** + * Returns the specified property of Chart. + * @param propertyName Name of the property. + */ + get(propertyName: string): any; + /** + * Sets the specified property of Chart. + * Notes: + * 1. Chart should be rendered before you can use this method. + * 2. Because the chart updates each time set is called by default, + * it is recommended to disable auto update (set updateChart to false) till the last step if you have to set multiple properties. + * Otherwise it can affect performance because of repeated chart rendering. You can see an example below. + * @param propertyName Name of the property. + * @param value value to be set on property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: ChartOptions, updateChart?: boolean): void; + /** + * Adds a new element of given type to the specified array. For example, it can be used to add new Axis to axisY array. + * Notes: + * 1. Chart should be rendered before you can use this method. + * 2. Chart renders automatically after addTo() operation. + * @param propertyName Name of the property + * @param options Option for the new element + * @param index Index of the array where the new element is to be added. Defaults to the length (end) of array. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + addTo(propertyName: string, options: ChartAxisXOptions | ChartAxisYOptions | ChartDataSeriesOptions, index?: number, updateChart?: boolean): void; + /** + * Export the chart as image (jpg / png). + * @param options Setting when export + */ + exportChart(options: { format: "jpg" | "png", toDataURL?: boolean, fileName?: string }): void; + /** + * Prints the Chart. + * Chart should be rendered before you can use this method. + */ + print(): void; + /** + * Removes the chart references internally, thus making the chart eligible for garbage collection, in turn clearing up the memory. + * Notes: + * 1. On calling chart.destroy(), chart won’t be responsive unless new chart is created. + * 2. chart.destroy() should be called before using the same variable to hold a newly allocated object/chart to prevent memory leaks. + */ + destroy(): void; } /** - * Adds a new chart color set - * @param the name of the color set - * @param an array of colors. - */ + * Adds a new chart color set + * @param colorSetName name of the color set + * @param colorSetArray array of colors. + */ function addColorSet(colorSetName: string, colorSetArray: string[]): void; - /** - * Adds a new culture info for your chart - * @param culture the name of the culture - * @param the information used by this culture - */ + * Adds a new culture info for your chart + * @param culture the name of the culture + * @param info information used by this culture + */ function addCultureInfo(culture: string, info: CultureInfo): void; + /** + * Formats number according to the given formatString(optional) & culture(optional). + * @param number Number to format. + * @param formatString Default formatString is “#,##0.##” . + * @param culture Default culture is “en” + */ + function formatNumber(number: number, formatString?: string, culture?: string): string; + /** + * Formats date/timestamp according to the given formatString(optional) & culture(optional). + * @param date Date type or timestamp number. + * @param formatString Default formatString is “DD MMM YYYY”. + * @param culture Default culture is “en”. + */ + function formatDate(date: Date | number, formatString?: string, culture?: string): void; interface CultureInfo { /** - * Character used to separate fractional part from the whole number. - */ + * Character used to separate fractional part from the whole number. + * Default: "." + * Example: “.“ ”,” + */ decimalSeparator?: string; /** - * Also referred to as Thousand Separator - */ + * Also referred to as Thousand Separator. + * Default: “,” + * Example: “,”, “.” + */ digitGroupSeparator?: string; /** - * Text is shown inside the Button till v1.4 - * v1.5 onwards Text is shown as tooltip. - */ + * Text is shown inside the Button till v1.4 + * v1.5 onwards Text is shown as tooltip. + * Default: "Zoom" + * Example: “zoom”, etc + */ zoomText?: string; /** - * Text is shown inside the Button till v1.4 - * v1.5 onwards Text is shown as tooltip. - */ + * Text is shown inside the Button till v1.4 + * v1.5 onwards Text is shown as tooltip. + * Default: “Pan” + * Example: “pan”, etc + */ panText?: string; /** - * Text is shown inside the Button till v1.4 - * v1.5 onwards Text is shown as tooltip. - */ + * Text is shown inside the Button till v1.4 + * v1.5 onwards Text is shown as tooltip. + * Default: “Reset” + * Example: “reset”, etc + */ resetText?: string; /** - * Set text is shown instead of Save as PNG. - */ + * Set text is shown instead of Save as PNG. + * Default: “Save as PNG” + * Example: “save as png”, etc + */ savePNGText?: string; /** - * Set text is shown instead of Save as JPG. - */ + * Set text is shown instead of Save as JPG. + * Default: “Save as JPG” + * Example: “save as jpg”, etc + */ saveJPGText?: string; /** - * Tool Tip for Menu Button. - */ + * Tool Tip for Menu Button. + * Default: “More Options” + * Example: “More Options”, etc + */ menuText?: string; /** - * Day names starting from Sunday. Should be exactly 7 in total. - */ + * Day names starting from Sunday. Should be exactly 7 in total. + * Default: [“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”] + * Example: [“domingo”, “lunes”, “martes”, “miércoles”, “jueves”, “viernes”, “sábado”] + */ days?: string[]; /** - * Short Day names starting from Sunday. Should be exactly 7 in total. - */ + * Short Day names starting from Sunday. Should be exactly 7 in total. + * Default: [“Sun”, “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”] + * Example: [“Sun”, “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”] + */ shortDays?: string[]; /** - * Month Names starting from January - */ + * Month Names starting from January. + * Default: [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”] + * Example: [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”] + */ months?: string[]; /** - * Short Month Names starting from January - */ + * Short Month Names starting from January. + * Default: [“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”] + * Example: [“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”] + */ shortMonths?: string[]; } interface ChartOptions { /** - * Enables / Disables Chart interactivity like toolTip, mouse and touch events - * Default: true - * Example: false, true - */ + * Enables / Disables Chart interactivity like toolTip, mouse and touch events. + * Default: true + * Example: false, true + */ interactivityEnabled?: boolean; /** - * Enables Animation while rendering the Chart. - * Default: true - * Example: false, true - */ + * Sets the duration of animation in milliseconds. + * Default: 1200 + * Example: 1000, 500 etc. + */ + animationDuration?: number; + /** + * Enables Animation while rendering the Chart. + * Default: true + * Example: false, true + */ animationEnabled?: boolean; /** - * While exporting any chart, "Chart" is used as the default fine name with corresponding extension "jpg" or "png". You can override this name using exportFileName property. - * Default: Chart - */ + * While exporting any chart, "Chart" is used as the default fine name with corresponding extension "jpg" or "png". You can override this name using exportFileName property. + * Default: Chart + */ exportFileName?: string; /** - * Setting exportEnabled to true enables the export feature. As of now JPG & PNG formats are supported. Export feature is available in all Chart Types. - * Default: false - * Options: true, false - */ + * Setting exportEnabled to true enables the export feature. As of now JPG & PNG formats are supported. Export feature is available in all Chart Types. + * Default: false + * Options: true, false + */ exportEnabled?: boolean; /** - * Setting zoomEnabled to true enables zooming and panning feature of Chart. This way you can zoom into an area of interest when there is a large amount of data. This will also allow you to pan through the chart. If not set, the property is automatically enabled for large number of dataPoints. You can switch between zooming & panning using the toolbar that appears on the chart. After Zooming in, you can reset the chart by clicking the reset button. - * Default: false - * Options: true, false - */ + * Setting zoomEnabled to true enables zooming and panning feature of Chart. + * This way you can zoom into an area of interest when there is a large amount of data. + * This will also allow you to pan through the chart. + * If not set, the property is automatically enabled for large number of dataPoints. You can switch between zooming & panning using the toolbar that appears on the chart. + * After Zooming in, you can reset the chart by clicking the reset button. + * Default: false + * Options: true, false + */ zoomEnabled?: boolean; /** - * Sets the theme of the Chart. Various predefined themes are bundled along with the library. User can easily switch these themes by changing theme property to the below mentioned options. - * Default: "theme1" - * Options: "theme1","theme2", "theme3" - */ + * Sets the theme of the Chart. Various predefined themes are bundled along with the library. User can easily switch these themes by changing theme property to the below mentioned options. + * Default: "theme1" + * Options: "theme1","theme2", "theme3" + */ theme?: string; /** - * Sets the background color of entire Chart Area. Values can be "HTML Color Name", "hex code" or "rgba values" - * Default: "white" - * Example: "yellow", "#F5DEB3".. - */ + * Sets the background color of entire Chart Area. Values can be "HTML Color Name", "hex code" or "rgba values" + * Default: "white" + * Example: "yellow", "#F5DEB3".. + */ backgroundColor?: string; /** - * Sets the colorSet of the Chart. Color Set is an array of colors that are used to render data. Various predefined Color Sets are bundled along with the library. You can either choose from the pre-defined Color Sets or define your own Color Set. - * Default: "colorset1" or as defined in the selected theme - * Example: "colorSet1", "colorSet2", "colorSet3" - */ + * Sets the colorSet of the Chart. Color Set is an array of colors that are used to render data. Various predefined Color Sets are bundled along with the library. + * You can either choose from the pre-defined Color Sets or define your own Color Set. + * Default: "colorset1" or as defined in the selected theme + * Example: "colorSet1", "colorSet2", "colorSet3" + */ colorSet?: string; /** - * CanvasJS allows you to localize various culture / language / country specific elements in the Chart like number formatting style – where you can choose which character to use as a decimal separator and as a digit group separator (also referred to as a thousand separator). By default CanvasJS is set to Neutral English Culture – "en". - * Default: "en" - */ + * CanvasJS allows you to localize various culture / language / country specific elements in the Chart like number formatting style – where you can choose + * which character to use as a decimal separator and as a digit group separator (also referred to as a thousand separator). + * By default CanvasJS is set to Neutral English Culture – "en". + * Default: "en" + */ culture?: string; /** - * Sets the width of the Chart. - * Default: Takes chart container’s width by default. If the width is not set for the chart container, defaults to 500. - * Example: 380, 500, 720 - */ + * Sets the width of the Chart. + * Default: Takes chart container’s width by default. If the width is not set for the chart container, defaults to 500. + * Example: 380, 500, 720 + */ width?: number; /** - * Sets the width of the Chart - * Default: Takes chart container’s height by default. If the height is not set for the chart container, defaults to 400. - * Example: 260, 300, 400 - */ + * Sets the width of the Chart + * Default: Takes chart container’s height by default. If the height is not set for the chart container, defaults to 400. + * Example: 260, 300, 400 + */ height?: number; /** - * Title allows you to set content, appearance and position of Chart’s Title. - */ + * dataPointMaxWidth sets the maximum width of dataPoints in column / bar, ohlc and candlestick, charts. + * This allows you to limit the width of dataPoints when there are very few of them in the chart. + * At the same time, when the number of dataPoints increase, chart reduces their width so that they don’t overlap. + * Default : Automatically calculated based on the chart size. + * Example : 10, 20, 30, etc. + */ + dataPointMaxWidth?: number; + /** + * Title allows you to set content, appearance and position of Chart’s Title. + */ title: ChartTitleOptions; /** - * Whenever the chart contains multiple dataSeries, it is recommended to represent each dataSeries in a legend. This way it becomes easier for the user to know what exactly is represented by each of the dataSeries. In case of Pie and Doughnut charts, an entry is created for each dataPoint and in rest of the chart types entries are created for each dataSeries. - * You can selectively show or hide a dataSeries in the Legend using showInLegend property of dataSeries. - */ + * Whenever the chart contains multiple dataSeries, it is recommended to represent each dataSeries in a legend. + * This way it becomes easier for the user to know what exactly is represented by each of the dataSeries. + * In case of Pie and Doughnut charts, an entry is created for each dataPoint and in rest of the chart types entries are created for each dataSeries. + * You can selectively show or hide a dataSeries in the Legend using showInLegend property of dataSeries. + */ legend?: ChartLegendOptions; /** - * axisX object lets you set various parameters of X Axis like interval, grid lines, etc. It is mostly horizontal, except when we are working with Bar Charts, where axisX is vertical. - */ - axisX?: ChartAxisXOptions; + * axisX object lets you set various parameters of X Axis like interval, grid lines, etc. It is mostly horizontal, except when we are working with Bar Charts, where axisX is vertical. + */ + axisX?: ChartAxisXOptions | ChartAxisXOptions[]; /** - * axisY object lets you set various parameters of Y Axis like interval, grid lines, etc. It is mostly vertical, except when we are working with Bar Charts, where axisY is horizontal. - */ - axisY?: ChartAxisYOptions; + * axisX2 is the secondary axis which renders on the opposite of primary axis (axisX). + * It is mostly horizontal on top, except when we are working with Bar Charts, where axisX2 is vertical on right. + */ + axisX2?: ChartAxisXOptions | ChartAxisXOptions[]; /** - * toolTip object lets user set behaviour of toolTip at global level like enabling/disabling animation, setting Border Color, sharing toolTip between multiple dataSeries, etc. You can also disable the toolTip by setting enabled property to false. - */ + * axisY object lets you set various parameters of Y Axis like interval, grid lines, etc. It is mostly vertical, except when we are working with Bar Charts, where axisY is horizontal. + */ + axisY?: ChartAxisYOptions | ChartAxisYOptions[]; + /** + * axisY2 is the secondary axis which renders on the opposite of primary axis (axisY). It is mostly vertical, except when we are working with Bar Charts, where axisY2 is horizontal. + */ + axisY2?: ChartAxisYOptions | ChartAxisYOptions[]; + /** + * toolTip object lets user set behaviour of toolTip at global level like enabling/disabling animation, setting Border Color, sharing toolTip between multiple dataSeries, etc. + * You can also disable the toolTip by setting enabled property to false. + */ toolTip?: ChartToolTipOptions; /** - * data is an array of dataSeries Objects. - */ - data: ChartDataOptions[]; + * data is an array of dataSeries Objects. + */ + data: ChartDataSeriesOptions[]; + /** + * subtitles is a collection of subtitle elements. This allows you to have as many subtitles as you want in a chart. + * subtitle allows you to set content, appearance and position of Chart’s subtitle. subtitle is very much like title except that its font size is lesser than title by default. + */ + subtitles?: ChartTitleOptions[]; } interface ChartTitleOptions { /** - * Sets the Title’s text. - * Default: null - * Example: "Chart title" - */ + * Sets the Title’s text. + * Default: null + * Example: "Chart title" + */ text?: string; /** - * This property lets you align the Chart Title vertically. - * Default: "top" - * Options: "top", "center", "bottom" - */ + * This property lets you align the Chart Title vertically. + * Default: "top" + * Options: "top", "center", "bottom" + */ verticalAlign?: string; /** - * This property lets you align the Chart Title horizontally. - * Default: "center" - * Options: "left", "right", "center" - */ + * This property lets you align the Chart Title horizontally. + * Default: "center" + * Options: "left", "right", "center" + */ horizontalAlign?: string; /** - * Sets the font Size of Chart Title in pixels. - * Default: Automatically Calculated based on Chart Size - * Example: 16,18,22 .. - */ + * Sets the font Size of Chart Title in pixels. + * Default: 20 + * Example: 16,18,22 .. + */ fontSize?: number; /** - * Sets the Font Family of Chart Title. - * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" - * Example: "arial" , "tahoma", "verdana" .. - */ + * Sets the Font Family of Chart Title. + * Default: "calibri, Optima, Candara, verdana, Geneva, sans-serif" + * Example: "arial" , "tahoma", "verdana" .. + */ fontFamily?: string; /** - * Sets the Font Weight used in the Chart Title. - * Default: "bold" - * Options: "lighter", "normal", "bold" , "bolder" - */ + * Sets the Font Weight used in the Chart Title. + * Default: "normal" + * Options: "lighter", "normal", "bold" , "bolder" + */ fontWeight?: string; /** - * Sets the font color of Chart Title. The value of fontColor can be a "HTML Color Name" or "hex" code . - * Default: "#3A3A3A" - * Example: "red", "#FAC003" .. - */ + * Sets the font color of Chart Title. The value of fontColor can be a "HTML Color Name" or "hex" code . + * Default: "black" + * Example: "red", "#FAC003" .. + */ fontColor?: string; /** - * Sets the fontStyle of Chart Title. fontStyle can be set to one of the below options. - * Default: "normal" - * Options: "normal", "italic" , "oblique" - */ + * Sets the fontStyle of Chart Title. fontStyle can be set to one of the below options. + * Default: "normal" + * Options: "normal", "italic" , "oblique" + */ fontStyle?: string; /** - * Sets the thickness of border around the Title in pixels. To display border around title, set the borderThickness to a number greater than zero. - * Default: 0 - * Example: 2,4 .. - */ + * Sets the thickness of border around the Title in pixels. To display border around title, set the borderThickness to a number greater than zero. + * Default: 0 + * Example: 2,4 .. + */ borderThickness?: number; /** - * To display rounded borders around the title, set the cornerRadius of title. Higher the value, more rounded are the corners. - * Default: 0 - * Options: 5,8 .. - */ + * To display rounded borders around the title, set the cornerRadius of title. Higher the value, more rounded are the corners. + * Default: 0 + * Options: 5,8 .. + */ cornerRadius?: number; /** - * Sets the color of border around Chart Title. Values of borderColor can be "HTML Color Name" or "hex" code . - * Default: "black" - * Example: "red", "#FF0000" .. - */ + * Sets the color of border around Chart Title. Values of borderColor can be "HTML Color Name" or "hex" code . + * Default: "black" + * Example: "red", "#FF0000" .. + */ borderColor?: string; /** - * Sets the background color of Chart Title. Values can be "HTML Color Name" or "hex" code. - * Default: null - * Example: "red", "#FF0000" .. - */ + * Sets the background color of Chart Title. Values can be "HTML Color Name" or "hex" code. + * Default: null + * Example: "red", "#FF0000" .. + */ backgroundColor?: string; /** - * This property lets you set margin around the Chart Title in pixels. - * Default: 10 - * Example: 4,12 .. - */ + * This property lets you set margin around the Chart Title in pixels. + * Default: 5 + * Example: 4,12 .. + */ margin?: number; /** - * This property allows you to set the padding for Chart Title - * Default: 0 - * Example: 5, 8 .. - */ + * This property allows you to set the padding for Chart Title + * Default: 0 + * Example: 5, 8 .. + */ padding?: number; + /** + * Wrap specifies whether to wrap the title once its width crosses maxWidth or not. If it is set to false, title gets clipped after reaching maxWidth. + * Default: true; + * Example : true, false + */ + wrap?: boolean; + /** + * Sets the maximum width of title after which it gets wrapped or clipped depending on whether wrap is set to true (default) or false. + * Default: Automatically calculated based on the chart size. + * Example: 200, 400 .. + */ + maxWidth?: number; + /** + * When dockInsidePlotArea is set to true, title renders inside the plot area there by giving more space to plot area. + * Default: false + * Example: false, true. + */ + dockInsidePlotArea?: boolean; + } + + interface ChartTitle extends ChartTitleOptions { + /** + * Can be accessed via get method or dot notation. + */ + readonly bounds: { + x1: number, + x2: number, + y1: number, + y2: number, + }; + /** + * Returns the specified property of title. + * @param propertyName Name of the property. + */ + get(propertyName: string): string | number | boolean; + /** + * Sets the specified property of Title. + * @param propertyName Name of the property. + * @param value value to be set on property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: string | number | boolean, updateChart: boolean): void; + /** + * Removes title of the chart. + */ + remove(): void; } interface ChartLegendOptions { /** - * Sets the cursor type for legend items. - * Default: "default" - * Examples: "pointer", "crosshair" .. - */ + * Sets the cursor type for legend items. + * Default: "default" + * Examples: "pointer", "crosshair" .. + */ cursor?: string; - /** - * Sets the font Size of Legend Text in pixels. - * Default: 12 - * Example: 16,18,22 .. - */ + * Sets the font Size of Legend Text in pixels. + * Default: 20 + * Example: 16,18,22 .. + */ fontSize?: number; /** - * Sets the Font Family of Legend Text. - * Default: "calibri" - * Example: "arial" , "tahoma", "verdana" .. - */ + * Sets the Font Family of Legend Text. + * Default: "calibri" + * Example: "arial" , "tahoma", "verdana" .. + */ fontFamily?: string; /** - * Sets the font color of Legend Text . The value of fontColor can be a "HTML Color Name" or "hex" code . - * Default: "black" - * Example: "red", "#FAC003" .. - */ + * Sets the font color of Legend Text . The value of fontColor can be a "HTML Color Name" or "hex" code . + * Default: "black" + * Example: "red", "#FAC003" .. + */ fontColor?: string; /** - * Sets the Font Weight of Legend Text. - * Default: "normal" - * Example: "lighter", "normal", "bold" , "bolder" - */ + * Sets the Font Weight of Legend Text. + * Default: "normal" + * Example: "lighter", "normal", "bold" , "bolder" + */ fontWeight?: string; /** - * Sets the fontStyle of Legend Text. fontStyle can be set to one of the below options. - * Default: "normal" - * Example: "normal", "italic" , "oblique" - */ + * Sets the fontStyle of Legend Text. fontStyle can be set to one of the below options. + * Default: "normal" + * Example: "normal", "italic" , "oblique" + */ fontStyle?: string; /** - * This property lets you align the Legend Position vertically. - * Default: "bottom" - * Example: "top", "center", "bottom" - */ + * This property lets you align the Legend Position vertically. + * Default: "bottom" + * Example: "top", "center", "bottom" + */ verticalAlign?: string; /** - * This property lets you align the Legend Position horizontally. - * Default: "right" - * Example: "left", "right", "center" - */ + * This property lets you align the Legend Position horizontally. + * Default: "right" + * Example: "left", "right", "center" + */ horizontalAlign?: string; /** - * Sets the mouseover event handler for the legend, which is triggered when the user moves the mouse(input device) over a legend item. After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. - * @param event a chart event - */ - itemmouseover?: (event: ChartEvent) => void; + * Sets the margin between marker and text of each item inside legend. + * Default: Automatically calculated based on the chart size. + * Example: 4,12 .. + */ + markerMargin?: number; /** - * Sets the mousemove event handler for the legend, which is triggered when the user moves the mouse(input device) within a legend item. When the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. - * @param event a chart event - */ - itemmousemove?: (event: ChartEvent) => void; + * Sets the mouseover event handler for the legend, which is triggered when the user moves the mouse(input device) over a legend item. + * After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ + itemmouseover?(event: ChartEvent): void; /** - * Sets the mouseout event handler for the legend, which is triggered when the user moves the mouse pointer outside a legend item. After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. - * @param event a chart event - */ - itemmouseout?: (event: ChartEvent) => void; + * Sets the mousemove event handler for the legend, which is triggered when the user moves the mouse(input device) within a legend item. + * When the event is triggered, the event related data is passed as a parameter to the assigned event handler. + * Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ + itemmousemove?(event: ChartEvent): void; /** - * Sets the click event handler for the legend, which is triggered when the user clicks on a legend item. After the event is triggered, the event related data is passed as a parameter to the assigned event handler. Parameters passed to the function are shown in the Event Object section below. - * @param event a chart event - */ - itemclick?: (event: ChartEvent) => void; + * Sets the mouseout event handler for the legend, which is triggered when the user moves the mouse pointer outside a legend item. + * After the event is triggered, the event related data is passed as a parameter to the assigned event handler. + * Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ + itemmouseout?(event: ChartEvent): void; + /** + * Sets the click event handler for the legend, which is triggered when the user clicks on a legend item. + * After the event is triggered, the event related data is passed as a parameter to the assigned event handler. + * Parameters passed to the function are shown in the Event Object section below. + * @param event a chart event + */ + itemclick?(event: ChartEvent): void; + /** + * Setting reversed property to true shows legend items in reverse order. + * Default: false; + * Example: true, false + */ + reversed?: boolean; + /** + * Sets the maximum width of legend. If any item is longer than the maxWidth, it gets wrapped or clipped depending on the itemWrap property. itemWrap is true by default. + * Whenever items are stacked horizontally, new items are moved to the next row once maxWidth is reached. + * Default: Automatically calculated based on the chart size. + * Example: 100, 200, 500 etc. + */ + maxWidth?: number; + /** + * Sets the maximum height of legend. Once the maximum height is reached, remaining legend items are not shown when horizontally stacked (while on top or bottom or plotArea) + * and a new column is created when items are vertically stacked (when displayed to the left or right of plotArea). + * Default: Automatically calculated based on chart size. + * Example: 100,200, 300 etc. + */ + maxHeight?: number; + /** + * Sets the maximum width of individual legend items after which they get wrapped or clipped depending on whether itemWrap is set to true (default) or false. + * itemMaxWidth can’t be greater than maxWidth of legend. + * Default: Automatically calculated based on the chart size. + * Example: 100, 150, 200 etc. + */ + itemMaxWidth?: number; + /** + * Sets the width of individual legend items after which the it gets wrapped or clipped depending on whether itemWrap is set to true (default) or false. + * itemWidth can’t be greater than itemMaxWidth and maxWidth of legend. + * Default: Automatically calculated based on chart size. + * Example: 100, 200, 300 etc. + */ + itemWidth?: number; + /** + * itemWrap specifies whether to wrap or clip legendText once its width crosses itemMaxWidth / maxWidth. + * Default: true + * Example: true, false + */ + itemWrap?: boolean; + /** + * A custom formatter function that returns text to be displayed inside individual legend items. + */ + itemTextFormatter?(e?: { chart: Chart, legend: ChartLegendOptions, dataSeries: ChartDataSeriesOptions, dataPoint: ChartDataPoint }): string; + /** + * When dockInsidePlotArea is set to true, legend renders inside the plot area there by giving more space to plot area. + * Default: false + * Example: true, false + */ + dockInsidePlotArea?: boolean; + } + + interface ChartLegend extends ChartLegendOptions { + /** + * Returns the specified property of legend. + * @param propertyName Name of the property. + */ + get(propertyName: string): number | string | boolean; + /** + * Sets the specified property of legend. + * @param propertyName Name of the property. + * @param value Name of the property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: number | string | boolean, updateChart?: boolean): void; } interface ChartEvent { /** - * The x value of the item - */ + * The x value of the item + */ x: any; /** - * The y value of the item - */ + * The y value of the item + */ y: number; /** - * The chart object - */ + * The chart object + */ chart: Chart; /** - * The datapoint options - */ + * The datapoint options + */ dataPoint: ChartDataPoint; /** - * The data series options - */ - dataSeries: ChartDataOptions; + * The data series options + */ + dataSeries: ChartDataSeriesOptions; /** - * The index of the data point - */ + * The index of the data point + */ dataPointIndex: number; /** - * The index of the data series - */ + * The index of the data series + */ dataSeriesIndex: number; } interface ChartAxisOptions { /** - * Sets the Axis Title. - * Default: null - * Example: "Axis X Title" - */ + * Sets the Axis Title. + * Default: null + * Example: "Axis X Title" + */ title?: string; /** - * Sets the Font Color of Axis Title. The value of titleFontColor can be a "HTML Color Name" or "hex" code . - * Default: "#666666" - * Example: "red", "#006400" . - */ + * Sets the Font Color of Axis Title. The value of titleFontColor can be a "HTML Color Name" or "hex" code . + * Default: "#666666" + * Example: "red", "#006400" . + */ titleFontColor?: string; /** - * Sets the Font Size of Axis Title in pixels. - * Default: Automatically Calculated based on Chart Size - * Example: 16, 25 .. - */ + * Sets the Font Size of Axis Title in pixels. + * Default: 20 + * Example: 16, 25 .. + */ titleFontSize?: number; /** - * Sets the Font Family of Axis Title. - * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" - * Example: "calibri", "tahoma, "verdana" .. - */ + * Sets the Font Family of Axis Title. + * Default: "arial" + * Example: "calibri", "tahoma, "verdana" .. + */ titleFontFamily?: string; /** - * Sets the Font Weight used in the Axis Title. It can be set to one of the options below. - * Default: "normal" - * Options: "lighter", "normal", "bold" , "bolder" - */ + * Sets the Font Weight used in the Axis Title. It can be set to one of the options below. + * Default: "normal" + * Options: "lighter", "normal", "bold" , "bolder" + */ titleFontWeight?: string; /** - * Sets the Font Style of Axis Title. It can be set to one of the below options. - * Default: "normal" - * Options: "normal", "italic" , "oblique" - */ + * Sets the Font Style of Axis Title. It can be set to one of the below options. + * Default: "normal" + * Options: "normal", "italic" , "oblique" + */ titleFontStyle?: string; /** - * This property lets you set margin between chart’s boundary and Axis. - * Default: 2 - * Example: 8, 10.. - */ + * This property lets you set margin between chart’s boundary and Axis. + * Default: 2 + * Example: 8, 10.. + */ margin?: number; /** - * Sets the angle for Axis Labels. - * Default: null - * Example: 20, 45, -30 .. - */ - labelAngle?: number; - /** - * Sets the Axis Label color. The value of labelFontColor can be a "HTML Color Name" or "hex" code . - * Default: "grey" - * Example: "red", "#FAC003" .. - */ - labelFontColor?: string; - /** - * Sets the Axis Label Font Size in pixels. - * Default: Automatically Calculated based on Chart Size - * Example: 16, 18, 22.. - */ - labelFontSize?: number; - /** - * Sets the Font Family of Axis labels. - * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" - * Example: "calibri", "tahoma", "verdana" .. - */ - labelFontFamily?: string; - /** - * Set the font Weight used in Axis Labels. It can be set to one of the options below. - * Default: "normal" - * Options: "lighter", "normal", "bold" , "bolder" - */ - labelFontWeight?: string; - /** - * Sets the Font Style of Axis Labels. It can be set to one of the below options. - * Default: "normal" - * Options: "italic", "oblique", "normal" - */ - labelFontStyle?: string; - /** - * A string that prepends all the labels on axisX. - * Default: null - * Example: "$","cat".. - */ - prefix?: string; - /** - * A string that appends all the labels on axisX. - * Default: null - * Example: "$","cat".. - */ - suffix?: string; - /** - * Defines how values must be formatted before they appear on Axis X. You can format numbers and date time values using this property. Below you will find descriptive table explaining various specifiers with example. - */ - valueFormatString?: string; - /** - * Sets the distance between Tick Marks, Grid Lines and Interlaced Colors. - * Default: Automatically Calculated - * Example: 50, 75.. - */ - interval?: number; - /** - * intervalType is the unit of interval property. intervalType is by default set to "number" and hence you need to specify the interval type (eg "week", "month", etc) depending on the type of interval you intend to set. If required interval is 3 months, you need to provide interval as 3 and intervalType as "month" - * Default: Automatically handled when interval property is not set. Defaults to "number" when you set the interval. - * Option: "number","millisecond" ,"second"," minute", "hour", "day", "month" ,"year" - * Example: for interval as 15 minutes, set interval as 15, and set intervalType as "minute", - */ - intervalType?: string; - /** - * Sets the length of Tick Marks that are drawn on the Axis. - * Default: 5 - * Example: 10, 14.. - */ - tickLength?: number; - /** - * Sets the color of Tick Marks drawn on the axis. The value of tickColor can be a "HTML Color Name" or "hex" code . - * Default: "#BBBBBB" - * Example: "red", "#006400". - */ - tickColor?: string; - /** - * Sets the thickness of the Tick Marks in pixels. - * Default: 2 - * Example: 3, 4.. - */ - tickThickness?: number; - /** - * Sets the color of Axis line. Axis line color can be a "HTML Color Name" or "hex" code . - * Default: "#BBBBBB" - * Example: "blue","#21AB13".. - */ + * Sets the color of Axis line. Axis line color can be a "HTML Color Name" or "hex" code . + * Default: "#BBBBBB" + * Example: "blue","#21AB13".. + */ lineColor?: string; /** - * Sets the Thickness of Axis line in pixels. - * Default: 2 - * Example: 2, 4.. - */ - lineThickness?: string; + * Sets the Thickness of Axis line in pixels. + * Default: 2 + * Example: 2, 4.. + */ + lineThickness?: number; /** - * Sets the Interlacing Color that alternates between the set interval. If the interval is not set explicitly, then the auto calculated interval is considered. The value of interlacedColor can be a "HTML Color Name" or "hex" code . - * Default: null - * Example: "#F8F1E4", "#FEFDDF" …. - */ - interlaceColor?: string; + * Sets the dash type for axisY. + * Default: "solid" + */ + lineDashType?: DashType; /** - * Sets the Thickness of Grid Lines. To display grid on Axis X, set the Grid Thickness to a number greater than zero. - * Default: 0 - * Example: 2,4 .. - */ - gridThickness?: number; - /** - * Sets the Color of Grid Lines. Value of gridColor can be a "HTML Color Name" or "hex" code . - * Default: "#BBBBBB" - * Example: "red", "#FEFDDF" .. - */ - gridColor?: string; - - /** - * Sets the Interlacing Color that alternates between the set interval. - * If the interval is not set explicitly, then the auto calculated interval is considered. - * The value of interlacedColor can be an "HTML Color Name" or "hex" code. - * Default: null - * Example: "#F8F1E4", "#FEFDDF" - */ - interlacedColor?: string; - - /** - * Strip Lines are vertical or horizontal lines used to highlight/mark a certain region on the plot area. You can choose whether to draw a line at a specific position or shade a region on the plot area. Strip Lines are sometimes referred to as trend lines. - * If you want to just mark a certain position on the axis, you can set the value attribute and it’ll draw a line at that position with the set thickness. If you want to shade a region instead, you need to set startValue and endValue attributes. This will fill the area within the specified range. - * In the case you set startValue and endValue attributes, value and thickness attributes are ignored (as either a single thread of line can exist, or a shaded region between two given points). - * Strip Lines can be displayed using AxisX or AxisY’s stripLines array. This allows you to have one or more strip lines on both x & y axis. - */ - stripLines?: ChartStripLines; - } - - interface ChartStripLines { - /** - * Sets the point where the stripLine has to be plotted or drawn along the axis X. - * Default: null - * Example: 20,30,100,50 - */ - value?: number; - /** - * Sets the point where the stripLine’s shaded region begins on the x-axis. - * Default: null - * Example: 20,30,100,50 - */ - startValue?: number; - /** - * Sets the point where the stripLine’s shaded region ends on the x-axis. - * Default: null - * Example: 50,60,200,300 - */ - endValue?: number; - /** - * Sets the thickness of the stripLine in pixels. - * Default: 2 - * Example: 2,4,5,6 - */ - thickness?: number; - /** - * Sets the color of the stripLine. - * Default: "orange" - * Example: "green", "#23EA23" - */ - color?: string; - /** - * Sets the label of the stripLine. These are shown on top of axis labels. - * Default: "" (empty string) - * Example: "Threshold", "Deaths in 1920" - */ - label?: string; - /** - * Sets the background color of stripLine’s label. - * Default: "#eeeeee" - * Example: "red","#fabd76" - */ - labelBackgroundColor?: string; - /** - * Sets the font-family of stripLine’s label. If the first font is not found in the system from the specified font-family list, it tries to use the next font in the list. - * Default: "arial" - * Example: "Arial, Trebuchet MS, Tahoma, sans-serif" - */ - labelFontFamily?: string; - /** - * Sets the font color of label. - * Default: "orange" - * Example: "blue","#4135e9" - */ - labelFontColor?: string; - /** - * Sets the font size of the label in pixels. - * Default: 12 - * Example: 18,19,20,22 - */ - labelFontSize?: number; - /** - * Sets the font weight of stripLine’s label. - * Default: "normal" - * Example: "lighter","normal","bold","bolder" - */ - labelFontWeight?: string; - /** - * Sets the font style of stripLine’s label. - * Default: "normal" - * Example: "normal","italic","oblique" - */ - labelFontStyle?: string; - } - - interface ChartAxisXOptions extends ChartAxisOptions { - /** - * Sets the minimum value of Axis. Values smaller than minimum are clipped. - * Default: Automatically Calculated based on the data - * Example: 100, 350.. - */ - minimum?: number | Date; - /** - * Sets the maximum value permitted on Axis. Values greater than maximum are clipped. - * Default: Automatically Calculated based on the data - * Example: 100, 350.. - */ - maximum?: number | Date; - } - - interface ChartAxisYOptions extends ChartAxisOptions { - /** - * When includeZero is set to true, axisY sets the range in such a way that Zero is a part of it. It is set to true by default. But, whenever y values are very big and difference among dataPoints are hard to judge, setting includeZero to false makes axisY to set a range that makes the differences prominently visible. - * Default: true - * Example: true, false - */ - includeZero?: boolean; - - /** - * Sets the minimum value of Axis. Values smaller than minimum are clipped. - * Default: Automatically Calculated based on the data - * Example: 100, 350.. - */ + * Sets the minimum value of Axis. Values smaller than minimum are clipped. minimum also sets the lower limit while panning chart. + * Default: Automatically Calculated based on the data. + * Example: 100, 350.. + */ minimum?: number; /** - * Sets the maximum value permitted on Axis. Values greater than maximum are clipped. - * Default: Automatically Calculated based on the data - * Example: 100, 350.. - */ + * Sets the maximum value permitted on Axis. Values greater than maximum are clipped. maximum also set the upper limit while panning chart. + * Default: Automatically Calculated based on the data. + * Example: 100, 350.. + */ maximum?: number; + /** + * Viewport is the visible range of the axis and viewportMinimum allows you to set its minimum value. + * This can be used in combination with viewportMaximum in order to zoom into a certain region programmatically. + * Default: Automatically Calculated based on the data. + * Example: -100, 350.. + */ + viewportMinimum?: number; + /** + * Viewport is the visible range of the axis and viewportMinimum allows you to set its minimum value. + * This can be used in combination with viewportMaximum in order to zoom into a certain region programmatically. + * Default: Automatically Calculated based on the data. + * Example: -100, 350.. + */ + viewportMaximum?: number; + } + + interface ChartStripLinesOptions { + /** + * Sets the point where the stripLine has to be plotted or drawn along the axis X. + * Default: null + * Example: 20,30,100,50 + */ + value?: number; + /** + * Sets the point where the stripLine’s shaded region begins on the x-axis. + * Default: null + * Example: 20,30,100,50 + */ + startValue?: number; + /** + * Sets the point where the stripLine’s shaded region ends on the x-axis. + * Default: null + * Example: 50,60,200,300 + */ + endValue?: number; + /** + * Sets the thickness of the stripLine in pixels. + * Default: 2 + * Example: 2,4,5,6 + */ + thickness?: number; + /** + * Sets the color of the stripLine. + * Default: "orange" + * Example: "green", "#23EA23" + */ + color?: string; + /** + * Sets the label of the stripLine. These are shown on top of axis labels. + * Default: "" (empty string) + * Example: "Threshold", "Deaths in 1920" + */ + label?: string; + /** + * labelPlacement allows you to place stripline’s Label either inside or outside of plotArea. + * Default: “inside” + * Options: “inside”, “outside” + */ + labelPlacement?: string; + /** + * labelAlign allows you to place the stripline’s Label far, center or near the axis. + * Default: “far” + * Options: “far”, “center”, “near” + */ + labelAlign?: string; + /** + * Setting labelWrap to true wraps the labels at labelMaxWidth. Clips the same when set to false. It overrides the labelWrap set at axis level. + * Default: true + * Example: true, false. + */ + labelWrap: boolean; + /** + * labelMaxWidth defines the maximum width of labels after which they get wrapped or clipped depending on labelWrap’s value. + * It overrides the labelMaxWidth value set at axis level. + * Default: Automatically calculated based on the length of label. + * Example: 4, 20, 100 etc. + */ + labelMaxWidth: number; + /** + * Sets the background color of stripLine’s label. + * Default: "#eeeeee" + * Example: "red","#fabd76" + */ + labelBackgroundColor?: string; + /** + * Sets the font-family of stripLine’s label. If the first font is not found in the system from the specified font-family list, it tries to use the next font in the list. + * Default: "arial" + * Example: "Arial, Trebuchet MS, Tahoma, sans-serif" + */ + labelFontFamily?: string; + /** + * Sets the font color of label. + * Default: "orange" + * Example: "blue","#4135e9" + */ + labelFontColor?: string; + /** + * Sets the font size of the label in pixels. + * Default: 12 + * Example: 18,19,20,22 + */ + labelFontSize?: number; + /** + * Sets the font weight of stripLine’s label. + * Default: "normal" + * Example: "lighter","normal","bold","bolder" + */ + labelFontWeight?: string; + /** + * Sets the font style of stripLine’s label. + * Default: "normal" + * Example: "normal","italic","oblique" + */ + labelFontStyle?: string; + /** + * stripLine is displayed on top of dataPoints when showOnTop is set to true. + * Default: false + * Example: true, false + */ + showOnTop?: boolean; + /** + * Sets the Dash Type for stripLine. + * Default: solid + */ + lineDashType?: DashType; + /** + * Sets opacity of stripLine. + * Default: null + * Example: .1, .5, 1 etc. + */ + opacity?: number; + /** + * A custom formatter function that returns stripLine’s label. + */ + labelFormatter?(e?: { chart: Chart, axis: ChartAxisYOptions, stripline: ChartStripLinesOptions }): string; + } + + interface ChartStrip extends ChartStripLinesOptions { + /** + * Returns the specified property of stripLines. + * @param propertyName Name of the property + */ + get(propertyName: string): number | string | boolean; + /** + * Sets the specified property of stripLines. + * @param propertyName Name of the property. + * @param value value to be set on property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: number | string | boolean, updateChart: boolean): void; + /** + * Removes specified stripLine from stripLines Array. + */ + remove(): void; + } + + interface ChartAxisXOptions extends ChartAxisOptions { + /** + * TitleWrap specifies whether to wrap or clip axis title once its width crosses titleMaxWidth. + * Default: true + * Options: true, false + */ + titleWrap?: boolean; + /** + * Sets the maximum width of title after which it gets wrapped or clipped depending on whether titleWrap is set to true (default) or false. + * Default: Automatically calculated based on the length of axis. + * Example: 100, 200... + */ + titleMaxWidth?: number; + /** + * Sets the Axis Label background color. The value of labelBackgroundColor can be a “HTML Color Name” or “hex” code. + * Default: “transparent” + * Example: “red”,”#fabd76″ + */ + labelBackgroundColor?: string; + /** + * Sets the maximum width of label after which it gets wrapped or clipped depending on whether labelWrap is set to true (default) or false. + * Default: Automatically calculated based on the length of label. + * Example: 4, 20, 100 etc. + */ + labelMaxWidth?: number; + /** + * labelWrap specifies whether to wrap or clip label once its width crosses labelMaxWidth. + * Default: true + * Example: true, false + */ + labelWrap?: boolean; + /** + * Setting labelAutoFit to true automatically wraps and/or rotates and/or reduces font size of label when they are too long and overlaps, + * finds the best-fit and automatically manages label overlapping. + * Default: true + * Options: true, false + */ + labelAutoFit?: boolean; + /** + * Sets the angle for Axis Labels. + * Notes: + * 1.Units in degrees. + * 2.Values can be positive or negative. + * Default: null; + * Example: 20, 45, -30.. + */ + labelAngle?: number; + /** + * Sets the Font Family of Axis labels. + * Default: “calibri, optima, Candara, Verdana, Geneva, sans-serif” + * Example: “calibri”, “tahoma”, “verdana” .. + */ + labelFontFamily?: string; + /** + * Sets the Axis Label color. The value of labelFontColor can be a "HTML Color Name" or "hex" code . + * Default: "grey" + * Example: "red", "#FAC003" .. + */ + labelFontColor?: string; + /** + * Sets the Axis Label Font Size in pixels. + * Default: Automatically Calculated based on Chart Size + * Example: 16, 18, 22.. + */ + labelFontSize?: number; + /** + * Set the font Weight used in Axis Labels. It can be set to one of the options below. + * Default: "normal" + * Options: "lighter", "normal", "bold" , "bolder" + */ + labelFontWeight?: string; + /** + * Sets the Font Style of Axis Labels. It can be set to one of the below options. + * Default: "normal" + * Options: "italic", "oblique", "normal" + */ + labelFontStyle?: string; + /** + * A string that prepends all the labels on axisX. + * Default: null + * Example: "$","cat".. + */ + prefix?: string; + /** + * A string that appends all the labels on axisX. + * Default: null + * Example: "$","cat".. + */ + suffix?: string; + /** + * Defines how values must be formatted before they appear on Axis X. + * You can format numbers and date time values using this property. + * More Detail: https://canvasjs.com/docs/charts/chart-options/axisx/valueformatstring/ + */ + valueFormatString?: string; + /** + * Sets the distance between Tick Marks, Grid Lines and Interlaced Colors. + * Default: Automatically Calculated + * Example: 50, 75.. + */ + interval?: number; + /** + * intervalType is the unit of interval property. + * intervalType is by default set to "number" and hence you need to specify the interval type (eg "week", "month", etc) depending on the type of interval you intend to set. + * If required interval is 3 months, you need to provide interval as 3 and intervalType as "month" + * Default: Automatically handled when interval property is not set. Defaults to "number" when you set the interval. + * Option: "number","millisecond" ,"second"," minute", "hour", "day", "month" ,"year" + * Example: for interval as 15 minutes, set interval as 15, and set intervalType as "minute", + */ + intervalType?: string; + /** + * Setting reversed property to true shows axis in reverse order. + * Default: false + * Options: true, false + */ + reversed?: boolean; + /** + * Setting logarithmic property to true changes axis scale to logarithmic scale. Default Logarithm Base is 10 – which you can customize using logarithmBase property. + * Default: false + * Options: true, false + */ + logarithmic?: boolean; + /** + * Sets the logarithm base for Axis X. Works only when logarithm property is set to true. + * Default: 10 + * Options: 2, 16, Math.E, .. + */ + logarithmBase?: number; + /** + * Sets the length of Tick Marks that are drawn on the Axis. + * Default: 5 + * Example: 10, 14.. + */ + tickLength?: number; + /** + * Sets the color of Tick Marks drawn on the axis. The value of tickColor can be a "HTML Color Name" or "hex" code . + * Default: "#BBBBBB" + * Example: "red", "#006400". + */ + tickColor?: string; + /** + * Sets the thickness of the Tick Marks in pixels. + * Default: 2 + * Example: 3, 4.. + */ + tickThickness?: number; + /** + * Sets the Interlacing Color that alternates between the set interval. + * If the interval is not set explicitly, then the auto calculated interval is considered. The value of interlacedColor can be a “HTML Color Name” or “hex” code. + * Default: null + * Example: "#F8F1E4", "#FEFDDF"... + */ + interlacedColor?: string; + /** + * Sets the Thickness of Grid Lines. To display grid on Axis X, set the Grid Thickness to a number greater than zero. + * Default: 0 + * Example: 2,4 .. + */ + gridThickness?: number; + /** + * Sets the Color of Grid Lines. Value of gridColor can be a "HTML Color Name" or "hex" code . + * Default: "#BBBBBB" + * Example: "red", "#FEFDDF" .. + */ + gridColor?: string; + /** + * Sets the Dash Type for grid lines on axisX. + * Default: solid + */ + gridDashType?: DashType; + /** + * A custom formatter function that returns label to be displayed on axisX. + * Notes: + * 1.labelFormatter function should return a string. + * 2.You can use formatNumber and formatDate functions to format number/date values inside the formatter function. + */ + labelFormatter?(e: { chart: Chart, axis: ChartAxisYOptions, value: number, label: string }): string; + /** + * Strip Lines / Trend Lines are vertical or horizontal lines used to highlight/mark a certain region on the plot area. + * You can choose whether to draw a line at a specific position or shade a region on the plot area. Strip Lines are also referred to as Trend Lines. + */ + stripLines?: ChartStripLinesOptions | ChartStripLinesOptions[]; + } + + interface ChartAxisX extends ChartAxisXOptions { + /** + * Returns the specified property of Axis. + * @param propertyName Name of the property. + */ + get(propertyName: string): string | number | boolean; + /** + * Sets the specified property of Axis. + * @param propertyName Name of the property. + * @param value value to be set on property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: string | number | boolean, updateChart: boolean): void; + /** + * Removes specified axis from axis Array. + */ + remove(): void; + /** + * Adds a new element of given type to the specified array. For example, it can be used to add new stripLine to stripLines array. + * @param propertyName Name of the property. + * @param options Option for the new element. + * @param index Index of the array where the new element is to be added. Defaults to the length (end) of array. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + addTo(propertyName: string, options: ChartStripLinesOptions, index?: number, updateChart?: boolean): void; + /** + * Return the pixel coordinate of the given value over axis. + * @param value Numeric value over Axis + */ + convertValueToPixel(value: number): number; + /** + * Return the value along Axis for given pixel coordinate. + * @param pixel pixel value over Axis + */ + convertPixelToValue(pixel: number): number; + } + interface ChartAxisYOptions extends ChartAxisXOptions { + /** + * When includeZero is set to true, axisY sets the range in such a way that Zero is a part of it. It is set to true by default. + * But, whenever y values are very big and difference among dataPoints are hard to judge, + * setting includeZero to false makes axisY to set a range that makes the differences prominently visible. + * Default: true + * Example: true, false + */ + includeZero?: boolean; + } + + interface ChartAxisY extends ChartAxisYOptions { + /** + * Returns the specified property of Axis. + * @param propertyName Name of the property. + */ + get(propertyName: string): string | number | boolean; + /** + * Sets the specified property of Axis. + * @param propertyName Name of the property. + * @param value value to be set on property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: string | number | boolean, updateChart: boolean): void; + /** + * Removes specified axis from axis Array. + */ + remove(): void; + /** + * Adds a new element of given type to the specified array. For example, it can be used to add new stripLine to stripLines array. + * @param propertyName Name of the property. + * @param options Option for the new element. + * @param index Index of the array where the new element is to be added. Defaults to the length (end) of array. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + addTo(propertyName: string, options: ChartStripLinesOptions, index?: number, updateChart?: boolean): void; + /** + * Return the pixel coordinate of the given value over axis. + * @param value Numeric value over Axis + */ + convertValueToPixel(value: number): number; + /** + * Return the value along Axis for given pixel coordinate. + * @param pixel pixel value over Axis + */ + convertPixelToValue(pixel: number): number; } interface ChartToolTipOptions { /** - * Enables or Disables the toolTip for the chart. - * Default: True - * Example: True, False - */ - enabled?: boolean; - /** - * In a Multi-Series or a Combination Chart, it is often required to display all values common to x value in a single bubble. Setting shared to true will show in a common bubble all the values of y from each series next to their name. - * Default: True - * Example: True, False - */ - shared?: boolean; - /** - * toolTip for entire chart can be set by adding content at toolTip object. content can either be a string or a custom function that returns HTML/String to be displayed inside the toolTip. - * Default: auto - */ - content?: string; - /** - * While mouse hovers from one dataPoint to another there is a smooth transition in toolTip. This effect can be controlled by animationEnabled Property. Setting it to false, will disable the animation and toolTip will directly switch from one dataPoint to the other. - * Default: True - * Example: True, False - */ + * While mouse hovers from one dataPoint to another there is a smooth transition in toolTip. + * This effect can be controlled by animationEnabled Property. Setting it to false, will disable the animation and toolTip will directly switch from one dataPoint to the other. + * Default: True + * Example: True, False + */ animationEnabled?: boolean; /** - * Sets the border color around Tool Tip. When not set it takes the color of corresponding dataSeries or dataPoint. - * Default: dataSeries color/ dataPoint color - * Example: "red", "#808080".. - */ + * Enables or Disables the toolTip for the chart. + * Default: True + * Example: True, False + */ + enabled?: boolean; + /** + * In a Multi-Series or a Combination Chart, it is often required to display all values common to x value in a single bubble. + * Setting shared to true will show in a common bubble all the values of y from each series next to their name. + * Default: True + * Example: True, False + */ + shared?: boolean; + /** + * Sets the border color around Tool Tip. When not set it takes the color of corresponding dataSeries or dataPoint. + * Default: dataSeries color/ dataPoint color + * Example: "red", "#808080".. + */ borderColor?: string; + /** + * toolTip for entire chart can be set by adding content at toolTip object. + * content can either be a string or a custom function that returns HTML/String to be displayed inside the toolTip. + * Default: auto + */ + content?: string; + /** + * Sets the Font Color of toolTipContent. The value of fontColor can be a “HTML Color Name” or “hex” code. + * Default: “black” + * Example: “red”, “#FAC003″ .. + */ + fontColor?: string; + /** + * Sets the Font Style of ToolTip Content. It can be set to one of the below options. + * Default: “italic” + * Example: “normal”, “italic” , “oblique” + */ + fontStyle?: string; + /** + * Sets the font Size of ToolTip Content in pixels. + * Default: 14 + * Example: 16,18,22 .. + */ + fontSize?: number; + /** + * Sets the Font Family of ToolTip Content. + * Default: “Calibri, Arial, Georgia, serif” + * Example: “arial” , “tahoma”, “verdana” .. + */ + fontFamily?: string; + /** + * Set the font Weight of ToolTip Content. + * Default: “normal” + * Example: “lighter”, “normal”, “bold” , “bolder” + */ + fontWeight?: string; + /** + * Sets the thickness of border around the toolTip in pixels. To display border around toolTip, set the borderThickness to a number greater than zero. Setting it to zero removes the border. + * Default: 2 + * Example: 2,4 .. + */ + borderThickness?: number; + /** + * Setting a value higher than 0 makes the corners of toolTip rounded. Higher the value, more rounded the corners are. + * Default: 5 + * Options: 2,3,8 .. + */ + cornerRadius?: number; + /** + * Reverses the order in which items inside toolTip are shown. + * Default: false + * Example: true, false + */ + reversed?: boolean; + /** + * A custom formatter function that returns the content (text/html) to be displayed inside the toolTip. + */ + contentFormatter?(e: { chart: Chart, toolTip: ChartToolTipOptions, entries: Array<{ dataPoint: ChartDataPoint, dataSeries: ChartDataSeriesOptions }> }): string; + /** + * Sets the background color of toolTip. Values can be “HTML Color Name” or “hex” code. + * Default: white + * Example: “red”, “#FF0000” .. + */ + backgroundColor?: string; + } + + interface ChartToolTip extends ChartToolTipOptions { + /** + * Returns the specified property of legend. + * @param propertyName Name of the property. + */ + get(propertyName: string): number | string | boolean; + /** + * Sets the specified property of legend. + * @param propertyName Name of the property. + * @param value Name of the property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: number | string | boolean, updateChart?: boolean): void; } interface ChartDataCommon { /** - * Sets the dataPoint Name. dataPoint name is shown in various places like toolTip & legend unless overridden. - * Default: Automatically Named ("dataPoint 1", "dataPoint 2" .. ) - * Example: "apple", "mango" .. - */ + * Sets the dataPoint Name. dataPoint name is shown in various places like toolTip & legend unless overridden. + * Default: Automatically Named ("dataPoint 1", "dataPoint 2" .. ) + * Example: "apple", "mango" .. + */ name?: string; /** - * Sets the color of dataSeries. The value of tickColor can be a "HTML Color Name" or "Hex Code". - * Default: Automatically set from Theme. - * Example: "red", "green" .. - */ + * Sets the color of dataSeries. The value of tickColor can be a "HTML Color Name" or "Hex Code". + * Default: Automatically set from Theme. + * Example: "red", "green" .. + */ color?: string; /** - * Instead of setting string values for all indexLabels, you can also use keywords like x, y, etc that will automatically show corresponding properties as indexLabel. This will allow you to define indexLabel at the series level once. While setting indexLabel you specify a keyword by enclosing it in flower brackets like {x}, {y}, {color}, etc. - * Range Charts have two indexLabels – one for each y value. This requires the use of a special keyword #index to show index label on either sides of the column/bar/area. - * eg: indexLabel: "{x}: {y[#index]}" - * Important keywords to keep in mind are. {x}, {y}, {name}, {label}. - * Default: null - * Example: "{label}", "Win", "x: {x}, y: {y} " - */ + * Enables or Disables highlighting of dataPoints on mouse hover. + * Default: true + * Example: true,false + */ + highlightEnabled?: boolean; + /** + * Instead of setting string values for all indexLabels, you can also use keywords like x, y, etc that will automatically show corresponding properties as indexLabel. + * This will allow you to define indexLabel at the series level once. While setting indexLabel you specify a keyword by enclosing it in flower brackets like {x}, {y}, {color}, etc. + * Range Charts have two indexLabels – one for each y value. This requires the use of a special keyword #index to show index label on either sides of the column/bar/area. + * eg: indexLabel: "{x}: {y[#index]}" + * Important keywords to keep in mind are. {x}, {y}, {name}, {label}. + * Default: null + * Example: "{label}", "Win", "x: {x}, y: {y} " + */ indexLabel?: string; /** - * Using this property you can define whether to render indexLabel "inside" or "outside" the dataPoint. - * Default: "outside" - * Example: "outside", "inside" - */ + * Sets the Dash Type for indexLabel’s line. It is applicable only for pie and doughnut charts when indexLabelPlacement is set to “outside”. + * For other chart-types, indexLabelLineThickness should be set greater than zero. + * Default: solid + */ + indexLabelLineDashType?: DashType; + /** + * A custom formatter function which returns the text to be displayed as indexLabel on dataPoints. + * @param e event object + */ + indexLabelFormatter?(e: { chart: Chart, dataSeries: ChartDataSeriesOptions, dataPoint: ChartDataPoint, index?: number, total?: number, pencent?: number }): string; + /** + * Using this property you can define whether to render indexLabel "inside" or "outside" the dataPoint. + * Default: "outside" + * Example: "outside", "inside" + */ indexLabelPlacement?: string; /** - * Sets the Orientation of indexLabel to "horizontal" or "vertical". - * Default: "horizontal" - * Options: "horizontal", "vertical" - */ + * Sets the Orientation of indexLabel to "horizontal" or "vertical". + * Default: "horizontal" + * Options: "horizontal", "vertical" + */ indexLabelOrientation?: string; /** - * Sets the Background color of Index Labels. The value of indexLabelBackgroundColor can be a "HTML Color Name" or "Hex Code". - * Default: null - * Example: "red", "#FAC003" .. - */ + * Sets the Background color of Index Labels. The value of indexLabelBackgroundColor can be a "HTML Color Name" or "Hex Code". + * Default: null + * Example: "red", "#FAC003" .. + */ indexLabelBackgroundColor?: string; /** - * Sets the Index Label’s Font Style. It can be set to one of the below options. - * Default: "normal" - * Options: "italic", "oblique", "normal" - */ + * Sets the Index Label’s Font Style. It can be set to one of the below options. + * Default: "normal" + * Options: "italic", "oblique", "normal" + */ indexLabelFontStyle?: string; /** - * Sets the Index Label’s Font color. The value of IndexLabelFontColor can be a "HTML Color Name" or "Hex Code". - * Default: "grey" - * Example: "red", "#FAC003" .. - */ + * Sets the Index Label’s Font color. The value of IndexLabelFontColor can be a "HTML Color Name" or "Hex Code". + * Default: "grey" + * Example: "red", "#FAC003" .. + */ indexLabelFontColor?: string; /** - * Sets the Index Label’s Font Size in pixels. - * Default: 18 - * Example: 12, 16, 22.. - */ + * Sets the Index Label’s Font Size in pixels. + * Default: 18 + * Example: 12, 16, 22.. + */ indexLabelFontSize?: number; /** - * Sets the Index Label’s Font Family. - * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" - * Example: "calibri", "tahoma", "verdana".. - */ + * Sets the Index Label’s Font Family. + * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" + * Example: "calibri", "tahoma", "verdana".. + */ indexLabelFontFamily?: string; /** - * Sets the Index Label’s Font Weight. It can be set to one of the below options. - * Default: "normal" - * Example: "lighter", "normal" ,"bold" , "bolder" - */ + * Sets the Index Label’s Font Weight. It can be set to one of the below options. + * Default: "normal" + * Example: "lighter", "normal" ,"bold" , "bolder" + */ indexLabelFontWeight?: string; /** - * Sets the color of line connecting index labels with their dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacment is outside. The value of indexLineColor can be a "HTML Color Name" or "Hex Code". - * Default: "lightgrey" - * Example: "red", "#FAC003" .. - */ + * Sets the color of line connecting index labels with their dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacment is outside. + * The value of indexLineColor can be a "HTML Color Name" or "Hex Code". + * Default: "lightgrey" + * Example: "red", "#FAC003" .. + */ indexLabelLineColor?: string; /** - * Sets the thickness of line connecting indexLabel with its corresponding dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacement is set to "outside". - * Default: 2 - * Example: 4, 6 - */ - indexLabelLineThickness?: string; + * Sets the thickness of line connecting indexLabel with its corresponding dataPoint. + * It is only applicable for pie and doughnut chart when indexLabelPlacement is set to "outside". + * Default: 2 + * Example: 4, 6 + */ + indexLabelLineThickness?: number; /** - * Default Tooltip can be modified at dataSeries or dataPoint level. You can add content to be displayed in toolTip using toolTipContent. toolTipContent set at dataPoint will override toolTipContent set at dataSeries level. - * Default: auto set depending on chart type. - */ + * Default Tooltip can be modified at dataSeries or dataPoint level. You can add content to be displayed in toolTip using toolTipContent. + * toolTipContent set at dataPoint will override toolTipContent set at dataSeries level. + * Default: auto set depending on chart type. + */ toolTipContent?: string; /** - * Sets marker type to be rendered at each dataPoint. While markers are helpful in highlighting individual dataPoints, they do not help much when the dataPoints are crowded. In case of large number of dataPoints it is recommended to disable markers in order to improve the appearance and performance of chart. - * Same marker type is also used in legend unless overridden by legendMarkerType property. - * Default: "circle" - * Options: "none", "circle", "square", "triangle" and "cross" - */ + * Sets marker type to be rendered at each dataPoint. While markers are helpful in highlighting individual dataPoints, they do not help much when the dataPoints are crowded. + * In case of large number of dataPoints it is recommended to disable markers in order to improve the appearance and performance of chart. + * Same marker type is also used in legend unless overridden by legendMarkerType property. + * Default: "circle" + * Options: "none", "circle", "square", "triangle" and "cross" + */ markerType?: string; /** - * Sets the color of marker that is displayed on the Chart. Legend Marker for the series uses the same Color as set here unless overridden using legendMarkerColor property. - * Default: dataSeries Color - * Example: "red", "#008000" .. - */ + * Sets the color of marker that is displayed on the Chart. Legend Marker for the series uses the same Color as set here unless overridden using legendMarkerColor property. + * Default: dataSeries Color + * Example: "red", "#008000" .. + */ markerColor?: string; /** - * Sets the Size of the marker that is drawn. To display marker in area Chart, set markerSize to a value greater than zero. For line, scatter chart, size it is automatically set unless overridden. - * Default: auto. Zero for area chart - * Example: 5, 10.. - */ + * Sets the Size of the marker that is drawn. To display marker in area Chart, set markerSize to a value greater than zero. + * For line, scatter chart, size it is automatically set unless overridden. + * Default: auto. Zero for area chart + * Example: 5, 10.. + */ markerSize?: number; /** - * Sets the border color around marker. Value of markerBorderColor can be "HTML Color Name" or "hex code". - * Default: dataSeries color. - * Example: "red", "#008000" .. - */ + * Sets the border color around marker. Value of markerBorderColor can be "HTML Color Name" or "hex code". + * Default: dataSeries color. + * Example: "red", "#008000" .. + */ markerBorderColor?: string; /** - * Sets the thickness of the Marker’s Border in pixels. - * Default: 1 - * Example: 2,4 .. - */ + * Sets the thickness of the Marker’s Border in pixels. + * Default: 1 + * Example: 2,4 .. + */ markerBorderThickness?: number; /** - * Sets the text that describes the dataSeries in legend. - * Default: "DataSeries 1", "DataSeries 2" ..etc - * Example: "2010", "2011".. - */ + * Sets the text that describes the dataSeries in legend. + * Default: "DataSeries 1", "DataSeries 2" ..etc + * Example: "2010", "2011".. + */ legendText?: string; /** - * Sets the Legend Marker to one of the options below. This property is used to override the default marker in legend, which is same as dataSeries Marker Type. - * Default: same as markerType - * Options: "circle", "square", "cross" and "triangle" - */ + * Sets the Legend Marker to one of the options below. This property is used to override the default marker in legend, which is same as dataSeries Marker Type. + * Default: same as markerType + * Options: "circle", "square", "cross" and "triangle" + */ legendMarkerType?: string; /** - * Sets the click event handler for dataSeries which is triggered when user clicks on a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. - * Default: null - */ - click?: (event: ChartEvent) => void; - /** - * Sets the color of marker that is displayed on legend. This property overrides default Marker’s Color in Legend, which is same as dataSeries Marker Color. Value of legendMarkerColor can be "HTML Color Name" or "hex code". - * Default: dataSeries marker color - * Example: "red", "#008000" .. - */ + * Sets the color of marker that is displayed on legend. This property overrides default Marker’s Color in Legend, which is same as dataSeries Marker Color. + * Value of legendMarkerColor can be "HTML Color Name" or "hex code". + * Default: dataSeries marker color + * Example: "red", "#008000" .. + */ legendMarkerColor?: string; /** - * Sets the mouseover event handler for dataSeries which is triggered when user moves Mouse Over a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. - * Default: null - */ - mouseover?: (event: ChartEvent) => void; + * Sets the border color around the legend marker. Value of legendMarkerBorderColor can be “color names” or “hex code”. + * Default: dataSeries color. + * Example: “red”, “#008000” .. + */ + legendMarkerBorderColor?: string; /** - * Sets the mousemove event handler for dataSeries which is triggered when user Moves mouse on a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. - * Default: null - */ - mousemove?: (event: ChartEvent) => void; + * Sets the thickness of the legend’s Marker Border in pixels. + * Default: 0 + * Example: 2, 4 .. + */ + legendMarkerBorderThickness?: number; /** - * Sets the mouseout event handler for dataSeries which is triggered when user moves mouse out of a dataSeries. Upon event, a parameter that contains event related data is sent to the assigned event handler. Parameter includes dataPoint and dataSeries corresponding to the event. - * Default: null - */ - mouseout?: (event: ChartEvent) => void; + * Sets the click event handler for dataSeries which is triggered when user clicks on a dataSeries. + * Upon event, a parameter that contains event related data is sent to the assigned event handler. + * Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + click?(event: ChartEvent): void; + /** + * Sets the mouseover event handler for dataSeries which is triggered when user moves Mouse Over a dataSeries. + * Upon event, a parameter that contains event related data is sent to the assigned event handler. + * Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + mouseover?(event: ChartEvent): void; + /** + * Sets the mousemove event handler for dataSeries which is triggered when user Moves mouse on a dataSeries. + * Upon event, a parameter that contains event related data is sent to the assigned event handler. + * Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + mousemove?(event: ChartEvent): void; + /** + * Sets the mouseout event handler for dataSeries which is triggered when user moves mouse out of a dataSeries. + * Upon event, a parameter that contains event related data is sent to the assigned event handler. + * Parameter includes dataPoint and dataSeries corresponding to the event. + * Default: null + */ + mouseout?(event: ChartEvent): void; } - interface ChartDataOptions extends ChartDataCommon { + interface ChartDataSeriesOptions extends ChartDataCommon { /** - * Sets the visibility of dataSeries. Data Series is visible by default and you can hide the same by setting visible property to false. - * Default: true - * Example: true, false - */ + * Sets the visibility of dataSeries. Data Series is visible by default and you can hide the same by setting visible property to false. + * Default: true + * Example: true, false + */ visible?: boolean; /** - * Sets the type of chart to be rendered for corresponding dataSeries. One can choose from the following options. - * Default: "column" - * Options: - * "line" - * "column" - * "bar" - * "area" - * "spline" - * "splineArea" - * "stepLine" - * "scatter" - * "bubble" - * "stackedColumn" - * "stackedBar" - * "stackedArea" - * "stackedColumn100" - * "stackedBar100" - * "stackedArea100" - * "pie" - * "doughnut" - */ + * Sets the type of chart to be rendered for corresponding dataSeries. One can choose from the following options. + * Default: "column" + * Options: + * "line" + * "column" + * "bar" + * "area" + * "spline" + * "splineArea" + * "stepLine" + * "scatter" + * "bubble" + * "stackedColumn" + * "stackedBar" + * "stackedArea" + * "stackedColumn100" + * "stackedBar100" + * "stackedArea100" + * "pie" + * "doughnut" + */ type?: string; /** - * Setting axisYType lets you choose between primary and secondary Y Axis for a dataSeries to plot against. By choosing "secondary" Axis you can plot the series against axisY2. - * In case of Multi-Series or Combinational Charts, one can assign primary axis to some series and secondary axis to other series. - * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against primary Y axis. - * Default: "primary" - * Options: "primary", "secondary" - */ + * Setting axisXType lets you choose between primary and secondary X Axis for a dataSeries to plot against. By choosing “secondary” Axis you can plot the series against axisX2. + * In case of Multi-Series or Combinational Charts, one can assign primary axis to some series and secondary axis to other series. + * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against primary X axis. + */ + axisXType?: string; + /** + * Setting axisYType lets you choose between primary and secondary Y Axis for a dataSeries to plot against. By choosing "secondary" Axis you can plot the series against axisY2. + * In case of Multi-Series or Combinational Charts, one can assign primary axis to some series and secondary axis to other series. + * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against primary Y axis. + * Default: "primary" + * Options: "primary", "secondary" + */ axisYType?: string; /** - * This defines the data type of x values. Data Type is normally figured out by default based on the object type that is assigned to x. But if you are providing time stamp (which is integer) values instead of Date objects, you’ll have to explicitly set the xValueType to "dateTime". - * Default: Automatically Calculated - * Options: "number", "dateTime" - */ + * Setting axisXIndex lets you choose to which X axis the dataSeries should be attached. + * In case of Multi-Series or Combinational Charts, one can assign some series to first X axis and rest to another axis. + * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against first axis. + */ + axisXIndex?: number; + /** + * Setting axisYIndex lets you choose to which Y axis the dataSeries should be attached to. + * In case of Multi-Series or Combinational Charts, one can assign some series to first Y axis and rest to another axis. + * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against first axis. + */ + axisYIndex?: number; + /** + * This defines the data type of x values. Data Type is normally figured out by default based on the object type that is assigned to x. + * But if you are providing time stamp (which is integer) values instead of Date objects, you’ll have to explicitly set the xValueType to "dateTime". + * Default: Automatically Calculated + * Options: "number", "dateTime" + */ xValueType?: string; /** - * Defines how y axis values must be formatted before they appear on the indexLabel or toolTip. You can format numbers and date time values using this property. - */ + * Defines how y axis values must be formatted before they appear on the indexLabel or toolTip. You can format numbers and date time values using this property. + */ yValueFormatString?: string; /** - * Defines how x axis values must be formatted before they appear on the indexLabel or toolTip. You can format numbers and date time values using this property. - */ + * Defines how x axis values must be formatted before they appear on the indexLabel or toolTip. You can format numbers and date time values using this property. + */ xValueFormatString?: string; /** - * Defines how z values is formatted before they appear on the indexLabel or toolTip. You can format numbers using this property. - */ + * Defines how z values is formatted before they appear on the indexLabel or toolTip. You can format numbers using this property. + */ zValueFormatString?: string; /** - * Sets the bevel property, which creates a chiselled effect at the corners of a Column Charts and Bar Charts. - * Default: "true" - * Example: "true", "false" - */ + * Defines how percent values are formatted before they appear on the indexLabel or toolTip. You can format percent values using this property. + */ + percentFormatString?: string; + /** + * Sets the bevel property, which creates a chiselled effect at the corners of a Column Charts and Bar Charts. + * Default: "true" + * Example: "true", "false" + */ bevelEnabled?: boolean; /** - * Sets opacity of the filled color. - * Default: .7 for Area Charts and 1 for all other chart types. - */ + * Sets opacity of the filled color. + * Default: .7 for Area Charts and 1 for all other chart types. + */ fillOpacity?: number; /** - * Sets the starting Angle of the Pie or Doughnut Chart in degrees. - * Default: 0 - * Example: 30, 240, -100.. - */ + * Sets the starting Angle of the Pie or Doughnut Chart in degrees. + * Default: 0 + * Example: 30, 240, -100.. + */ startAngle?: number; /** - * Sets the thickness of line in line charts and area charts. - * Default: 2 - * Example: 3,4.. - */ + * innerRadius property allows you to set a Doughnut chart’s inner radius. + * Value can either be in pixels (number – ex: 100) or percent (string – ex: “80%”). Percent values are relative to the outer radius of doughnut chart. + * Default: “70%” + * Example: 200, 150, “90%”, “75%” + */ + innerRadius?: number | string; + /** + * radius property allows you to set the Pie/Doughnut chart’s (outer) radius. + * Value can either be in pixels (number – ex: 100) or percent (string – ex: “80%”). Percent values are relative to the plot area’s size. + * By default, a pie/doughnut chart’s size(radius) changes in order to best fit the indexLabels. This can lead to charts of different sizes in the same page. + * In order to override this behavior and set equal sizes to all pie/doughnut charts in a page, you can use radius property. + * Default: Automatically calculate in order to best fit the indexLabels. + * Example: 200, 150, “90%”, “75%” + */ + radius?: number | string; + /** + * Sets the thickness of line in line charts and area charts. + * Default: 2 + * Example: 3,4.. + */ lineThickness?: number; /** - * Setting this property to true makes the dataSeries to appear in legend. In case of pie/ doughnut chart, dataPoints of the single series chart appear in legend. - * Default: false - * Options: false, true - */ + * Setting this property to true makes the dataSeries to appear in legend. In case of pie/ doughnut chart, dataPoints of the single series chart appear in legend. + * Default: false + * Options: false, true + */ showInLegend?: boolean; /** - * In candle Stick chart, when Closing Price is greater than Opening price, the body is filled with white by default and it can be overridden by risingColor property. - * Default: "white" - * Options: "red", "#DD7E86", etc. - */ + * Enables or disables exploding of Pie/Doughnut segment on click. + * Default: true + * Options: false, true + */ + explodeOnClick?: boolean; + /** + * In candle Stick chart, when Closing Price is greater than Opening price, the body is filled with white by default and it can be overridden by risingColor property. + * Default: "white" + * Options: "red", "#DD7E86", etc. + */ risingColor?: string; /** - * It represents collection dataPoint inside dataSeries . - */ + * It represents collection dataPoint inside dataSeries. + */ dataPoints: ChartDataPoint[]; + /** + * By default, a line breaks wherever a null dataPoint (y = null) is present. + * You can change this behaviour to draw a line between adjacent non-null dataPoints by setting connectNullData to true. + * Default: false + * Example: true, false + */ + connectNullData?: boolean; + /** + * Sets the Line Dash Type for all Line and Area Charts. + * Default: solid + */ + lineDashType?: DashType; + /** + * Sets the Line Dash Type of line wherever null data is present. + * Note: + * 1.Will effect only if connectNullData is set to true. + * 2.Supported with all Line and Area Charts. + * 3.Not Supported on IE8. + * Default: "dash" + */ + nullDataLineDashType?: DashType; + } + + interface ChartDataSeries extends ChartDataSeriesOptions { + /** + * Returns the specified property of dataSeries + * @param propertyName Name of the property. + */ + get(propertyName: string): boolean | string | number | ChartDataPoint; + /** + * Sets the specified property of dataSeries. + * @param propertyName Name of the property. + * @param value value to be set on property. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + set(propertyName: string, value: boolean | string | number | ChartDataPoint, updateChart: boolean): void; + /** + * Adds a new element of given type to the specified array. For example, it can be used to add new dataPoint to datPoints array. + * @param propertyName Name of the property + * @param options Option for the new element + * @param index Index of the array where the new element is to be added. Defaults to the length (end) of array. + * @param updateChart When true, Updates the chart automatically after setting the value. Defaults to true. + */ + addTo(propertyName: string, options: ChartDataPoint, index?: number, updateChart?: boolean): void; + /** + * Removes specified dataSeries from data Array. + */ + remove(): void; } interface ChartDataPoint extends ChartDataCommon { /** - * Sets the x value. It determines the position of the dataPoint on X Axis. It can be numeric or a dateTime value. Values can be positive or Negative. - * Default: null - * Example: 10, 20, 30 .. - * new Date(2011, 08, 01) - */ - x?: any; + * Sets the x value. It determines the position of the dataPoint on X Axis. It can be numeric or a dateTime value. Values can be positive or Negative. + * If no x value is provided, they are automatically set sequentially starting from zero + * Default: null + * Example: 10, 20, 30 .. + * new Date(2011, 08, 01) + */ + x?: number | Date; /** - * Sets the y value of dataPoint. It determines the position of dataPoint on Y Axis. Values can be positive or Negative - * Default: null - * Example: 5, 20, -30 .. - */ - y?: number; + * Sets the y value of dataPoint. It determines the position of dataPoint on Y Axis. Values can be positive or Negative + * Default: null + * Example: 5, 20, -30 .. + */ + y?: number | null; /** - * Sets the z value of dataPoint. It is only applicable in case of Bubble chart. This value determines the size of the bubble. - * Default: 1 - * Example: 10, 20, 35.. - */ + * Sets the z value of dataPoint. It is only applicable in case of Bubble chart. This value determines the size of the bubble. + * Default: 1 + * Example: 10, 20, 35.. + */ z?: number; /** - * Sets label value of a dataPoint. The value appears next to the dataPoint on axisX Line. If not provided, it takes x value for label. - * Default: x value - * Example: "label1", "label2".. - */ + * Sets label value of a dataPoint. The value appears next to the dataPoint on axisX Line. If not provided, it takes x value for label. + * Default: x value + * Example: "label1", "label2".. + */ label?: string; /** - * Sets the exploded value of dataPoint. It is applicable only in case of Pie and Doughnut Charts. This property causes the Pie/Doughnut slice to separate out. - * Default: true - * Example: true, false - */ + * Sets the exploded value of dataPoint. It is applicable only in case of Pie and Doughnut Charts. This property causes the Pie/Doughnut slice to separate out. + * Default: true + * Example: true, false + */ exploded?: boolean; - /** - * Sets the color of marker that is displayed on legend. This property works only with Pie and Doughnut charts. Value of legendMarkerColor can be "HTML Color Name" or "hex" code. - * Default: dataSeries marker color - * Example: "red", "#008000".. - */ - legendMarkerColor?: string; } } +declare function CanvasJS(): void; +export = CanvasJS; +export as namespace CanvasJS; diff --git a/types/canvasjs/tsconfig.json b/types/canvasjs/tsconfig.json index 218036fa08..459ca95138 100644 --- a/types/canvasjs/tsconfig.json +++ b/types/canvasjs/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "canvasjs-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/canvasjs/tslint.json b/types/canvasjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/canvasjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/capitalize/index.d.ts b/types/capitalize/index.d.ts index b844784757..660592cfa6 100644 --- a/types/capitalize/index.d.ts +++ b/types/capitalize/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for capitalize 1.0 // Project: https://github.com/grncdr/js-capitalize -// Definitions by: Frederick Fogerty +// Definitions by: Frederick Fogerty // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 diff --git a/types/capitalize/tslint.json b/types/capitalize/tslint.json index 2750cc0197..939faba9c2 100644 --- a/types/capitalize/tslint.json +++ b/types/capitalize/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } \ No newline at end of file +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-duplicate-imports": false + } +} \ No newline at end of file diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 1f7f2fe33d..4b9d6a7d9d 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for nodejs-driver v0.8.2 // Project: https://github.com/datastax/nodejs-driver -// Definitions by: Marc Fisher +// Definitions by: Marc Fisher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -508,6 +508,7 @@ export interface Client extends events.EventEmitter { batch(queries: Array | Array<{ query: string, params?: any }>, options: QueryOptions, callback: ResultCallback): void; connect(callback: Callback): void; eachRow(query: string, params?: any, options?: QueryOptions, rowCallback?: Callback, callback?: Callback): void; + execute(query: string, params?: any, callback?: ResultCallback): void; execute(query: string, params?: any, options?: QueryOptions, callback?: ResultCallback): void; getReplicas(keyspace: string, token: Buffer): Array; // TODO: Should this be a more explicit return? shutdown(callback?: Callback): void; diff --git a/types/catbox/catbox-tests.ts b/types/catbox/catbox-tests.ts new file mode 100644 index 0000000000..565573adad --- /dev/null +++ b/types/catbox/catbox-tests.ts @@ -0,0 +1,27 @@ +import Catbox = require("catbox"); + +const Memory: Catbox.EnginePrototypeOrObject = { + start(callback: Catbox.CallBackNoResult) {}, + stop() {}, + get() {}, + set() {}, + drop() {}, + isReady(): boolean { return true; }, + validateSegmentName(segment: string): null { return null; }, +}; + +const client = new Catbox.Client(Memory, { partition: 'cache' }); + +const cache = new Catbox.Policy({ + expiresIn: 5000, +}, client, 'cache'); + +cache.set('foo', 'bar', 5000, () => {}); + +cache.get('foo', () => {}); + +cache.drop('foo', () => {}); + +cache.isReady(); + +cache.stats(); diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 5dad5af29a..7bc691abdc 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -1,17 +1,13 @@ // Type definitions for catbox 7.1 // Project: https://github.com/hapijs/catbox -// Definitions by: Jason Swearingen , AJP +// Definitions by: Jason Swearingen , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as Boom from 'boom'; -export interface CallBackNoResult { - (err?: Boom.BoomError): void; -} -export interface CallBackWithResult { - (err: Boom.BoomError | null | undefined, result: T): void; -} +export type CallBackNoResult = (err?: Boom.BoomError) => void; +export type CallBackWithResult = (err: Boom.BoomError | null | undefined, result: T) => void; /** * Client @@ -20,14 +16,44 @@ export interface CallBackWithResult { * * function - a prototype function with the signature function(options). catbox will call new func(options). * * object - a pre instantiated client implementation object. Does not support passing options. * options - the strategy configuration object. Each strategy defines its own configuration options with the following common options: - * * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. + * * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, + * the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. * @see {@link https://github.com/hapijs/catbox#client} */ -export interface Client extends ClientApi { - new(engine: EnginePrototypeOrObject, options: ClientOptions): Client; +export class Client implements ClientApi { + constructor(engine: EnginePrototypeOrObject, options: ClientOptions); + + /** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */ + start(callback: CallBackNoResult): void; + /** stop() - terminates the connection to the cache server. */ + stop(): void; + /** + * get(key, callback) - retrieve an item from the cache engine if found where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned + */ + get(key: CacheKey, callback: CallBackWithResult): CacheItem; + /** + * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: + * * key - a cache key object (see [ICacheKey]). + * * value - the string or object value to be stored. + * * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * * callback - a function with the signature function(err). + */ + set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void; + /** + * drop(key, callback) - remove an item from cache where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err). + */ + drop(key: CacheKey, callback: CallBackNoResult): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */ + isReady(): boolean; + /** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */ + validateSegmentName(segment: string): null | Boom.BoomError; } -type EnginePrototypeOrObject = EnginePrototype | ClientApi; +export type EnginePrototypeOrObject = EnginePrototype | ClientApi; /** * A prototype CatBox engine function @@ -50,7 +76,7 @@ export interface ClientApi { * get(key, callback) - retrieve an item from the cache engine if found where: * * key - a cache key object (see [ICacheKey]). * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned - */ + */ get(key: CacheKey, callback: CallBackWithResult): CacheItem; /** * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: @@ -92,21 +118,52 @@ export interface CachedObject { ttl: number; } -type CacheItem = any; +export type CacheItem = any; export interface ClientOptions { partition: string; } /** - * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. The object is constructed using new Policy(options, [cache, segment]) where: + * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. + * The object is constructed using new Policy(options, [cache, segment]) where: * * options - an object with the IPolicyOptions structure * * cache - a Client instance (which has already been started). * * segment - required when cache is provided. The segment name used to isolate cached items within the cache partition. * @see {@link https://github.com/hapijs/catbox#policy} */ -export interface Policy extends PolicyAPI { - new(options: PolicyOptions, cache: Client, segment: string): Policy; +export class Policy implements PolicyAPI { + constructor(options: PolicyOptions, cache: Client, segment: string); + /** + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. + * * callback - the return function. + */ + get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem; + /** + * set(id, value, ttl, callback) - store an item in the cache where: + * * id - the unique item identifier (within the policy segment). + * * value - the string or object value to be stored. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * callback - a function with the signature function(err). + */ + set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; + /** + * drop(id, callback) - remove the item from cache where: + * * id - the unique item identifier (within the policy segment). + * * callback - a function with the signature function(err). + */ + drop(id: string | {id: string}, callback: CallBackNoResult): void; + /** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */ + ttl(created: number): number; + /** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */ + rules(options: PolicyOptions): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */ + isReady(): boolean; + /** stats - an object with cache statistics */ + stats(): CacheStatisticsObject; } /** @@ -116,7 +173,8 @@ export interface Policy extends PolicyAPI { */ export interface PolicyAPI { /** - * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. * * callback - the return function. */ @@ -125,7 +183,8 @@ export interface PolicyAPI { * set(id, value, ttl, callback) - store an item in the cache where: * * id - the unique item identifier (within the policy segment). * * value - the string or object value to be stored. - * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * This should be set to 0 in order to use the caching rules configured when creating the Policy object. * * callback - a function with the signature function(err). */ set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; @@ -152,9 +211,7 @@ export interface PolicyAPI { * @param cached - null if a valid item was not found in the cache, or IPolicyGetCallbackCachedOptions * @param report - an object with logging information about the generation operation */ -export interface PolicyGetCallback{ - (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog): void; -} +export type PolicyGetCallback = (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog) => void; export interface PolicyGetCallbackCachedOptions { /** item - the cached value. */ @@ -178,14 +235,19 @@ export interface PolicyOptions { /** generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: */ generateFunc?: GenerateFunc; /** - * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: + * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. + * Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: * * stored - the timestamp when the item was stored in the cache (in milliseconds). * * ttl - the remaining time-to-live (not the original value used when storing the object). - */ + */ staleIn?: number | ((stored: number, ttl: number) => number); /** staleTimeout - number of milliseconds to wait before returning a stale value while generateFunc is generating a fresh value. */ staleTimeout?: number; - /** generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. */ + /** + * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. + * When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. + * Set to false to disable timeouts which may cause all get() requests to get stuck forever. + */ generateTimeout?: number | false; /** dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. */ dropOnError?: boolean; @@ -193,7 +255,10 @@ export interface PolicyOptions { generateOnReadError?: boolean; /** generateIgnoreWriteError - if false, an upstream cache write error will be passed back with the generated value when calling the get() method. Defaults to true. */ generateIgnoreWriteError?: boolean; - /** pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. */ + /** + * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. + * Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. + */ pendingGenerateTimeout?: number; } @@ -208,9 +273,7 @@ export interface PolicyOptions { * * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. * @see {@link https://github.com/hapijs/catbox#policy} */ -export interface GenerateFunc { - (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)): void; -} +export type GenerateFunc = (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)) => void; /** * An object with logging information about the generation operation containing the following keys (as relevant): @@ -242,6 +305,6 @@ export interface CacheStatisticsObject { stales: number; /** generates - number of calls to the generate function. */ generates: number; - /** errors - cache operations errors. TODO check this*/ + /** errors - cache operations errors. TODO check this */ errors: number; } diff --git a/types/catbox/tsconfig.json b/types/catbox/tsconfig.json index 3bc13b0278..b04177a675 100644 --- a/types/catbox/tsconfig.json +++ b/types/catbox/tsconfig.json @@ -16,6 +16,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "catbox-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/catbox/tslint.json b/types/catbox/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/catbox/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai-arrays/chai-arrays-tests.ts b/types/chai-arrays/chai-arrays-tests.ts index 7fabaacbca..1562272240 100644 --- a/types/chai-arrays/chai-arrays-tests.ts +++ b/types/chai-arrays/chai-arrays-tests.ts @@ -1,14 +1,11 @@ -import { expect } from 'chai'; -import { assert } from 'chai'; - -import chai = require('chai'); +import { assert, expect, use, should } from 'chai'; import ChaiArrays = require('chai-arrays'); -chai.use(ChaiArrays); -chai.should(); +use(ChaiArrays); +should(); const arr: any[] = [1, 2, 3]; -const str: string = 'abcdef'; +const str = 'abcdef'; const otherArr: number[] = [1, 2, 3]; const anotherArr: number[] = [2, 4]; diff --git a/types/chai-arrays/index.d.ts b/types/chai-arrays/index.d.ts index d50be4f101..1e61eec3ae 100644 --- a/types/chai-arrays/index.d.ts +++ b/types/chai-arrays/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for chai-arrays 1.0 // Project: https://github.com/GaneshSPatil/chai-arrays -// Definitions by: Clément Prévot +// Definitions by: Clément Prévot // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/chai-datetime/index.d.ts b/types/chai-datetime/index.d.ts index c008586cfe..176d112dc0 100644 --- a/types/chai-datetime/index.d.ts +++ b/types/chai-datetime/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for chai-datetime // Project: https://github.com/gaslight/chai-datetime.git -// Definitions by: Cliff Burger +// Definitions by: Cliff Burger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/chai-http/chai-http-tests.ts b/types/chai-http/chai-http-tests.ts index 369e5b8ee3..7c1c7a6b42 100644 --- a/types/chai-http/chai-http-tests.ts +++ b/types/chai-http/chai-http-tests.ts @@ -1,6 +1,3 @@ -/// - - import fs = require('fs'); import http = require('http'); import chai = require('chai'); @@ -16,7 +13,7 @@ if (!global.Promise) { chai.request.addPromises(when.promise); } -var app: http.Server; +declare const app: http.Server; chai.request(app).get('/'); chai.request('http://localhost:8080').get('/'); @@ -42,7 +39,7 @@ chai.request(app) chai.request(app) .get('/search') - .query({name: 'foo', limit: 10}); + .query({ name: 'foo', limit: 10 }); chai.request(app) .put('/user/me') @@ -58,7 +55,7 @@ chai.request(app) .then((res: ChaiHttp.Response) => chai.expect(res).to.have.status(200)) .catch((err: any) => { throw err; }); -var agent = chai.request.agent(app); +const agent = chai.request.agent(app); agent .post('/session') @@ -72,7 +69,7 @@ agent }); function test1() { - var req = chai.request(app).get('/'); + const req = chai.request(app).get('/'); req.then((res: ChaiHttp.Response) => { chai.expect(res).to.have.status(200); chai.expect(res).to.have.header('content-type', 'text/plain'); @@ -94,9 +91,16 @@ function test1() { chai.expect(res).to.have.cookie('session_id', '1234'); chai.expect(res).to.not.have.cookie('PHPSESSID'); chai.expect(res.body).to.have.property('version', '4.0.0'); + chai.expect(res.text).to.equal(''); }, (err: any) => { throw err; }); } when(chai.request(app).get('/')).done(() => console.log('success'), () => console.log('failure')); + +Promise.resolve(1) + .then(val => chai.request(app).get(`/user/${val}`)) + .then(res => { + chai.expect(res).to.have.status(200); + }); diff --git a/types/chai-http/index.d.ts b/types/chai-http/index.d.ts index 2e619b6166..f0957cc454 100644 --- a/types/chai-http/index.d.ts +++ b/types/chai-http/index.d.ts @@ -1,85 +1,87 @@ -// Type definitions for chai-http +// Type definitions for chai-http 3.0 // Project: https://github.com/chaijs/chai-http // Definitions by: Wim Looman +// Liam Jones +// Federico Caselli // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// -declare namespace Chai { +declare global { + namespace Chai { + interface ChaiStatic { + request: ChaiHttpRequest; + } - 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 | 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; + } } - interface ChaiHttpRequest { - (server: any): ChaiHttp.Agent; - agent(server: any): ChaiHttp.Agent; - addPromises(promiseConstructor: any): void; - } + namespace ChaiHttp { + interface Promise { + then(onFulfilled: (value: T) => U, onRejected?: (reason: any) => U): Promise; + } - 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 Response { + body: any; + type: string; + status: number; + text: string; + } - interface TypeComparison { - ip: Assertion; + interface Request extends FinishedRequest { + attach(field: string, file: string|Buffer, filename: string): Request; + set(field: string, val: string): Request; + query(params: any): Request; + send(data: any): Request; + auth(user: string, name: string): Request; + field(name: string, val: string): Request; + buffer(): Request; + end(callback?: (err: any, res: Response) => void): FinishedRequest; + } + + interface FinishedRequest { + then(success?: (res: T) => TR1 | PromiseLike, failure?: (err: any) => TR2 | PromiseLike): 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 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; - buffer(): 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; -} +declare function chaiHttp(chai: any, utils: any): void; +export = chaiHttp; diff --git a/types/chai-http/tslint.json b/types/chai-http/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/chai-http/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai-jest-snapshot/chai-jest-snapshot-tests.ts b/types/chai-jest-snapshot/chai-jest-snapshot-tests.ts new file mode 100644 index 0000000000..05cf190765 --- /dev/null +++ b/types/chai-jest-snapshot/chai-jest-snapshot-tests.ts @@ -0,0 +1,23 @@ +import chaiJestSnapshot from 'chai-jest-snapshot'; +import { expect } from 'chai'; + +chai.use(chaiJestSnapshot); + +expect({}).to.matchSnapshot(); +expect({}).to.matchSnapshot(true); +expect({}).to.matchSnapshot("filename"); +expect({}).to.matchSnapshot("filename", "snapshotname"); +expect({}).to.matchSnapshot("filename", "snapshotname", false); + +const mockContext: Mocha.IBeforeAndAfterContext = { + currentTest: { + file: 'testfile', + fullTitle: () => 'fullTitle' + } +}; + +chaiJestSnapshot.setFileName("filename"); +chaiJestSnapshot.setTestName("testname"); +chaiJestSnapshot.configureUsingMochaContext(mockContext); +chaiJestSnapshot.resetSnapshotRegistry(); +chaiJestSnapshot.addSerializer({}); diff --git a/types/chai-jest-snapshot/index.d.ts b/types/chai-jest-snapshot/index.d.ts new file mode 100644 index 0000000000..f19158e282 --- /dev/null +++ b/types/chai-jest-snapshot/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for chai-jest-snapshot 1.3 +// Project: https://github.com/suchipi/chai-jest-snapshot#readme +// Definitions by: Matt Perry +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare global { + namespace Chai { + interface Assertion { + /** + * Assert that the object matches the snapshot + * @param snapshotFilename + * @param snapshotName + * @param update + */ + matchSnapshot(snapshotFilename?: string, snapshotName?: string, update?: boolean): Assertion; + matchSnapshot(update: boolean): Assertion; + } + } +} + +interface ChaiJestSnapshot { + /** + * Chai bootstrapper + * @param chai + * @param utils + */ + (chai: any, utils: any): void; + + /** + * Set snapshot file name + * @param filename + */ + setFileName(filename: string): void; + + /** + * Set snapshot test name + * @param testname + */ + setTestName(testname: string): void; + + /** + * Configure snapshot name using mocha context + * @param context + */ + configureUsingMochaContext(context: Mocha.IBeforeAndAfterContext): void; + + /** + * Reset snapshot registry + */ + resetSnapshotRegistry(): void; + + /** + * Add a serializer plugin + * @param serializer + */ + addSerializer(serializer: any): void; +} + +declare var ChaiJestSnapshot: ChaiJestSnapshot; +export default ChaiJestSnapshot; diff --git a/types/chai-jest-snapshot/tsconfig.json b/types/chai-jest-snapshot/tsconfig.json new file mode 100644 index 0000000000..32dea54632 --- /dev/null +++ b/types/chai-jest-snapshot/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "chai-jest-snapshot-tests.ts" + ] +} diff --git a/types/chai-jest-snapshot/tslint.json b/types/chai-jest-snapshot/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/chai-jest-snapshot/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai-jquery/index.d.ts b/types/chai-jquery/index.d.ts index 453336b08b..e1628f1743 100644 --- a/types/chai-jquery/index.d.ts +++ b/types/chai-jquery/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for chai-jquery 1.1.1 // Project: https://github.com/chaijs/chai-jquery -// Definitions by: Kazi Manzur Rashid +// Definitions by: Kazi Manzur Rashid // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/chai-json-schema/chai-json-schema-tests.ts b/types/chai-json-schema/chai-json-schema-tests.ts index 7273ac60cc..ee57572ae1 100644 --- a/types/chai-json-schema/chai-json-schema-tests.ts +++ b/types/chai-json-schema/chai-json-schema-tests.ts @@ -1,11 +1,8 @@ -import { expect } from 'chai'; -import { assert } from 'chai'; - -import chai = require('chai'); +import { assert, expect, use, should, tv4 } from 'chai'; import ChaiJsonSchema = require('chai-json-schema'); -chai.use(ChaiJsonSchema); -chai.should(); +use(ChaiJsonSchema); +should(); const goodApple = { skin: 'thin', @@ -63,5 +60,5 @@ const schema = { const data1 = [true, false]; const data2 = [true, 123]; -expect(chai.tv4.validate(data1, schema)).to.be.true; -expect(chai.tv4.validate(data2, schema)).to.be.false; +expect(tv4.validate(data1, schema)).to.be.true; +expect(tv4.validate(data2, schema)).to.be.false; diff --git a/types/chai-string/index.d.ts b/types/chai-string/index.d.ts index 1c880dc87e..fad380cf07 100644 --- a/types/chai-string/index.d.ts +++ b/types/chai-string/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for chai-string 1.1.4 // Project: https://github.com/onechiporenko/chai-string -// Definitions by: Nick Malaguti +// Definitions by: Nick Malaguti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/chai-subset/index.d.ts b/types/chai-subset/index.d.ts index 3e0818aa2b..615f9f52e4 100644 --- a/types/chai-subset/index.d.ts +++ b/types/chai-subset/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for chai-subset 1.3 // Project: https://github.com/e-conomic/chai-subset -// Definitions by: Sam Noedel , Andrew Brown +// Definitions by: Sam Noedel , Andrew Brown // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/chai-xml/chai-xml-tests.ts b/types/chai-xml/chai-xml-tests.ts index c217662316..afc867387e 100644 --- a/types/chai-xml/chai-xml-tests.ts +++ b/types/chai-xml/chai-xml-tests.ts @@ -9,7 +9,7 @@ function test_chaiXml() { expect('nope').xml.not.to.be.valid(); expect(testXml).xml.to.be.valid(); expect(testXml).xml.to.equal('\ntest\n'); - expect(testXml).xml.to.not.equal('' ); + expect(testXml).xml.to.not.equal(''); } test_chaiXml(); diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index 20f3c2b7df..bb730fe598 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -1,11 +1,12 @@ // Type definitions for chai 4.0.0 // Project: http://chaijs.com/ -// Definitions by: Jed Mao , +// Definitions by: Jed Mao , // Bart van der Schoor , // Andrew Brown , // Olivier Chevet , // Matt Wistrand , // Josh Goldberg +// Shaun Luttin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @@ -487,6 +488,24 @@ declare namespace Chai { */ isNotNaN(value: T, message?: string): void; + /** + * Asserts that the target is neither null nor undefined. + * + * @type T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + exists(value: T, message?: string): void; + + /** + * Asserts that the target is either null or undefined. + * + * @type T Type of value. + * @param value Actual value. + * @param message Message to display on error. + */ + notExists(value: T, message?: string): void; + /** * Asserts that value is undefined. * @@ -1318,6 +1337,29 @@ declare namespace Chai { * @param message Message to display on error. */ notFrozen(object: T, message?: string): void; + + /** + * Asserts that the target does not contain any values. For arrays and + * strings, it checks the length property. For Map and Set instances, it + * checks the size property. For non-function objects, it gets the count + * of own enumerable string keys. + * + * @type T Type of object + * @param object Actual value. + * @param message Message to display on error. + */ + isEmpty(object: T, message?: string): void; + + /** + * Asserts that the target contains values. For arrays and strings, it checks + * the length property. For Map and Set instances, it checks the size property. + * For non-function objects, it gets the count of own enumerable string keys. + * + * @type T Type of object. + * @param object Object to test. + * @param message Message to display on error. + */ + isNotEmpty(object: T, message?: string): void; } export interface Config { diff --git a/types/chance/chance-tests.ts b/types/chance/chance-tests.ts index a426142d7f..dfb942f5c5 100644 --- a/types/chance/chance-tests.ts +++ b/types/chance/chance-tests.ts @@ -37,3 +37,4 @@ var timeString: string = chance.time(); var chanceConstructedWithSeed100 = new Chance(100); var chanceCalledWithSeed100 = Chance() +var chanceConstructedWithStringSeed = new Chance("test") diff --git a/types/chance/index.d.ts b/types/chance/index.d.ts index fc5347e859..3b477c4bce 100644 --- a/types/chance/index.d.ts +++ b/types/chance/index.d.ts @@ -1,23 +1,24 @@ // Type definitions for Chance 0.7.3 // Project: http://chancejs.com -// Definitions by: Chris Bowdon +// Definitions by: Chris Bowdon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Chance { + type Seed = number | string; interface Seeded { - seed: number; + seed: Seed; } type SeededChance = Chance & Seeded; interface ChanceStatic { (): Chance - (seed: number): SeededChance + (seed: Seed): SeededChance (generator: () => any): Chance new(): Chance; - new(seed: number): SeededChance; + new(seed: Seed): SeededChance; new(generator: () => any): Chance; } @@ -156,7 +157,7 @@ declare namespace Chance { // "Hidden" cc_types(): CreditCardType[]; - mersenne_twister(seed?: number): any; // API return type not defined in docs + mersenne_twister(seed?: Seed): any; // API return type not defined in docs months(): Month[]; name_prefixes(): Name[]; provinces(): Name[]; diff --git a/types/charm/index.d.ts b/types/charm/index.d.ts index 2ce1b9e13a..63b8c3daa3 100644 --- a/types/charm/index.d.ts +++ b/types/charm/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Charm 1.0 // Project: https://github.com/substack/node-charm/ -// Definitions by: Jad Sarout +// Definitions by: Jad Sarout // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/chart.js/chart.js-tests.ts b/types/chart.js/chart.js-tests.ts index b9ffd7a8f6..a4cccb0bae 100644 --- a/types/chart.js/chart.js-tests.ts +++ b/types/chart.js/chart.js-tests.ts @@ -4,9 +4,9 @@ import { Chart, ChartData } from 'chart.js'; // import chartjs = require('chart.js'); // => chartjs.Chart -let chart: Chart = new Chart(new CanvasRenderingContext2D(), { +const chart: Chart = new Chart(new CanvasRenderingContext2D(), { type: 'bar', - data: { + data: { labels: ['group 1'], datasets: [ { @@ -18,11 +18,36 @@ let chart: Chart = new Chart(new CanvasRenderingContext2D(), { ] }, options: { + hover: { + intersect: true + }, + tooltips: { + filter: data => Number(data.yLabel) > 0, + intersect: true, + itemSort: (a, b) => Math.random() - 0.5, + position: "average", + caretPadding: 2, + displayColors: true, + borderColor: "rgba(0,0,0,0)", + borderWidth: 1, + }, scales: { xAxes: [{ + ticks: { + callback: Math.floor + }, gridLines: { display: false } }] } } }); chart.update(); + +console.log(chart.ctx && chart.ctx.font); +console.log(chart.canvas && chart.canvas.tagName); +if (chart.chartArea) { + console.log(chart.chartArea.top); + console.log(chart.chartArea.right); + console.log(chart.chartArea.bottom); + console.log(chart.chartArea.left); +} diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 6724d27112..f04fbc1119 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for Chart.js 2.4 +// Type definitions for Chart.js 2.6 // Project: https://github.com/nnnick/Chart.js // Definitions by: Alberto Nuti // Fabien Lavocat +// KentarouTakeda +// Larry Bahr // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -26,6 +28,9 @@ declare class Chart { getElementAtEvent: (e: any) => {}; getElementsAtEvent: (e: any) => Array<{}>; getDatasetAtEvent: (e: any) => Array<{}>; + ctx: CanvasRenderingContext2D|null; + canvas: HTMLCanvasElement|null; + chartArea: Chart.ChartArea; static pluginService: PluginServiceStatic; static defaults: { @@ -80,6 +85,13 @@ declare namespace Chart { type PositionType = 'left' | 'right' | 'top' | 'bottom'; + interface ChartArea { + top: number; + right: number; + bottom: number; + left: number; + } + interface ChartLegendItem { text?: string; fillStyle?: string; @@ -147,7 +159,11 @@ declare namespace Chart { animation?: ChartAnimationOptions; elements?: ChartElementsOptions; scales?: ChartScales; + showLines?: boolean; + spanGaps?: boolean; cutoutPercentage?: number; + circumference?: number; + rotation?: number; } interface ChartFontOptions { @@ -191,6 +207,7 @@ declare namespace Chart { enabled?: boolean; custom?(a: any): void; mode?: string; + intersect?: boolean; backgroundColor?: ChartColor; titleFontFamily?: string; titleFontSize?: number; @@ -215,11 +232,19 @@ declare namespace Chart { cornerRadius?: number; multiKeyBackground?: string; callbacks?: ChartTooltipCallback; + filter?(item: ChartTooltipItem): boolean; + itemSort?(itemA: ChartTooltipItem, itemB: ChartTooltipItem): number; + position?: "average"|"nearest"; + caretPadding?: number; + displayColors?: boolean; + borderColor?: ChartColor; + borderWidth?: number; } interface ChartHoverOptions { mode?: string; animationDuration?: number; + intersect?: boolean; onHover?(active: any): void; } @@ -307,7 +332,7 @@ declare namespace Chart { interface TickOptions { autoSkip?: boolean; - callback?(value: any, index: any, values: any): string; + callback?(value: any, index: any, values: any): string|number; display?: boolean; fontColor?: ChartColor; fontFamily?: string; @@ -361,6 +386,7 @@ declare namespace Chart { type ChartColor = string | CanvasGradient | CanvasPattern | string[]; interface ChartDataSets { + cubicInterpolationMode?: string; backgroundColor?: ChartColor | ChartColor[]; borderWidth?: number; borderColor?: ChartColor; @@ -388,6 +414,7 @@ declare namespace Chart { hidden?: boolean; hideInLegendAndTooltip?: boolean; stack?: string; + spanGaps?: string; } interface ChartScales { diff --git a/types/chart.js/tsconfig.json b/types/chart.js/tsconfig.json index a798d69e23..aae63d6394 100644 --- a/types/chart.js/tsconfig.json +++ b/types/chart.js/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/chayns/chayns-tests.ts b/types/chayns/chayns-tests.ts new file mode 100644 index 0000000000..8e8912430a --- /dev/null +++ b/types/chayns/chayns-tests.ts @@ -0,0 +1,14 @@ +// Test file for chayns typings + +chayns.register({ + strictMode: false, + appName: 'chayns-typings-test' +}); + +chayns.ready.then(data => { + return data; +}).catch(err => { + return err; +}); + +chayns.dialog.alert('chayns-typings', 'Test chayns-typings!'); diff --git a/types/chayns/index.d.ts b/types/chayns/index.d.ts new file mode 100644 index 0000000000..a1989a1c51 --- /dev/null +++ b/types/chayns/index.d.ts @@ -0,0 +1,938 @@ +// Type definitions for chayns 3.1 +// Project: https://github.com/TobitSoftware/chayns-js +// Definitions by: Henning Kuehl +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/** + * Definition file for chayns v3.1 + */ +declare namespace chayns { + /** + * Getting Started + * chayns + * + */ + let ready: Promise; + + function register(config: RegisterConfig): void; + + /** + * Basic Functions + * chayns + */ + function login(parameters?: string[]): Promise; + + function getUser(config: GetUserConfig): Promise; + + function getUacGroups(siteId: number, updateCache?: boolean): Promise; + + function startInteractionIdentification(config: InteractionIdentificationConfig): Promise; + + function stopInteractionIdentification(): Promise; + + function allowRefreshScroll(): Promise; + + function disallowRefreshScroll(): Promise; + + function showTitleImage(): Promise; + + function hideTitleImage(): Promise; + + function setOnActivateCallback(callback: (tappEvent: number) => any): Promise; + + function setNetworkChangeCallback(callback: (result: NetworkChangeResult) => any, ongoing: boolean): Promise; + + function setNfcCallback(callback: (rfid: string) => any): Promise; + + function removeNfcCallback(): Promise; + + function startNfcDetection(callback: (result: NfcDetectionResult) => any, interval: number, vibrate: boolean): Promise; + + function stopNfcDetection(): Promise; + + function scanQRCode(cameryType?: number, timeout?: number): Promise; // TODO interface for promise result + + function createQRCode(text: string): Promise; + + function showFinetradingQRCode(): Promise; + + function selectTapp(tapp: SelectTappConfig, parameter?: string[]): Promise; + + function openUrl(config: OpenUrlConfig): void; + + function closeUrl(): void; + + function openUrlInBrowser(url: string): void; + + function getGeoLocation(): Promise; + + function getLocationBeacons(forceReload: boolean): Promise; + + function getBeaconHistory(subNumber?: number): Promise; + + function getBaseColor(color?: string, colorMode?: number): string; + + function share(config: ShareConfig): Promise; // TODO interface for promise result + + function getAvailableSharingServices(): Promise; + + function navigateBack(): Promise; + + function updateNavigation(tappId?: number, config?: UpdateNavigationConfig): Promise; + + function enableDisplayTimeout(): Promise; + + function disableDisplayTimeout(): Promise; + + function setSpeechToText(callback: (result: SpeechToTextResult) => any, title?: string): Promise; + + function createTappShortcut(name: string, imageUrl: string): Promise; + + function setSubTapp(config: SubTappConfig): void; + + function removeSubTapp(config: RemoveSubTappConfig): void; + + function vibrate(ms: number[]): Promise; + + function setHeight(config: SetHeightConfig): Promise; + + function scrollToY(position: number): Promise; + + function addToWallet(passbook: string): Promise; // TODO check passbock parameter + + function addScrollListener(callback: (data: any) => any, throttle?: number): Promise; // TODO interface for callback data + + function setScreenOrientation(orientation: number): Promise; + + function findSite(name: string, skip?: number, take?: number): Promise; + + /** + * UI Functions + * Waitcursor + * chayns + */ + function showWaitCursor(text?: string, timeout?: number): Promise; + + function hideWaitCursor(): Promise; + + /** + * UI Functions + * Floating Button + * chayns + */ + function showFloatingButton(config: FloatingConfig, callback: () => any): void; + + function hideFloatingButton(): void; + + /** + * Media Functions + * Image + * chayns + */ + function openImage(urls: string[], start?: number): Promise; + + function uploadImage(): Promise; + + /** + * Media Functions + * Miscellaneous + * chayns + */ + function openVideo(url: string): Promise; + + function saveAppointment(config: SaveAppointmentConfig): Promise; + + function playSound(url: string, playOnMute?: boolean): Promise; + + function addErrorListener(logFn: (error: any) => Promise<{}>, appName: string): void; + + function getGlobalData(): GlobalData; + + /** + * chayns.smartShop + */ + let smartShop: any; + + /** + * Basic Functions + * chayns.intercom + */ + namespace intercom { + function sendMessageToUser(userId: number, config: IntercomConfig): Promise; // TODO set interface for promise result + + function sendMessageToGroup(groupId: number, config: IntercomConfig): Promise; // TODO set interface for promise result + + function sendMessageToPage(config: IntercomConfig): Promise; // TODO set interface for promise result + } + + /** + * Basic Functions + * chayns.passKit + */ + namespace passKit { + function getInstalled(): Promise; // TODO interface for promise result + + function isInstalled(identifier: string): Promise; // TODO interface for promise result + } + + /** + * Environmental Variables + * chayns.env + */ + namespace env { + let _parameters: any; + + let parameters: any; + + let isBrowser: boolean; + + let isChaynsWeb: boolean; + + let isChaynsWebDesktop: boolean; + + let isChaynsWebMobile: boolean; + + let isDesktop: boolean; + + let isMobile: boolean; + + let isApp: boolean; + + let isIOS: boolean; + + let isAndroid: boolean; + + let isTablet: boolean; + + let isWP: boolean; + + let appVersion: number; + + let os: string; + + let apiVersion: number; + + let debugMode: boolean; + + let isChaynsParent: boolean; + + let isChaynsWebLight: boolean; + + let isInFacebookFrame: boolean; + + let isInFrame: boolean; + + let isWidget: boolean; + + let language: string; + + /** + * Environmental Variables + * chayns.env.user + */ + namespace user { + let tobitAccessToken: string; + + let facebookAccessToken: string; + + let facebookId: string; + + let id: number; + + let name: string; + + let personId: string; + + let isAuthenticated: boolean; + + let language: string; + + let groups: UserGroup[]; + } + + /** + * Environmental Variables + * chayns.env.site + */ + namespace site { + let color: string; + + let colorMode: number; + + let colorScheme: number; + + let domain: string; + + let facebookAppId: string; + + let facebookPageId: string; + + let id: string; + + let isAdEnabled: boolean; + + let isArEnabled: boolean; + + let language: string; + + let locationId: number; + + let locationPersonId: string; + + let tapps: SiteTapp[]; + + let title: string; + + let url: string; + + let version: string; + + /** + * Environmental Variables + * chayns.env.site.tapp + */ + namespace tapp { + let customUrl: string; + + let id: number; + + let internalName: string; + + let isExclusiveView: boolean; + + let isKioskMode: boolean; + + let isSubTapp: boolean; + + let showName: string; + + let sortId: number; + + let userGroupIds: number[]; + } + } + + /** + * Environmental Variables + * chayns.env.app + */ + namespace app { + let flavor: string; + + let languageId: string; + + let model: string; + + let name: string; + + let uid: string; + + let version: string; + } + + /** + * Environmental Variables + * chayns.env.device + */ + namespace device { + let fontScale: any; + + let imei: string; + + let languageId: string; + + let model: string; + + let systemName: string; + + let systemVersion: number; + + let uid: string; + } + + /** + * Environmental Variables + * chayns.env.browser + */ + namespace browser { + let name: string; + + let version: string; + } + } + + /** + * UI Functions + * chayns.dialog + */ + namespace dialog { + enum buttonType { + CANCEL = -1, + NEGATIVE = 0, + POSITIVE = 1 + } + + enum buttonText { + CANCEL = 'Abbrechen', + NO = 'Nein', + OK = 'OK', + YES = 'Ja' + } + + enum dateType { + DATE, + TIME, + DATE_TIME + } + + enum inputType { + DEFAULT = 0, + PASSWORD = 1 + } + + function alert(title: string, message?: string): Promise; + + function confirm(title: string, message?: string, buttons?: DialogButton[]): Promise; + + function date(config: DialogDateConfig): Promise; + + function select(config: DialogSelectConfig): Promise; + + function input(config: DialogInputConfig): Promise; + + function facebook(options: DialogFacebookOptions): Promise; + } + + /** + * chayns.ui + */ + namespace ui { + /** + * UI Functions + * chayns.ui.modeSwitch + */ + namespace modeSwitch { + function init(config: ModeSwitchConfig): void; + + function addItem(item: ModeSwitchItem, index?: number): void; + + function changeMode(item: number | ModeSwitchItem): void; + + function remove(): void; + + function add(): void; + } + + /** + * Media Functions + * chayns.ui.gallery + */ + namespace gallery { + function create(id: string, urls: string[]): void; + + function setUrls(id: string, urls: string[]): void; + + function getUrls(id: string): string[]; + + function addUrl(id: string, url: string): void; + + function removeUrl(id: string, url: string): void; + } + + /** + * chayns.ui.tooltip + */ + namespace tooltip { + function init(config: UiTooltipInitConfig, rootElement: any): Promise; + } + + /** + * chayns.ui.slider + */ + namespace slider { + function refreshTrack(): void; + } + } + + /** + * Utility Functions + * chayns.utils + */ + namespace utils { + /** + * Utility Functions + * Check Types + * chayns.utils + */ + function isHex(parameter: any, shorthand: boolean): boolean; + + function isArray(parameter: any): boolean; + + function isBLEAdress(parameter: any): boolean; + + function isBlank(parameter: any): boolean; + + function isDate(parameter: any): boolean; + + function isDefined(parameter: any): boolean; + + function isFormData(parameter: any): boolean; + + function isFunction(parameter: any): boolean; + + function isGUID(parameter: any): boolean; + + function isMacAdress(parameter: any): boolean; + + function isNumber(parameter: any): boolean; + + function isObject(parameter: any): boolean; + + function isPromise(parameter: any): boolean; + + function isString(parameter: any): boolean; + + function isUUID(parameter: any): boolean; + + function isUndefined(parameter: any): boolean; + + function isDeferred(parameter: any): boolean; + + function isJwt(parameter: any): boolean; + + function isUrl(parameter: any): boolean; + + /** + * Utility Functions + * Miscellaneous + * chayns.utils + */ + function getJwtPayload(token: string): JwtPaylod; + + function mod(number: number, modulo: number): number; + + function trim(test: string): string; + + function replacePlaceholder(text: string, parameters: any[]): string; // TODO set interface for parameters + + function mixColor(color1: string, color2: string, saturation: number): string; + + function isPresent(parameter: any): boolean; + + function setLevel(level: number): void; + + /** + * Utility Functions + * Local Storage + * chayns.utils.ls + */ + namespace ls { + function set(key: string, value: string): void; + + function get(key: string): string; + + function remove(key: string): void; + + function removeAll(): void; + } + + namespace lang { + function init(config: any): void; + + function renderTextStrings(): void; + + function get(textString: string): string; + + function translateDomStrings(): void; + } + } + + /** + * chayns.storage + */ + namespace storage { + enum accessMode { + PUBLIC, + PROTECTED, + PRIVATE + } + + function set(key: string, value: any, accessMode?: accessMode, tappIds?: number[]): Promise; + + function get(key: string, accessMode?: accessMode): any; + + function remove(key: string, accessMode?: accessMode): Promise; + } +} + +/** + * Getting Started + * chayns + * interfaces + */ +// chayns.register() +interface RegisterConfig { + strictMode?: boolean; + appName?: string; + cssPrefix?: string; + callbackPrefix?: string; + initialHeight?: number; + autoResize?: boolean; +} + +/** + * Basic Functions + * chayns + * interfaces + */ +// chayns.getUser() +interface GetUserConfig { + accessToken?: string; + userId?: number; + fbId?: string; + personId?: string; +} + +interface User { + FacebookID: string; + FirstName: string; + LastName: string; + PersonID: string; + UserFullName: string; + UserID: number; +} + +// chayns.getUacGroups() +interface UacGroup { + id: number; + name: string; + showName: string; +} + +// chayns.startInteractionIdentification() +interface InteractionIdentificationConfig { + duration: number; + delay?: number; + callback: any; + resetOnInteraction?: boolean; + foregroundColor: string; + backgroundColor?: string; +} + +// chayns.setNetworkChangeCallback() +interface NetworkChangeResult { + isConnected: boolean; + type: number; +} + +// chayns.startNfcDetection() +interface NfcDetectionResult { + connected: boolean; + rfid: string; +} + +// chayns.selectTapp() +interface SelectTappConfig { + id?: number; + internalName?: string; + showName?: string; + position?: number; +} + +// chayns.openUrl() +interface OpenUrlConfig { + url: string; + title?: string; + exclusiveView?: boolean; + darkenBackground?: boolean; + fullSize?: boolean; + width?: number; +} + +// chayns.getGeoLocation() +interface GeoLocationResult { + longitude: number; + latitude: number; +} + +// chayns.getLocationBeacons() +interface LocationBeacon { + id: number; + pushMessage: string; + latitude: number; + longitude: number; +} + +// chayns.getBeaconHistory() +interface BeaconHistory { + id: number; + timestamp: number; +} + +// chayns.share() +interface ShareConfig { + title?: string; + text: string; + imageUrl?: string; + sharingApp: number; + sharingAndroidApp?: string; +} + +// chayns.updateNavigation() +interface UpdateNavigationConfig { + stateOnly?: boolean; + updateTapp?: boolean; +} + +// chayns.setSpeecToText() +interface SpeechToTextResult { + languageCode: string; + text: string[]; +} + +// chayns.setSubTapp() +interface SubTappConfig { + tappID: number; + name: string; + color: string; + colorText?: string; + sortID: number; + icon: string; + callbackURL?(result: any): any; + url: string; + buttonName: string; + isExclusiveView?: boolean; + replaceParent?: boolean; + boldText?: boolean; +} + +// chayns.removeSubTapp() +interface RemoveSubTappConfig { + tappID: number; + close: boolean; + remove: boolean; +} + +// chayns.setHeight() +interface SetHeightConfig { + height: number; + growOnly?: boolean; + full?: boolean; + fullViewport?: boolean; +} + +// chayns.findSite() +interface Site { + appstoreName: string; + facebookId: string; + siteId: string; + locationId: number; +} + +/** + * Basic Functions + * chayns.intercom + * interfaces + */ +interface IntercomConfig { + text: string; +} + +/** + * UI Functions + * chayns.dialog + * interfaces + */ +// chayns.dialog.confirm() +interface DialogButton { + text: string; + buttonType: chayns.dialog.buttonType; +} + +// chayns.dialog.date() +interface DialogDateConfig { + dateType: chayns.dialog.dateType; + preSelect?: Date; + minDate?: Date; + maxDate?: Date; +} + +interface DialogDateResult { + timestamp: number; + buttonType: chayns.dialog.buttonType; +} + +// chayns.dialog.select() +interface DialogSelectConfig { + title: string; + message?: string; + quickfind?: boolean; + multiselect?: boolean; + buttons?: any[]; // TODO interface for buttons + list: DialogSelectConfigItem[]; +} + +interface DialogSelectConfigItem { + name: string; + value?: string; + image?: string; + isSelected?: boolean; +} + +interface DialogSelectResult { + buttonType: chayns.dialog.buttonType; + selection: DialogSelectResultItem[]; +} + +interface DialogSelectResultItem { + name: string; + value?: string; +} + +// chayns.dialog.input() +interface DialogInputConfig { + title: string; + message?: string; + placeholderText?: string; + text?: string; + buttons?: DialogButton[]; +} + +interface DialogInputResult { + buttonType: chayns.dialog.buttonType; + text: string; +} + +/** + * UI Functions + * chayns.ui.modeswitch + * interfaces + */ +// chayns.ui.modeswitch.init() +interface ModeSwitchConfig { + items: ModeSwitchItem[]; + callback(result: ModeSwitchItem): void; + headline?: string; + preventclose?: boolean; +} + +interface ModeSwitchItem { + name: string; + value: number; + default?: boolean; +} + +/** + * UI Functions + * Floating Button + * chayns + * interfaces + */ +// chayns.showFloatingButton() +interface FloatingConfig { + text?: string; + color?: string; + colorText?: string; + icon?: string; +} + +/** + * Media Functions + * Miscellaneous + * chayns + * interfaces + */ +// chayns.saveAppointment() +interface SaveAppointmentConfig { + name: string; + location: string; + description: string; + start: Date; + end: Date; +} + +/** + * Utility Functions + * Miscellaneous + * chayns.utils + * interfaces + */ +// chayns.utils.getJwtPayload() +interface JwtPaylod { + FacebookUserID: string; + FirstName: string; + LastName: string; + PersonID: string; + LocationID: number; + TobitUserID: number; + LoginType: number; + isAdmin: boolean; +} + +/** + * Enviroment Variables + * User + * interfaces + */ +// chayns.env.user.groups +interface UserGroup { + id: number; + isActive?: boolean; + isSystemGroup?: boolean; + name: string; + showName?: string; +} + +/** + * Enviroment Variables + * Site + * interfaces + */ +interface SiteTapp { + customUrl: string; + id: number; + internalName: string; + isExclusiveView: boolean; + isKioskMode: boolean; + isSubTapp: boolean; + showName: string; + sortId: number; + userGroupIds: number[]; +} + +interface GlobalData { + _result: any; +} + +interface DialogFacebookOptions { + title: string; + message?: string; + quickfind?: number; + multiselect?: number; + button?: DialogFacebookButton[]; + preSelected: number[]; // TODO: Verify type +} + +interface DialogFacebookButton { + text: string; + value: number; // TODO: Verify type +} + +interface DialogFacebookResult { + buttonType: number; + selection: DialogFacebookResultSelection[]; +} + +interface DialogFacebookResultSelection { + first_name: string; + last_name: string; + id: string; + gender: string; + name: string; +} + +interface UiTooltipInitConfig { + tooltipClass: string; + preventAnimation: boolean; +} diff --git a/types/chayns/tsconfig.json b/types/chayns/tsconfig.json new file mode 100644 index 0000000000..99d0599998 --- /dev/null +++ b/types/chayns/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "chayns-tests.ts" + ] +} diff --git a/types/chayns/tslint.json b/types/chayns/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/chayns/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/check-sum/check-sum-tests.ts b/types/check-sum/check-sum-tests.ts new file mode 100644 index 0000000000..e1f310e74d --- /dev/null +++ b/types/check-sum/check-sum-tests.ts @@ -0,0 +1,18 @@ +import checksum = require('check-sum'); +import * as fs from 'fs'; + +const stream = fs.createReadStream('package.json'); + +checksum(stream, { + md5: 'asdfasdfasdf', + sha1: 'asdfasdfasdf' +}, err => { + err; // $ExpectType any +}); + +checksum('package.json', { + md5: 'asdfasdfasdf', + sha1: 'asdfasdfasdf' +}, err => { + err; // $ExpectType Error | ChecksumError | undefined +}); diff --git a/types/check-sum/index.d.ts b/types/check-sum/index.d.ts new file mode 100644 index 0000000000..d1e4b7eb02 --- /dev/null +++ b/types/check-sum/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for check-sum 0.1 +// Project: https://github.com/stream-utils/check-sum +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import { Readable } from 'stream'; + +export = checksum; + +declare function checksum(stream: Readable, hashes: checksum.Hashes, callback: (error: checksum.ChecksumError | any) => void): (fn: () => void) => void; +declare function checksum(path: string, hashes: checksum.Hashes, callback: (error: checksum.ChecksumError | Error | undefined) => void): (fn: () => void) => void; + +declare namespace checksum { + interface ChecksumError { + algorithm: string; + expected: string; + actual: string; + } + + interface Hashes { + [algorithm: string]: string | Buffer; + } +} diff --git a/types/check-sum/tsconfig.json b/types/check-sum/tsconfig.json new file mode 100644 index 0000000000..2143ca3bd6 --- /dev/null +++ b/types/check-sum/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "check-sum-tests.ts" + ] +} diff --git a/types/check-sum/tslint.json b/types/check-sum/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/check-sum/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chmodr/chmodr-tests.ts b/types/chmodr/chmodr-tests.ts new file mode 100644 index 0000000000..886dc9e3db --- /dev/null +++ b/types/chmodr/chmodr-tests.ts @@ -0,0 +1,14 @@ +import chmodr = require('chmodr'); +import { URL } from 'url'; + +chmodr('', '', err => { + err; // $ExpectType ErrnoException +}); +chmodr(new Buffer(''), '', () => {}); +chmodr(new URL(''), '', () => {}); +chmodr(new URL(''), 1, () => {}); + +chmodr.sync('', ''); +chmodr.sync(new Buffer(''), ''); +chmodr.sync(new URL(''), ''); +chmodr.sync(new URL(''), 1); diff --git a/types/chmodr/index.d.ts b/types/chmodr/index.d.ts new file mode 100644 index 0000000000..16eeaf7cbd --- /dev/null +++ b/types/chmodr/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for chmodr 1.0 +// Project: https://github.com/isaacs/chmodr#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import { URL } from 'url'; + +export = chmodr; + +declare function chmodr(path: chmodr.PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + +declare namespace chmodr { + function sync(path: PathLike, mode: string | number): void; + + type PathLike = string | Buffer | URL; +} diff --git a/types/chmodr/tsconfig.json b/types/chmodr/tsconfig.json new file mode 100644 index 0000000000..5aa0c9aac2 --- /dev/null +++ b/types/chmodr/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "chmodr-tests.ts" + ] +} diff --git a/types/chmodr/tslint.json b/types/chmodr/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/chmodr/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chocolatechipjs/chocolatechipjs-tests.ts b/types/chocolatechipjs/chocolatechipjs-tests.ts index bbb6ae72e3..a723d1b8f9 100644 --- a/types/chocolatechipjs/chocolatechipjs-tests.ts +++ b/types/chocolatechipjs/chocolatechipjs-tests.ts @@ -1,5 +1,5 @@ // ChocolateChipStatic -- DOM creation, etc. -$(function() { +$(() => { alert('Ready to do stuff!'); }); const docRoot = $(); @@ -20,10 +20,10 @@ const moreEls = $.html('

      Stuff

      '); const oldTag = $('#oldTag'); const newTag = $('#newTag'); $.replace(oldTag, newTag); -$.require('./scripts/myscript.js', function() { +$.require('./scripts/myscript.js', () => { $.noop; }); -$.defer(function() { +$.defer(() => { console.log("This comes after Squawk!"); }); const concatenation = $.concat('This', ' ', 'is', ' ', 'a', ' ', 'string', '.'); @@ -41,7 +41,7 @@ $.isInteger(123); $.isInteger(123.123); // should return false $.isFloat(123.123); // should return true const newUuid = $.makeUuid(); -$.each(['a', 'b', 'c'], function(ctx: string, idx: number) { +$.each(['a', 'b', 'c'], (ctx: string, idx: number) => { console.log(ctx); console.log(idx); }); @@ -55,7 +55,7 @@ $.fn.extend({ }); // ChocolateChipElementArray extensions: -$('li').each(function(ctx, idx) { +$('li').each((ctx, idx) => { console.log(ctx.nodeName); }); const uniqueElements = $('li').unique(); @@ -63,19 +63,19 @@ const secondElement = $('li').eq(1); const lastElement = $('li').eq(-1); const whichIndex = $('li').index($('.selected')); const whichListItemIndex = $('li').eq(3).index(); -$('.elems').is('div').each(function(ctx) { +$('.elems').is('div').each(ctx => { console.log('This element is a div.'); }); -$('.elems').isnt('p').each(function() { +$('.elems').isnt('p').each(() => { console.log('This element is not a paragraph tag.'); }); -$('li').has('p').each(function(ctx) { +$('li').has('p').each(ctx => { console.log('This list item has a paragraph tag.'); }); -$('li').hasnt('p').each(function(ctx) { +$('li').hasnt('p').each(ctx => { console.log('This list item does not have a paragraph tag.'); }); -$('ul').find('li').each(function(ctx) { +$('ul').find('li').each(ctx => { console.log(ctx); }); $('li').css('color'); @@ -124,14 +124,14 @@ $('ul').hide(); $('ul').hide('slow'); $('ul').hide('fast'); $('ul').hide(1000); -$('ul').hide('fast', function() { +$('ul').hide('fast', () => { console.log('Finished hiding these.'); }); $('ul').show(); $('ul').show('slow'); $('ul').show('fast'); $('ul').show(1000); -$('ul').show('fast', function() { +$('ul').show('fast', () => { console.log('Finished hiding these.'); }); $('#list').prev().css('display', 'none'); @@ -198,22 +198,22 @@ const isSafari = $.isSafari; const isNativeAndroid = $.isNativeAndroid; // Events: -$('li').bind('click', function() { +$('li').bind('click', () => { $.noop; }, false); -$('li').unbind('click', function() { +$('li').unbind('click', () => { $.noop; }, false); -$('ul').delegate('click', 'li', function() { +$('ul').delegate('click', 'li', () => { $.noop; }, false); -$('ul').undelegate('click', 'li', function() { +$('ul').undelegate('click', 'li', () => { $.noop; }, false); -$('li').on('click', function() { +$('li').on('click', () => { $.noop; }); -$('ul').on('click', 'li', function() { +$('ul').on('click', 'li', () => { console.log($(this).text()); }); $('li').off('click'); @@ -224,22 +224,22 @@ $('.selected').data('selection', 'This is awesome!'); // set the value of data v $('.selected').data('selection'); // return the data value of "selection" on ".selected" // Promises: -let myPromise = new Promise(function(resolve, reject) { +let myPromise = new Promise((resolve, reject) => { $.noop; }); -myPromise = new Promise(function(resolve, reject) { +myPromise = new Promise((resolve, reject) => { // Resolve the promise: resolve('Success!'); // or reject it: // reject('Lost in Space!'); }); -myPromise.then(function(value) { +myPromise.then(value => { // Success: console.log(value); }, // Opps! There was a problem: - function(reason) { + reason => { console.log(reason); }); @@ -256,10 +256,10 @@ interface WineInterface { } fetch('../data/wines.json') .then($.json) -.then(function(obj: any): any { +.then((obj: any) => { $('#message_ajax').empty(); - obj.data.forEach(function(wine: any) { - $('#message_ajax').append('
    • ' + wine.name + '
    • '); + obj.data.forEach((wine: any) => { + $('#message_ajax').append(`
    • ${wine.name}
    • `); }); }); @@ -278,12 +278,12 @@ fetch('../controllers/php-post.php', { body: formData }) .then($.json) -.then(function(data: any): any { +.then((data: any) => { if (data.email_check === "valid") { - $("#message_ajax").html("
      " + data.email + " is a valid e-mail address. Thank you, " + data.name + ".
      "); - $("#message_ajax").append('

      ' + data.msg + '

      '); + $("#message_ajax").html(`
      ${data.email} is a valid e-mail address. Thank you, ${data.name}.
      `); + $("#message_ajax").append(`

      ${data.msg}

      `); } else { - $("#message_ajax").html("
      Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.
      "); + $("#message_ajax").html(`
      Sorry ${data.name}, ${data.email} is NOT a valid e-mail address. Try again.
      `); } }); // PUT: @@ -301,12 +301,12 @@ fetch('../controllers/php-put.php', { body: putData }) .then($.json) -.then(function(data: any): any { +.then((data: any) => { console.dir(data.base); - $("#message_ajax").append('

      ' + data.result + '

      '); - $("#message_ajax").append('

      The file name is: ' + data.fileName + '

      '); + $("#message_ajax").append(`

      ${data.result}

      `); + $("#message_ajax").append(`

      The file name is: ${data.fileName}

      `); }) -.catch(function(error: Error) { +.catch((error: Error) => { console.log(error); $("#message_ajax").html("
      Sorry, put was not successful.
      "); }); @@ -324,15 +324,15 @@ fetch('../controllers/php-delete.php', { body: file }) .then($.json) -.then(function(data: any): any { +.then((data: any) => { $("#message_ajax").html("
      DELETE was sent to the server successfully.
      "); - $("#message_ajax").append('

      ' + data.result + '

      '); + $("#message_ajax").append(`

      ${data.result}

      `); }, -function(data: any) { +(data: any) => { console.log('PROBLEM'); console.log(data); }) -.catch(function(error: any) { +.catch((error: any) => { $("#message_ajax").html("
      Sorry, 'DELETE' was not successful.
      "); error.reject(); }); @@ -349,30 +349,30 @@ fetch('../controllers/php-post.php', { timeout: 10000 }) .then($.json) - .then(function (data: any): any { + .then((data: any) => { if (data.email_check === "valid") { - $("#message_ajax").html("
      " + data.email + " is a valid e-mail address. Thank you, " + data.name + ".
      "); - $("#message_ajax").append('

      ' + data.msg + '

      '); + $("#message_ajax").html(`
      ${data.email} is a valid e-mail address. Thank you, ${data.name}.
      `); + $("#message_ajax").append(`

      ${data.msg}

      `); } else { - $("#message_ajax").html("
      Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.
      "); + $("#message_ajax").html(`
      Sorry ${data.name}, ${data.email} is NOT a valid e-mail address. Try again.
      `); } }) // Catch timeout: - .catch(function(error) { + .catch(error => { console.log(error); }); // $.jsonp: $.jsonp('https://api.github.com/users/rbiggs/repos?name=chipper', {timeout: 10000}) .then($.json) -.then(function(obj: any): any { +.then((obj: any) => { console.log(obj); - obj.data.forEach(function(repo: any): any { - $('#message_ajax').append("
    • " + repo.name + "
    • "); + obj.data.forEach((repo: any) => { + $('#message_ajax').append(`
    • ${repo.name}
    • `); }); }) -.catch(function(error: any): any { - $('#message_ajax').append("
    • " + error.message + "
    • "); +.catch((error: any) => { + $('#message_ajax').append(`
    • ${error.message}
    • `); }); // Templates: @@ -411,10 +411,9 @@ $.template.data['myRepeater'] = [{ name: "Joe" }, { name: "Sally" }, {name: "Tom $.template.repeater(); // Pub/Sub: -const arraySubscriber = function(topic: string, data: any): any { - $('.list').append('
    • ' + topic + '

      ' + data + '

    • '); -}; -const newsSubscription = $.subscribe('news/update', arraySubscriber); +const newsSubscription = $.subscribe('news/update', (topic: string, data: any) => { + $('.list').append(`
    • ${topic}

      ${data}

    • `); +}); $.publish('news/update', 'The New York Stock Exchange rose an unprecedented 1000 points in just three minutes. Analysts and investors are confused and uncertain how to respond.'); $.unsubscribe('news/update'); // Due to being unsubscribed above, this does nothing: diff --git a/types/chocolatechipjs/tslint.json b/types/chocolatechipjs/tslint.json index e502fddef8..04f74b7c27 100644 --- a/types/chocolatechipjs/tslint.json +++ b/types/chocolatechipjs/tslint.json @@ -4,7 +4,7 @@ // TODOs "adjacent-overload-signatures": false, "ban-types": false, - "only-arrow-functions": false, + "dt-header": false, "unified-signatures": false } } diff --git a/types/chokidar/index.d.ts b/types/chokidar/index.d.ts index 09e957aa05..683214fe35 100644 --- a/types/chokidar/index.d.ts +++ b/types/chokidar/index.d.ts @@ -1,12 +1,12 @@ // Type definitions for chokidar 1.7.0 // Project: https://github.com/paulmillr/chokidar -// Definitions by: Stefan Steinhart , Felix Becker +// Definitions by: Stefan Steinhart , Felix Becker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// import * as fs from 'fs'; -import {EventEmitter} from 'events'; +import { EventEmitter } from 'events'; /** * The object's keys are all the directories (using absolute paths unless the `cwd` option was diff --git a/types/chosen-js/index.d.ts b/types/chosen-js/index.d.ts index 221eefb3d3..c9a5556c26 100644 --- a/types/chosen-js/index.d.ts +++ b/types/chosen-js/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Chosen.JQuery 1.6.1 // Project: http://harvesthq.github.com/chosen/ -// Definitions by: Boris Yankov , denis +// Definitions by: Boris Yankov , denis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/chownr/chownr-tests.ts b/types/chownr/chownr-tests.ts new file mode 100644 index 0000000000..b544ce288e --- /dev/null +++ b/types/chownr/chownr-tests.ts @@ -0,0 +1,14 @@ +import chownr = require('chownr'); +import { URL } from 'url'; + +chownr('', 1, 1, err => { + err; // $ExpectType ErrnoException +}); +chownr(new Buffer(''), 1, 1, () => {}); +chownr(new URL(''), 1, 1, () => {}); +chownr(new URL(''), 1, 1, () => {}); + +chownr.sync('', 1, 1); +chownr.sync(new Buffer(''), 1, 1); +chownr.sync(new URL(''), 1, 1); +chownr.sync(new URL(''), 1, 1); diff --git a/types/chownr/index.d.ts b/types/chownr/index.d.ts new file mode 100644 index 0000000000..8ca1404bf9 --- /dev/null +++ b/types/chownr/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for chownr 1.0 +// Project: https://github.com/isaacs/chownr#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import { URL } from 'url'; + +export = chownr; + +declare function chownr(path: chownr.PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + +declare namespace chownr { + function sync(path: PathLike, uid: number, gid: number): void; + + type PathLike = string | Buffer | URL; +} diff --git a/types/chownr/tsconfig.json b/types/chownr/tsconfig.json new file mode 100644 index 0000000000..587c9ef8f8 --- /dev/null +++ b/types/chownr/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "chownr-tests.ts" + ] +} diff --git a/types/chownr/tslint.json b/types/chownr/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/chownr/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chroma-js/chroma-js-tests.ts b/types/chroma-js/chroma-js-tests.ts index 53a3e912b8..82cfb7274d 100644 --- a/types/chroma-js/chroma-js-tests.ts +++ b/types/chroma-js/chroma-js-tests.ts @@ -182,3 +182,8 @@ function test_scale() { chroma.scale('RdYlBu'); chroma.scale('RdYlBu').padding(0.15); } + +function test_types() { + const color: chroma.Color = chroma('orange'); + const scale: chroma.Scale = chroma.scale('RdYlBu'); +} diff --git a/types/chroma-js/index.d.ts b/types/chroma-js/index.d.ts index 1b679b816a..41f7a36785 100644 --- a/types/chroma-js/index.d.ts +++ b/types/chroma-js/index.d.ts @@ -7,7 +7,7 @@ /** * Chroma.js is a tiny library for all kinds of color conversions and color scales. */ -declare namespace Chroma { +declare namespace chroma { interface ColorSpaces { rgb: [number, number, number]; rgba: [number, number, number, number]; @@ -353,7 +353,7 @@ declare namespace Chroma { } } -declare var chroma: Chroma.ChromaStatic; +declare var chroma: chroma.ChromaStatic; export = chroma; export as namespace chroma; diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index ee61cf5575..42ba4c1804 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -7366,7 +7366,7 @@ declare namespace chrome.webRequest { interface WebRedirectionResponseEvent extends _WebResponseHeadersEvent {} interface WebAuthenticationChallengeEvent extends chrome.events.Event<(details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void> { - addListener(callback: (details: WebAuthenticationChallengeDetails) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; + addListener(callback: (details: WebAuthenticationChallengeDetails, callback?: (response: BlockingResponse) => void) => void, filter?: RequestFilter, opt_extraInfoSpec?: string[]): void; } interface WebResponseErrorEvent extends _WebResponseHeadersEvent {} diff --git a/types/chunked-dc/index.d.ts b/types/chunked-dc/index.d.ts index d200c07899..5e57953621 100644 --- a/types/chunked-dc/index.d.ts +++ b/types/chunked-dc/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for chunked-dc 0.1 // Project: https://github.com/saltyrtc/chunked-dc-js -// Definitions by: Danilo Bargen +// Definitions by: Danilo Bargen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Interfaces diff --git a/types/circular-json/index.d.ts b/types/circular-json/index.d.ts index b724f92577..1b4e5c1d2b 100644 --- a/types/circular-json/index.d.ts +++ b/types/circular-json/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for circular-json v0.1.6 // Project: https://github.com/WebReflection/circular-json -// Definitions by: Jonathan Pevarnek +// Definitions by: Jonathan Pevarnek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index 71a9202557..c158678c6e 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for CKEditor // Project: http://ckeditor.com/ -// Definitions by: Ondrej Sevcik +// Definitions by: Ondrej Sevcik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // WORK-IN-PROGRESS: Any contribution support welcomed. diff --git a/types/clamp-js/index.d.ts b/types/clamp-js/index.d.ts index 2fa557bac6..b905e16e8f 100644 --- a/types/clamp-js/index.d.ts +++ b/types/clamp-js/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for clamp-js 0.7 // Project: https://github.com/xavi160/Clamp.js -// Definitions by: Sebastiaan de Rooij +// Definitions by: Sebastiaan de Rooij // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace clamp { diff --git a/types/classnames/bind.d.ts b/types/classnames/bind.d.ts new file mode 100644 index 0000000000..4af94d1835 --- /dev/null +++ b/types/classnames/bind.d.ts @@ -0,0 +1,3 @@ +import * as cn from "./index"; + +export function bind(styles: Record): typeof cn; diff --git a/types/classnames/classnames-tests.ts b/types/classnames/classnames-tests.ts index 1938acb4f9..b2b8c9eba4 100644 --- a/types/classnames/classnames-tests.ts +++ b/types/classnames/classnames-tests.ts @@ -1,5 +1,6 @@ import classNames = require('classnames'); import * as classNames2 from 'classnames'; +import * as cn from 'classnames/bind'; classNames2('foo', 'bar'); // => 'foo bar' @@ -23,3 +24,17 @@ classNames(null, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1' // Supporting booleans is tricky since we should only support passing in false, which is ignored // classNames(false, 'bar', 0, 1, { baz: null }, ''); // => 'bar 1' + +// Support for CSS-Modules. Example from README: +// https://github.com/JedWatson/classnames/blob/master/README.md#alternate-bind-version-for-css-modules +const styles = { + foo: 'abc', + bar: 'def', + baz: 'xyz' +}; + +const cx = cn.bind(styles); +const className = cx('foo', ['bar'], { baz: true }); // => "abc def xyz" + +// falsey values are just ignored +cx(null, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1' diff --git a/types/classnames/index.d.ts b/types/classnames/index.d.ts index 42352fc9b8..ce2abb5ee3 100644 --- a/types/classnames/index.d.ts +++ b/types/classnames/index.d.ts @@ -3,9 +3,11 @@ // Definitions by: Dave Keen // Adi Dahiya // Jason Killian -// Sean Kelley +// Sean Kelley // Michal Adamczyk +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null | false; diff --git a/types/classnames/tsconfig.json b/types/classnames/tsconfig.json index 8eeaf9b1ca..bb39a9d874 100644 --- a/types/classnames/tsconfig.json +++ b/types/classnames/tsconfig.json @@ -17,6 +17,7 @@ }, "files": [ "index.d.ts", + "bind.d.ts", "classnames-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/classnames/tslint.json b/types/classnames/tslint.json index 3db14f85ea..946c3b6691 100644 --- a/types/classnames/tslint.json +++ b/types/classnames/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "dt-header": false + } +} diff --git a/types/cldrjs/index.d.ts b/types/cldrjs/index.d.ts index 70a7c1c753..1837e9c88d 100644 --- a/types/cldrjs/index.d.ts +++ b/types/cldrjs/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Cldr.js 0.4.4 // Project: https://github.com/rxaviers/cldrjs -// Definitions by: Raman But-Husaim , Grégoire Castre +// Definitions by: Raman But-Husaim , Grégoire Castre // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = self; diff --git a/types/clean-stack/clean-stack-tests.ts b/types/clean-stack/clean-stack-tests.ts new file mode 100644 index 0000000000..72bef3f6b3 --- /dev/null +++ b/types/clean-stack/clean-stack-tests.ts @@ -0,0 +1,8 @@ +import cleanStack = require('clean-stack'); + +const error = new Error('Missing unicorn'); + +if (error.stack) { + cleanStack(error.stack); // $ExpectType string + cleanStack(error.stack, {pretty: true}); // $ExpectType string +} diff --git a/types/clean-stack/index.d.ts b/types/clean-stack/index.d.ts new file mode 100644 index 0000000000..59af64e31b --- /dev/null +++ b/types/clean-stack/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for clean-stack 1.3 +// Project: https://github.com/sindresorhus/clean-stack#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = cleanStack; + +declare function cleanStack(stack: string, options?: cleanStack.Options): string; + +declare namespace cleanStack { + interface Options { + pretty?: boolean; + } +} diff --git a/types/clean-stack/tsconfig.json b/types/clean-stack/tsconfig.json new file mode 100644 index 0000000000..79e1474200 --- /dev/null +++ b/types/clean-stack/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clean-stack-tests.ts" + ] +} diff --git a/types/clean-stack/tslint.json b/types/clean-stack/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clean-stack/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/clear-require/clear-require-tests.ts b/types/clear-require/clear-require-tests.ts new file mode 100644 index 0000000000..53aea4d832 --- /dev/null +++ b/types/clear-require/clear-require-tests.ts @@ -0,0 +1,8 @@ +import * as clear from 'clear-require'; + +clear('my-module'); // clear specific module from require cache + +clear.all(); // clear all of the require cache + +clear.match(new RegExp('^.*$')); // clear all modules which match the RegExp +clear.match(/^.*$/); // similar to above but using /regex/ notation diff --git a/types/clear-require/index.d.ts b/types/clear-require/index.d.ts new file mode 100644 index 0000000000..4b9118a008 --- /dev/null +++ b/types/clear-require/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for clear-require 2.0 +// Project: https://github.com/sindresorhus/clear-module +// Definitions by: dan-j +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface ClearRequire { + (moduleId: string): boolean; + all(): void; + match(regex: RegExp): void; +} + +declare const clear: ClearRequire; + +export = clear; diff --git a/types/clear-require/tsconfig.json b/types/clear-require/tsconfig.json new file mode 100644 index 0000000000..9c28741f0b --- /dev/null +++ b/types/clear-require/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clear-require-tests.ts" + ] +} diff --git a/types/clear-require/tslint.json b/types/clear-require/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clear-require/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cli-table2/index.d.ts b/types/cli-table2/index.d.ts index 46d4619162..b216b23832 100644 --- a/types/cli-table2/index.d.ts +++ b/types/cli-table2/index.d.ts @@ -70,7 +70,7 @@ declare namespace CliTable2 { } interface GenericTable extends Array { - options: CliTable2.TableInstanceOptions; + options: TableInstanceOptions; readonly width: number; } diff --git a/types/client-sessions/client-sessions-tests.ts b/types/client-sessions/client-sessions-tests.ts new file mode 100644 index 0000000000..7498aac12d --- /dev/null +++ b/types/client-sessions/client-sessions-tests.ts @@ -0,0 +1,25 @@ +import express = require("express"); +import session = require("client-sessions"); + +const secret = "yolo"; +const app = express(); +const options = { secret }; + +let middleware = session(options); +middleware = session({ secret, cookieName: "_s" }); +middleware = session({ secret, duration: 600000 }); +middleware = session({ secret, activeDuration: 42 }); +middleware = session({ + secret, + cookie: { + httpOnly: false, + } +}); + +app.use(middleware); +app.use((req: any, res: any) => { + req.session = { test: true }; +}); + +const encoded = session.util.encode(options, { test: true }); +session.util.decode(options, encoded); diff --git a/types/client-sessions/index.d.ts b/types/client-sessions/index.d.ts new file mode 100644 index 0000000000..6a4b3b2b2f --- /dev/null +++ b/types/client-sessions/index.d.ts @@ -0,0 +1,74 @@ +// Type definitions for client-sessions 0.8 +// Project: https://github.com/mozilla/node-client-sessions +// Definitions by: Aditya +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import * as cookies from "cookies"; + +declare namespace client_sessions { + type NextFunction = (err?: Error) => void; + type RequestHandler = (req: any, res: any, next: NextFunction) => any; + + interface SessionOptions { + /** + * encryption secret for the session. + * required + */ + secret: string; + + /** + * session cookie name. + * Default: 'session_state' + */ + cookieName?: string; + + /** + * how long the session will stay valid in ms. + * Default: 24 hours + */ + duration?: number; + + /** + * if expiresIn < activeDuration, the session will be extended by activeDuration milliseconds. + * Default: 5 minutes + */ + activeDuration?: number; + + /** + * session accessor on the request object. + * Default: 'session' + */ + requestKey?: string; + + cookie?: cookies.IOptions; + } + + interface DecodeResult { + content: any; + createdAt: number; + duration: number; + } + + interface ComputeHmacOptions { + signatureAlgorithm: string; + signatureKey: Buffer; + } + + interface Util { + computeHmac(options: any, iv: string, ciphertext: string, duration: number, createdAt: number): Buffer; + encode(options: SessionOptions, content: any, duration?: number, createdAt?: number): string; + decode(options: SessionOptions, encoded: string): DecodeResult; + } + + interface Sessions { + (options: SessionOptions): RequestHandler; + util: Util; + } +} + +declare var client_sessions: client_sessions.Sessions; +export = client_sessions; +export as namespace client_sessions; diff --git a/types/client-sessions/tsconfig.json b/types/client-sessions/tsconfig.json new file mode 100644 index 0000000000..151ca87623 --- /dev/null +++ b/types/client-sessions/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "client-sessions-tests.ts" + ] +} diff --git a/types/client-sessions/tslint.json b/types/client-sessions/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/client-sessions/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/clipboardy/clipboardy-tests.ts b/types/clipboardy/clipboardy-tests.ts new file mode 100644 index 0000000000..33ae8ac9a8 --- /dev/null +++ b/types/clipboardy/clipboardy-tests.ts @@ -0,0 +1,10 @@ +import clipboardy = require('clipboardy'); + +clipboardy.writeSync('🦄'); +clipboardy.write('🦄').then(() => {}); + +let str: string; +str = clipboardy.readSync(); +clipboardy.read().then(toPaste => { + str = toPaste; +}); diff --git a/types/clipboardy/index.d.ts b/types/clipboardy/index.d.ts new file mode 100644 index 0000000000..12e2c3b85a --- /dev/null +++ b/types/clipboardy/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for clipboardy 1.1 +// Project: https://github.com/sindresorhus/clipboardy#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function write(input: string): Promise; +export function writeSync(input: string): void; +export function read(): Promise; +export function readSync(): string; diff --git a/types/clipboardy/tsconfig.json b/types/clipboardy/tsconfig.json new file mode 100644 index 0000000000..455154a1d2 --- /dev/null +++ b/types/clipboardy/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clipboardy-tests.ts" + ] +} diff --git a/types/clipboardy/tslint.json b/types/clipboardy/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clipboardy/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/closure-compiler/closure-compiler-tests.ts b/types/closure-compiler/closure-compiler-tests.ts index 3dd827a0f8..44693fca43 100644 --- a/types/closure-compiler/closure-compiler-tests.ts +++ b/types/closure-compiler/closure-compiler-tests.ts @@ -1,4 +1,4 @@ -import {compile} from 'closure-compiler'; +import { compile } from 'closure-compiler'; compile('some.source()', {'check-only': null}, (err: Error, stdout: string, stderr: string): void => { diff --git a/types/cloudflare-apps/cloudflare-apps-tests.ts b/types/cloudflare-apps/cloudflare-apps-tests.ts new file mode 100644 index 0000000000..0db1b525d5 --- /dev/null +++ b/types/cloudflare-apps/cloudflare-apps-tests.ts @@ -0,0 +1,78 @@ +declare function describe(desc: string, f: () => void): void; +declare function it(desc: string, f: () => void): void; + +describe("Globals", () => { + it("INSTALL_OPTIONS returns InstallOptions (dictionary)", () => { + const options: CloudflareApps.InstallOptions = INSTALL_OPTIONS; + }); + + it("INSTALL_ID should return string", () => { + const id: string = INSTALL_ID; + }); + + it("INSTALL_SCOPE returns InstallScope (dictionary)", () => { + const scope: CloudflareApps.InstallScope = INSTALL_SCOPE; + }); + + it("INSTALL_PRODUCT returns InstallProduct", () => { + const product: CloudflareApps.InstallProduct | undefined = INSTALL_PRODUCT; + + if (product != null) { + const id = product.id; + } + }); + + it("INSTALL", () => { + const id: string = INSTALL.siteId; + }); + + it("CloudflareApps is CloudflareApps object", () => { + const apps: CloudflareApps.CloudflareApps = CloudflareApps; + }); +}); + +describe("CloudflareApps methods", () => { + it("createElement", () => { + const element: Element = CloudflareApps.createElement({ + method: "replace", + selector: "body > *" + }); + + const div: HTMLDivElement = document.createElement("div"); + const divElement: HTMLDivElement = CloudflareApps.createElement({ + method: "replace", + selector: "body > *" + }, div); + }); + + it("matchPage", () => { + // Example: domain.com + const truthyMatch: boolean = CloudflareApps.matchPage(["domain"]); + const falsyMatch: boolean = CloudflareApps.matchPage(["foobar"]); + }); + + it("querySelector", () => { + const element: Element | null = CloudflareApps.querySelector("body > *"); + const bodyElement: HTMLBodyElement | null = CloudflareApps.querySelector("body"); + }); +}); + +describe("CloudflareApps properties", () => { + it("installs", () => { + const appId = "preview"; + const app: CloudflareApps.App | undefined = CloudflareApps.installs[appId]; + + if (app != null) { + const id: string = app.appId; + } + }); + + it("proxy", () => { + const proxy: CloudflareApps.CloudflareAppsProxy = CloudflareApps.proxy; + const siteId: string = proxy.embedSiteId; + }); + + it("siteId", () => { + const siteId: string = CloudflareApps.siteId; + }); +}); diff --git a/types/cloudflare-apps/index.d.ts b/types/cloudflare-apps/index.d.ts new file mode 100644 index 0000000000..ca1162d11a --- /dev/null +++ b/types/cloudflare-apps/index.d.ts @@ -0,0 +1,125 @@ +// Type definitions for cloudflare-apps 0.1 +// Project: https://www.cloudflare.com/apps/ +// Definitions by: MartynasZilinskas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +// tslint:disable-next-line:no-single-declare-module +declare module "cloudflare-apps" { + global { + /** + * An object which contains all of the options the installer specified, + * based on the structure given in the options section of your `install.json`. + */ + const INSTALL_OPTIONS: CloudflareApps.InstallOptions; + + /** + * A string ID which is equal to the ID of this install. + * Its primary purpose is to allow you to easily distinguish between your app being loaded + * in the Cloudflare Preview or the installer’s live website. + */ + const INSTALL_ID: string; + + /** + * An object which you can use to store arbitrary values + * which you would like to be accessable from other Cloudflare scripts, + * without polluting the global scope. + * For example, it’s commonly used to share an update function with its update handler. + */ + const INSTALL_SCOPE: CloudflareApps.InstallScope; + + /** + * This object is specific to paid apps. It allows you to know which product the user has purchased. + * When you create a paid app you will be given product ids for each of the plans you wish to sell the product for. + * `INSTALL_PRODUCT.id` will then be that id for the plan the user has purchased. + * This value is absent for free apps and will always be set for paid apps even if the user is on a free plan. + */ + const INSTALL_PRODUCT: CloudflareApps.InstallProduct | undefined; + + /** + * It's the same as CloudflareApps variable. + * + * DON'T use this variable directly. + * BAD Example: + * ```ts + * const apps: cloudflareApps.CloudflareApps = INSTALL; + * ``` + * ------------------------------------------------- + * Use directly properties and methods. + * GOOD Example: + * ```ts + * const siteId: string = INSTALL.siteId; + * ``` + */ + const INSTALL: CloudflareApps.CloudflareApps; + + /** + * This is undocumented global variable. + * The documentation may arrive later. + */ + const CloudflareApps: CloudflareApps.CloudflareApps; + + namespace CloudflareApps { + interface InstallOptions { + [key: string]: any; + } + + interface InstallScope { + [key: string]: any; + } + + interface InstallProduct { + id: string; + } + + interface CloudflareAppsMethods { + createElement(options: ElementLocation, previousElement?: T): T; + + matchPage(patterns: string[]): boolean; + + querySelector(selectors: K): ElementTagNameMap[K] | null; + querySelector(selectors: string): Element | null; + } + + interface CloudflareApps extends CloudflareAppsMethods { + installs: { [id: string]: App | undefined }; + proxy: CloudflareAppsProxy; + siteId: string; + } + + interface App { + appId: string; + options: InstallOptions; + scope: InstallScope; + } + + interface CloudflareAppsProxy { + embedSiteId: string; + hasRocketEmbed: boolean; + originalURL: OriginalURL; + } + + interface OriginalURL { + raw: string; + parsed: OriginalURLParsed; + } + + interface OriginalURLParsed { + fragment: string; + host: string; + path: string; + scheme: "https" | "http"; + query: URLQuery; + } + + interface URLQuery { + [key: string]: string[]; + } + + interface ElementLocation { + method: "before" | "prepend" | "append" | "after" | "replace"; + selector: string; + } + } + } +} diff --git a/types/cloudflare-apps/tsconfig.json b/types/cloudflare-apps/tsconfig.json new file mode 100644 index 0000000000..9f3ed2ece7 --- /dev/null +++ b/types/cloudflare-apps/tsconfig.json @@ -0,0 +1,24 @@ +{ + "files": [ + "index.d.ts", + "cloudflare-apps-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + } +} diff --git a/types/cloudflare-apps/tslint.json b/types/cloudflare-apps/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/cloudflare-apps/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/co-views/index.d.ts b/types/co-views/index.d.ts index 3eda7191b1..db37de3611 100644 --- a/types/co-views/index.d.ts +++ b/types/co-views/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for co-views 2.1 // Project: https://github.com/tj/co-views/ -// Definitions by: devlee , Joshua DeVinney +// Definitions by: devlee , Joshua DeVinney // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace CoViews { diff --git a/types/codemirror/codemirror-runmode.d.ts b/types/codemirror/codemirror-runmode.d.ts index 2252eb9649..e08be74ee0 100644 --- a/types/codemirror/codemirror-runmode.d.ts +++ b/types/codemirror/codemirror-runmode.d.ts @@ -20,5 +20,5 @@ declare module "codemirror" { * tokens will be converted to span elements as in an editor, * and inserted into the node (through innerHTML). */ - function runMode(text: string, modespec: any, callback: (HTMLElement | ((text: string, style: string) => void)), options? : { tabSize?: number; state?: any; }): void; + function runMode(text: string, modespec: any, callback: (HTMLElement | ((text: string, style: string | null) => void)), options? : { tabSize?: number; state?: any; }): void; } diff --git a/types/codemirror/codemirror-showhint.d.ts b/types/codemirror/codemirror-showhint.d.ts index 55a3d6012b..c6f367d0d2 100644 --- a/types/codemirror/codemirror-showhint.d.ts +++ b/types/codemirror/codemirror-showhint.d.ts @@ -1,6 +1,8 @@ // Type definitions for CodeMirror // Project: https://github.com/marijnh/CodeMirror -// Definitions by: jacqt , basarat +// Definitions by: jacqt +// basarat +// mbilsing // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // See docs https://codemirror.net/doc/manual.html#addon_show-hint @@ -16,7 +18,7 @@ declare module "codemirror" { and return a {list, from, to} object, where list is an array of strings or objects (the completions), and from and to give the start and end of the token that is being completed as {line, ch} objects. An optional selectedHint property (an integer) can be added to the completion object to control the initially selected hint. */ - function showHint(cm: CodeMirror.Doc, hinter?: HintFunction, options?: ShowHintOptions): void; + function showHint(cm: CodeMirror.Editor, hinter?: HintFunction, options?: ShowHintOptions): void; interface Hints { from: Position; @@ -32,7 +34,7 @@ declare module "codemirror" { displayText?: string; from?: Position; /** Called if a completion is picked. If provided *you* are responsible for applying the completion */ - hint?: (cm: any, data: Hints, cur: Hint) => void; + hint?: (cm: CodeMirror.Editor, data: Hints, cur: Hint) => void; render?: (element: HTMLLIElement, data: Hints, cur: Hint) => void; to?: Position; } @@ -41,18 +43,15 @@ declare module "codemirror" { /** An extension of the existing CodeMirror typings for the Editor.on("keyup", func) syntax */ on(eventName: string, handler: (doc: CodeMirror.Doc, event: any) => void): void; off(eventName: string, handler: (doc: CodeMirror.Doc, event: any) => void): void; - } - - interface Doc { showHint: (options: ShowHintOptions) => void; } interface HintFunction { - (doc: CodeMirror.Doc): Hints; + (cm: CodeMirror.Editor): Hints; } interface AsyncHintFunction { - (doc: CodeMirror.Doc, callback: (hints: Hints) => any): any; + (cm: CodeMirror.Editor, callback: (hints: Hints) => any): any; async?: boolean; } diff --git a/types/codemirror/index.d.ts b/types/codemirror/index.d.ts index b42ebabae3..fb755fae4b 100644 --- a/types/codemirror/index.d.ts +++ b/types/codemirror/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for CodeMirror // Project: https://github.com/marijnh/CodeMirror // Definitions by: mihailik +// nrbernard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = CodeMirror; @@ -102,6 +103,21 @@ declare namespace CodeMirror { To fire your own events, use CodeMirror.signal(target, name, args...), where target is a non-DOM-node object. */ function signal(target: any, name: string, ...args: any[]): void; + type DOMEvent = 'mousedown' | 'dblclick' | 'touchstart' | 'contextmenu' | 'keydown' | 'keypress' | 'keyup' | 'cut' | 'copy' | 'paste' | 'dragstart' | 'dragenter' | 'dragover' | 'dragleave' | 'drop'; + + interface Token { + /** The character(on the given line) at which the token starts. */ + start: number; + /** The character at which the token ends. */ + end: number; + /** The token's string. */ + string: string; + /** The token type the mode assigned to the token, such as "keyword" or "comment" (may also be null). */ + type: string | null; + /** The mode's state at the end of this token. */ + state: any; + } + interface Editor { /** Tells you whether the editor currently has focus. */ @@ -163,7 +179,7 @@ declare namespace CodeMirror { /** Sets the gutter marker for the given gutter (identified by its CSS class, see the gutters option) to the given value. Value can be either null, to clear the marker, or a DOM element, to set it. The DOM element will be shown in the specified gutter next to the specified line. */ - setGutterMarker(line: any, gutterID: string, value: HTMLElement): CodeMirror.LineHandle; + setGutterMarker(line: any, gutterID: string, value: HTMLElement | null): CodeMirror.LineHandle; /** Remove all gutter markers in the gutter with the given ID. */ clearGutter(gutterID: string): void; @@ -228,7 +244,7 @@ declare namespace CodeMirror { setSize(width: any, height: any): void; /** Scroll the editor to a given(pixel) position.Both arguments may be left as null or undefined to have no effect. */ - scrollTo(x: number, y: number): void; + scrollTo(x?: number | null, y?: number | null): void; /** Get an { left , top , width , height , clientWidth , clientHeight } object that represents the current scroll position, the size of the scrollable area, and the size of the visible area(minus scrollbars). */ @@ -236,7 +252,7 @@ declare namespace CodeMirror { /** Scrolls the given element into view. pos is a { line , ch } position, referring to a given character, null, to refer to the cursor. The margin parameter is optional. When given, it indicates the amount of pixels around the given area that should be made visible as well. */ - scrollIntoView(pos: CodeMirror.Position, margin?: number): void; + scrollIntoView(pos: CodeMirror.Position | null, margin?: number): void; /** Scrolls the given element into view. pos is a { left , top , right , bottom } object, in editor-local coordinates. The margin parameter is optional. When given, it indicates the amount of pixels around the given area that should be made visible as well. */ @@ -287,20 +303,11 @@ declare namespace CodeMirror { you should probably follow up by calling this method to ensure CodeMirror is still looking as intended. */ refresh(): void; - /** Retrieves information about the token the current mode found before the given position (a {line, ch} object). */ - getTokenAt(pos: CodeMirror.Position): { - /** The character(on the given line) at which the token starts. */ - start: number; - /** The character at which the token ends. */ - end: number; - /** The token's string. */ - string: string; - /** The token type the mode assigned to the token, such as "keyword" or "comment" (may also be null). */ - type: string; - /** The mode's state at the end of this token. */ - state: any; - }; + getTokenAt(pos: CodeMirror.Position): Token; + + /** This is similar to getTokenAt, but collects all tokens for a given line into an array. */ + getLineTokens(line: number, precise?: boolean): Token[]; /** Returns the mode's parser state, if any, at the end of the given line number. If no line number is given, the state at the end of the document is returned. @@ -405,6 +412,10 @@ declare namespace CodeMirror { on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: CodeMirror.LineHandle, element: HTMLElement) => void ): void; off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: CodeMirror.LineHandle, element: HTMLElement) => void ): void; + /** Fires when one of the DOM events fires. */ + on(eventName: DOMEvent, handler: (instance: CodeMirror.Editor, event: Event) => void ): void; + off(eventName: DOMEvent, handler: (instance: CodeMirror.Editor, event: Event) => void ): void; + /** Expose the state object, so that the Editor.state.completionActive property is reachable*/ state: any; } @@ -464,7 +475,7 @@ declare namespace CodeMirror { getLineHandle(num: number): CodeMirror.LineHandle; /** Given a line handle, returns the current position of that line (or null when it is no longer in the document). */ - getLineNumber(handle: CodeMirror.LineHandle): number; + getLineNumber(handle: CodeMirror.LineHandle): number | null; /** Iterate over the whole document, and call f for each line, passing the line handle. This is a faster way to visit a range of line handlers than calling getLineHandle for each of them. @@ -487,6 +498,9 @@ declare namespace CodeMirror { /** Get the currently selected code. */ getSelection(): string; + + /** Returns an array containing a string for each selection, representing the content of the selections. */ + getSelections(lineSep?: string): Array; /** Replace the selection with the given string. By default, the new selection will span the inserted text. The optional collapse argument can be used to change this � passing "start" or "end" will collapse the selection to the start or end of the inserted text. */ @@ -522,7 +536,7 @@ declare namespace CodeMirror { /** Retrieve the editor associated with a document. May return null. */ - getEditor(): CodeMirror.Editor; + getEditor(): CodeMirror.Editor | null; /** Create an identical copy of the given doc. When copyHistory is true , the history will also be copied.Can not be called directly on an editor. */ @@ -935,12 +949,12 @@ declare namespace CodeMirror { /** * Returns the next character in the stream without advancing it. Will return an null at the end of the line. */ - peek(): string; + peek(): string | null; /** * Returns the next character in the stream and advances it. Also returns null when no more characters are available. */ - next(): string; + next(): string | null; /** * match can be a character, a regular expression, or a function that takes a character and returns a boolean. @@ -1016,7 +1030,7 @@ declare namespace CodeMirror { * This function should read one token from the stream it is given as an argument, optionally update its state, * and return a style string, or null for tokens that do not have to be styled. Multiple styles can be returned, separated by spaces. */ - token(stream: StringStream, state: T): string; + token(stream: StringStream, state: T): string | null; /** * A function that produces a state object to be used at the start of a document. diff --git a/types/codemirror/test/showhint.ts b/types/codemirror/test/showhint.ts index 00dbe6bed4..0aabcc9a86 100644 --- a/types/codemirror/test/showhint.ts +++ b/types/codemirror/test/showhint.ts @@ -1,16 +1,16 @@ -var doc = new CodeMirror.Doc('text'); +var cm = CodeMirror(document.body, {value: 'text'}); var pos = new CodeMirror.Pos(2, 3); -CodeMirror.showHint(doc); -CodeMirror.showHint(doc, function (cm) { +CodeMirror.showHint(cm); +CodeMirror.showHint(cm, function (cm) { return { from: pos, list: ["one", "two"], to: pos }; }); -CodeMirror.showHint(doc, function (cm) { +CodeMirror.showHint(cm, function (cm) { return { from: pos, list: [ @@ -32,7 +32,7 @@ CodeMirror.showHint(doc, function (cm) { }; }); var asyncHintFunc : CodeMirror.AsyncHintFunction = - (doc: CodeMirror.Doc, callback: (hints: CodeMirror.Hints) => any) => { + (cm: CodeMirror.Editor, callback: (hints: CodeMirror.Hints) => any) => { callback({ from: pos, list: ["one", "two"], @@ -41,7 +41,7 @@ var asyncHintFunc : CodeMirror.AsyncHintFunction = }; asyncHintFunc.async = true; -doc.showHint({ +cm.showHint({ completeSingle: false, hint: asyncHintFunc }) diff --git a/types/color-convert/color-convert-tests.ts b/types/color-convert/color-convert-tests.ts new file mode 100644 index 0000000000..fe45e209f3 --- /dev/null +++ b/types/color-convert/color-convert-tests.ts @@ -0,0 +1,6 @@ +import * as color from 'color-convert'; +import * as conv from 'color-convert/conversions'; + +const hsv: [number, number, number] = color.rgb.hsv([1, 2, 3]); +const hsv_raw: [number, number, number] = color.rgb.hsv.raw([1, 2, 3]); +const aaa: [number, number, number] = color.rgb.hsv([1, 2, 3]); diff --git a/types/color-convert/conversions.d.ts b/types/color-convert/conversions.d.ts new file mode 100644 index 0000000000..aa461d40b0 --- /dev/null +++ b/types/color-convert/conversions.d.ts @@ -0,0 +1,136 @@ +import * as cssKeywords from 'color-name'; + +export type RGB = [number, number, number]; +export type HSL = [number, number, number]; +export type HSV = [number, number, number]; +export type HWB = [number, number, number]; +export type CMYK = [number, number, number, number]; +export type XYZ = [number, number, number]; +export type LAB = [number, number, number]; +export type LCH = [number, number, number]; +export type HEX = string; +export type KEYWORD = keyof typeof cssKeywords; +export type ANSI16 = number; +export type ANSI256 = number; +export type HCG = [number, number, number]; +export type APPLE = [number, number, number]; +export type GRAY = [number]; + +export namespace rgb { + const channels: 3; + const labels: 'rgb'; + function hsl(rgb: RGB): HSL; + function hsv(rgb: RGB): HSV; + function hwb(rgb: RGB): HWB; + function cmyk(rgb: RGB): CMYK; + function keyword(rgb: RGB): KEYWORD; + function xyz(rgb: RGB): XYZ; + function lab(rgb: RGB): LAB; + function ansi16(rgb: RGB): ANSI16; + function ansi256(rgb: RGB): ANSI256; + function hex(rgb: RGB): HEX; + function hcg(rgb: RGB): HCG; + function apple(rgb: RGB): APPLE; + function gray(rgb: RGB): GRAY; +} + +export namespace hsl { + const channels: 3; + const labels: 'hsl'; + function rgb(hsl: HSL): RGB; + function hsv(hsl: HSL): HSV; + function hcg(hsl: HSL): HCG; +} + +export namespace hsv { + const channels: 3; + const labels: 'hsv'; + function rgb(hsv: HSV): RGB; + function hsl(hsv: HSV): HSL; + function ansi16(hsv: HSV): ANSI16; + function hcg(hsv: HSV): HCG; +} + +export namespace hwb { + const channels: 3; + const labels: 'hwb'; + function rgb(hwb: HWB): RGB; + function hcg(hwb: HWB): HCG; +} + +export namespace cmyk { + const channels: 4; + const labels: 'cmyk'; + function rgb(cmyk: CMYK): RGB; +} + +export namespace xyz { + const channels: 3; + const labels: 'xyz'; + function rgb(xyz: XYZ): RGB; + function lab(xyz: XYZ): LAB; +} + +export namespace lab { + const channels: 3; + const labels: 'lab'; + function xyz(lab: LAB): XYZ; + function lch(lab: LAB): LCH; +} + +export namespace lch { + const channels: 3; + const labels: 'lch'; + function lab(lch: LCH): LAB; +} + +export namespace hex { + const channels: 1; + const labels: ['hex']; + function rgb(hex: HEX): RGB; +} + +export namespace keyword { + const channels: 1; + const labels: ['keyword']; + function rgb(keyword: KEYWORD): RGB; +} + +export namespace ansi16 { + const channels: 1; + const labels: ['ansi16']; + function rgb(ansi16: ANSI16): RGB; +} + +export namespace ansi256 { + const channels: 1; + const labels: ['ansi256']; + function rgb(ansi256: ANSI256): RGB; +} + +export namespace hcg { + const channels: 3; + const labels: ['h', 'c', 'g']; + function rgb(hcg: HCG): RGB; + function hsv(hcg: HCG): HSV; + function hsl(hcg: HCG): HSL; + function hwb(hcg: HCG): HWB; +} + +export namespace apple { + const channels: 3; + const labels: ['r16', 'g16', 'b16']; + function rgb(apple: APPLE): RGB; +} + +export namespace gray { + const channels: 1; + const labels: ['gray']; + function rgb(gray: GRAY): RGB; + function hsl(gray: GRAY): HSL; + function hsv(gray: GRAY): HSV; + function hwb(gray: GRAY): HWB; + function cmyk(gray: GRAY): CMYK; + function lab(gray: GRAY): LAB; + function hex(gray: GRAY): HEX; +} diff --git a/types/color-convert/index.d.ts b/types/color-convert/index.d.ts new file mode 100644 index 0000000000..be2a0dafa6 --- /dev/null +++ b/types/color-convert/index.d.ts @@ -0,0 +1,98 @@ +// Type definitions for color-convert 1.9 +// Project: https://github.com/qix-/color-convert#readme +// Definitions by: Junyoung Clare Jang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import conversions = require('./conversions'); +import route = require('./route'); + +export const rgb: typeof conversions.rgb & route.rgb & { + [F in keyof route.rgb]: { + raw: route.rgb[F] + } +}; + +export const hsl: typeof conversions.hsl & route.hsl & { + [F in keyof route.hsl]: { + raw: route.hsl[F] + } +}; + +export const hsv: typeof conversions.hsv & route.hsv & { + [F in keyof route.hsv]: { + raw: route.hsv[F] + } +}; + +export const hwb: typeof conversions.hwb & route.hwb & { + [F in keyof route.hwb]: { + raw: route.hwb[F] + } +}; + +export const cmyk: typeof conversions.cmyk & route.cmyk & { + [F in keyof route.cmyk]: { + raw: route.cmyk[F] + } +}; + +export const xyz: typeof conversions.xyz & route.xyz & { + [F in keyof route.xyz]: { + raw: route.xyz[F] + } +}; + +export const lab: typeof conversions.lab & route.lab & { + [F in keyof route.lab]: { + raw: route.lab[F] + } +}; + +export const lch: typeof conversions.lch & route.lch & { + [F in keyof route.lch]: { + raw: route.lch[F] + } +}; + +export const hex: typeof conversions.hex & route.hex & { + [F in keyof route.hex]: { + raw: route.hex[F] + } +}; + +export const keyword: typeof conversions.keyword & route.keyword & { + [F in keyof route.keyword]: { + raw: route.keyword[F] + } +}; + +export const ansi16: typeof conversions.ansi16 & route.ansi16 & { + [F in keyof route.ansi16]: { + raw: route.ansi16[F] + } +}; + +export const ansi256: typeof conversions.ansi256 & route.ansi256 & { + [F in keyof route.ansi256]: { + raw: route.ansi256[F] + } +}; + +export const hcg: typeof conversions.hcg & route.hcg & { + [F in keyof route.hcg]: { + raw: route.hcg[F] + } +}; + +export const apple: typeof conversions.apple & route.apple & { + [F in keyof route.apple]: { + raw: route.apple[F] + } +}; + +export const gray: typeof conversions.gray & route.gray & { + [F in keyof route.gray]: { + raw: route.gray[F] + } +}; diff --git a/types/color-convert/route.d.ts b/types/color-convert/route.d.ts new file mode 100644 index 0000000000..f9ea4f7cf8 --- /dev/null +++ b/types/color-convert/route.d.ts @@ -0,0 +1,262 @@ +import conversions = require('./conversions'); + +declare namespace route { + interface rgb { + hsl(from: conversions.RGB): conversions.HSL; + hsv(from: conversions.RGB): conversions.HSV; + hwb(from: conversions.RGB): conversions.HWB; + cmyk(from: conversions.RGB): conversions.CMYK; + xyz(from: conversions.RGB): conversions.XYZ; + lab(from: conversions.RGB): conversions.LAB; + lch(from: conversions.RGB): conversions.LCH; + hex(from: conversions.RGB): conversions.HEX; + keyword(from: conversions.RGB): conversions.KEYWORD; + ansi16(from: conversions.RGB): conversions.ANSI16; + ansi256(from: conversions.RGB): conversions.ANSI256; + hcg(from: conversions.RGB): conversions.HCG; + apple(from: conversions.RGB): conversions.APPLE; + gray(from: conversions.RGB): conversions.GRAY; + } + interface hsl { + rgb(from: conversions.HSL): conversions.RGB; + hsv(from: conversions.HSL): conversions.HSV; + hwb(from: conversions.HSL): conversions.HWB; + cmyk(from: conversions.HSL): conversions.CMYK; + xyz(from: conversions.HSL): conversions.XYZ; + lab(from: conversions.HSL): conversions.LAB; + lch(from: conversions.HSL): conversions.LCH; + hex(from: conversions.HSL): conversions.HEX; + keyword(from: conversions.HSL): conversions.KEYWORD; + ansi16(from: conversions.HSL): conversions.ANSI16; + ansi256(from: conversions.HSL): conversions.ANSI256; + hcg(from: conversions.HSL): conversions.HCG; + apple(from: conversions.HSL): conversions.APPLE; + gray(from: conversions.HSL): conversions.GRAY; + } + interface hsv { + rgb(from: conversions.HSV): conversions.RGB; + hsl(from: conversions.HSV): conversions.HSL; + hwb(from: conversions.HSV): conversions.HWB; + cmyk(from: conversions.HSV): conversions.CMYK; + xyz(from: conversions.HSV): conversions.XYZ; + lab(from: conversions.HSV): conversions.LAB; + lch(from: conversions.HSV): conversions.LCH; + hex(from: conversions.HSV): conversions.HEX; + keyword(from: conversions.HSV): conversions.KEYWORD; + ansi16(from: conversions.HSV): conversions.ANSI16; + ansi256(from: conversions.HSV): conversions.ANSI256; + hcg(from: conversions.HSV): conversions.HCG; + apple(from: conversions.HSV): conversions.APPLE; + gray(from: conversions.HSV): conversions.GRAY; + } + interface hwb { + rgb(from: conversions.HWB): conversions.RGB; + hsl(from: conversions.HWB): conversions.HSL; + hsv(from: conversions.HWB): conversions.HSV; + cmyk(from: conversions.HWB): conversions.CMYK; + xyz(from: conversions.HWB): conversions.XYZ; + lab(from: conversions.HWB): conversions.LAB; + lch(from: conversions.HWB): conversions.LCH; + hex(from: conversions.HWB): conversions.HEX; + keyword(from: conversions.HWB): conversions.KEYWORD; + ansi16(from: conversions.HWB): conversions.ANSI16; + ansi256(from: conversions.HWB): conversions.ANSI256; + hcg(from: conversions.HWB): conversions.HCG; + apple(from: conversions.HWB): conversions.APPLE; + gray(from: conversions.HWB): conversions.GRAY; + } + interface cmyk { + rgb(from: conversions.CMYK): conversions.RGB; + hsl(from: conversions.CMYK): conversions.HSL; + hsv(from: conversions.CMYK): conversions.HSV; + hwb(from: conversions.CMYK): conversions.HWB; + xyz(from: conversions.CMYK): conversions.XYZ; + lab(from: conversions.CMYK): conversions.LAB; + lch(from: conversions.CMYK): conversions.LCH; + hex(from: conversions.CMYK): conversions.HEX; + keyword(from: conversions.CMYK): conversions.KEYWORD; + ansi16(from: conversions.CMYK): conversions.ANSI16; + ansi256(from: conversions.CMYK): conversions.ANSI256; + hcg(from: conversions.CMYK): conversions.HCG; + apple(from: conversions.CMYK): conversions.APPLE; + gray(from: conversions.CMYK): conversions.GRAY; + } + interface xyz { + rgb(from: conversions.XYZ): conversions.RGB; + hsl(from: conversions.XYZ): conversions.HSL; + hsv(from: conversions.XYZ): conversions.HSV; + hwb(from: conversions.XYZ): conversions.HWB; + cmyk(from: conversions.XYZ): conversions.CMYK; + lab(from: conversions.XYZ): conversions.LAB; + lch(from: conversions.XYZ): conversions.LCH; + hex(from: conversions.XYZ): conversions.HEX; + keyword(from: conversions.XYZ): conversions.KEYWORD; + ansi16(from: conversions.XYZ): conversions.ANSI16; + ansi256(from: conversions.XYZ): conversions.ANSI256; + hcg(from: conversions.XYZ): conversions.HCG; + apple(from: conversions.XYZ): conversions.APPLE; + gray(from: conversions.XYZ): conversions.GRAY; + } + interface lab { + rgb(from: conversions.LAB): conversions.RGB; + hsl(from: conversions.LAB): conversions.HSL; + hsv(from: conversions.LAB): conversions.HSV; + hwb(from: conversions.LAB): conversions.HWB; + cmyk(from: conversions.LAB): conversions.CMYK; + xyz(from: conversions.LAB): conversions.XYZ; + lch(from: conversions.LAB): conversions.LCH; + hex(from: conversions.LAB): conversions.HEX; + keyword(from: conversions.LAB): conversions.KEYWORD; + ansi16(from: conversions.LAB): conversions.ANSI16; + ansi256(from: conversions.LAB): conversions.ANSI256; + hcg(from: conversions.LAB): conversions.HCG; + apple(from: conversions.LAB): conversions.APPLE; + gray(from: conversions.LAB): conversions.GRAY; + } + interface lch { + rgb(from: conversions.LCH): conversions.RGB; + hsl(from: conversions.LCH): conversions.HSL; + hsv(from: conversions.LCH): conversions.HSV; + hwb(from: conversions.LCH): conversions.HWB; + cmyk(from: conversions.LCH): conversions.CMYK; + xyz(from: conversions.LCH): conversions.XYZ; + lab(from: conversions.LCH): conversions.LAB; + hex(from: conversions.LCH): conversions.HEX; + keyword(from: conversions.LCH): conversions.KEYWORD; + ansi16(from: conversions.LCH): conversions.ANSI16; + ansi256(from: conversions.LCH): conversions.ANSI256; + hcg(from: conversions.LCH): conversions.HCG; + apple(from: conversions.LCH): conversions.APPLE; + gray(from: conversions.LCH): conversions.GRAY; + } + interface hex { + rgb(from: conversions.HEX): conversions.RGB; + hsl(from: conversions.HEX): conversions.HSL; + hsv(from: conversions.HEX): conversions.HSV; + hwb(from: conversions.HEX): conversions.HWB; + cmyk(from: conversions.HEX): conversions.CMYK; + xyz(from: conversions.HEX): conversions.XYZ; + lab(from: conversions.HEX): conversions.LAB; + lch(from: conversions.HEX): conversions.LCH; + keyword(from: conversions.HEX): conversions.KEYWORD; + ansi16(from: conversions.HEX): conversions.ANSI16; + ansi256(from: conversions.HEX): conversions.ANSI256; + hcg(from: conversions.HEX): conversions.HCG; + apple(from: conversions.HEX): conversions.APPLE; + gray(from: conversions.HEX): conversions.GRAY; + } + interface keyword { + rgb(from: conversions.KEYWORD): conversions.RGB; + hsl(from: conversions.KEYWORD): conversions.HSL; + hsv(from: conversions.KEYWORD): conversions.HSV; + hwb(from: conversions.KEYWORD): conversions.HWB; + cmyk(from: conversions.KEYWORD): conversions.CMYK; + xyz(from: conversions.KEYWORD): conversions.XYZ; + lab(from: conversions.KEYWORD): conversions.LAB; + lch(from: conversions.KEYWORD): conversions.LCH; + hex(from: conversions.KEYWORD): conversions.HEX; + ansi16(from: conversions.KEYWORD): conversions.ANSI16; + ansi256(from: conversions.KEYWORD): conversions.ANSI256; + hcg(from: conversions.KEYWORD): conversions.HCG; + apple(from: conversions.KEYWORD): conversions.APPLE; + gray(from: conversions.KEYWORD): conversions.GRAY; + } + interface ansi16 { + rgb(from: conversions.ANSI16): conversions.RGB; + hsl(from: conversions.ANSI16): conversions.HSL; + hsv(from: conversions.ANSI16): conversions.HSV; + hwb(from: conversions.ANSI16): conversions.HWB; + cmyk(from: conversions.ANSI16): conversions.CMYK; + xyz(from: conversions.ANSI16): conversions.XYZ; + lab(from: conversions.ANSI16): conversions.LAB; + lch(from: conversions.ANSI16): conversions.LCH; + hex(from: conversions.ANSI16): conversions.HEX; + keyword(from: conversions.ANSI16): conversions.KEYWORD; + ansi256(from: conversions.ANSI16): conversions.ANSI256; + hcg(from: conversions.ANSI16): conversions.HCG; + apple(from: conversions.ANSI16): conversions.APPLE; + gray(from: conversions.ANSI16): conversions.GRAY; + } + interface ansi256 { + rgb(from: conversions.ANSI256): conversions.RGB; + hsl(from: conversions.ANSI256): conversions.HSL; + hsv(from: conversions.ANSI256): conversions.HSV; + hwb(from: conversions.ANSI256): conversions.HWB; + cmyk(from: conversions.ANSI256): conversions.CMYK; + xyz(from: conversions.ANSI256): conversions.XYZ; + lab(from: conversions.ANSI256): conversions.LAB; + lch(from: conversions.ANSI256): conversions.LCH; + hex(from: conversions.ANSI256): conversions.HEX; + keyword(from: conversions.ANSI256): conversions.KEYWORD; + ansi16(from: conversions.ANSI256): conversions.ANSI16; + hcg(from: conversions.ANSI256): conversions.HCG; + apple(from: conversions.ANSI256): conversions.APPLE; + gray(from: conversions.ANSI256): conversions.GRAY; + } + interface hcg { + rgb(from: conversions.HCG): conversions.RGB; + hsl(from: conversions.HCG): conversions.HSL; + hsv(from: conversions.HCG): conversions.HSV; + hwb(from: conversions.HCG): conversions.HWB; + cmyk(from: conversions.HCG): conversions.CMYK; + xyz(from: conversions.HCG): conversions.XYZ; + lab(from: conversions.HCG): conversions.LAB; + lch(from: conversions.HCG): conversions.LCH; + hex(from: conversions.HCG): conversions.HEX; + keyword(from: conversions.HCG): conversions.KEYWORD; + ansi16(from: conversions.HCG): conversions.ANSI16; + ansi256(from: conversions.HCG): conversions.ANSI256; + apple(from: conversions.HCG): conversions.APPLE; + gray(from: conversions.HCG): conversions.GRAY; + } + interface apple { + rgb(from: conversions.APPLE): conversions.RGB; + hsl(from: conversions.APPLE): conversions.HSL; + hsv(from: conversions.APPLE): conversions.HSV; + hwb(from: conversions.APPLE): conversions.HWB; + cmyk(from: conversions.APPLE): conversions.CMYK; + xyz(from: conversions.APPLE): conversions.XYZ; + lab(from: conversions.APPLE): conversions.LAB; + lch(from: conversions.APPLE): conversions.LCH; + hex(from: conversions.APPLE): conversions.HEX; + keyword(from: conversions.APPLE): conversions.KEYWORD; + ansi16(from: conversions.APPLE): conversions.ANSI16; + ansi256(from: conversions.APPLE): conversions.ANSI256; + hcg(from: conversions.APPLE): conversions.HCG; + gray(from: conversions.APPLE): conversions.GRAY; + } + interface gray { + rgb(from: conversions.GRAY): conversions.RGB; + hsl(from: conversions.GRAY): conversions.HSL; + hsv(from: conversions.GRAY): conversions.HSV; + hwb(from: conversions.GRAY): conversions.HWB; + cmyk(from: conversions.GRAY): conversions.CMYK; + xyz(from: conversions.GRAY): conversions.XYZ; + lab(from: conversions.GRAY): conversions.LAB; + lch(from: conversions.GRAY): conversions.LCH; + hex(from: conversions.GRAY): conversions.HEX; + keyword(from: conversions.GRAY): conversions.KEYWORD; + ansi16(from: conversions.GRAY): conversions.ANSI16; + ansi256(from: conversions.GRAY): conversions.ANSI256; + hcg(from: conversions.GRAY): conversions.HCG; + apple(from: conversions.GRAY): conversions.APPLE; + } +} + +declare function route(fromModel: 'rgb'): route.rgb; +declare function route(fromModel: 'hsl'): route.hsl; +declare function route(fromModel: 'hsv'): route.hsv; +declare function route(fromModel: 'hwb'): route.hwb; +declare function route(fromModel: 'cmyk'): route.cmyk; +declare function route(fromModel: 'xyz'): route.xyz; +declare function route(fromModel: 'lab'): route.lab; +declare function route(fromModel: 'lch'): route.lch; +declare function route(fromModel: 'hex'): route.hex; +declare function route(fromModel: 'keyword'): route.keyword; +declare function route(fromModel: 'ansi16'): route.ansi16; +declare function route(fromModel: 'ansi256'): route.ansi256; +declare function route(fromModel: 'hcg'): route.hcg; +declare function route(fromModel: 'apple'): route.apple; +declare function route(fromModel: 'gray'): route.gray; + +export = route; diff --git a/types/color-convert/tsconfig.json b/types/color-convert/tsconfig.json new file mode 100644 index 0000000000..70b4bd0fd9 --- /dev/null +++ b/types/color-convert/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "conversions.d.ts", + "route.d.ts", + "color-convert-tests.ts" + ] +} diff --git a/types/color-convert/tslint.json b/types/color-convert/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-convert/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/color-name/color-name-tests.ts b/types/color-name/color-name-tests.ts new file mode 100644 index 0000000000..5d8998c97a --- /dev/null +++ b/types/color-name/color-name-tests.ts @@ -0,0 +1,5 @@ +import * as colorname from 'color-name'; + +let color: [number, number, number] = colorname.aliceblue; +color = colorname.darkkhaki; +color = colorname.gainsboro; diff --git a/types/color-name/index.d.ts b/types/color-name/index.d.ts new file mode 100644 index 0000000000..65b4ecc8fb --- /dev/null +++ b/types/color-name/index.d.ts @@ -0,0 +1,161 @@ +// Type definitions for color-name 1.1 +// Project: https://www.npmjs.com/package/color-name +// Definitions by: Junyoung Clare Jang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Tuple of Red, Green, and Blue + * @example + * // Red = 55, Green = 70, Blue = 0 + * const rgb: RGB = [55, 70, 0]; + */ +export type RGB = [number, number, number]; + +export const aliceblue: RGB; +export const antiquewhite: RGB; +export const aqua: RGB; +export const aquamarine: RGB; +export const azure: RGB; +export const beige: RGB; +export const bisque: RGB; +export const black: RGB; +export const blanchedalmond: RGB; +export const blue: RGB; +export const blueviolet: RGB; +export const brown: RGB; +export const burlywood: RGB; +export const cadetblue: RGB; +export const chartreuse: RGB; +export const chocolate: RGB; +export const coral: RGB; +export const cornflowerblue: RGB; +export const cornsilk: RGB; +export const crimson: RGB; +export const cyan: RGB; +export const darkblue: RGB; +export const darkcyan: RGB; +export const darkgoldenrod: RGB; +export const darkgray: RGB; +export const darkgreen: RGB; +export const darkgrey: RGB; +export const darkkhaki: RGB; +export const darkmagenta: RGB; +export const darkolivegreen: RGB; +export const darkorange: RGB; +export const darkorchid: RGB; +export const darkred: RGB; +export const darksalmon: RGB; +export const darkseagreen: RGB; +export const darkslateblue: RGB; +export const darkslategray: RGB; +export const darkslategrey: RGB; +export const darkturquoise: RGB; +export const darkviolet: RGB; +export const deeppink: RGB; +export const deepskyblue: RGB; +export const dimgray: RGB; +export const dimgrey: RGB; +export const dodgerblue: RGB; +export const firebrick: RGB; +export const floralwhite: RGB; +export const forestgreen: RGB; +export const fuchsia: RGB; +export const gainsboro: RGB; +export const ghostwhite: RGB; +export const gold: RGB; +export const goldenrod: RGB; +export const gray: RGB; +export const green: RGB; +export const greenyellow: RGB; +export const grey: RGB; +export const honeydew: RGB; +export const hotpink: RGB; +export const indianred: RGB; +export const indigo: RGB; +export const ivory: RGB; +export const khaki: RGB; +export const lavender: RGB; +export const lavenderblush: RGB; +export const lawngreen: RGB; +export const lemonchiffon: RGB; +export const lightblue: RGB; +export const lightcoral: RGB; +export const lightcyan: RGB; +export const lightgoldenrodyellow: RGB; +export const lightgray: RGB; +export const lightgreen: RGB; +export const lightgrey: RGB; +export const lightpink: RGB; +export const lightsalmon: RGB; +export const lightseagreen: RGB; +export const lightskyblue: RGB; +export const lightslategray: RGB; +export const lightslategrey: RGB; +export const lightsteelblue: RGB; +export const lightyellow: RGB; +export const lime: RGB; +export const limegreen: RGB; +export const linen: RGB; +export const magenta: RGB; +export const maroon: RGB; +export const mediumaquamarine: RGB; +export const mediumblue: RGB; +export const mediumorchid: RGB; +export const mediumpurple: RGB; +export const mediumseagreen: RGB; +export const mediumslateblue: RGB; +export const mediumspringgreen: RGB; +export const mediumturquoise: RGB; +export const mediumvioletred: RGB; +export const midnightblue: RGB; +export const mintcream: RGB; +export const mistyrose: RGB; +export const moccasin: RGB; +export const navajowhite: RGB; +export const navy: RGB; +export const oldlace: RGB; +export const olive: RGB; +export const olivedrab: RGB; +export const orange: RGB; +export const orangered: RGB; +export const orchid: RGB; +export const palegoldenrod: RGB; +export const palegreen: RGB; +export const paleturquoise: RGB; +export const palevioletred: RGB; +export const papayawhip: RGB; +export const peachpuff: RGB; +export const peru: RGB; +export const pink: RGB; +export const plum: RGB; +export const powderblue: RGB; +export const purple: RGB; +export const rebeccapurple: RGB; +export const red: RGB; +export const rosybrown: RGB; +export const royalblue: RGB; +export const saddlebrown: RGB; +export const salmon: RGB; +export const sandybrown: RGB; +export const seagreen: RGB; +export const seashell: RGB; +export const sienna: RGB; +export const silver: RGB; +export const skyblue: RGB; +export const slateblue: RGB; +export const slategray: RGB; +export const slategrey: RGB; +export const snow: RGB; +export const springgreen: RGB; +export const steelblue: RGB; +export const tan: RGB; +export const teal: RGB; +export const thistle: RGB; +export const tomato: RGB; +export const turquoise: RGB; +export const violet: RGB; +export const wheat: RGB; +export const white: RGB; +export const whitesmoke: RGB; +export const yellow: RGB; +export const yellowgreen: RGB; diff --git a/types/color-name/tsconfig.json b/types/color-name/tsconfig.json new file mode 100644 index 0000000000..30cfb50814 --- /dev/null +++ b/types/color-name/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "forceConsistentCasingInFileNames": true, + "lib": [ + "es6" + ], + "module": "commonjs", + "noEmit": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "types": [], + "typeRoots": ["../"] + }, + "files": [ + "index.d.ts", + "color-name-tests.ts" + ] +} diff --git a/types/color-name/tslint.json b/types/color-name/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-name/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/color-string/color-string-tests.ts b/types/color-string/color-string-tests.ts new file mode 100644 index 0000000000..3f084fbc25 --- /dev/null +++ b/types/color-string/color-string-tests.ts @@ -0,0 +1,38 @@ +import * as colorString from 'color-string'; + +let colorDescriptor: colorString.ColorDescriptor | null; +colorDescriptor = colorString.get('#FFF'); +colorDescriptor = colorString.get('#FFFA'); +colorDescriptor = colorString.get('#FFFFFFAA'); +colorDescriptor = colorString.get('hsl(360, 100%, 50%)'); +colorDescriptor = colorString.get('hwb(60, 3%, 60%)'); + +let color: colorString.Color | null; +color = colorString.get.rgb('#FFF'); +color = colorString.get.rgb('blue'); +color = colorString.get.rgb('rgba(200, 60, 60, 0.3)'); +color = colorString.get.rgb('rgb(200, 200, 200)'); + +color = colorString.get.hsl('hsl(360, 100%, 50%)'); +color = colorString.get.hsl('hsla(360, 60%, 50%, 0.4)'); +color = colorString.get.hwb('hwb(60, 3%, 60%)'); + +color = colorString.get.hwb('hwb(60, 3%, 60%, 0.6)'); + +color = colorString.get.rgb('invalid color string'); + +let stringifiedColor: string; +stringifiedColor = colorString.to.hex([255, 255, 255]); +stringifiedColor = colorString.to.hex([0, 0, 255, 0.4]); +stringifiedColor = colorString.to.hex([0, 0, 255], 0.4); +stringifiedColor = colorString.to.rgb([255, 255, 255]); +stringifiedColor = colorString.to.rgb([0, 0, 255, 0.4]); +stringifiedColor = colorString.to.rgb([0, 0, 255], 0.4); +stringifiedColor = colorString.to.rgb.percent([0, 0, 255]); +stringifiedColor = colorString.to.keyword([255, 255, 0]); +stringifiedColor = colorString.to.hsl([360, 100, 100]); +stringifiedColor = colorString.to.hwb([50, 3, 15]); + +stringifiedColor = colorString.to.rgb(0, [0, 255], 0.4); +stringifiedColor = colorString.to.rgb([0, 0], [255], 0.4); +stringifiedColor = colorString.to.rgb([0], 0, [255, 0.4]); diff --git a/types/color-string/index.d.ts b/types/color-string/index.d.ts new file mode 100644 index 0000000000..4eda883297 --- /dev/null +++ b/types/color-string/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for color-string 1.5 +// Project: https://github.com/qix-/color-string#readme +// Definitions by: BendingBender +// Dan Marshall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Color = [number, number, number, number]; + +export interface ColorDescriptor { + model: 'rgb' | 'hsl' | 'hwb'; + value: Color; +} + +export function get(colorString: string): ColorDescriptor | null; + +export namespace get { + function hsl(colorString: string): Color | null; + function hwb(colorString: string): Color | null; + function rgb(colorString: string): Color | null; +} + +export namespace to { + function hex(...args: Array): string; + function rgb(...args: Array): string; + namespace rgb { + function percent(...args: Array): string; + } + function keyword(...args: Array): string; + function hsl(...args: Array): string; + function hwb(...args: Array): string; +} diff --git a/types/color-string/tsconfig.json b/types/color-string/tsconfig.json new file mode 100644 index 0000000000..bf5a829c6e --- /dev/null +++ b/types/color-string/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "color-string-tests.ts" + ] +} diff --git a/types/color-string/tslint.json b/types/color-string/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-string/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/color/color-tests.ts b/types/color/color-tests.ts index 2d05e86f05..4e475a0ce0 100644 --- a/types/color/color-tests.ts +++ b/types/color/color-tests.ts @@ -1,41 +1,43 @@ -import * as Color from "color" +import Color = require('color'); -var color: Color.Color = Color("white") -var colorOther: Color.Color = Color("black") -var colorRGB: Color.Color = Color({ r : 0, g : 0, b : 0 }, "rgb") -var colorInt: Color.Color = Color(0x000000) +const color: Color = new Color("white"); +const colorOther: Color = new Color("black"); +const colorRGB: Color = new Color({ r: 0, g: 0, b: 0 }, "rgb"); +const colorInt: Color = new Color(0x000000); +const colorWithoutNew: Color = Color(0x000000); +const colorByStaticMethod: Color = Color.rgb({ r: 0, g: 0, b: 0 }); -var hex: string = color.hex() -var percent: string = color.percentString() -var keyword: string | void = color.keyword() -var alpha: number = color.alpha() -var red: number = color.red() -var green: number = color.green() -var blue: number = color.blue() -var hue: number = color.hue() -var saturationl: number = color.saturationl() -var lightness: number = color.lightness() -var saturationv: number = color.saturationv() -var value: number = color.value() -var cyan: number = color.cyan() -var magenta: number = color.magenta() -var yellow: number = color.yellow() -var black: number = color.black() -var luminosity: number = color.luminosity() -var contrast: number = color.contrast(colorOther) -var dark: boolean = color.dark() -var light: boolean = color.light() -var level: string = color.level(colorOther) +const hex: string = color.hex(); +const percent: string = color.percentString(); +const keyword: string = color.keyword(); +const alpha: number = color.alpha(); +const red: number = color.red(); +const green: number = color.green(); +const blue: number = color.blue(); +const hue: number = color.hue(); +const saturationl: number = color.saturationl(); +const lightness: number = color.lightness(); +const saturationv: number = color.saturationv(); +const value: number = color.value(); +const cyan: number = color.cyan(); +const magenta: number = color.magenta(); +const yellow: number = color.yellow(); +const black: number = color.black(); +const luminosity: number = color.luminosity(); +const contrast: number = color.contrast(colorOther); +const dark: boolean = color.dark(); +const light: boolean = color.light(); +const level: string = color.level(colorOther); -var x: number = color.x() -var y: number = color.y() -var z: number = color.z() -var l: number = color.l() -var a: number = color.a() -var b: number = color.b() -var rgbNumber: number = color.rgbNumber() +const x: number = color.x(); +const y: number = color.y(); +const z: number = color.z(); +const l: number = color.l(); +const a: number = color.a(); +const b: number = color.b(); +const rgbNumber: number = color.rgbNumber(); -var chain: Color.Color = color +const chain: Color = color .alpha(0) .red(0) .green(0) @@ -54,7 +56,7 @@ var chain: Color.Color = color .darken(0) .saturate(0) .desaturate(0) - .greyscale() + .grayscale() .whiten(0) .blacken(0) .opaquer(0) diff --git a/types/color/index.d.ts b/types/color/index.d.ts index a9fc18f29a..8290b78129 100644 --- a/types/color/index.d.ts +++ b/types/color/index.d.ts @@ -1,101 +1,135 @@ -// Type definitions for color 1.0 -// Project: https://www.npmjs.com/package/color -// Definitions by: Karol Janyst +// Type definitions for color 2.0 +// Project: https://github.com/qix-/color#readme +// Definitions by: Junyoung Clare Jang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -declare namespace Color { +import convert = require('color-convert'); - type ColorParam = string | { [param: string]: number } | number; +type ColorParam = Color | string | ArrayLike | number | { [key: string]: any }; - type ColorModel = "rgb" | "hsl" | "hsv" | "hwb" | "hcg" | "cmyk" | "xyz" | "lab" | "hex" | "gray" | "keyword"; +interface Color { + toString(): string; + toJSON(): Color; + string(places?: number): string; + percentString(places?: number): string; + array(): number[]; + object(): { alpha?: number } & { [key: string]: number }; + unitArray(): number[]; + unitObject(): { r: number, g: number, b: number, alpha?: number }; + round(places?: number): Color; + alpha(): number; + alpha(val: number): Color; + red(): number; + red(val: number): Color; + green(): number; + green(val: number): Color; + blue(): number; + blue(val: number): Color; + hue(): number; + hue(val: number): Color; + saturationl(): number; + saturationl(val: number): Color; + lightness(): number; + lightness(val: number): Color; + saturationv(): number; + saturationv(val: number): Color; + value(): number; + value(val: number): Color; + chroma(): number; + chroma(val: number): Color; + gray(): number; + gray(val: number): Color; + white(): number; + white(val: number): Color; + wblack(): number; + wblack(val: number): Color; + cyan(): number; + cyan(val: number): Color; + magenta(): number; + magenta(val: number): Color; + yellow(): number; + yellow(val: number): Color; + black(): number; + black(val: number): Color; + x(): number; + x(val: number): Color; + y(): number; + y(val: number): Color; + z(): number; + z(val: number): Color; + l(): number; + l(val: number): Color; + a(): number; + a(val: number): Color; + b(): number; + b(val: number): Color; + keyword(): string; + keyword(val: string): Color; + hex(): string; + hex(val: string): Color; + rgbNumber(): number; + luminosity(): number; + contrast(color2: Color): number; + level(color2: Color): 'AAA' | 'AA' | ''; + dark(): boolean; + light(): boolean; + negate(): Color; + lighten(ratio: number): Color; + darken(ratio: number): Color; + saturate(ratio: number): Color; + desaturate(ratio: number): Color; + whiten(ratio: number): Color; + blacken(ratio: number): Color; + grayscale(): Color; + fade(ratio: number): Color; + opaquer(ratio: number): Color; + rotate(degrees: number): Color; + mix(mixinColor: Color, weight?: number): Color; - interface Color { - (color: ColorParam | Color, model?: ColorModel) : Color; - toString(): string; - toJSON(): any; - string(places?: number): string; - percentString(placse?: number): string; - array(): number[]; - object(): any; - unitArray(): any[]; - unitObject(): any; - round(places?: number): Color; - alpha(alpha: number): Color; - alpha(): number; - red(red: number): Color; - red(): number; - green(green: number): Color; - green(): number; - blue(blue: number): Color; - blue(): number; - hue(hue: number): Color; - hue(): number; - saturationl(saturation: number): Color; - saturationl(): number; - lightness(lightness: number): Color; - lightness(): number; - saturationv(saturationv: number): Color; - saturationv(): number; - value(value: number): Color; - value(): number; - chroma(chroma: number): Color; - chroma(): number; - gray(value: number): Color; - gray(): number; - cyan(cyan: number): Color; - cyan(): number; - magenta(magenta: number): Color; - magenta(): number; - yellow(yellow: number): Color; - yellow(): number; - black(black: number): Color; - black(): number; - x(x: number): Color; - x(): number; - y(y: number): Color; - y(): number; - z(z: number): Color; - z(): number; - l(l: number): Color; - l(): number; - a(a: number): Color; - a(): number; - b(b: number): Color; - b(): number; - keyword(keyword: string): Color; - keyword(): string | undefined; - hex(color: string): Color; - hex(): string; - rgb(): Color; - hsl(): Color; - hsv(): Color; - hwb(): Color; - hcg(): Color; - cmyk(): Color; - xyz(): Color; - lab(): Color; - rgbNumber(): number; - luminosity(): number; - contrast(color: Color): number; - level(color: Color): string; - dark(): boolean; - light(): boolean; - negate(): Color; - lighten(value: number): Color; - darken(value: number): Color; - saturate(value: number): Color; - desaturate(value: number): Color; - whiten(value: number): Color; - blacken(value: number): Color; - greyscale(): Color; - fade(ratio: number): Color; - opaquer(value: number): Color; - rotate(value: number): Color; - mix(color: Color, value?: number): Color; - hsl(): Color; - } + rgb(...args: number[]): Color; + hsl(...args: number[]): Color; + hsv(...args: number[]): Color; + hwb(...args: number[]): Color; + cmyk(...args: number[]): Color; + xyz(...args: number[]): Color; + lab(...args: number[]): Color; + lch(...args: number[]): Color; + ansi16(...args: number[]): Color; + ansi256(...args: number[]): Color; + hcg(...args: number[]): Color; + apple(...args: number[]): Color; } -declare const Color: Color.Color; +interface ColorConstructor { + (obj?: ColorParam, model?: keyof (typeof convert)): Color; + new(obj?: ColorParam, model?: keyof (typeof convert)): Color; + rgb(...val: number[]): Color; + rgb(color: ColorParam): Color; + hsl(...val: number[]): Color; + hsl(color: ColorParam): Color; + hsv(...val: number[]): Color; + hsv(color: ColorParam): Color; + hwb(...val: number[]): Color; + hwb(color: ColorParam): Color; + cmyk(...val: number[]): Color; + cmyk(color: ColorParam): Color; + xyz(...val: number[]): Color; + xyz(color: ColorParam): Color; + lab(...val: number[]): Color; + lab(color: ColorParam): Color; + lch(...val: number[]): Color; + lch(color: ColorParam): Color; + ansi16(...val: number[]): Color; + ansi16(color: ColorParam): Color; + ansi256(...val: number[]): Color; + ansi256(color: ColorParam): Color; + hcg(...val: number[]): Color; + hcg(color: ColorParam): Color; + apple(...val: number[]): Color; + apple(color: ColorParam): Color; +} + +declare const Color: ColorConstructor; + export = Color; -export as namespace Color; diff --git a/types/color/tsconfig.json b/types/color/tsconfig.json index 3034984bd5..77175286b3 100644 --- a/types/color/tsconfig.json +++ b/types/color/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "color-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/color/tslint.json b/types/color/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/color/v1/color-tests.ts b/types/color/v1/color-tests.ts new file mode 100644 index 0000000000..2d05e86f05 --- /dev/null +++ b/types/color/v1/color-tests.ts @@ -0,0 +1,63 @@ +import * as Color from "color" + +var color: Color.Color = Color("white") +var colorOther: Color.Color = Color("black") +var colorRGB: Color.Color = Color({ r : 0, g : 0, b : 0 }, "rgb") +var colorInt: Color.Color = Color(0x000000) + +var hex: string = color.hex() +var percent: string = color.percentString() +var keyword: string | void = color.keyword() +var alpha: number = color.alpha() +var red: number = color.red() +var green: number = color.green() +var blue: number = color.blue() +var hue: number = color.hue() +var saturationl: number = color.saturationl() +var lightness: number = color.lightness() +var saturationv: number = color.saturationv() +var value: number = color.value() +var cyan: number = color.cyan() +var magenta: number = color.magenta() +var yellow: number = color.yellow() +var black: number = color.black() +var luminosity: number = color.luminosity() +var contrast: number = color.contrast(colorOther) +var dark: boolean = color.dark() +var light: boolean = color.light() +var level: string = color.level(colorOther) + +var x: number = color.x() +var y: number = color.y() +var z: number = color.z() +var l: number = color.l() +var a: number = color.a() +var b: number = color.b() +var rgbNumber: number = color.rgbNumber() + +var chain: Color.Color = color + .alpha(0) + .red(0) + .green(0) + .blue(0) + .hue(0) + .saturationl(0) + .lightness(0) + .saturationv(0) + .value(0) + .cyan(0) + .magenta(0) + .yellow(0) + .black(0) + .negate() + .lighten(0) + .darken(0) + .saturate(0) + .desaturate(0) + .greyscale() + .whiten(0) + .blacken(0) + .opaquer(0) + .rotate(0) + .mix(colorOther, 0) + .hsl(); diff --git a/types/color/v1/index.d.ts b/types/color/v1/index.d.ts new file mode 100644 index 0000000000..a9fc18f29a --- /dev/null +++ b/types/color/v1/index.d.ts @@ -0,0 +1,101 @@ +// Type definitions for color 1.0 +// Project: https://www.npmjs.com/package/color +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Color { + + type ColorParam = string | { [param: string]: number } | number; + + type ColorModel = "rgb" | "hsl" | "hsv" | "hwb" | "hcg" | "cmyk" | "xyz" | "lab" | "hex" | "gray" | "keyword"; + + interface Color { + (color: ColorParam | Color, model?: ColorModel) : Color; + toString(): string; + toJSON(): any; + string(places?: number): string; + percentString(placse?: number): string; + array(): number[]; + object(): any; + unitArray(): any[]; + unitObject(): any; + round(places?: number): Color; + alpha(alpha: number): Color; + alpha(): number; + red(red: number): Color; + red(): number; + green(green: number): Color; + green(): number; + blue(blue: number): Color; + blue(): number; + hue(hue: number): Color; + hue(): number; + saturationl(saturation: number): Color; + saturationl(): number; + lightness(lightness: number): Color; + lightness(): number; + saturationv(saturationv: number): Color; + saturationv(): number; + value(value: number): Color; + value(): number; + chroma(chroma: number): Color; + chroma(): number; + gray(value: number): Color; + gray(): number; + cyan(cyan: number): Color; + cyan(): number; + magenta(magenta: number): Color; + magenta(): number; + yellow(yellow: number): Color; + yellow(): number; + black(black: number): Color; + black(): number; + x(x: number): Color; + x(): number; + y(y: number): Color; + y(): number; + z(z: number): Color; + z(): number; + l(l: number): Color; + l(): number; + a(a: number): Color; + a(): number; + b(b: number): Color; + b(): number; + keyword(keyword: string): Color; + keyword(): string | undefined; + hex(color: string): Color; + hex(): string; + rgb(): Color; + hsl(): Color; + hsv(): Color; + hwb(): Color; + hcg(): Color; + cmyk(): Color; + xyz(): Color; + lab(): Color; + rgbNumber(): number; + luminosity(): number; + contrast(color: Color): number; + level(color: Color): string; + dark(): boolean; + light(): boolean; + negate(): Color; + lighten(value: number): Color; + darken(value: number): Color; + saturate(value: number): Color; + desaturate(value: number): Color; + whiten(value: number): Color; + blacken(value: number): Color; + greyscale(): Color; + fade(ratio: number): Color; + opaquer(value: number): Color; + rotate(value: number): Color; + mix(color: Color, value?: number): Color; + hsl(): Color; + } +} + +declare const Color: Color.Color; +export = Color; +export as namespace Color; diff --git a/types/color/v1/tsconfig.json b/types/color/v1/tsconfig.json new file mode 100644 index 0000000000..66541f0172 --- /dev/null +++ b/types/color/v1/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "color": [ + "color/v1" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "color-tests.ts" + ] +} diff --git a/types/command-line-args/index.d.ts b/types/command-line-args/index.d.ts index 33af16bcf5..442ee5cb93 100644 --- a/types/command-line-args/index.d.ts +++ b/types/command-line-args/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for command-line-args 4.0.6 // Project: https://github.com/75lb/command-line-args -// Definitions by: CzBuCHi +// Definitions by: CzBuCHi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** diff --git a/types/command-line-commands/index.d.ts b/types/command-line-commands/index.d.ts index cf69198dac..8cfc9c094d 100644 --- a/types/command-line-commands/index.d.ts +++ b/types/command-line-commands/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for command-line-commands 2.0.0 // Project: https://github.com/75lb/command-line-commands -// Definitions by: CzBuCHi +// Definitions by: CzBuCHi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** diff --git a/types/commander/index.d.ts b/types/commander/index.d.ts index 017495784a..9e5feded68 100644 --- a/types/commander/index.d.ts +++ b/types/commander/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for commander 2.9 // Project: https://github.com/visionmedia/commander.js -// Definitions by: Alan Agius , Marcelo Dezem , vvakame +// Definitions by: Alan Agius , Marcelo Dezem , vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/commonmark/commonmark-tests.ts b/types/commonmark/commonmark-tests.ts index 8d3a3a5447..b85eb16ace 100644 --- a/types/commonmark/commonmark-tests.ts +++ b/types/commonmark/commonmark-tests.ts @@ -26,18 +26,18 @@ function logNode(node: commonmark.Node) { const parser = new commonmark.Parser({ smart: true, time: true }); const node = parser.parse('# a piece of _markdown_'); -let w = node.walker(); -let step = w.next(); +const w = node.walker(); +const step = w.next(); if (step.entering) { logNode(step.node); } -let xmlRenderer = new commonmark.XmlRenderer({ sourcepos: true, time: true }); -let xml = xmlRenderer.render(node); +const xmlRenderer = new commonmark.XmlRenderer({ sourcepos: true, time: true }); +const xml = xmlRenderer.render(node); console.log(xml); -let htmlRenderer = new commonmark.HtmlRenderer({ safe: true, smart: true, sourcepos: true, time: true }); -let html = htmlRenderer.render(node); +const htmlRenderer = new commonmark.HtmlRenderer({ safe: true, smart: true, sourcepos: true, time: true }); +const html = htmlRenderer.render(node); console.log(html); function basic_usage() { diff --git a/types/compare-version/index.d.ts b/types/compare-version/index.d.ts index 1807abe537..5a2639a7c8 100644 --- a/types/compare-version/index.d.ts +++ b/types/compare-version/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for compare-version v0.1.2 // Project: https://www.npmjs.com/package/compare-version -// Definitions by: Jonathan Pevarnek +// Definitions by: Jonathan Pevarnek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/component-emitter/index.d.ts b/types/component-emitter/index.d.ts index 52f8f05655..95682f6ca4 100644 --- a/types/component-emitter/index.d.ts +++ b/types/component-emitter/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for component-emitter v1.2.1 // Project: https://www.npmjs.com/package/component-emitter -// Definitions by: Peter Snider +// Definitions by: Peter Snider // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/emitter-component diff --git a/types/compressible/compressible-tests.ts b/types/compressible/compressible-tests.ts new file mode 100644 index 0000000000..d793f8d877 --- /dev/null +++ b/types/compressible/compressible-tests.ts @@ -0,0 +1,5 @@ +import compressible = require('compressible'); + +// $ExpectType boolean | undefined +compressible('text/html'); +compressible('image/png'); diff --git a/types/compressible/index.d.ts b/types/compressible/index.d.ts new file mode 100644 index 0000000000..fe0d27ae23 --- /dev/null +++ b/types/compressible/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for compressible 2.0 +// Project: https://github.com/jshttp/compressible#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = compressible; + +declare function compressible(type: string): boolean | undefined; diff --git a/types/compressible/tsconfig.json b/types/compressible/tsconfig.json new file mode 100644 index 0000000000..fb011bf968 --- /dev/null +++ b/types/compressible/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "compressible-tests.ts" + ] +} diff --git a/types/compressible/tslint.json b/types/compressible/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/compressible/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/compression/index.d.ts b/types/compression/index.d.ts index 5099a3fb1b..75c37d4374 100644 --- a/types/compression/index.d.ts +++ b/types/compression/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for compression // Project: https://github.com/expressjs/compression -// Definitions by: Santi Albo +// Definitions by: Santi Albo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as express from 'express'; diff --git a/types/concat-stream/concat-stream-tests.ts b/types/concat-stream/concat-stream-tests.ts index 4f3bf839e0..b89cde817b 100644 --- a/types/concat-stream/concat-stream-tests.ts +++ b/types/concat-stream/concat-stream-tests.ts @@ -3,7 +3,7 @@ import concat = require("concat-stream"); import { Readable } from "stream"; class MyReadable extends Readable { - i: number = 1; + i = 1; _read() { if (this.i <= 100) { this.push(this.i.toString()); diff --git a/types/conf/conf-tests.ts b/types/conf/conf-tests.ts index 0b9f49ff79..1da0e4de2d 100644 --- a/types/conf/conf-tests.ts +++ b/types/conf/conf-tests.ts @@ -1,19 +1,41 @@ import Conf = require('conf'); -const conf = new Conf(); +const conf = new Conf(); +new Conf({ + defaults: { + foo: 'bar', + unicorn: 'rainbow' + }, + configName: '', + projectName: 'foo', + cwd: '' +}); +// $ExpectError +new Conf({ + defaults: { + foo: 'bar', + unicorn: ['rainbow'] + } +}); conf.set('foo', 'bar'); conf.set('hello', 1); conf.set('unicorn', false); -conf.set('object', { - foo: 'bar', - unicorn: ['rainbow'] -}); +conf.set('null', null); // $ExpectError -conf.get('foo'); +conf.get('foo'); // $ExpectType string | number | boolean +conf.get('foo', 'bar'); // $ExpectType string | number | boolean +conf.get('foo', null); // $ExpectError conf.delete('foo'); -conf.has('foo'); +conf.has('foo'); // $ExpectType boolean conf.clear(); -for (const value of conf) { - console.log(value[0], value[1]); +conf.store = { + foo: 'bar', + unicorn: 'rainbow' +}; +conf.path; // $ExpectType string + +for (const [key, value] of conf) { + key; // $ExpectType string + value; // $ExpectType string | number | boolean } diff --git a/types/conf/index.d.ts b/types/conf/index.d.ts index 21c136e823..9f88a88355 100644 --- a/types/conf/index.d.ts +++ b/types/conf/index.d.ts @@ -1,29 +1,30 @@ -// Type definitions for conf 0.11 +// Type definitions for conf 1.1 // Project: https://github.com/sindresorhus/conf // Definitions by: Sam Verschueren +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -interface Options { - defaults?: any; +interface Options { + defaults?: {[key: string]: T}; configName?: string; projectName?: string; cwd?: string; } -declare class Conf implements Iterable<[string, string | number | boolean | symbol | {}]> { - path: string; - store: any; - +declare class Conf implements Iterable<[string, T]> { + store: {[key: string]: T}; + readonly path: string; readonly size: number; - constructor(options?: Options); - get(key: string): any; - set(key: string, val: string | number | boolean | symbol | {}): void; - set(object: {}): void; + constructor(options?: Options); + get(key: string, defaultValue?: T): T; + set(key: string, val: T): void; + set(object: {[key: string]: T}): void; has(key: string): boolean; delete(key: string): void; clear(): void; - [Symbol.iterator](): Iterator<[string, string | number | boolean | symbol | {}]>; + [Symbol.iterator](): Iterator<[string, T]>; } export = Conf; diff --git a/types/conf/tsconfig.json b/types/conf/tsconfig.json index 8ef2367ca4..d165e88ea2 100644 --- a/types/conf/tsconfig.json +++ b/types/conf/tsconfig.json @@ -2,13 +2,12 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "target": "es6", "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -21,4 +20,4 @@ "index.d.ts", "conf-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/conf/v0/conf-tests.ts b/types/conf/v0/conf-tests.ts new file mode 100644 index 0000000000..1368e45c29 --- /dev/null +++ b/types/conf/v0/conf-tests.ts @@ -0,0 +1,20 @@ +import Conf = require('conf'); + +const conf = new Conf(); +conf.set('foo', 'bar'); +conf.set('hello', 1); +conf.set('unicorn', false); +conf.set('object', { + foo: 'bar', + unicorn: ['rainbow'] +}); + +conf.get('foo'); +conf.delete('foo'); +conf.has('foo'); +conf.clear(); + +for (const [key, value] of conf) { + key; // $ExpectType string + value; // $ExpectType string | number | boolean | symbol | {} +} diff --git a/types/conf/v0/index.d.ts b/types/conf/v0/index.d.ts new file mode 100644 index 0000000000..21c136e823 --- /dev/null +++ b/types/conf/v0/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for conf 0.11 +// Project: https://github.com/sindresorhus/conf +// Definitions by: Sam Verschueren +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Options { + defaults?: any; + configName?: string; + projectName?: string; + cwd?: string; +} + +declare class Conf implements Iterable<[string, string | number | boolean | symbol | {}]> { + path: string; + store: any; + + readonly size: number; + + constructor(options?: Options); + get(key: string): any; + set(key: string, val: string | number | boolean | symbol | {}): void; + set(object: {}): void; + has(key: string): boolean; + delete(key: string): void; + clear(): void; + [Symbol.iterator](): Iterator<[string, string | number | boolean | symbol | {}]>; +} + +export = Conf; diff --git a/types/conf/v0/tsconfig.json b/types/conf/v0/tsconfig.json new file mode 100644 index 0000000000..6047f464f4 --- /dev/null +++ b/types/conf/v0/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "conf": ["conf/v0"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "conf-tests.ts" + ] +} diff --git a/types/conf/v0/tslint.json b/types/conf/v0/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/conf/v0/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/confit/index.d.ts b/types/confit/index.d.ts index b78bd88727..14e2940ad4 100644 --- a/types/confit/index.d.ts +++ b/types/confit/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Confit 2.x // Project: https://github.com/krakenjs/confit -// Definitions by: Ethan Resnick +// Definitions by: Ethan Resnick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "confit" { diff --git a/types/connect-flash/index.d.ts b/types/connect-flash/index.d.ts index 1a10aae6db..edee056b1a 100644 --- a/types/connect-flash/index.d.ts +++ b/types/connect-flash/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for connect-flash // Project: https://github.com/jaredhanson/connect-flash -// Definitions by: Andreas Gassmann +// Definitions by: Andreas Gassmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/connect-history-api-fallback/connect-history-api-fallback-tests.ts b/types/connect-history-api-fallback/connect-history-api-fallback-tests.ts index 382e436366..6095d2fecb 100644 --- a/types/connect-history-api-fallback/connect-history-api-fallback-tests.ts +++ b/types/connect-history-api-fallback/connect-history-api-fallback-tests.ts @@ -57,7 +57,7 @@ historyApiFallback({ { from: /^\/libs\/(.*)$/, to(context) { - return '/' + context.match[2] + '/' + context.match[3]; + return `/${context.match[2]}/${context.match[3]}`; } } ] diff --git a/types/connect-livereload/index.d.ts b/types/connect-livereload/index.d.ts index 993e610b04..b0dadcfcc8 100644 --- a/types/connect-livereload/index.d.ts +++ b/types/connect-livereload/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for connect-livereload v0.5.3 // Project: https://github.com/intesso/connect-livereload -// Definitions by: Maxime LUCE +// Definitions by: Maxime LUCE // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/connect-modrewrite/index.d.ts b/types/connect-modrewrite/index.d.ts index 00a8b4fe46..41372046d1 100644 --- a/types/connect-modrewrite/index.d.ts +++ b/types/connect-modrewrite/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for connect-modrewrite // Project: https://github.com/tinganho/connect-modrewrite -// Definitions by: Tingan Ho +// Definitions by: Tingan Ho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/connect-timeout/index.d.ts b/types/connect-timeout/index.d.ts index bfaa7c473d..0ec4963306 100644 --- a/types/connect-timeout/index.d.ts +++ b/types/connect-timeout/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/expressjs/timeout // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/connect/index.d.ts b/types/connect/index.d.ts index 66c5b7562c..8cebd6ba78 100644 --- a/types/connect/index.d.ts +++ b/types/connect/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for connect v3.4.0 // Project: https://github.com/senchalabs/connect -// Definitions by: Maxime LUCE +// Definitions by: Maxime LUCE // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/console-stamp/index.d.ts b/types/console-stamp/index.d.ts index ff6571330d..c7b9547cc8 100644 --- a/types/console-stamp/index.d.ts +++ b/types/console-stamp/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for console-stamp 0.2.0 // Project: https://github.com/starak/node-console-stamp -// Definitions by: Eric Byers +// Definitions by: Eric Byers // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/consul/index.d.ts b/types/consul/index.d.ts index 4d577cd2a1..3d344ae983 100644 --- a/types/consul/index.d.ts +++ b/types/consul/index.d.ts @@ -7,7 +7,7 @@ -import {IncomingMessage as HttpIncomingMessage} from "http"; +import { IncomingMessage as HttpIncomingMessage } from "http"; declare namespace Consul { diff --git a/types/content-type/content-type-tests.ts b/types/content-type/content-type-tests.ts index 0705d440c1..4be9519a94 100644 --- a/types/content-type/content-type-tests.ts +++ b/types/content-type/content-type-tests.ts @@ -1,18 +1,19 @@ -import contentType = require('content-type'); -import express = require('express'); +/// -let obj = contentType.parse('image/svg+xml; charset=utf-8'); +import * as contentType from 'content-type'; +import * as http from 'http'; -console.log(obj.type); // => 'image/svg+xml' -console.log(obj.parameters.charset); // => 'utf-8' +const mediaType = contentType.parse('image/svg+xml; charset=utf-8'); +mediaType; // $ExpectType ParsedMediaType +mediaType.type; // $ExpectType string +mediaType.parameters; // $ExpectType { [key: string]: string; } -let req: express.Request; -obj = contentType.parse(req); +http.createServer((req, res) => { + contentType.parse(req); + contentType.parse(res); +}); -let res: express.Response; -obj = contentType.parse(res); - -let str: string = contentType.format({type: 'image/svg+xml'}); - -let media: contentType.MediaType; -contentType.format(media); +// $ExpectType string +contentType.format({type: 'image/svg+xml'}); +contentType.format({type: 'image/svg+xml', parameters: {charset: 'utf-8'}}); +contentType.format(mediaType); diff --git a/types/content-type/index.d.ts b/types/content-type/index.d.ts index ec60de446f..5ff4ae7ff1 100644 --- a/types/content-type/index.d.ts +++ b/types/content-type/index.d.ts @@ -1,21 +1,26 @@ // Type definitions for content-type 1.1 // Project: https://www.npmjs.com/package/content-type // Definitions by: Hiroki Horiuchi +// BendingBender // Definitions: https://github.com/borisyankov/DefinitelyTyped -import * as express from 'express'; +export function parse(input: RequestLike | ResponseLike | string): ParsedMediaType; +export function format(obj: MediaType): string; -declare var ct: ct.StaticFunctions; -export = ct; +export interface ParsedMediaType { + type: string; + parameters: {[key: string]: string}; +} -declare namespace ct { - interface StaticFunctions { - parse(input: express.Request | express.Response | string): MediaType; - format(obj: MediaType): string; - } +export interface MediaType { + type: string; + parameters?: {[key: string]: string}; +} - interface MediaType { - type: string; - parameters?: any; - } +export interface RequestLike { + headers: {[header: string]: string | string[]}; +} + +export interface ResponseLike { + getHeader(name: string): number | string | string[] | undefined; } diff --git a/types/content-type/tsconfig.json b/types/content-type/tsconfig.json index 4eaa2f42f4..3361989225 100644 --- a/types/content-type/tsconfig.json +++ b/types/content-type/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "content-type-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/continuation-local-storage/continuation-local-storage-tests.ts b/types/continuation-local-storage/continuation-local-storage-tests.ts index 3d85886d73..aee44866af 100644 --- a/types/continuation-local-storage/continuation-local-storage-tests.ts +++ b/types/continuation-local-storage/continuation-local-storage-tests.ts @@ -21,7 +21,7 @@ function test(topic: string, callback: (t: Test) => any) { test("asynchronously propagating state with local-context-domains", function (t) { t.plan(2); - var namespace = cls.createNamespace('namespace'); + const namespace = cls.createNamespace('namespace'); // t.ok(process.namespaces.namespace, "namespace has been created"); namespace.run(function () { @@ -39,7 +39,7 @@ test("minimized test case that caused #6011 patch to fail", function (t) { // when the flaw was in the patch, commenting out this line would fix things: process.nextTick(function () { console.log('!'); }); - var n = cls.createNamespace("test"); + const n = cls.createNamespace("test"); t.ok(!n.get('state'), "state should not yet be visible"); n.run(function () { @@ -59,7 +59,7 @@ test("event emitters bound to CLS context", function (t) { t.test("handler registered in context, emit out of context", function (t) { t.plan(1); - var n = cls.createNamespace('in') + const n = cls.createNamespace('in') , ee = new EventEmitter() ; @@ -78,7 +78,7 @@ test("event emitters bound to CLS context", function (t) { t.test("once handler registered in context", function (t) { t.plan(1); - var n = cls.createNamespace('inOnce') + const n = cls.createNamespace('inOnce') , ee = new EventEmitter() ; @@ -97,7 +97,7 @@ test("event emitters bound to CLS context", function (t) { t.test("handler registered out of context, emit in context", function (t) { t.plan(1); - var n = cls.createNamespace('out') + const n = cls.createNamespace('out') , ee = new EventEmitter() ; @@ -117,7 +117,7 @@ test("event emitters bound to CLS context", function (t) { t.test("once handler registered out of context", function (t) { t.plan(1); - var n = cls.createNamespace('outOnce') + const n = cls.createNamespace('outOnce') , ee = new EventEmitter() ; @@ -137,7 +137,7 @@ test("event emitters bound to CLS context", function (t) { t.test("handler registered out of context, emit out of context", function (t) { t.plan(1); - var n = cls.createNamespace('out') + const n = cls.createNamespace('out') , ee = new EventEmitter() ; @@ -155,12 +155,12 @@ test("event emitters bound to CLS context", function (t) { }); t.test("once handler registered out of context on Readable", function (t) { - var Readable = require('stream').Readable; + const Readable = require('stream').Readable; if (Readable) { t.plan(12); - var n = cls.createNamespace('outOnceReadable') + const n = cls.createNamespace('outOnceReadable') , re = new Readable() ; @@ -203,7 +203,7 @@ test("event emitters bound to CLS context", function (t) { t.test("emitter with newListener that removes handler", function (t) { t.plan(3); - var n = cls.createNamespace('newListener') + const n = cls.createNamespace('newListener') , ee = new EventEmitter() ; @@ -239,12 +239,12 @@ test("event emitters bound to CLS context", function (t) { }); t.test("handler registered in context on Readable", function (t) { - var Readable = require('stream').Readable; + const Readable = require('stream').Readable; if (Readable) { t.plan(12); - var n = cls.createNamespace('outOnReadable') + const n = cls.createNamespace('outOnReadable') , re = new Readable() ; @@ -288,7 +288,7 @@ test("event emitters bound to CLS context", function (t) { t.test("handler added but used entirely out of context", function (t) { t.plan(2); - var n = cls.createNamespace('none') + const n = cls.createNamespace('none') , ee = new EventEmitter() ; @@ -309,12 +309,12 @@ test("event emitters bound to CLS context", function (t) { t.test("handler added but no listeners registered", function (t) { t.plan(3); - var http = require('http') + const http = require('http') , n = cls.createNamespace('no_listener') ; // only fails on Node < 0.10 - var server = http.createServer(function (req: any, res: any) { + const server = http.createServer(function (req: any, res: any) { n.bindEmitter(req); t.doesNotThrow(function () { @@ -342,7 +342,7 @@ test("event emitters bound to CLS context", function (t) { t.test("listener with parameters added but not bound to context", function (t) { t.plan(2); - var ee = new EventEmitter() + const ee = new EventEmitter() , n = cls.createNamespace('param_list') ; @@ -361,7 +361,7 @@ test("event emitters bound to CLS context", function (t) { t.test("listener that throws doesn't leave removeListener wrapped", function (t) { t.plan(4); - var ee = new EventEmitter() + const ee = new EventEmitter() , n = cls.createNamespace('kaboom') ; @@ -385,7 +385,7 @@ test("event emitters bound to CLS context", function (t) { t.test("emitter bound to multiple namespaces handles them correctly", function (t) { t.plan(8); - var ee = new EventEmitter() + const ee = new EventEmitter() , ns1 = cls.createNamespace('1') , ns2 = cls.createNamespace('2') ; @@ -430,7 +430,7 @@ test("event emitters bound to CLS context", function (t) { // multiple contexts in use test("simple tracer built on contexts", function (t) { - var tracer = cls.createNamespace('tracer'); + const tracer = cls.createNamespace('tracer'); class Trace { harvester: any; @@ -438,7 +438,7 @@ test("simple tracer built on contexts", function (t) { this.harvester = harvester; } runHandler(callback: any) { - var wrapped = tracer.bind(function () { + const wrapped = tracer.bind(function () { callback(); this.harvester.emit('finished', tracer.get('transaction')); }.bind(this)); @@ -448,8 +448,8 @@ test("simple tracer built on contexts", function (t) { t.plan(6); - var harvester = new EventEmitter(); - var trace = new Trace(harvester); + const harvester = new EventEmitter(); + const trace = new Trace(harvester); harvester.on('finished', function (transaction: any) { t.ok(transaction, "transaction should have been passed in"); diff --git a/types/convert-hrtime/convert-hrtime-tests.ts b/types/convert-hrtime/convert-hrtime-tests.ts new file mode 100644 index 0000000000..986b427027 --- /dev/null +++ b/types/convert-hrtime/convert-hrtime-tests.ts @@ -0,0 +1,9 @@ +/// + +import convertHrtime = require('convert-hrtime'); + +const time = convertHrtime(process.hrtime(process.hrtime())); +let num: number; +num = time.seconds; +num = time.milliseconds; +num = time.nanoseconds; diff --git a/types/convert-hrtime/index.d.ts b/types/convert-hrtime/index.d.ts new file mode 100644 index 0000000000..a23d222eec --- /dev/null +++ b/types/convert-hrtime/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for convert-hrtime 2.0 +// Project: https://github.com/sindresorhus/convert-hrtime#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = convertHrtime; + +declare function convertHrtime(hrtime: [number, number]): convertHrtime.HRTime; + +declare namespace convertHrtime { + interface HRTime { + seconds: number; + milliseconds: number; + nanoseconds: number; + } +} diff --git a/types/convert-hrtime/tsconfig.json b/types/convert-hrtime/tsconfig.json new file mode 100644 index 0000000000..08efd1ab39 --- /dev/null +++ b/types/convert-hrtime/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "convert-hrtime-tests.ts" + ] +} diff --git a/types/convert-hrtime/tslint.json b/types/convert-hrtime/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/convert-hrtime/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/convert-source-map/index.d.ts b/types/convert-source-map/index.d.ts index 9576e5a08f..6b1346b61f 100644 --- a/types/convert-source-map/index.d.ts +++ b/types/convert-source-map/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for convert-source-map 1.3 +// Type definitions for convert-source-map 1.5 // Project: https://github.com/thlorenz/convert-source-map -// Definitions by: Andrew Gaspar , Melvin Groenhoff , TeamworkGuy2 +// Definitions by: Andrew Gaspar , Melvin Groenhoff , TeamworkGuy2 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** Converts a source-map from/to different formats and allows adding/changing properties. @@ -47,17 +47,14 @@ export function fromBase64(base64: string): SourceMapConverter; /** Returns source map converter from given base64 encoded json string prefixed with //# sourceMappingURL=... */ export function fromComment(comment: string): SourceMapConverter; -/**Returns source map converter from given filename by parsing //# sourceMappingURL=filename. +/** Returns source map converter from given filename by parsing //# sourceMappingURL=filename. * filename must point to a file that is found inside the mapFileDir. Most tools store this file right next to the generated file, i.e. the one containing the source map. */ export function fromMapFileComment(comment: string, commentFileDir: string): SourceMapConverter; /** Finds last sourcemap comment in file and returns source map converter or returns null if no source map comment was found. - * If largeSource is set to true, an algorithm that does not use regex is applied to find the source map. - * This is faster and especially useful if you're running into "call stack size exceeded" errors with the default algorithm. - * However, it is less accurate and may match content that isn't a source map comment. */ -export function fromSource(content: string, largeSource?: boolean): SourceMapConverter | null; +export function fromSource(content: string): SourceMapConverter | null; /** Finds last sourcemap comment in file and returns source map converter or returns null if no source map comment was found. * The sourcemap will be read from the map file found by parsing # sourceMappingURL=file comment. For more info see fromMapFileComment. @@ -70,10 +67,10 @@ export function removeComments(src: string): string; /** Returns src with all source map comments pointing to map files removed */ export function removeMapFileComments(src: string): string; -/** Returns the regex used to find source map comments */ +/** Returns a new regex used to find source map comments */ export const commentRegex: RegExp; -/** Returns the regex used to find source map comments pointing to map files */ +/** Returns a new regex used to find source map comments pointing to map files */ export const mapFileCommentRegex: RegExp; /** Returns a comment that links to an external source map via file. diff --git a/types/convict/convict-tests.ts b/types/convict/convict-tests.ts index daa07c6875..98a107d8e8 100644 --- a/types/convict/convict-tests.ts +++ b/types/convict/convict-tests.ts @@ -35,7 +35,7 @@ convict.addFormats({ } }); -let conf = convict({ +const conf = convict({ env: { doc: 'The applicaton environment.', format: ['production', 'development', 'test'], @@ -98,9 +98,9 @@ let conf = convict({ // load environment dependent configuration -let env = conf.get('env'); -let dbip = conf.get('db.ip'); -conf.loadFile('./config/' + env + '.json'); +const env = conf.get('env'); +const dbip = conf.get('db.ip'); +conf.loadFile(`./config/${env}.json`); conf.loadFile(['./configs/always.json', './configs/sometimes.json']); // perform validation @@ -113,13 +113,13 @@ conf.validate({ allowed: 'warn' }); conf .loadFile(['./configs/always.json', './configs/sometimes.json']) - .loadFile('./config/' + env + '.json') + .loadFile(`./config/${env}.json`) .load({ jsonKey: 'jsonValue' }) .set('key', 'value') .validate({ allowed: 'warn' }) .toString(); -let port: number = conf.default('port'); +const port: number = conf.default('port'); if (conf.has('key')) { conf.set('the.awesome', true); diff --git a/types/convict/index.d.ts b/types/convict/index.d.ts index 183d91ed91..d7904ec5d6 100644 --- a/types/convict/index.d.ts +++ b/types/convict/index.d.ts @@ -28,7 +28,7 @@ declare namespace convict { } interface Schema { - [name: string]: convict.Schema | { + [name: string]: Schema | { default: any; doc?: string; /** diff --git a/types/cookie-parser/cookie-parser-tests.ts b/types/cookie-parser/cookie-parser-tests.ts index 1f9aaa1a8b..3a9f885efd 100644 --- a/types/cookie-parser/cookie-parser-tests.ts +++ b/types/cookie-parser/cookie-parser-tests.ts @@ -1,6 +1,31 @@ - import express = require('express'); import cookieParser = require('cookie-parser'); -var app = express(); +const app = express(); app.use(cookieParser('optional secret string')); + +let obj: object; +let str: string; +let notTrue: false; +let undef: undefined; + +const res = cookieParser.JSONCookie('foo'); +if (typeof res === 'undefined') { + undef = res; +} else { + obj = res; +} + +const res2 = cookieParser.JSONCookies({foo: 'bar'}); +const jsonRes: { foo?: object } = res2; + +const res3 = cookieParser.signedCookie('', 'keyboard cat'); +cookieParser.signedCookie('', ['keyboard', 'cat']); +if (typeof res3 === 'string') { + str = res3; +} else { + notTrue = res3; +} + +const res4 = cookieParser.signedCookies({foo: 'bar'}, 'keyboard cat'); +const signedCookieRes: { foo?: string | false } = res4; diff --git a/types/cookie-parser/index.d.ts b/types/cookie-parser/index.d.ts index 96412d6ee9..9d0c6c1f0a 100644 --- a/types/cookie-parser/index.d.ts +++ b/types/cookie-parser/index.d.ts @@ -1,12 +1,26 @@ -// Type definitions for cookie-parser v1.3.4 +// Type definitions for cookie-parser 1.4 // Project: https://github.com/expressjs/cookie-parser -// Definitions by: Santi Albo +// Definitions by: Santi Albo +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +import * as express from 'express'; +declare function cookieParser(secret?: string | string[], options?: cookieParser.CookieParseOptions): express.RequestHandler; +declare namespace cookieParser { + interface CookieParseOptions { + decode?(val: string): string; + } -import express = require('express'); -declare function e(secret?: string, options?: any): express.RequestHandler; -declare namespace e { } -export = e; + function JSONCookie(jsonCookie: string): object | undefined; + + function JSONCookies(jsonCookies: T): { [P in keyof T]: object | undefined }; + + function signedCookie(cookie: string, secret: string | string[]): string | false; + + function signedCookies(cookies: T, secret: string | string[]): { [P in keyof T]?: string | false}; +} + +export = cookieParser; diff --git a/types/cookie-parser/tslint.json b/types/cookie-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cookie-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cookie-session/index.d.ts b/types/cookie-session/index.d.ts index b0f4a1060e..29562d0320 100644 --- a/types/cookie-session/index.d.ts +++ b/types/cookie-session/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for cookie-session 2.0 // Project: https://github.com/expressjs/cookie-session -// Definitions by: Borislav Zhivkov +// Definitions by: Borislav Zhivkov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/cookie/cookie-tests.ts b/types/cookie/cookie-tests.ts index dd5be0f850..08e4d43519 100644 --- a/types/cookie/cookie-tests.ts +++ b/types/cookie/cookie-tests.ts @@ -1,23 +1,21 @@ - - import cookie = require('cookie'); function test_serialize(): void { - var retVal: string; + let retVal: string; retVal = cookie.serialize('foo', 'bar'); retVal = cookie.serialize('foo', 'bar', { httpOnly: true }); } function test_parse(): void { - var retVal: { [key: string]: string }; + let retVal: { [key: string]: string }; retVal = cookie.parse('foo=bar; bar=baz;'); retVal = cookie.parse('foo=bar; bar=baz', { decode: x => x }); } function test_options(): void { - var serializeOptions: cookie.CookieSerializeOptions = { + const serializeOptions: cookie.CookieSerializeOptions = { encode: (x: string) => x, path: '/', expires: new Date(), @@ -27,7 +25,7 @@ function test_options(): void { httpOnly: false }; - var parseOptios: cookie.CookieParseOptions = { + const parseOptios: cookie.CookieParseOptions = { decode: (x: string) => x }; } diff --git a/types/cookie/index.d.ts b/types/cookie/index.d.ts index 507eaee01d..bb7fc2cb54 100644 --- a/types/cookie/index.d.ts +++ b/types/cookie/index.d.ts @@ -1,15 +1,16 @@ -// Type definitions for cookie v0.3.0 +// Type definitions for cookie 0.3 // Project: https://github.com/jshttp/cookie // Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface CookieSerializeOptions { +export interface CookieSerializeOptions { /** * Specifies the value for the Domain Set-Cookie attribute. By default, no * domain is set, and most clients will consider the cookie to apply to only * the current domain. */ domain?: string; + /** * Specifies a function that will be used to encode a cookie's value. Since * value of a cookie has a limited character set (and must be a simple @@ -20,7 +21,8 @@ interface CookieSerializeOptions { * encode a JavaScript string into UTF-8 byte sequences and then URL-encode * any that fall outside of the cookie range. */ - encode?: (val: string) => string; + encode?(val: string): string; + /** * Specifies the `Date` object to be the value for the `Expires` * `Set-Cookie` attribute. By default, no expiration is set, and most @@ -83,7 +85,7 @@ interface CookieSerializeOptions { secure?: boolean; } -interface CookieParseOptions { +export interface CookieParseOptions { /** * Specifies a function that will be used to decode a cookie's value. Since * the value of a cookie has a limited character set (and must be a simple @@ -96,7 +98,7 @@ interface CookieParseOptions { * *Note* if an error is thrown from this function, the original, non-decoded * cookie value will be returned as the cookie's value. */ - decode?: (val: string) => string; + decode?(val: string): string; } /** diff --git a/types/cookie/tslint.json b/types/cookie/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cookie/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cookies/cookies-tests.ts b/types/cookies/cookies-tests.ts index c65bcbd4aa..2f78f8ad49 100644 --- a/types/cookies/cookies-tests.ts +++ b/types/cookies/cookies-tests.ts @@ -1,26 +1,39 @@ import * as Cookies from 'cookies'; import * as http from 'http'; +import * as Keygrip from 'keygrip'; +import * as express from 'express'; +import * as connect from 'connect'; const server = http.createServer((req, res) => { const cookies = new Cookies(req, res); + new Cookies(req, res, {keys: []}); + new Cookies(req, res, {keys: new Keygrip([])}); + new Cookies(req, res, {secure: true}); + let unsigned: string; let signed: string; let tampered: string; if (req.url === "/set") { cookies - // set a regular cookie + // set a regular cookie .set("unsigned", "foo", { httpOnly: false }) - // set a signed cookie + // set a signed cookie .set("signed", "bar", { signed: true }) - // mimic a signed cookie, but with a bogus signature + // mimic a signed cookie, but with a bogus signature .set("tampered", "baz") - .set("tampered.sig", "bogus"); + .set("tampered.sig", "bogus") + + // sameSite option + .set("samesite", "same", {sameSite: 'lax'}) + .set("samesite", "same", {sameSite: 'strict'}) + .set("samesite", "same", {sameSite: false}); res.writeHead(302, { Location: "/" }); - return res.end("Now let's check."); + res.end("Now let's check."); + return; } unsigned = cookies.get("unsigned"); @@ -29,11 +42,23 @@ const server = http.createServer((req, res) => { res.writeHead(200, { "Content-Type": "text/plain" }); res.end( - "unsigned expected: foo\n\n" + - "unsigned actual: " + unsigned + "\n\n" + - "signed expected: bar\n\n" + - "signed actual: " + signed + "\n\n" + - "tampered expected: undefined\n\n" + - "tampered: " + tampered + "\n\n" - ); + `unsigned expected: foo + +unsigned actual: ${unsigned} + +signed expected: bar + +signed actual: ${signed} + +tampered expected: undefined + +tampered: ${tampered} + +`); }); + +const eApp = express(); +eApp.use(Cookies.express([])); + +const cApp = connect(); +cApp.use(Cookies.connect([])); diff --git a/types/cookies/index.d.ts b/types/cookies/index.d.ts index 55feb7ec7d..8a897cfeae 100644 --- a/types/cookies/index.d.ts +++ b/types/cookies/index.d.ts @@ -1,11 +1,15 @@ -// Type definitions for cookies 0.6 +// Type definitions for cookies 0.7 // Project: https://github.com/pillarjs/cookies -// Definitions by: Wang Zishi , jKey Lu +// Definitions by: Wang Zishi +// jKey Lu +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// import { IncomingMessage, ServerResponse } from 'http'; import * as Keygrip from 'keygrip'; +import * as express from 'express'; +import * as connect from 'connect'; interface Cookies { secure: boolean; @@ -38,7 +42,7 @@ declare namespace Cookies { type IOptions = SetOption; interface Option { - keys: string[] | Keygrip; + keys?: string[] | Keygrip; secure?: boolean; } @@ -78,6 +82,11 @@ declare namespace Cookies { * and not made available to client JavaScript (true by default). */ httpOnly?: boolean; + /** + * a boolean or string indicating whether the cookie is a "same site" cookie (false by default). + * This can be set to 'strict', 'lax', or true (which maps to 'strict'). + */ + sameSite?: 'strict' | 'lax' | boolean; /** * a boolean indicating whether the cookie is to be signed (false by default). * If this is true, another cookie of the same name with the .sig suffix @@ -102,7 +111,7 @@ declare namespace Cookies { name: string; value: string; /** - * "maxage"" is deprecated, use "maxAge" instead + * "maxage" is deprecated, use "maxAge" instead */ maxage: number; maxAge: number; @@ -111,6 +120,7 @@ declare namespace Cookies { domain: string; secure: boolean; httpOnly: boolean; + sameSite: boolean; overwrite: boolean; toString(): string; @@ -146,6 +156,9 @@ interface CookiesFunction { Cookie: { new (name: string, value?: string, attrs?: Cookies.CookieAttr): Cookies.Cookie; }; + + express(keys: string[] | Keygrip): express.Handler; + connect(keys: string[] | Keygrip): connect.NextHandleFunction; } declare const Cookies: CookiesFunction; diff --git a/types/copy-text-to-clipboard/copy-text-to-clipboard-tests.ts b/types/copy-text-to-clipboard/copy-text-to-clipboard-tests.ts new file mode 100644 index 0000000000..4a1e63b28c --- /dev/null +++ b/types/copy-text-to-clipboard/copy-text-to-clipboard-tests.ts @@ -0,0 +1,8 @@ +import copy = require('copy-text-to-clipboard'); + +const button: HTMLButtonElement | null = document.getElementById('my-button'); +if (button) { + button.addEventListener('click', () => { + copy('🦄🌈'); + }); +} diff --git a/types/copy-text-to-clipboard/index.d.ts b/types/copy-text-to-clipboard/index.d.ts new file mode 100644 index 0000000000..56493778d0 --- /dev/null +++ b/types/copy-text-to-clipboard/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for copy-text-to-clipboard 1.0 +// Project: https://github.com/sindresorhus/copy-text-to-clipboard#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = copy; + +declare function copy(text: string): boolean; diff --git a/types/copy-text-to-clipboard/tsconfig.json b/types/copy-text-to-clipboard/tsconfig.json new file mode 100644 index 0000000000..71b4595292 --- /dev/null +++ b/types/copy-text-to-clipboard/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "copy-text-to-clipboard-tests.ts" + ] +} diff --git a/types/copy-text-to-clipboard/tslint.json b/types/copy-text-to-clipboard/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/copy-text-to-clipboard/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/copy-webpack-plugin/index.d.ts b/types/copy-webpack-plugin/index.d.ts index 11a3a30dd9..8bfae1e0ed 100644 --- a/types/copy-webpack-plugin/index.d.ts +++ b/types/copy-webpack-plugin/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for copy-webpack-plugin v4.0.0 // Project: https://github.com/kevlened/copy-webpack-plugin -// Definitions by: flying-sheep +// Definitions by: flying-sheep // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { Plugin } from 'webpack' diff --git a/types/cordova-plugin-app-version/index.d.ts b/types/cordova-plugin-app-version/index.d.ts index b30beef9c6..ea727815a4 100644 --- a/types/cordova-plugin-app-version/index.d.ts +++ b/types/cordova-plugin-app-version/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for cordova-plugin-app-version v0.1.7 // Project: https://github.com/whiteoctober/cordova-plugin-app-version -// Definitions by: Markus Wagner +// Definitions by: Markus Wagner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Cordova { diff --git a/types/cordova-plugin-ibeacon/index.d.ts b/types/cordova-plugin-ibeacon/index.d.ts index 3530ccb70d..eb2115448d 100644 --- a/types/cordova-plugin-ibeacon/index.d.ts +++ b/types/cordova-plugin-ibeacon/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for cordova-plugin-ibeacon v3.3.0 // Project: https://github.com/petermetz/cordova-plugin-ibeacon -// Definitions by: Markus Wagner +// Definitions by: Markus Wagner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as Q from "q"; diff --git a/types/cordova-plugin-inappbrowser/cordova-plugin-inappbrowser-tests.ts b/types/cordova-plugin-inappbrowser/cordova-plugin-inappbrowser-tests.ts index 1497eec386..2506df887d 100644 --- a/types/cordova-plugin-inappbrowser/cordova-plugin-inappbrowser-tests.ts +++ b/types/cordova-plugin-inappbrowser/cordova-plugin-inappbrowser-tests.ts @@ -4,7 +4,7 @@ // signature of window.open() added by InAppBrowser plugin // is similar to native window.open signature, so the compiler can's // select proper overload, but we cast result to InAppBrowser manually. -const iab = window.open('google.com', '_self'); +const iab = window.open('google.com', '_self'); iab.addEventListener('loadstart', (ev: InAppBrowserEvent) => { console.log('Start opening ' + ev.url); }); iab.addEventListener('loadstart', (ev) => { console.log('loadstart' + ev.url); }); diff --git a/types/cordova-plugin-inappbrowser/tslint.json b/types/cordova-plugin-inappbrowser/tslint.json index 3db14f85ea..946c3b6691 100644 --- a/types/cordova-plugin-inappbrowser/tslint.json +++ b/types/cordova-plugin-inappbrowser/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "dt-header": false + } +} diff --git a/types/cordova-plugin-insomnia/index.d.ts b/types/cordova-plugin-insomnia/index.d.ts index 3b5fbd9e4d..122511e519 100644 --- a/types/cordova-plugin-insomnia/index.d.ts +++ b/types/cordova-plugin-insomnia/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Insomnia-PhoneGap-Plugin v4.0.1 // Project: https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin/ -// Definitions by: Markus Wagner +// Definitions by: Markus Wagner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Window { diff --git a/types/cordova-plugin-mapsforge/index.d.ts b/types/cordova-plugin-mapsforge/index.d.ts index e4c5d02eee..79f3ac6735 100644 --- a/types/cordova-plugin-mapsforge/index.d.ts +++ b/types/cordova-plugin-mapsforge/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for cordova-plugin-mapsforge // Project: https://github.com/afsuarez/mapsforge-cordova-plugin -// Definitions by: rafw87 +// Definitions by: rafw87 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Window { diff --git a/types/cordova-plugin-qrscanner/index.d.ts b/types/cordova-plugin-qrscanner/index.d.ts index 0f2a498a9c..d61777f3a4 100644 --- a/types/cordova-plugin-qrscanner/index.d.ts +++ b/types/cordova-plugin-qrscanner/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for cordova-plugin-qrscanner v1.0.1 // Project: https://github.com/bitpay/cordova-plugin-qrscanner -// Definitions by: Jason Dreyzehner +// Definitions by: Jason Dreyzehner // Josh Bronson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/cordova-plugin-vibration/index.d.ts b/types/cordova-plugin-vibration/index.d.ts index 192c4781f5..317576a523 100644 --- a/types/cordova-plugin-vibration/index.d.ts +++ b/types/cordova-plugin-vibration/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Apache Cordova Vibration plugin // Project: https://github.com/apache/cordova-plugin-vibration -// Definitions by: Microsoft Open Technologies Inc , Louis Lagrange +// Definitions by: Microsoft Open Technologies Inc , Louis Lagrange // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // // Copyright (c) Microsoft Open Technologies Inc diff --git a/types/cordova-plugin-x-socialsharing/index.d.ts b/types/cordova-plugin-x-socialsharing/index.d.ts index 4560dd3f1a..a5105c898c 100644 --- a/types/cordova-plugin-x-socialsharing/index.d.ts +++ b/types/cordova-plugin-x-socialsharing/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for SocialSharing-PhoneGap-Plugin v5.1.8 // Project: https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin -// Definitions by: Markus Wagner , Larry Bahr +// Definitions by: Markus Wagner , Larry Bahr // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Window { diff --git a/types/cordova-sqlite-storage/cordova-sqlite-storage-tests.ts b/types/cordova-sqlite-storage/cordova-sqlite-storage-tests.ts index 6d2e3c3454..215be1d3de 100644 --- a/types/cordova-sqlite-storage/cordova-sqlite-storage-tests.ts +++ b/types/cordova-sqlite-storage/cordova-sqlite-storage-tests.ts @@ -104,13 +104,13 @@ function sampleWithPRAGMA() { }); tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], (tx, res) => { - console.log("insertId: " + res.insertId + " -- probably 1"); - console.log("rowsAffected: " + res.rowsAffected + " -- should be 1"); + console.log(`insertId: ${res.insertId} -- probably 1`); + console.log(`rowsAffected: ${res.rowsAffected} -- should be 1`); db.transaction(tx => { tx.executeSql("select count(id) as cnt from test_table;", [], (tx, res) => { - console.log("res.rows.length: " + res.rows.length + " -- should be 1"); - console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1"); + console.log(`res.rows.length: ${res.rows.length} -- should be 1`); + console.log(`res.rows.item(0).cnt: ${res.rows.item(0).cnt} -- should be 1`); }); }); @@ -135,12 +135,12 @@ function sampleWithTransactionLevelNesting() { tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)'); tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], (tx, res) => { - console.log("insertId: " + res.insertId + " -- probably 1"); - console.log("rowsAffected: " + res.rowsAffected + " -- should be 1"); + console.log(`insertId: ${res.insertId} -- probably 1`); + console.log(`rowsAffected: ${res.rowsAffected} -- should be 1`); tx.executeSql("select count(id) as cnt from test_table;", [], (tx, res) => { - console.log("res.rows.length: " + res.rows.length + " -- should be 1"); - console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1"); + console.log(`res.rows.length: ${res.rows.length} -- should be 1`); + console.log(`res.rows.item(0).cnt: ${res.rows.item(0).cnt} -- should be 1`); }); }, (tx, e) => { console.log("ERROR: " + e.message); diff --git a/types/cordova-sqlite-storage/index.d.ts b/types/cordova-sqlite-storage/index.d.ts index 2f78c908ff..6ba48b08d2 100644 --- a/types/cordova-sqlite-storage/index.d.ts +++ b/types/cordova-sqlite-storage/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for cordova-sqlite-storage 1.5 // Project: https://github.com/litehelpers/Cordova-sqlite-storage -// Definitions by: rafw87 +// Definitions by: rafw87 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Window { diff --git a/types/cordova.plugins.diagnostic/index.d.ts b/types/cordova.plugins.diagnostic/index.d.ts index 5952b41851..e9ad96deb2 100644 --- a/types/cordova.plugins.diagnostic/index.d.ts +++ b/types/cordova.plugins.diagnostic/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for cordova.plugins.diagnostic v3.4.x // Project: https://github.com/dpa99c/cordova-diagnostic-plugin -// Definitions by: Dave Alden +// Definitions by: Dave Alden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/core-decorators/core-decorators-tests.ts b/types/core-decorators/core-decorators-tests.ts index ef4659e56b..c617de5fcc 100644 --- a/types/core-decorators/core-decorators-tests.ts +++ b/types/core-decorators/core-decorators-tests.ts @@ -31,7 +31,7 @@ import { readonly } from 'core-decorators'; class Meal { @readonly - entree: string = 'steak'; + entree = 'steak'; } const dinner = new Meal(); @@ -155,7 +155,7 @@ class Meal2 { entree = 'steak'; @nonenumerable - cost: number = 4.44; + cost = 4.44; } const dinner2 = new Meal2(); @@ -175,7 +175,7 @@ import { nonconfigurable } from 'core-decorators'; class Meal3 { @nonconfigurable - entree: string = 'steak'; + entree = 'steak'; } const dinner3 = new Meal3(); diff --git a/types/core-decorators/tslint.json b/types/core-decorators/tslint.json index e14af8449b..bade6d465f 100644 --- a/types/core-decorators/tslint.json +++ b/types/core-decorators/tslint.json @@ -1,7 +1,9 @@ { "extends": "dtslint/dt.json", "rules": { + // TODOs "callable-types": false, - "ban-types": false + "ban-types": false, + "no-duplicate-imports": false } } diff --git a/types/core-js/core-js-tests.ts b/types/core-js/core-js-tests.ts index 325ff56fc1..32eb2d502c 100644 --- a/types/core-js/core-js-tests.ts +++ b/types/core-js/core-js-tests.ts @@ -59,7 +59,7 @@ let dictOfAny: Dict; // es6.object.to-string, es6.function.name and es6.function.has-instance. // ############################################################################################# -point = Object.assign(point, point); +point = Object.assign(point, point); // tslint:disable-line prefer-object-spread b = Object.is(point, point); Object.setPrototypeOf(point, point); s = f.name; diff --git a/types/core-js/index.d.ts b/types/core-js/index.d.ts index 0a8f506df4..5fb9400d75 100644 --- a/types/core-js/index.d.ts +++ b/types/core-js/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for core-js 0.9 // Project: https://github.com/zloirock/core-js/ -// Definitions by: Ron Buckton , Michel Felipe +// Definitions by: Ron Buckton , Michel Felipe // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 diff --git a/types/cp-file/cp-file-tests.ts b/types/cp-file/cp-file-tests.ts new file mode 100644 index 0000000000..173a650e8f --- /dev/null +++ b/types/cp-file/cp-file-tests.ts @@ -0,0 +1,19 @@ +import cpFile = require('cp-file'); + +cpFile('src/unicorn.png', 'dist/unicorn.png').then(() => {}); +cpFile('src/unicorn.png', 'dist/unicorn.png', {overwrite: false}).then(() => {}); +cpFile('src/unicorn.png', 'dist/unicorn.png') + .on('progress', data => { + let str: string; + let num: number; + + str = data.src; + str = data.dest; + num = data.size; + num = data.written; + num = data.percent; + }) + .then(() => {}); + +cpFile.sync('src/unicorn.png', 'dist/unicorn.png'); +cpFile.sync('src/unicorn.png', 'dist/unicorn.png', {overwrite: false}); diff --git a/types/cp-file/index.d.ts b/types/cp-file/index.d.ts new file mode 100644 index 0000000000..d0966f4c85 --- /dev/null +++ b/types/cp-file/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for cp-file 4.2 +// Project: https://github.com/sindresorhus/cp-file#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = cpFile; + +declare function cpFile(source: string, destination: string, options?: cpFile.Options): Promise & cpFile.ProgressEmitter; + +declare namespace cpFile { + function sync(source: string, destination: string, options?: Options): void; + + interface ProgressEmitter { + on(event: 'progress', handler: (data: ProgressData) => void): Promise; + } + + interface Options { + overwrite?: boolean; + } + + interface ProgressData { + src: string; + dest: string; + size: number; + written: number; + percent: number; + } +} diff --git a/types/cp-file/tsconfig.json b/types/cp-file/tsconfig.json new file mode 100644 index 0000000000..ab4eca94d8 --- /dev/null +++ b/types/cp-file/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cp-file-tests.ts" + ] +} diff --git a/types/cp-file/tslint.json b/types/cp-file/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cp-file/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cpy/cpy-tests.ts b/types/cpy/cpy-tests.ts index 3bc0cbb32a..1800ab35bf 100644 --- a/types/cpy/cpy-tests.ts +++ b/types/cpy/cpy-tests.ts @@ -1,9 +1,18 @@ import cpy = require('cpy'); -cpy(['src/*.png', '!src/goat.png'], 'dist').then(() => { - console.log('files copied'); -}); - +cpy(['src/*.png', '!src/goat.png'], 'dist').then(() => {}); cpy('foo.js', 'destination', { - rename: basename => `prefix-${basename}` + rename: basename => `prefix-${basename}`, + cwd: '/', + parents: true, + stat: true, + overwrite: false, }); +cpy('foo.js', 'destination') + .on('progress', progress => { + let num: number; + num = progress.completedFiles; + num = progress.totalFiles; + num = progress.completedSize; + }) + .then(() => {}); diff --git a/types/cpy/index.d.ts b/types/cpy/index.d.ts index 8ef585250b..b6ca781137 100644 --- a/types/cpy/index.d.ts +++ b/types/cpy/index.d.ts @@ -1,10 +1,31 @@ -// Type definitions for cpy 5.0 +// Type definitions for cpy 5.1 // Project: https://github.com/sindresorhus/cpy#readme // Definitions by: Mohamed Hegazy +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import glob = require('glob'); +import cpFile = require('cp-file'); + export = cpy; -declare function cpy( - src: string | string[], - dest: string, - opts?: { cwd?: string, parents?: boolean, rename?(s: string): string }): Promise; +declare function cpy(files: string | string[], destination: string, opts?: cpy.Options): Promise & cpy.ProgressEmitter; + +declare namespace cpy { + interface ProgressEmitter { + on(event: 'progress', handler: (progress: ProgressData) => void): Promise; + } + + type Options = CpyOptions & glob.IOptions & cpFile.Options; + + interface CpyOptions { + cwd?: string; + parents?: boolean; + rename?: string | ((basename: string) => string); + } + + interface ProgressData { + completedFiles: number; + totalFiles: number; + completedSize: number; + } +} diff --git a/types/cpy/tsconfig.json b/types/cpy/tsconfig.json index 6cb55952aa..75f61a1e5d 100644 --- a/types/cpy/tsconfig.json +++ b/types/cpy/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, @@ -20,4 +19,4 @@ "index.d.ts", "cpy-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/crypto-js/crypto-js-tests.ts b/types/crypto-js/crypto-js-tests.ts index c0c23bcc79..c36def9f90 100644 --- a/types/crypto-js/crypto-js-tests.ts +++ b/types/crypto-js/crypto-js-tests.ts @@ -1,15 +1,15 @@ import CryptoJS = require('crypto-js'); // Hashers -var str: string; -str = CryptoJS.MD5('some message'); -str = CryptoJS.MD5('some message', 'some key'); +var wordArray: CryptoJS.WordArray; +wordArray = CryptoJS.MD5('some message'); +wordArray = CryptoJS.MD5('some message', 'some key'); -str = CryptoJS.SHA1('some message'); -str = CryptoJS.SHA1('some message', 'some key', { any: true }); +wordArray = CryptoJS.SHA1('some message'); +wordArray = CryptoJS.SHA1('some message', 'some key', { any: true }); -str = CryptoJS.format.OpenSSL('some message'); -str = CryptoJS.format.OpenSSL('some message', 'some key'); +wordArray = CryptoJS.format.OpenSSL('some message'); +wordArray = CryptoJS.format.OpenSSL('some message', 'some key'); // Ciphers diff --git a/types/crypto-js/index.d.ts b/types/crypto-js/index.d.ts index 07a8d18dfc..8e80c74a07 100644 --- a/types/crypto-js/index.d.ts +++ b/types/crypto-js/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for crypto-js v3.1.4 +// Type definitions for crypto-js v3.1.8 // Project: https://github.com/evanvosberg/crypto-js -// Definitions by: Michael Zabka +// Definitions by: Michael Zabka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = CryptoJS; @@ -8,7 +8,7 @@ export as namespace CryptoJS; declare var CryptoJS: CryptoJS.Hashes; declare namespace CryptoJS { - type Hash = (message: string, key?: string, ...options: any[]) => string; + type Hash = (message: string, key?: string, ...options: any[]) => WordArray; interface Cipher { encrypt(message: string, secretPassphrase: string, option?: CipherOption): WordArray; decrypt(encryptedMessage: string | WordArray, secretPassphrase: string, option?: CipherOption): DecryptedMessage; @@ -30,6 +30,7 @@ declare namespace CryptoJS { salt: string; ciphertext: string; key?: string; + toString(encoder?: Encoder): string; } export type DecryptedMessage = { toString(encoder?: Encoder): string; diff --git a/types/crypto-js/test/submodule-tests.ts b/types/crypto-js/test/submodule-tests.ts index 0cfd8cd83f..423d094143 100644 --- a/types/crypto-js/test/submodule-tests.ts +++ b/types/crypto-js/test/submodule-tests.ts @@ -52,15 +52,15 @@ import PadZeroPadding = require('../pad-zeropadding'); import PadNoPadding = require('../pad-nopadding'); // Hashers -var str: string; -str = MD5('some message'); -str = MD5('some message', 'some key'); +var wordArray: CryptoJS.WordArray; +wordArray = MD5('some message'); +wordArray = MD5('some message', 'some key'); -str = SHA1('some message'); -str = SHA1('some message', 'some key', { any: true }); +wordArray = SHA1('some message'); +wordArray = SHA1('some message', 'some key', { any: true }); -str = FormatOpenSSL('some message'); -str = FormatOpenSSL('some message', 'some key'); +wordArray = FormatOpenSSL('some message'); +wordArray = FormatOpenSSL('some message', 'some key'); // Ciphers diff --git a/types/css-modules/css-modules-tests.ts b/types/css-modules/css-modules-tests.ts new file mode 100644 index 0000000000..e6479ba2d5 --- /dev/null +++ b/types/css-modules/css-modules-tests.ts @@ -0,0 +1,21 @@ +import styles from './main.sass'; +import * as classNames from 'classnames'; + +class App { + private theme: string; + constructor(theme: string) { + this.theme = theme; + } + + render() { + // as a style tag (using webpack's css-loader) + const tpl = `
      `; + // or as scoped unique classes, also latest typescript versions allow prop access using dot like styles.darkUI instead of styles['darkUI'] + return ` +
      +
      + `; + } +} diff --git a/types/css-modules/index.d.ts b/types/css-modules/index.d.ts new file mode 100644 index 0000000000..832ae27406 --- /dev/null +++ b/types/css-modules/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for css-modules 1.0 +// Project: https://github.com/css-modules/css-modules +// Definitions by: NeekSandhu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +interface Stringifyable { + /** + * Stringifies the imported stylesheet for use with inline style tags + */ + toString(): string; +} +interface SelectorNode { + /** + * Returns the specific selector from imported stylesheet as string + */ + [key: string]: string; +} + +declare module '*.css' { + const styles: SelectorNode & Stringifyable; + export default styles; +} + +declare module '*.scss' { + const styles: SelectorNode & Stringifyable; + export default styles; +} + +declare module '*.sass' { + const styles: SelectorNode & Stringifyable; + export default styles; +} + +declare module '*.less' { + const styles: SelectorNode & Stringifyable; + export default styles; +} diff --git a/types/css-modules/tsconfig.json b/types/css-modules/tsconfig.json new file mode 100644 index 0000000000..40a428a927 --- /dev/null +++ b/types/css-modules/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "css-modules-tests.ts" + ] +} \ No newline at end of file diff --git a/types/css-modules/tslint.json b/types/css-modules/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/css-modules/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/csurf/index.d.ts b/types/csurf/index.d.ts index 53b86392f1..362b4c6e8e 100644 --- a/types/csurf/index.d.ts +++ b/types/csurf/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for csurf 1.9.0 // Project: https://www.npmjs.org/package/csurf -// Definitions by: Hiroki Horiuchi +// Definitions by: Hiroki Horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/types/csv-parse/index.d.ts b/types/csv-parse/index.d.ts index cbf79729e5..e85742c1c9 100644 --- a/types/csv-parse/index.d.ts +++ b/types/csv-parse/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for csv-parse 1.1 // Project: https://github.com/wdavidw/node-csv-parse // Definitions by: David Muller +// Jan Sziegaud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -111,6 +112,16 @@ declare namespace parse { * If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option. */ auto_parse_date?: boolean; + + /** + * Start returning records from a particular line. + */ + from?: number; + + /** + * Stop returning records after a particular line. + */ + to?: number; } // TODO: what is this for? diff --git a/types/csv-stringify/csv-stringify-tests.ts b/types/csv-stringify/csv-stringify-tests.ts index d7a6f0196b..803575e554 100644 --- a/types/csv-stringify/csv-stringify-tests.ts +++ b/types/csv-stringify/csv-stringify-tests.ts @@ -12,9 +12,28 @@ stringify([["1", "2", "3"], ["4", "5", "6"]], { // nothing }); +stringify([{a: "1", b: "2", c: "3"}, {c: "4", b: "5", a: "6"}], { + delimiter: "," +}, (error: Error, output: string): void => { + // nothing +}); + +stringify([["1", true, new Date()], ["4", false, new Date()]], { + delimiter: ",", + formatters: { + bool: value => value ? 'yes' : 'no', + date: value => value.toISOString() + } +}, (error: Error, output: string): void => { + // nothing +}); + stream = stringify({ delimiter: "," }); stream.write(["1", "2", "3"]); +stream.write(["4", true, new Date()], 'utf8', (err: Error, output: string): void => { + // nothing +}); const transform: NodeJS.ReadWriteStream = stream; diff --git a/types/csv-stringify/index.d.ts b/types/csv-stringify/index.d.ts index a636547187..2e8cb32edb 100644 --- a/types/csv-stringify/index.d.ts +++ b/types/csv-stringify/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for csv-stringify 1.0 +// Type definitions for csv-stringify 1.4 // Project: https://github.com/wdavidw/node-csv-stringify // Definitions by: Rogier Schouten +// Arjen van der Ende // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -55,15 +56,24 @@ declare namespace stringify { * special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). */ rowDelimiter?: string; + /** + * Override serialization of boolean, dates and complex objects. + */ + formatters?: FormatterOpts; + } + + interface FormatterOpts { + bool?: (value: boolean) => string; + date?: (value: Date) => string; + object?: (value: any) => string; } interface Stringifier extends NodeJS.ReadWriteStream { - // Stringifier stream takes array of strings or Object - write(line: string[] | any): boolean; + // Stringifier stream takes array of strings or Object, and optional encoding and callback + write(line: string[] | any, encoding?: string, cb?: (error: Error | undefined, output: string) => void): boolean; // repeat declarations from NodeJS.WritableStream to avoid compile error - write(buffer: string | Buffer, cb?: () => void): boolean; - write(str: string, encoding?: string, cb?: () => void): boolean; + write(buffer: string | Buffer, cb?: (error: Error | undefined, output: string) => void): boolean; } } @@ -75,7 +85,7 @@ declare function stringify(opts?: stringify.StringifyOpts): stringify.Stringifie /** * Callback version: string in --> callback with string out */ -declare function stringify(input: any[][], opts: stringify.StringifyOpts, callback: (error: Error | undefined, output: string) => void): void; -declare function stringify(input: any[][], callback: (error: Error | undefined, output: string) => void): void; +declare function stringify(input: any[][] | Array<{}>, opts: stringify.StringifyOpts, callback: (error: Error | undefined, output: string) => void): void; +declare function stringify(input: any[][] | Array<{}>, callback: (error: Error | undefined, output: string) => void): void; export = stringify; diff --git a/types/csv-stringify/tslint.json b/types/csv-stringify/tslint.json index 3db14f85ea..11584e5acd 100644 --- a/types/csv-stringify/tslint.json +++ b/types/csv-stringify/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "prefer-method-signature": false + } +} diff --git a/types/csvtojson/csvtojson-tests.ts b/types/csvtojson/csvtojson-tests.ts index 5b58451fac..2d6e36c84f 100644 --- a/types/csvtojson/csvtojson-tests.ts +++ b/types/csvtojson/csvtojson-tests.ts @@ -5,7 +5,7 @@ import fs = require('fs'); ///////////////////////////// // From CSV String -const csvStr: string = `1,2,3 +const csvStr = `1,2,3 4,5,6 7,8,9`; diff --git a/types/cucumber/cucumber-tests.ts b/types/cucumber/cucumber-tests.ts index 53ca726230..46531711f3 100644 --- a/types/cucumber/cucumber-tests.ts +++ b/types/cucumber/cucumber-tests.ts @@ -6,42 +6,44 @@ function StepSample() { type Table = cucumber.TableDefinition; type HookScenarioResult = cucumber.HookScenarioResult; - cucumber.defineSupportCode(function ({setWorldConstructor, defineParameterType, After, Around, Before, registerHandler, Given, When, Then}) { - setWorldConstructor(function ({attach, parameters}: any) { + cucumber.defineSupportCode(({setWorldConstructor, defineParameterType, After, Around, Before, registerHandler, Given, When, Then}) => { + setWorldConstructor(function({attach, parameters}) { this.attach = attach; this.parameters = parameters; - this.visit = function (url: string, callback: Callback) { + this.visit = (url: string, callback: Callback) => { callback(null, 'pending'); + }; + }); + + Before((scenarioResult: HookScenarioResult, callback: Callback) => { + console.log(scenarioResult.status === "failed"); + callback(); + }); + + Before({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback: Callback) => { + console.log(scenarioResult.status === "failed"); + callback(); + }); + + Around((scenarioResult: HookScenarioResult, runScenario: (error: string | null, callback?: () => void) => void) => { + if (scenarioResult.status === "failed") { + runScenario(null, () => { + console.log('finish tasks'); + }); } }); - Before(function (scenarioResult: HookScenarioResult, callback: Callback) { - console.log(scenarioResult.status === "failed"); - callback(); - }); - - Before({ timeout: 1000 }, function (scenarioResult: HookScenarioResult, callback: Callback) { - console.log(scenarioResult.status === "failed"); - callback(); - }); - - Around(function (scenarioResult: HookScenarioResult, runScenario: (error: string, callback?: Function) => void) { - scenarioResult.status === "failed" && runScenario(null, function () { - console.log('finish tasks'); - }); - }); - - After((scenarioResult: HookScenarioResult, callback?: Callback) => { + After((scenarioResult: HookScenarioResult, callback: Callback) => { console.log("After"); callback(); }); - After({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback?: Callback) => { + After({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback: Callback) => { console.log("After"); callback(); }); - registerHandler('AfterFeatures', function (event: any, callback: Function) { + registerHandler('AfterFeatures', (event: any, callback: () => void) => { callback(); }); @@ -53,16 +55,16 @@ function StepSample() { console.log(typeof x); }); - Given(/^I am on the Cucumber.js GitHub repository$/, function (callback: Callback) { + Given(/^I am on the Cucumber.js GitHub repository$/, function(callback: Callback) { this.visit('https://github.com/cucumber/cucumber-js', callback); }); - When(/^I go to the README file$/, function (title: string, callback: Callback) { + When(/^I go to the README file$/, (title: string, callback: Callback) => { callback(null, 'pending'); }); - Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function (title: string, callback: Callback) { - var pageTitle = this.browser.text('title'); + Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function(title: string, callback: Callback) { + const pageTitle = this.browser.text('title'); if (title === pageTitle) { callback(); @@ -74,39 +76,42 @@ function StepSample() { // Type for data_table.js on // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js - Given(/^a table step with Table raw$/, function (table: Table) { - var expected = [ + Given(/^a table step with Table raw$/, (table: Table) => { + const expected = [ ['Cucumber', 'Cucumis sativus'], ['Burr Gherkin', 'Cucumis anguria'] ]; - - assert.deepEqual(table.raw(), expected); + const actual: string[][] = table.raw(); + assert.deepEqual(actual, expected); }); - Given(/^a table step with Table rows$/, function (table: Table) { - var expected = [ + Given(/^a table step with Table rows$/, (table: Table) => { + const expected = [ ['Apricot', '5'], ['Brocolli', '2'], ['Cucumber', '10'] ]; - assert.deepEqual(table.rows(), expected) + const actual: string[][] = table.rows(); + assert.deepEqual(actual, expected); }); - Given(/^a table step with Table rowHash$/, function (table: Table) { - var expected = { - 'Cucumber': 'Cucumis sativus', + Given(/^a table step with Table rowHash$/, (table: Table) => { + const expected = { + Cucumber: 'Cucumis sativus', 'Burr Gherkin': 'Cucumis anguria' }; - assert.deepEqual(table.rowsHash(), expected) + const actual: { [firstCol: string]: string } = table.rowsHash(); + assert.deepEqual(actual, expected); }); - Given(/^a table step$/, function (table: Table) { - var expected = [ - {'Vegetable': 'Apricot', 'Rating': '5'}, - {'Vegetable': 'Brocolli', 'Rating': '2'}, - {'Vegetable': 'Cucumber', 'Rating': '10'} + Given(/^a table step$/, (table: Table) => { + const expected = [ + {Vegetable: 'Apricot', Rating: '5'}, + {Vegetable: 'Brocolli', Rating: '2'}, + {Vegetable: 'Cucumber', Rating: '10'} ]; - assert.deepEqual(table.hashes(), expected) + const actual: Array<{ [colName: string]: string }> = table.hashes(); + assert.deepEqual(actual, expected); }); defineParameterType({ @@ -115,21 +120,19 @@ function StepSample() { typeName: 'param' }); - Given('a {param} step', function (param) { - assert.equal(param, 'PARTICULAR') + Given('a {param} step', param => { + assert.equal(param, 'PARTICULAR'); }); - }); - let fns: cucumber.SupportCodeConsumer[] = cucumber.getSupportCodeFns(); + const fns: cucumber.SupportCodeConsumer[] = cucumber.getSupportCodeFns(); cucumber.clearSupportCodeFns(); } function registerListener(): cucumber.EventListener { - let listener = Object.assign(cucumber.Listener(), { + const listener = Object.assign(cucumber.Listener(), { handleBeforeScenarioEvent: (scenario: cucumber.events.ScenarioPayload, callback: () => void) => { - // do some interesting stuff ... callback(); diff --git a/types/cucumber/index.d.ts b/types/cucumber/index.d.ts index 60e3d27d5d..90ed0abe4a 100644 --- a/types/cucumber/index.d.ts +++ b/types/cucumber/index.d.ts @@ -1,196 +1,124 @@ -// Type definitions for cucumber-js v2.0.0 +// Type definitions for cucumber-js 2.0 // Project: https://github.com/cucumber/cucumber-js -// Definitions by: Abraão Alves , Jan Molak , Isaiah Soung +// Definitions by: Abraão Alves +// Jan Molak +// Isaiah Soung +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -export = cucumber; +export interface CallbackStepDefinition { + pending(): PromiseLike; + (error?: any, pending?: string): void; +} -declare namespace cucumber { +export interface TableDefinition { + raw(): string[][]; + rows(): string[][]; + rowsHash(): { [firstCol: string]: string }; + hashes(): Array<{ [colName: string]: string }>; +} - export interface CallbackStepDefinition { - pending: () => PromiseLike; - (error?: any, pending?: string): void; +export type StepDefinitionParam = string | number | CallbackStepDefinition | TableDefinition; + +export type StepDefinitionCode = (this: {[key: string]: any}, ...stepArgs: StepDefinitionParam[]) => PromiseLike | any | void; + +export interface StepDefinitionOptions { + timeout?: number; +} + +export interface StepDefinitions { + Given(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; + Given(pattern: RegExp | string, code: StepDefinitionCode): void; + When(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; + When(pattern: RegExp | string, code: StepDefinitionCode): void; + Then(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; + Then(pattern: RegExp | string, code: StepDefinitionCode): void; + setDefaultTimeout(time: number): void; +} + +export interface HookScenarioResult { + duration: number; + failureException: Error; + scenario: Scenario; + status: string; + stepsResults: any; +} + +export type HookCode = (this: { [key: string]: any }, scenario: HookScenarioResult, callback?: CallbackStepDefinition) => void; + +// tslint:disable-next-line ban-types +export type AroundCode = (scenario: HookScenarioResult, runScenario?: (error: string, callback?: Function) => void) => void; + +export interface Transform { + regexp: RegExp; + transformer(arg: string): any; + typeName: string; +} + +export interface HookOptions { + timeout?: number; + tags?: any; +} + +export interface Hooks { + Before(code: HookCode): void; + Before(options: HookOptions, code: HookCode): void; + After(code: HookCode): void; + After(options: HookOptions, code: HookCode): void; + Around(code: AroundCode): void; + setDefaultTimeout(time: number): void; + // tslint:disable-next-line ban-types + setWorldConstructor(world: ((this: {[key: string]: any}, init: {attach: Function, parameters: {[key: string]: any}}) => void) | {}): void; + registerHandler(handlerOption: string, code: (event: any, callback: CallbackStepDefinition) => void): void; + registerListener(listener: EventListener): void; + defineParameterType(transform: Transform): void; +} + +export class EventListener { + hear(event: events.Event, callback: () => void): void; + hasHandlerForEvent(event: events.Event): boolean; + buildHandlerNameForEvent(event: events.Event): string; + getHandlerForEvent(event: events.Event): EventHook; + buildHandlerName(shortName: string): string; + setHandlerForEvent(shortName: string, handler: EventListener): void; +} + +export function Listener(): EventListener; + +export namespace events { + interface Event { + name: string; + data: any; } - export interface TableDefinition { - raw: () => Array; - rows: () => Array; - rowsHash: () => {}; - hashes: () => {}; + // tslint:disable-next-line no-empty-interface + interface EventPayload { } - type StepDefinitionParam = string | number | CallbackStepDefinition | TableDefinition; - - interface StepDefinitionCode { - (...stepArgs: Array): PromiseLike | any | void; + interface FeaturesPayload extends EventPayload { + getFeatures(): any[]; // https://github.com/cucumber/cucumber-js/blob/dc698bf5bc10d591fa7adeec5fa21b2d90dc9679/lib/cucumber/runtime.js#L34 } - interface StepDefinitionOptions { - timeout?: number; - } - - export interface StepDefinitions { - Given(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; - Given(pattern: RegExp | string, code: StepDefinitionCode): void; - When(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; - When(pattern: RegExp | string, code: StepDefinitionCode): void; - Then(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; - Then(pattern: RegExp | string, code: StepDefinitionCode): void; - setDefaultTimeout(time: number): void; - } - - interface HookScenarioResult { + interface FeaturesResultPayload extends EventPayload { duration: number; - failureException: Error; - scenario: Scenario; - status: string; - stepsResults: any; + scenarioResults: any[]; + success: boolean; + stepsResults: any[]; + strict: boolean; } - interface HookCode { - (scenario: HookScenarioResult, callback?: CallbackStepDefinition): void; - } - - interface AroundCode { - (scenario: HookScenarioResult, runScenario?: (error: string, callback?: Function) => void): void; - } - - interface Transform { - regexp: RegExp; - transformer: (arg: string) => any; - typeName: string; - } - - interface HookOptions { - timeout?: number; - tags?: any; - } - - export interface Hooks { - Before(code: HookCode): void; - Before(options: HookOptions, code: HookCode): void; - After(code: HookCode): void; - After(options: HookOptions, code: HookCode): void; - Around(code: AroundCode): void; - setDefaultTimeout(time: number): void; - setWorldConstructor(world: (() => void) | ({})): void; - registerHandler(handlerOption: string, code: (event: any, callback: CallbackStepDefinition) => void): void; - registerListener(listener: EventListener): void; - defineParameterType(transform: Transform): void; - } - - export class EventListener { - hear(event: events.Event, callback: () => void): void; - hasHandlerForEvent(event: events.Event): boolean; - buildHandlerNameForEvent(event: events.Event): string; - getHandlerForEvent(event: events.Event): EventHook; - buildHandlerName(shortName: string): string; - setHandlerForEvent(shortName: string, handler: EventListener): void; - } - - export function Listener(): EventListener; - - export namespace events { - - interface Event { - name: string; - data: any; - } - - interface EventPayload { - } - - interface FeaturesPayload extends EventPayload { - getFeatures(): any[]; // https://github.com/cucumber/cucumber-js/blob/dc698bf5bc10d591fa7adeec5fa21b2d90dc9679/lib/cucumber/runtime.js#L34 - } - - interface FeaturesResultPayload extends EventPayload { - duration: number; - scenarioResults: any[]; - success: boolean; - stepsResults: any[]; - strict: boolean; - } - - interface FeaturePayload extends EventPayload { - description: string; - keyword: string; - line: number; - name: string; - tags: Tag[]; - uri: string; - scenarios: Scenario[]; - } - - interface ScenarioPayload extends EventPayload { - feature: Feature; - exception: Error; - keyword: string; - lines: number[]; - name: string; - tags: Tag[]; - uri: string; - line: number; - description: string; - steps: Step[]; - } - - interface ScenarioResultPayload extends EventPayload { - duration: any; - failureException: Error; - scenario: Scenario; - status: string; - stepResults: any[]; - } - - interface StepPayload extends EventPayload { - arguments: any; - line: number; - name: string; - scenario: Scenario; - uri: string; - isBackground: boolean; - keyword: string; - keywordType: string; - } - - interface StepResultPayload extends EventPayload { - ambiguousStepDefinitions: any; - attachments: any[]; - duration: any; - failureException: Error; - step: Step; - stepDefinition: StepDefinition; - status: string; - } - - } - - export interface StepDefinition { - code: Function; - line: number; - options: {}; - pattern: any; - uri: string; - } - - export interface Tag { - name: string; - line: number; - } - - export interface Step { - arguments: any; - line: number; - name: string; - scenario: Scenario; - uri: string; - isBackground: boolean; + interface FeaturePayload extends EventPayload { + description: string; keyword: string; - keywordType: string; + line: number; + name: string; + tags: Tag[]; + uri: string; + scenarios: Scenario[]; } - export interface Scenario { + interface ScenarioPayload extends EventPayload { feature: Feature; exception: Error; keyword: string; @@ -203,62 +131,125 @@ declare namespace cucumber { steps: Step[]; } - export interface Feature { - description: string; - keyword: string; + interface ScenarioResultPayload extends EventPayload { + duration: any; + failureException: Error; + scenario: Scenario; + status: string; + stepResults: any[]; + } + + interface StepPayload extends EventPayload { + arguments: any; line: number; name: string; - tags: Tag[]; + scenario: Scenario; uri: string; - scenarios: Scenario[]; + isBackground: boolean; + keyword: string; + keywordType: string; } - interface EventHook { - (event: events.Event, callback?: () => void): void; + interface StepResultPayload extends EventPayload { + ambiguousStepDefinitions: any; + attachments: any[]; + duration: any; + failureException: Error; + step: Step; + stepDefinition: StepDefinition; + status: string; } +} - export interface SupportCodeConsumer { - (stepDefinitions: StepDefinitions & Hooks): void; - } +export interface StepDefinition { + // tslint:disable-next-line ban-types + code: Function; + line: number; + options: {}; + pattern: any; + uri: string; +} - export function defineSupportCode(consumer: SupportCodeConsumer): void; +export interface Tag { + name: string; + line: number; +} - export function getSupportCodeFns(): SupportCodeConsumer[]; +export interface Step { + arguments: any; + line: number; + name: string; + scenario: Scenario; + uri: string; + isBackground: boolean; + keyword: string; + keywordType: string; +} - export function clearSupportCodeFns(): void; +export interface Scenario { + feature: Feature; + exception: Error; + keyword: string; + lines: number[]; + name: string; + tags: Tag[]; + uri: string; + line: number; + description: string; + steps: Step[]; +} - // https://github.com/cucumber/cucumber-js/commit/231183a8a11c985ef7ced1155b7a75f5120a34b6 - export class Formatter { - constructor(options?: any); +export interface Feature { + description: string; + keyword: string; + line: number; + name: string; + tags: Tag[]; + uri: string; + scenarios: Scenario[]; +} - log(data: any): void; - } +export type EventHook = (event: events.Event, callback?: () => void) => void; - export class SummaryFormatter extends Formatter { - indent(text: string, numberOfSpaces: number): any; - } - export class PrettyFormatter extends SummaryFormatter { - formatTags(tags: Tag[]): any; - logIndented(text: string, level: number): void; - logStepResult(stepResult: any): void; - } +export type SupportCodeConsumer = (stepDefinitions: StepDefinitions & Hooks) => void; - export class ProgressFormatter extends SummaryFormatter { - } +export function defineSupportCode(consumer: SupportCodeConsumer): void; - export class RerunFormatter extends Formatter { - } +export function getSupportCodeFns(): SupportCodeConsumer[]; - export class SnippetsFormatter extends Formatter { - } +export function clearSupportCodeFns(): void; - export class UsageFormatter extends Formatter { - } +// https://github.com/cucumber/cucumber-js/commit/231183a8a11c985ef7ced1155b7a75f5120a34b6 +export class Formatter { + constructor(options?: any); - export class UsageJsonFormatter extends Formatter { - } + log(data: any): void; +} - export class JsonFormatter extends Formatter { - } +export class SummaryFormatter extends Formatter { + indent(text: string, numberOfSpaces: number): any; +} +export class PrettyFormatter extends SummaryFormatter { + formatTags(tags: Tag[]): any; + logIndented(text: string, level: number): void; + logStepResult(stepResult: any): void; +} + +export class ProgressFormatter extends SummaryFormatter { +} + +export class RerunFormatter extends Formatter { +} + +export class SnippetsFormatter extends Formatter { +} + +export class UsageFormatter extends Formatter { +} + +export class UsageJsonFormatter extends Formatter { +} + +export class JsonFormatter extends Formatter { } diff --git a/types/cucumber/tsconfig.json b/types/cucumber/tsconfig.json index c7fe6d2258..a2bd1c7023 100644 --- a/types/cucumber/tsconfig.json +++ b/types/cucumber/tsconfig.json @@ -6,8 +6,8 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -20,4 +20,4 @@ "index.d.ts", "cucumber-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/cucumber/tslint.json b/types/cucumber/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cucumber/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cucumber/v1/cucumber-tests.ts b/types/cucumber/v1/cucumber-tests.ts index 596772274f..6007df8c03 100644 --- a/types/cucumber/v1/cucumber-tests.ts +++ b/types/cucumber/v1/cucumber-tests.ts @@ -1,45 +1,47 @@ -import * as assert from "power-assert"; -import cucumber = require("cucumber"); +import * as assert from 'power-assert'; +import cucumber = require('cucumber'); -function StepSample() { +function StepSample(this: cucumber.StepDefinitions & cucumber.Hooks) { type Callback = cucumber.CallbackStepDefinition; type Table = cucumber.TableDefinition; type HookScenario = cucumber.HookScenario; - var step = this; - var hook = this; + const step = this; + const hook = this; - hook.Before(function (scenario: HookScenario, callback: Callback) { + hook.Before((scenario: HookScenario, callback: Callback) => { scenario.isFailed() && callback.pending(); }); - - hook.Before({ timeout: 1000 }, function(scenario: HookScenario, callback: Callback) { - callback(); - }); - - hook.After({ timeout: 1000 }, function(scenario: HookScenario, callback: Callback) { + + hook.Before({ timeout: 1000 }, (scenario: HookScenario, callback: Callback) => { callback(); }); - hook.Around(function (scenario: HookScenario, runScenario: (error: string, callback?: Function) => void) { - scenario.isFailed() && runScenario(null, function () { - console.log('finish tasks'); - }); + hook.After({ timeout: 1000 }, (scenario: HookScenario, callback: Callback) => { + callback(); + }); + + hook.Around((scenario: HookScenario, runScenario: (error: string | null, callback?: () => void) => void) => { + if (scenario.isFailed()) { + runScenario(null, () => { + console.log('finish tasks'); + }); + } }); - hook.registerHandler('AfterFeatures', function (event: any, callback: Function) { + hook.registerHandler('AfterFeatures', (event: any, callback: () => void) => { callback(); }); - step.Given(/^I am on the Cucumber.js GitHub repository$/, function (callback: Callback) { + step.Given(/^I am on the Cucumber.js GitHub repository$/, function(callback: Callback) { this.visit('https://github.com/cucumber/cucumber-js', callback); }); - step.When(/^I go to the README file$/, function (title: string, callback: Callback) { + step.When(/^I go to the README file$/, (title: string, callback: Callback) => { callback(null, 'pending'); }); - step.Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function (title: string, callback: Callback) { - var pageTitle = this.browser.text('title'); + step.Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function(title: string, callback: Callback) { + const pageTitle = this.browser.text('title'); if (title === pageTitle) { callback(); @@ -51,47 +53,48 @@ function StepSample() { // Type for data_table.js on // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js - step.Given(/^a table step with Table raw$/, function (table: Table) { - var expected = [ + step.Given(/^a table step with Table raw$/, (table: Table) => { + const expected = [ ['Cucumber', 'Cucumis sativus'], ['Burr Gherkin', 'Cucumis anguria'] ]; - - assert.deepEqual(table.raw(), expected); + const actual: string[][] = table.raw(); + assert.deepEqual(actual, expected); }); - step.Given(/^a table step with Table rows$/, function (table: Table) { - var expected = [ + step.Given(/^a table step with Table rows$/, (table: Table) => { + const expected = [ ['Apricot', '5'], ['Brocolli', '2'], ['Cucumber', '10'] ]; - assert.deepEqual(table.rows(), expected) + const actual: string[][] = table.rows(); + assert.deepEqual(actual, expected); }); - step.Given(/^a table step with Table rowHash$/, function (table: Table) { - var expected = { - 'Cucumber': 'Cucumis sativus', + step.Given(/^a table step with Table rowHash$/, (table: Table) => { + const expected = { + Cucumber: 'Cucumis sativus', 'Burr Gherkin': 'Cucumis anguria' }; - assert.deepEqual(table.rowsHash(), expected) + const actual: { [firstCol: string]: string } = table.rowsHash(); + assert.deepEqual(actual, expected); }); - step.Given(/^a table step$/, function (table: Table) { - var expected = [ - {'Vegetable': 'Apricot', 'Rating': '5'}, - {'Vegetable': 'Brocolli', 'Rating': '2'}, - {'Vegetable': 'Cucumber', 'Rating': '10'} + step.Given(/^a table step$/, (table: Table) => { + const expected = [ + {Vegetable: 'Apricot', Rating: '5'}, + {Vegetable: 'Brocolli', Rating: '2'}, + {Vegetable: 'Cucumber', Rating: '10'} ]; - assert.deepEqual(table.hashes(), expected) + const actual: Array<{ [colName: string]: string }> = table.hashes(); + assert.deepEqual(actual, expected); }); - } function registerListener(): cucumber.EventListener { - let listener = Object.assign(cucumber.Listener(), { - handleBeforeScenarioEvent: (scenario: cucumber.events.ScenarioPayload, callback: () => void) => { - + const listener = Object.assign(cucumber.Listener(), { + handleBeforeScenarioEvent(scenario: cucumber.events.ScenarioPayload, callback: () => void) { // do some interesting stuff ... callback(); diff --git a/types/cucumber/v1/index.d.ts b/types/cucumber/v1/index.d.ts index bdf30d740d..18c70c5ea6 100644 --- a/types/cucumber/v1/index.d.ts +++ b/types/cucumber/v1/index.d.ts @@ -1,215 +1,206 @@ -// Type definitions for cucumber-js v1.3.1 +// Type definitions for cucumber-js 1.3 // Project: https://github.com/cucumber/cucumber-js -// Definitions by: Abraão Alves , Jan Molak , Isaiah Soung +// Definitions by: Abraão Alves +// Jan Molak +// Isaiah Soung +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -export = cucumber; +export interface CallbackStepDefinition { + pending(): PromiseLike; + (error?: any, pending?: string): void; +} -declare namespace cucumber { +export interface TableDefinition { + raw(): string[][]; + rows(): string[][]; + rowsHash(): { [firstCol: string]: string }; + hashes(): Array<{ [colName: string]: string }>; +} - export interface CallbackStepDefinition { - pending: () => PromiseLike; - (error?: any, pending?: string): void; - } +export type StepDefinitionParam = string | CallbackStepDefinition | TableDefinition; - export interface TableDefinition { - raw: () => Array; - rows: () => Array; - rowsHash: () => {}; - hashes: () => {}; - } +export type StepDefinitionCode = (this: { [key: string]: any }, ...stepArgs: StepDefinitionParam[]) => PromiseLike | any | void; - type StepDefinitionParam = string | CallbackStepDefinition | TableDefinition; +export interface StepDefinitionOptions { + timeout?: number; +} - interface StepDefinitionCode { - (...stepArgs: Array): PromiseLike | any | void; - } +export interface StepDefinitions { + Given(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; + Given(pattern: RegExp | string, code: StepDefinitionCode): void; + When(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; + When(pattern: RegExp | string, code: StepDefinitionCode): void; + Then(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; + Then(pattern: RegExp | string, code: StepDefinitionCode): void; + setDefaultTimeout(time: number): void; +} - interface StepDefinitionOptions { - timeout?: number; - } +export interface HookScenario { + getKeyword(): string; + getName(): string; + getDescription(): string; + getUri(): string; + getLine(): number; + getTags(): string[]; + getException(): Error; + getAttachments(): any[]; + attach(data: any, mimeType?: string, callback?: (err?: any) => void): void; + isSuccessful(): boolean; + isFailed(): boolean; + isPending(): boolean; + isUndefined(): boolean; + isSkipped(): boolean; +} - export interface StepDefinitions { - Given(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; - Given(pattern: RegExp | string, code: StepDefinitionCode): void; - When(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; - When(pattern: RegExp | string, code: StepDefinitionCode): void; - Then(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; - Then(pattern: RegExp | string, code: StepDefinitionCode): void; - setDefaultTimeout(time: number): void; - } +export type HookCode = (this: { [key: string]: any }, scenario: HookScenario, callback?: CallbackStepDefinition) => void; - interface HookScenario { - getKeyword(): string; +// tslint:disable-next-line ban-types +export type AroundCode = (scenario: HookScenario, runScenario?: (error: string, callback?: Function) => void) => void; + +export interface HookOptions { + timeout?: number; + tags?: any; +} + +export interface Hooks { + Before(code: HookCode): void; + Before(options: HookOptions, code: HookCode): void; + After(code: HookCode): void; + After(options: HookOptions, code: HookCode): void; + Around(code: AroundCode): void; + setDefaultTimeout(time: number): void; + registerHandler(handlerOption: string, code: (event: any, callback: CallbackStepDefinition) => void): void; + registerListener(listener: EventListener): void; +} + +export class EventListener { + hear(event: events.Event, callback: () => void): void; + hasHandlerForEvent(event: events.Event): boolean; + buildHandlerNameForEvent(event: events.Event): string; + getHandlerForEvent(event: events.Event): EventHook; + buildHandlerName(shortName: string): string; + setHandlerForEvent(shortName: string, handler: EventListener): void; +} + +export function Listener(): EventListener; + +export namespace events { + interface Event { getName(): string; - getDescription(): string; - getUri(): string; - getLine(): number; - getTags(): string[]; - getException(): Error; - getAttachments(): any[]; - attach(data: any, mimeType?: string, callback?: (err?: any) => void): void; + getPayloadItem(name: string): EventPayload; + } + + // tslint:disable-next-line no-empty-interface + interface EventPayload { + } + + interface FeaturesPayload extends EventPayload { + getFeatures(): any[]; // https://github.com/cucumber/cucumber-js/blob/dc698bf5bc10d591fa7adeec5fa21b2d90dc9679/lib/cucumber/runtime.js#L34 + } + + interface FeaturesResultPayload extends EventPayload { + getDuration(): any; + getScenarioCounts(): any; + getStepCounts(): any; isSuccessful(): boolean; - isFailed(): boolean; - isPending(): boolean; - isUndefined(): boolean; - isSkipped(): boolean; } - interface HookCode { - (scenario: HookScenario, callback?: CallbackStepDefinition): void; - } - - interface AroundCode { - (scenario: HookScenario, runScenario?: (error: string, callback?: Function) => void): void; - } - - interface HookOptions { - timeout?: number; - tags?: any; - } - - export interface Hooks { - Before(code: HookCode): void; - Before(options: HookOptions, code: HookCode): void; - After(code: HookCode): void; - After(options: HookOptions, code: HookCode): void; - Around(code: AroundCode): void; - setDefaultTimeout(time: number): void; - registerHandler(handlerOption: string, code: (event: any, callback: CallbackStepDefinition) => void): void; - registerListener(listener: EventListener): void; - } - - export class EventListener { - hear(event: events.Event, callback: () => void): void; - hasHandlerForEvent(event: events.Event): boolean; - buildHandlerNameForEvent(event: events.Event): string; - getHandlerForEvent(event: events.Event): EventHook; - buildHandlerName(shortName: string): string; - setHandlerForEvent(shortName: string, handler: EventListener): void; - } - - export function Listener(): EventListener; - - export namespace events { - - interface Event { - getName(): string; - getPayloadItem(name: string): EventPayload; - } - - interface EventPayload { - } - - interface FeaturesPayload extends EventPayload { - getFeatures(): any[]; // https://github.com/cucumber/cucumber-js/blob/dc698bf5bc10d591fa7adeec5fa21b2d90dc9679/lib/cucumber/runtime.js#L34 - } - - interface FeaturesResultPayload extends EventPayload { - getDuration(): any; - getScenarioCounts(): any; - getStepCounts(): any; - isSuccessful(): boolean; - } - - interface FeaturePayload extends EventPayload { - getStepKeywordByLines(): any; - getScenarioKeyword(): string; - getKeyword(): string; - getName(): string; - getDescription(): string; - getUri(): string; - getLine(): number; - getTags(): Tag[]; - getScenarios(): ScenarioPayload[]; - getPayloadItem(): FeaturePayload; - } - - interface ScenarioPayload extends EventPayload { - getName(): string; - getKeyword(): string; - getDescription(): string; - getFeature(): FeaturePayload; - getUri(): string; - getUris(): string[]; - getLine(): number; - getLines(): number[]; - getTags(): Tag[]; - getSteps(): any[]; - getPayloadItem(): ScenarioPayload; - } - - interface ScenarioResultPayload extends EventPayload { - getFailureException(): Error; - getScenario(): any; - getStatus(): any; - } - - interface StepPayload extends EventPayload { - isHidden(): boolean; - isOutlineStep(): boolean; - getKeyword(): string; - getName(): string; - hasUri(): boolean; - getUri(): string; - getLine(): number; - getPreviousStep(): any; - hasPreviousStep(): boolean; - getAttachment(): any; - getAttachmentContents(): any; - getDocString(): string; - getDataTable(): any; - hasAttachment(): boolean; - hasDocString(): boolean; - hasDataTable(): boolean; - ensureDataTableIsAttached(): void; - isOutcomeStep(): boolean; - isEventStep(): boolean; - hasOutcomeStepKeyword(): boolean; - hasEventStepKeyword(): boolean; - isRepeatingOutcomeStep(): boolean; - isRepeatingEventStep(): boolean; - hasRepeatStepKeyword(): boolean; - isPrecededByOutcomeStep(): boolean; - isPrecededByEventStep(): boolean; - } - - interface StepResultPayload extends EventPayload { - getAmbiguousStepDefinitions(): any[]; - getAttachments(): any[]; - getDuration(): any; - getFailureException(): Error; - getStep(): any; - getStepDefinition(): any; - getStatus(): any; - hasAttachments(): boolean; - } - - } - - interface Tag { - getName(): string; - getLine(): number; - } - - export interface Scenario { + interface FeaturePayload extends EventPayload { + getStepKeywordByLines(): any; + getScenarioKeyword(): string; getKeyword(): string; getName(): string; getDescription(): string; getUri(): string; getLine(): number; getTags(): Tag[]; - getException(): Error; - getAttachments(): any[]; - attach(data: any, mimeType?: string, callback?: (err?: any) => void): void; - isSuccessful(): boolean; - isFailed(): boolean; - isPending(): boolean; - isUndefined(): boolean; - isSkipped(): boolean; + getScenarios(): ScenarioPayload[]; + getPayloadItem(): FeaturePayload; } - interface EventHook { - (event: events.Event, callback?: () => void): void; + interface ScenarioPayload extends EventPayload { + getName(): string; + getKeyword(): string; + getDescription(): string; + getFeature(): FeaturePayload; + getUri(): string; + getUris(): string[]; + getLine(): number; + getLines(): number[]; + getTags(): Tag[]; + getSteps(): any[]; + getPayloadItem(): ScenarioPayload; + } + + interface ScenarioResultPayload extends EventPayload { + getFailureException(): Error; + getScenario(): any; + getStatus(): any; + } + + interface StepPayload extends EventPayload { + isHidden(): boolean; + isOutlineStep(): boolean; + getKeyword(): string; + getName(): string; + hasUri(): boolean; + getUri(): string; + getLine(): number; + getPreviousStep(): any; + hasPreviousStep(): boolean; + getAttachment(): any; + getAttachmentContents(): any; + getDocString(): string; + getDataTable(): any; + hasAttachment(): boolean; + hasDocString(): boolean; + hasDataTable(): boolean; + ensureDataTableIsAttached(): void; + isOutcomeStep(): boolean; + isEventStep(): boolean; + hasOutcomeStepKeyword(): boolean; + hasEventStepKeyword(): boolean; + isRepeatingOutcomeStep(): boolean; + isRepeatingEventStep(): boolean; + hasRepeatStepKeyword(): boolean; + isPrecededByOutcomeStep(): boolean; + isPrecededByEventStep(): boolean; + } + + interface StepResultPayload extends EventPayload { + getAmbiguousStepDefinitions(): any[]; + getAttachments(): any[]; + getDuration(): any; + getFailureException(): Error; + getStep(): any; + getStepDefinition(): any; + getStatus(): any; + hasAttachments(): boolean; } } + +export interface Tag { + getName(): string; + getLine(): number; +} + +export interface Scenario { + getKeyword(): string; + getName(): string; + getDescription(): string; + getUri(): string; + getLine(): number; + getTags(): Tag[]; + getException(): Error; + getAttachments(): any[]; + attach(data: any, mimeType?: string, callback?: (err?: any) => void): void; + isSuccessful(): boolean; + isFailed(): boolean; + isPending(): boolean; + isUndefined(): boolean; + isSkipped(): boolean; +} + +export type EventHook = (event: events.Event, callback?: () => void) => void; diff --git a/types/cucumber/v1/tsconfig.json b/types/cucumber/v1/tsconfig.json index b467d8c4b4..3c64799f9a 100644 --- a/types/cucumber/v1/tsconfig.json +++ b/types/cucumber/v1/tsconfig.json @@ -1,31 +1,31 @@ { - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, - "baseUrl": "../../", - "typeRoots": [ - "../../" - ], - "types": [], - "paths": { - "cucumber": [ - "cucumber/v1" - ], - "cucumber/*": [ - "cucumber/v1/*" - ] + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "cucumber": [ + "cucumber/v1" + ], + "cucumber/*": [ + "cucumber/v1/*" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true }, - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "cucumber-tests.ts" - ] + "files": [ + "index.d.ts", + "cucumber-tests.ts" + ] } diff --git a/types/cucumber/v1/tslint.json b/types/cucumber/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cucumber/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cwise-compiler/index.d.ts b/types/cwise-compiler/index.d.ts index e661934a6a..8703355ba3 100644 --- a/types/cwise-compiler/index.d.ts +++ b/types/cwise-compiler/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/scijs/cwise-compiler // Definitions by: taoqf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { CompiledRoutine } from 'cwise-parser'; import * as ndarray from 'ndarray'; diff --git a/types/cwise/cwise-tests.ts b/types/cwise/cwise-tests.ts index 66843adfe2..b759fb1a0c 100644 --- a/types/cwise/cwise-tests.ts +++ b/types/cwise/cwise-tests.ts @@ -66,7 +66,7 @@ tape("binary", (t) => { const binary = cwise({ args: ["array", "array", "scalar", "shape", "index"], body(a: number, b: number, t: tape.Test, s: number[], idx: number) { - if (!(a === 0)) t.fail("idx:" + idx + ", shape:" + s + ",a:" + a); + if (!(a === 0)) t.fail(`idx:${idx}, shape:${s},a:${a}`); a = b + 1001; } }); @@ -80,7 +80,7 @@ tape("binary", (t) => { binary(P, Q, t); for (let i = 0; i < P.shape[0]; ++i) { if (!(P.get(i) === i + 1001)) { - t.fail(testName + "; encountered " + P.get(i) + " instead of " + (i + 1001) + " at " + i); + t.fail(`${testName}; encountered ${P.get(i)} instead of ${(i + 1001)} at ${i}`); return; } } @@ -128,7 +128,7 @@ tape("binary", (t) => { for (let i = 0; i < P.shape[0]; ++i) { for (let j = 0; j < P.shape[1]; ++j) { if (!(P.get(i, j) === i * 1000 + j + 1001)) { - t.fail(testName + "; encountered " + P.get(i, j) + " instead of " + (i * 1000 + j + 1001) + " at (" + i + "," + j + ")"); + t.fail(`${testName}; encountered ${P.get(i, j)} instead of ${(i * 1000 + j + 1001)} at (" + i + "," + j + ")`); return; } } @@ -163,7 +163,7 @@ function bundleCasesFrom(i: number) { if (i >= cases.length) return; const b = browserify(); b.ignore("tape"); - b.add(__dirname + "/" + cases[i] + ".js"); + b.add(`${__dirname}/${cases[i]}.js`); b.transform(path.normalize(__dirname + "/../cwise.js")); tape(cases[i], (t) => { // Without nested tests, the asynchronous nature of bundle causes issues with tape... b.bundle((err, src) => { @@ -209,7 +209,7 @@ tape("fill", (t) => { for (let i = 0; i < xlen; i++) { for (let j = 0; j < ylen; j++) { - t.equals(array.get(i, j), 0, 'fill (' + i + ',' + j + ')'); + t.equals(array.get(i, j), 0, `fill (${i},${j})`); } } @@ -219,7 +219,7 @@ tape("fill", (t) => { for (let i = 0; i < xlen; i++) { for (let j = 0; j < ylen; j++) { - t.equals(array.get(i, j), 10 * (i + j), 'fill (' + i + ',' + j + ')'); + t.equals(array.get(i, j), 10 * (i + j), `fill (${i},${j})`); } } @@ -231,7 +231,7 @@ tape("offset", (t) => { const binary = cwise({ args: ["array", "array", { offset: [1], array: 1 }, "scalar", "shape", "index"], body(a, b, c, t, s, idx) { - if (!(a === 0)) t.fail("idx:" + idx + ", shape:" + s + ",a:" + a); + if (!(a === 0)) t.fail(`idx:${idx}, shape:${s},a:${a}`); a = c + b + 1000; } }); @@ -246,7 +246,7 @@ tape("offset", (t) => { binary(P, Q.hi(Q.shape[0] - 1), t); for (let i = 0; i < P.shape[0]; ++i) { if (!(P.get(i) === 2 * i + 1001)) { - t.fail(testName + "; encountered " + P.get(i) + " instead of " + (2 * i + 1001) + " at " + i); + t.fail(`${testName}; encountered ${P.get(i)} instead of ${2 * i + 1001} at ${i}`); return; } } @@ -292,7 +292,7 @@ tape("unary", (t) => { unary(arr); for (let i = 0; i < arr.shape[0]; ++i) { if (!(arr.get(i) === i + 1)) { - t.fail(testName + "; encountered " + arr.get(i) + " instead of " + (i + 1) + " at " + i); + t.fail(`${testName}; encountered ${arr.get(i)} instead of ${i + 1} at ${i}`); return; } } @@ -336,7 +336,7 @@ tape("unary", (t) => { for (let i = 0; i < arr.shape[0]; ++i) { for (let j = 0; j < arr.shape[1]; ++j) { if (!(arr.get(i, j) === 1 + i + j * arr.shape[0])) { - t.fail(testName + "; encountered " + arr.get(i, j) + " instead of " + (1 + i + j * arr.shape[0]) + " at (" + i + "," + j + ")"); + t.fail(`${testName}; encountered ${arr.get(i, j)} instead of ${1 + i + j * arr.shape[0]} at (${i},${j})`); return; } } diff --git a/types/cwise/index.d.ts b/types/cwise/index.d.ts index d99d43ce59..95df45bb03 100644 --- a/types/cwise/index.d.ts +++ b/types/cwise/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/scijs/cwise#readme // Definitions by: taoqf // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { ArgType } from "cwise-compiler"; import * as ndarray from "ndarray"; diff --git a/types/d3-array/d3-array-tests.ts b/types/d3-array/d3-array-tests.ts index b95da5774f..42bf95bcfe 100644 --- a/types/d3-array/d3-array-tests.ts +++ b/types/d3-array/d3-array-tests.ts @@ -43,9 +43,9 @@ let num: number; let date: Date; let numOrUndefined: number | undefined; -let strOrUndefined: string |  undefined; -let numericOrUndefined: NumCoercible |  undefined; -let dateOrUndefined: Date |  undefined; +let strOrUndefined: string | undefined; +let numericOrUndefined: NumCoercible | undefined; +let dateOrUndefined: Date | undefined; let numOrUndefinedExtent: [number, number] | [undefined, undefined]; let strOrUndefinedExtent: [string, string] | [undefined, undefined]; let numericOrUndefinedExtent: [NumCoercible, NumCoercible] | [undefined, undefined]; @@ -55,9 +55,10 @@ let dateOrUndefinedExtent: [Date, Date] | [undefined, undefined]; let numbersArray = [10, 20, 30, 40, 50]; const numbersOrUndefinedArray = [10, 20, undefined, null, 40, 50]; -const stringyNumbersArray = ['10', '20', '30', '40', '50']; +let stringyNumbersArray = ['10', '20', '30', '40', '50']; const numericArray = [new NumCoercible(10), new NumCoercible(20), new NumCoercible(30), new NumCoercible(40), new NumCoercible(50)]; -const dateArray = [new Date(2016, 6, 1), new Date(2016, 7, 30), new Date(2015, 3, 15)]; +let dateArray = [new Date(2016, 6, 1), new Date(2016, 7, 30), new Date(2015, 3, 15)]; + const mixedObjectArray = [ new MixedObject(10, new Date(2016, 6, 1)), new MixedObject(20, new Date(2016, 7, 30)), @@ -65,8 +66,18 @@ const mixedObjectArray = [ new MixedObject(40, new Date(2014, 3, 15)), new MixedObject(50, new Date(2017, 4, 15)) ]; + const mixedObjectOrUndefinedArray = [...mixedObjectArray, undefined]; +let typedArray = Uint8Array.from(numbersArray); +let readonlyNumbersArray = numbersArray as ReadonlyArray; +const readonlyNumbersOrUndefinedArray = numbersOrUndefinedArray as ReadonlyArray; +const readonlyStringyNumbersArray = stringyNumbersArray as ReadonlyArray; +const readonlyNumericArray = numericArray as ReadonlyArray; +const readonlyDateArray = dateArray as ReadonlyArray; +const readonlyMixedObjectArray = mixedObjectArray as ReadonlyArray; +const readonlyMixedObjectOrUndefinedArray = mixedObjectOrUndefinedArray as ReadonlyArray; + function accessorMixedObjectToNum(datum: MixedObject, index: number, array: MixedObject[]): number { return datum.num; } @@ -104,6 +115,14 @@ strOrUndefined = d3Array.max(stringyNumbersArray); numericOrUndefined = d3Array.max(numericArray); dateOrUndefined = d3Array.max(dateArray); +// ArrayLike test cases + +numOrUndefined = d3Array.max(typedArray); +numOrUndefined = d3Array.max(readonlyNumbersOrUndefinedArray); +strOrUndefined = d3Array.max(readonlyStringyNumbersArray); +numericOrUndefined = d3Array.max(readonlyNumericArray); +dateOrUndefined = d3Array.max(readonlyDateArray); + // with accessors numOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNum); @@ -112,6 +131,7 @@ numericOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNumeric) dateOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToDate); numOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNumOrUndefined); strOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToStrOrUndefined); +numOrUndefined = d3Array.max(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // min() ----------------------------------------------------------------------- @@ -122,6 +142,14 @@ strOrUndefined = d3Array.min(stringyNumbersArray); numericOrUndefined = d3Array.min(numericArray); dateOrUndefined = d3Array.min(dateArray); +// ArrayLike test cases + +numOrUndefined = d3Array.min(typedArray); +numOrUndefined = d3Array.min(readonlyNumbersOrUndefinedArray); +strOrUndefined = d3Array.min(readonlyStringyNumbersArray); +numericOrUndefined = d3Array.min(readonlyNumericArray); +dateOrUndefined = d3Array.min(readonlyDateArray); + // with accessors numOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNum); @@ -130,6 +158,7 @@ numericOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNumeric) dateOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToDate); numOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNumOrUndefined); strOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToStrOrUndefined); +numOrUndefined = d3Array.max(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // extent() -------------------------------------------------------------------- @@ -140,6 +169,14 @@ strOrUndefinedExtent = d3Array.extent(stringyNumbersArray); numericOrUndefinedExtent = d3Array.extent(numericArray); dateOrUndefinedExtent = d3Array.extent(dateArray); +// ArrayLike test cases + +numOrUndefinedExtent = d3Array.extent(typedArray); +numOrUndefinedExtent = d3Array.extent(readonlyNumbersOrUndefinedArray); +strOrUndefinedExtent = d3Array.extent(readonlyStringyNumbersArray); +numericOrUndefinedExtent = d3Array.extent(readonlyNumericArray); +dateOrUndefinedExtent = d3Array.extent(readonlyDateArray); + // with accessors numOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNum); @@ -148,6 +185,7 @@ mixedOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToN dateMixedOrUndefined = d3Array.extent(mixedObjectArray, accessorMixedObjectToDate); numOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNumOrUndefined); strOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToStrOrUndefined); +numOrUndefinedExtent = d3Array.extent(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // mean() ---------------------------------------------------------------------- @@ -155,8 +193,14 @@ numOrUndefined = d3Array.mean(numbersArray); numOrUndefined = d3Array.mean(numericArray); numOrUndefined = d3Array.mean(numbersOrUndefinedArray); +numOrUndefined = d3Array.mean(typedArray); +numOrUndefined = d3Array.mean(readonlyNumbersOrUndefinedArray); +numOrUndefined = d3Array.mean(readonlyNumericArray); +numOrUndefined = d3Array.mean(readonlyNumbersOrUndefinedArray); + numOrUndefined = d3Array.mean(mixedObjectArray, accessorMixedObjectToNum); numOrUndefined = d3Array.mean(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.mean(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // median() -------------------------------------------------------------------- @@ -164,8 +208,14 @@ numOrUndefined = d3Array.median(numbersArray); numOrUndefined = d3Array.median(numericArray); numOrUndefined = d3Array.median(numbersOrUndefinedArray); +numOrUndefined = d3Array.median(typedArray); +numOrUndefined = d3Array.median(readonlyNumbersArray); +numOrUndefined = d3Array.median(readonlyNumericArray); +numOrUndefined = d3Array.median(readonlyNumbersOrUndefinedArray); + numOrUndefined = d3Array.median(mixedObjectArray, accessorMixedObjectToNum); numOrUndefined = d3Array.median(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.median(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // quantile() ------------------------------------------------------------------ @@ -173,8 +223,14 @@ numOrUndefined = d3Array.quantile(numbersArray, 0.5); numOrUndefined = d3Array.quantile(numericArray, 0.5); numOrUndefined = d3Array.quantile(numbersOrUndefinedArray, 0.5); +numOrUndefined = d3Array.quantile(typedArray, 0.5); +numOrUndefined = d3Array.quantile(readonlyNumbersArray, 0.5); +numOrUndefined = d3Array.quantile(readonlyNumericArray, 0.5); +numOrUndefined = d3Array.quantile(readonlyNumbersOrUndefinedArray, 0.5); + numOrUndefined = d3Array.quantile(mixedObjectArray, 0.5, accessorMixedObjectToNum); numOrUndefined = d3Array.quantile(mixedObjectOrUndefinedArray, 0.5, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.quantile(readonlyMixedObjectOrUndefinedArray, 0.5, accessorMixedObjectToNumOrUndefined); // sum() ----------------------------------------------------------------------- @@ -182,8 +238,14 @@ numOrUndefined = d3Array.sum(numbersArray); numOrUndefined = d3Array.sum(numericArray); numOrUndefined = d3Array.sum(numbersOrUndefinedArray); +numOrUndefined = d3Array.sum(typedArray); +numOrUndefined = d3Array.sum(readonlyNumbersArray); +numOrUndefined = d3Array.sum(readonlyNumericArray); +numOrUndefined = d3Array.sum(readonlyNumbersOrUndefinedArray); + numOrUndefined = d3Array.sum(mixedObjectArray, accessorMixedObjectToNum); numOrUndefined = d3Array.sum(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.sum(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // deviation() ----------------------------------------------------------------- @@ -191,8 +253,14 @@ numOrUndefined = d3Array.deviation(numbersArray); numOrUndefined = d3Array.deviation(numericArray); numOrUndefined = d3Array.deviation(numbersOrUndefinedArray); +numOrUndefined = d3Array.deviation(typedArray); +numOrUndefined = d3Array.deviation(readonlyNumbersArray); +numOrUndefined = d3Array.deviation(readonlyNumericArray); +numOrUndefined = d3Array.deviation(readonlyNumbersOrUndefinedArray); + numOrUndefined = d3Array.deviation(mixedObjectArray, accessorMixedObjectToNum); numOrUndefined = d3Array.deviation(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.deviation(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // variance() ------------------------------------------------------------------ @@ -200,16 +268,29 @@ numOrUndefined = d3Array.variance(numbersArray); numOrUndefined = d3Array.variance(numericArray); numOrUndefined = d3Array.variance(numbersOrUndefinedArray); +numOrUndefined = d3Array.variance(typedArray); +numOrUndefined = d3Array.variance(readonlyNumbersArray); +numOrUndefined = d3Array.variance(readonlyNumericArray); +numOrUndefined = d3Array.variance(readonlyNumbersOrUndefinedArray); + numOrUndefined = d3Array.variance(mixedObjectArray, accessorMixedObjectToNum); numOrUndefined = d3Array.variance(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.variance(readonlyMixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); // ----------------------------------------------------------------------------- // Test Searching Arrays // ----------------------------------------------------------------------------- +numbersArray = [0, 2, 3, 4, 7, 8]; +stringyNumbersArray = ['0', '2', '3', '4', '7', '8']; +dateArray = [new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)]; +typedArray = Uint8Array.from(numbersArray); + // scan() ---------------------------------------------------------------------- numOrUndefined = d3Array.scan(numbersArray); +numOrUndefined = d3Array.scan(typedArray); +numOrUndefined = d3Array.scan(readonlyNumbersArray); numOrUndefined = d3Array.scan(mixedObjectArray, (a, b) => { const aElem: MixedObject = a; @@ -217,53 +298,113 @@ numOrUndefined = d3Array.scan(mixedObjectArray, (a, b) => { return a.num - b.num; }); +numOrUndefined = d3Array.scan(readonlyMixedObjectArray, (a, b) => { + const aElem: MixedObject = a; + const bElem: MixedObject = b; + return a.num - b.num; +}); + numOrUndefined = d3Array.scan(mixedObjectOrUndefinedArray, (a, b) => { const aElem: MixedObject | undefined = a; const bElem: MixedObject | undefined = b; return a && b ? a.num - b.num : NaN; }); +numOrUndefined = d3Array.scan(readonlyMixedObjectOrUndefinedArray, (a, b) => { + const aElem: MixedObject | undefined = a; + const bElem: MixedObject | undefined = b; + return a && b ? a.num - b.num : NaN; +}); + // bisectLeft() ---------------------------------------------------------------- -num = d3Array.bisectLeft([0, 2, 3, 4, 7, 8], 4); -num = d3Array.bisectLeft([0, 2, 3, 4, 7, 8], 4, 1); -num = d3Array.bisectLeft([0, 2, 3, 4, 7, 8], 4, 1, 4); +num = d3Array.bisectLeft(numbersArray, 4); +num = d3Array.bisectLeft(numbersArray, 4, 1); +num = d3Array.bisectLeft(numbersArray, 4, 1, 4); -num = d3Array.bisectLeft(['0', '2', '3', '4', '7', '8'], '21'); -num = d3Array.bisectLeft(['0', '2', '3', '4', '7', '8'], '21', 1); -num = d3Array.bisectLeft(['0', '2', '3', '4', '7', '8'], '21', 1, 4); +num = d3Array.bisectLeft(stringyNumbersArray, '21'); +num = d3Array.bisectLeft(stringyNumbersArray, '21', 1); +num = d3Array.bisectLeft(stringyNumbersArray, '21', 1, 4); -num = d3Array.bisectLeft([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1)); -num = d3Array.bisectLeft([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1), 1); -num = d3Array.bisectLeft([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1), 1, 2); +num = d3Array.bisectLeft(dateArray, new Date(2011, 2, 1)); +num = d3Array.bisectLeft(dateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisectLeft(dateArray, new Date(2011, 2, 1), 1, 2); + +num = d3Array.bisectLeft(typedArray, 4); +num = d3Array.bisectLeft(typedArray, 4, 1); +num = d3Array.bisectLeft(typedArray, 4, 1, 4); + +num = d3Array.bisectLeft(readonlyNumbersArray, 4); +num = d3Array.bisectLeft(readonlyNumbersArray, 4, 1); +num = d3Array.bisectLeft(readonlyNumbersArray, 4, 1, 4); + +num = d3Array.bisectLeft(readonlyStringyNumbersArray, '21'); +num = d3Array.bisectLeft(readonlyStringyNumbersArray, '21', 1); +num = d3Array.bisectLeft(readonlyStringyNumbersArray, '21', 1, 4); + +num = d3Array.bisectLeft(readonlyDateArray, new Date(2011, 2, 1)); +num = d3Array.bisectLeft(readonlyDateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisectLeft(readonlyDateArray, new Date(2011, 2, 1), 1, 2); // bisectRight() --------------------------------------------------------------- -num = d3Array.bisectRight([0, 2, 3, 4, 7, 8], 4); -num = d3Array.bisectRight([0, 2, 3, 4, 7, 8], 4, 1); -num = d3Array.bisectRight([0, 2, 3, 4, 7, 8], 4, 1, 4); +num = d3Array.bisectRight(numbersArray, 4); +num = d3Array.bisectRight(numbersArray, 4, 1); +num = d3Array.bisectRight(numbersArray, 4, 1, 4); -num = d3Array.bisectRight(['0', '2', '3', '4', '7', '8'], '21'); -num = d3Array.bisectRight(['0', '2', '3', '4', '7', '8'], '21', 1); -num = d3Array.bisectRight(['0', '2', '3', '4', '7', '8'], '21', 1, 4); +num = d3Array.bisectRight(stringyNumbersArray, '21'); +num = d3Array.bisectRight(stringyNumbersArray, '21', 1); +num = d3Array.bisectRight(stringyNumbersArray, '21', 1, 4); -num = d3Array.bisectRight([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1)); -num = d3Array.bisectRight([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1), 1); -num = d3Array.bisectRight([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1), 1, 2); +num = d3Array.bisectRight(dateArray, new Date(2011, 2, 1)); +num = d3Array.bisectRight(dateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisectRight(dateArray, new Date(2011, 2, 1), 1, 2); + +num = d3Array.bisectRight(typedArray, 4); +num = d3Array.bisectRight(typedArray, 4, 1); +num = d3Array.bisectRight(typedArray, 4, 1, 4); + +num = d3Array.bisectRight(readonlyNumbersArray, 4); +num = d3Array.bisectRight(readonlyNumbersArray, 4, 1); +num = d3Array.bisectRight(readonlyNumbersArray, 4, 1, 4); + +num = d3Array.bisectRight(readonlyStringyNumbersArray, '21'); +num = d3Array.bisectRight(readonlyStringyNumbersArray, '21', 1); +num = d3Array.bisectRight(readonlyStringyNumbersArray, '21', 1, 4); + +num = d3Array.bisectRight(readonlyDateArray, new Date(2011, 2, 1)); +num = d3Array.bisectRight(readonlyDateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisectRight(readonlyDateArray, new Date(2011, 2, 1), 1, 2); // bisect() -------------------------------------------------------------------- -num = d3Array.bisect([0, 2, 3, 4, 7, 8], 4); -num = d3Array.bisect([0, 2, 3, 4, 7, 8], 4, 1); -num = d3Array.bisect([0, 2, 3, 4, 7, 8], 4, 1, 4); +num = d3Array.bisect(numbersArray, 4); +num = d3Array.bisect(numbersArray, 4, 1); +num = d3Array.bisect(numbersArray, 4, 1, 4); -num = d3Array.bisect(['0', '2', '3', '4', '7', '8'], '21'); -num = d3Array.bisect(['0', '2', '3', '4', '7', '8'], '21', 1); -num = d3Array.bisect(['0', '2', '3', '4', '7', '8'], '21', 1, 4); +num = d3Array.bisect(stringyNumbersArray, '21'); +num = d3Array.bisect(stringyNumbersArray, '21', 1); +num = d3Array.bisect(stringyNumbersArray, '21', 1, 4); -num = d3Array.bisect([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1)); -num = d3Array.bisect([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1), 1); -num = d3Array.bisect([new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)], new Date(2011, 2, 1), 1, 2); +num = d3Array.bisect(dateArray, new Date(2011, 2, 1)); +num = d3Array.bisect(dateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisect(dateArray, new Date(2011, 2, 1), 1, 2); + +num = d3Array.bisect(typedArray, 4); +num = d3Array.bisect(typedArray, 4, 1); +num = d3Array.bisect(typedArray, 4, 1, 4); + +num = d3Array.bisect(readonlyNumbersArray, 4); +num = d3Array.bisect(readonlyNumbersArray, 4, 1); +num = d3Array.bisect(readonlyNumbersArray, 4, 1, 4); + +num = d3Array.bisect(readonlyStringyNumbersArray, '21'); +num = d3Array.bisect(readonlyStringyNumbersArray, '21', 1); +num = d3Array.bisect(readonlyStringyNumbersArray, '21', 1, 4); + +num = d3Array.bisect(readonlyDateArray, new Date(2011, 2, 1)); +num = d3Array.bisect(readonlyDateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisect(readonlyDateArray, new Date(2011, 2, 1), 1, 2); // bisector() ------------------------------------------------------------------ @@ -283,11 +424,19 @@ num = mixedObjectDateBisectorObject.left(mixedObjectArray, new Date(2015, 3, 14) num = mixedObjectDateBisectorObject.left(mixedObjectArray, new Date(2015, 3, 14), 1); num = mixedObjectDateBisectorObject.left(mixedObjectArray, new Date(2015, 3, 14), 3, 4); +num = mixedObjectDateBisectorObject.left(readonlyMixedObjectArray, new Date(2015, 3, 14)); +num = mixedObjectDateBisectorObject.left(readonlyMixedObjectArray, new Date(2015, 3, 14), 1); +num = mixedObjectDateBisectorObject.left(readonlyMixedObjectArray, new Date(2015, 3, 14), 3, 4); + // bisect right num = mixedObjectDateBisectorObject.right(mixedObjectArray, new Date(2015, 3, 14)); num = mixedObjectDateBisectorObject.right(mixedObjectArray, new Date(2015, 3, 14), 1); num = mixedObjectDateBisectorObject.right(mixedObjectArray, new Date(2015, 3, 14), 3, 4); +num = mixedObjectDateBisectorObject.right(readonlyMixedObjectArray, new Date(2015, 3, 14)); +num = mixedObjectDateBisectorObject.right(readonlyMixedObjectArray, new Date(2015, 3, 14), 1); +num = mixedObjectDateBisectorObject.right(readonlyMixedObjectArray, new Date(2015, 3, 14), 3, 4); + // ascending() ----------------------------------------------------------------- num = d3Array.ascending(undefined, 20); @@ -308,32 +457,44 @@ num = d3Array.descending(new Date(2016, 6, 13), new Date(2016, 6, 14)); // merge() --------------------------------------------------------------------- -let testArrays: MixedObject[][] = [ - [ - new MixedObject(10, new Date(2016, 6, 1)), - new MixedObject(20, new Date(2016, 7, 30)), - new MixedObject(30, new Date(2015, 3, 15)), - new MixedObject(40, new Date(2014, 3, 15)), - new MixedObject(50, new Date(2017, 4, 15)) - ], - [ - new MixedObject(40, new Date(2016, 3, 1)), - new MixedObject(50, new Date(2016, 9, 30)), - ] +const testArray1 = [ + new MixedObject(10, new Date(2016, 6, 1)), + new MixedObject(20, new Date(2016, 7, 30)), + new MixedObject(30, new Date(2015, 3, 15)), + new MixedObject(40, new Date(2014, 3, 15)), + new MixedObject(50, new Date(2017, 4, 15)) ]; +const testArray2 = [ + new MixedObject(40, new Date(2016, 3, 1)), + new MixedObject(50, new Date(2016, 9, 30)), +]; + +let testArrays: MixedObject[][] = [testArray1, testArray2]; + +const readonlyTestArray1 = testArray1 as ReadonlyArray; +const readonlyTestArray2 = testArray2 as ReadonlyArray; +const readonlyTestArrays = [testArray1, testArray2] as ReadonlyArray>; + let mergedArray: MixedObject[]; mergedArray = d3Array.merge(testArrays); // inferred type mergedArray = d3Array.merge(testArrays); // explicit type // mergedArray = d3Array.merge([[10, 40, 30], [15, 30]]); // fails, type mismatch +// mergedArray = d3Array.merge([testArray1, [15, 30]]); // fails, type mismatch + +mergedArray = d3Array.merge(readonlyTestArrays); // inferred type +mergedArray = d3Array.merge(readonlyTestArrays); // explicit type // cross() --------------------------------------------------------------------- let crossed: Array<[string, number]>; -crossed = d3Array.cross(['x', 'y'], [1, 2]); -crossed = d3Array.cross(['x', 'y'], [1, 2]); +const chars = ['x', 'y']; +const nums = [1, 2]; + +crossed = d3Array.cross(chars, nums); +crossed = d3Array.cross(chars, nums); let strArray: string[] = d3Array.cross([2, 3], [5, 6], (a, b) => (a + b) + 'px'); strArray = d3Array.cross([2, 3], [5, 6], (a, b) => { @@ -342,6 +503,21 @@ strArray = d3Array.cross([2, 3], [5, 6], (a, b) => { return (aa + bb) + 'px'; }); +const readonlyChars = chars as ReadonlyArray; +const readonlyNums = new Uint8Array(nums); + +crossed = d3Array.cross(readonlyChars, readonlyNums); +crossed = d3Array.cross(readonlyChars, readonlyNums); + +strArray = d3Array.cross([2, 3] as ReadonlyArray, new Uint8ClampedArray([5, 6]), (a, b) => (a + b) + 'px'); +strArray = d3Array.cross([2, 3] as ReadonlyArray, new Uint8ClampedArray([5, 6]), (a, b) => { + const aa: number = a; + const bb: number = b; + return (aa + bb) + 'px'; +}); + +d3Array.cross(new Uint8Array([1, 2, 3, 4, 5]), new Uint8Array([10, 20, 30, 40, 50])); + // pairs() --------------------------------------------------------------------- let pairs: Array<[MixedObject, MixedObject]>; @@ -355,10 +531,21 @@ numbersArray = d3Array.pairs(mergedArray, (a, b) => { return bb.num - aa.num; }); +const readonlyMergedArray = mergedArray as ReadonlyArray; +pairs = d3Array.pairs(readonlyMergedArray); + +numbersArray = d3Array.pairs(readonlyMergedArray, (a, b) => b.num - a.num); +numbersArray = d3Array.pairs(readonlyMergedArray, (a, b) => { + const aa: MixedObject = a; + const bb: MixedObject = b; + return bb.num - aa.num; +}); + // permute() ------------------------------------------------------------------- // getting a permutation of array elements mergedArray = d3Array.permute(mergedArray, [1, 0, 2, 5, 3, 4, 6]); +mergedArray = d3Array.permute(readonlyMergedArray, [1, 0, 2, 5, 3, 4, 6]); // Getting an ordered array with object properties @@ -380,10 +567,20 @@ numbersArray = d3Array.range(1, 10, 0.5); // shuffle() ------------------------------------------------------------------- mergedArray = d3Array.shuffle(mergedArray); - mergedArray = d3Array.shuffle(mergedArray, 1); - mergedArray = d3Array.shuffle(mergedArray, 1, 3); +// mergedArray = d3Array.shuffle(readonlyMergedArray); // fails, shuffle mutates input array in-place + +// Test each TypedArray explicitly. Can't use ArrayLike in this case because shuffle is mutable and ArrayLike would include ReadonlyArray +const resultInt8: Int8Array = d3Array.shuffle(new Int8Array(numbersArray)); +const resultUint8: Uint8Array = d3Array.shuffle(new Uint8Array(numbersArray)); +const resultUint8Clamped: Uint8ClampedArray = d3Array.shuffle(new Uint8ClampedArray(numbersArray)); +const resultInt16: Int16Array = d3Array.shuffle(new Int16Array(numbersArray)); +const resultUint6: Uint16Array = d3Array.shuffle(new Uint16Array(numbersArray)); +const resultInt32: Int32Array = d3Array.shuffle(new Int32Array(numbersArray)); +const resultUint32: Uint32Array = d3Array.shuffle(new Uint32Array(numbersArray)); +const resultFloat32: Float32Array = d3Array.shuffle(new Float32Array(numbersArray)); +const resultFloat64: Float64Array = d3Array.shuffle(new Float64Array(numbersArray)); // ticks() --------------------------------------------------------------------- @@ -399,32 +596,13 @@ numDiff = d3Array.tickStep(1, 10, 5); // transpose() ----------------------------------------------------------------- -testArrays = d3Array.transpose([ - [ - new MixedObject(10, new Date(2016, 6, 1)), - new MixedObject(50, new Date(2017, 4, 15)) - ], - [ - new MixedObject(40, new Date(2016, 3, 1)), - new MixedObject(50, new Date(2016, 9, 30)), - ] -]); +testArrays = d3Array.transpose([testArray1, testArray2]); +testArrays = d3Array.transpose([readonlyTestArray1, readonlyTestArray2] as ReadonlyArray>); // zip() ----------------------------------------------------------------------- -testArrays = d3Array.zip( - [ - new MixedObject(10, new Date(2016, 6, 1)), - new MixedObject(20, new Date(2016, 7, 30)), - new MixedObject(30, new Date(2015, 3, 15)), - new MixedObject(40, new Date(2014, 3, 15)), - new MixedObject(50, new Date(2017, 4, 15)) - ], - [ - new MixedObject(40, new Date(2016, 3, 1)), - new MixedObject(50, new Date(2016, 9, 30)), - ] -); +testArrays = d3Array.zip(testArray1, testArray2); +testArrays = d3Array.zip(readonlyTestArray1, readonlyTestArray2); // ----------------------------------------------------------------------------- // Test Histogram @@ -447,7 +625,7 @@ testHistogram = d3Array.histogram(); testHistogram = testHistogram.value((d, i, data) => { const datum: MixedObject = d; // d is of type MixedObject const index: number = i; // i is number - const array: MixedObject[] = data; // data is of type MixedObject[] + const array: ArrayLike = data; // data is of type MixedObject[] return datum.date; }); @@ -496,8 +674,10 @@ testHistogram = testHistogram.thresholds(tScale.ticks(timeYear)); // Use histogram generator ===================================================== +numbersArray = [-1, 0, 1, 1, 3, 20, 234]; + let defaultBins: Array>; -defaultBins = defaultHistogram([-1, 0, 1, 1, 3, 20, 234]); +defaultBins = defaultHistogram(numbersArray); let defaultBin: d3Array.Bin; defaultBin = defaultBins[0]; @@ -509,6 +689,7 @@ num = defaultBin.x1; // bin upper bound is number let testBins: Array>; testBins = testHistogram(mixedObjectArray); +testBins = testHistogram(readonlyMixedObjectArray); let testBin: d3Array.Bin; testBin = testBins[0]; @@ -520,8 +701,18 @@ date = testBin.x1; // bin upper bound is Date // Histogram Tresholds ========================================================= -num = d3Array.thresholdFreedmanDiaconis([-1, 0, 1, 1, 3, 20, 234], -1, 234); +numbersArray = [-1, 0, 1, 1, 3, 20, 234]; +typedArray = new Uint8Array(numbersArray); +readonlyNumbersArray = numbersArray as ReadonlyArray; -num = d3Array.thresholdScott([-1, 0, 1, 1, 3, 20, 234], -1, 234); +num = d3Array.thresholdFreedmanDiaconis(numbersArray, -1, 234); +num = d3Array.thresholdFreedmanDiaconis(typedArray, -1, 234); +num = d3Array.thresholdFreedmanDiaconis(readonlyNumbersArray, -1, 234); -num = d3Array.thresholdSturges([-1, 0, 1, 1, 3, 20, 234]); +num = d3Array.thresholdScott(numbersArray, -1, 234); +num = d3Array.thresholdScott(typedArray, -1, 234); +num = d3Array.thresholdScott(readonlyNumbersArray, -1, 234); + +num = d3Array.thresholdSturges(numbersArray); +num = d3Array.thresholdSturges(typedArray); +num = d3Array.thresholdSturges(readonlyNumbersArray); diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index aee2ef38c7..67cd291f22 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -28,133 +28,133 @@ export interface Numeric { /** * Return the maximum value in the array of strings using natural order. */ -export function max(array: string[]): string | undefined; +export function max(array: ArrayLike): string | undefined; /** * Return the maximum value in the array of numbers using natural order. */ -export function max(array: T[]): T | undefined; +export function max(array: ArrayLike): T | undefined; /** * Return the maximum value in the array using natural order and a projection function to map values to strings. */ -export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): string | undefined; +export function max(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => string | undefined | null): string | undefined; /** * Return the maximum value in the array using natural order and a projection function to map values to easily-sorted values. */ -export function max(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): U | undefined; +export function max(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => U | undefined | null): U | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: string[]): string | undefined; +export function min(array: ArrayLike): string | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: T[]): T | undefined; +export function min(array: ArrayLike): T | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): string | undefined; +export function min(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => string | undefined | null): string | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): U | undefined; +export function min(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => U | undefined | null): U | undefined; /** * Return the min and max simultaneously. */ -export function extent(array: string[]): [string, string] | [undefined, undefined]; +export function extent(array: ArrayLike): [string, string] | [undefined, undefined]; /** * Return the min and max simultaneously. */ -export function extent(array: T[]): [T, T] | [undefined, undefined]; +export function extent(array: ArrayLike): [T, T] | [undefined, undefined]; /** * Return the min and max simultaneously. */ -export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => string | undefined | null): [string, string] | [undefined, undefined]; +export function extent(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => string | undefined | null): [string, string] | [undefined, undefined]; /** * Return the min and max simultaneously. */ -export function extent(array: T[], accessor: (datum: T, index: number, array: T[]) => U | undefined | null): [U, U] | [undefined, undefined]; +export function extent(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => U | undefined | null): [U, U] | [undefined, undefined]; /** * Return the mean of an array of numbers */ -export function mean(array: Array): number | undefined; -export function mean(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined; +export function mean(array: ArrayLike): number | undefined; +export function mean(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number | undefined; /** * Return the median of an array of numbers */ -export function median(array: Array): number | undefined; -export function median(array: T[], accessor: (element: T, i: number, array: T[]) => number | undefined | null): number | undefined; +export function median(array: ArrayLike): number | undefined; +export function median(array: ArrayLike, accessor: (element: T, i: number, array: ArrayLike) => number | undefined | null): number | undefined; /** * Returns the p-quantile of an array of numbers */ -export function quantile(array: Array, p: number): number | undefined; -export function quantile(array: T[], p: number, accessor: (element: T, i: number, array: T[]) => number | undefined | null): number | undefined; +export function quantile(array: ArrayLike, p: number): number | undefined; +export function quantile(array: ArrayLike, p: number, accessor: (element: T, i: number, array: ArrayLike) => number | undefined | null): number | undefined; /** * Compute the sum of an array of numbers. */ -export function sum(array: Array): number; +export function sum(array: ArrayLike): number; /** * Compute the sum of an array, using the given accessor to convert values to numbers. */ -export function sum(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number; +export function sum(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number; /** * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array of numbers. */ -export function deviation(array: Array): number | undefined; +export function deviation(array: ArrayLike): number | undefined; /** * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array, * using the given accessor to convert values to numbers. */ -export function deviation(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined; +export function deviation(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number | undefined; /** * Compute an unbiased estimator of the population variance of the given array of numbers. */ -export function variance(array: Array): number | undefined; +export function variance(array: ArrayLike): number | undefined; /** * Compute an unbiased estimator of the population variance of the given array, * using the given accessor to convert values to numbers. */ -export function variance(array: T[], accessor: (datum: T, index: number, array: T[]) => number | undefined | null): number | undefined; +export function variance(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number | undefined; // -------------------------------------------------------------------------------------- // Searching Arrays // -------------------------------------------------------------------------------------- -export function scan(array: number[], comparator?: (a: number, b: number) => number): number | undefined; -export function scan(array: T[], comparator: (a: T, b: T) => number): number | undefined; +export function scan(array: ArrayLike, comparator?: (a: number, b: number) => number): number | undefined; +export function scan(array: ArrayLike, comparator: (a: T, b: T) => number): number | undefined; -export function bisectLeft(array: number[], x: number, lo?: number, hi?: number): number; -export function bisectLeft(array: string[], x: string, lo?: number, hi?: number): number; -export function bisectLeft(array: Date[], x: Date, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: number, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: string, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: Date, lo?: number, hi?: number): number; -export function bisectRight(array: number[], x: number, lo?: number, hi?: number): number; -export function bisectRight(array: string[], x: string, lo?: number, hi?: number): number; -export function bisectRight(array: Date[], x: Date, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: number, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: string, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: Date, lo?: number, hi?: number): number; export const bisect: typeof bisectRight; export interface Bisector { - left(array: T[], x: U, lo?: number, hi?: number): number; - right(array: T[], x: U, lo?: number, hi?: number): number; + left(array: ArrayLike, x: U, lo?: number, hi?: number): number; + right(array: ArrayLike, x: U, lo?: number, hi?: number): number; } export function bisector(comparator: (a: T, b: U) => number): Bisector; @@ -184,7 +184,7 @@ export function descending(a: Primitive | undefined, b: Primitive | undefined): * @param a First input array. * @param b Second input array. */ -export function cross(a: S[], b: T[]): Array<[S, T]>; +export function cross(a: ArrayLike, b: ArrayLike): Array<[S, T]>; /** * Returns the Cartesian product of the two arrays a and b. @@ -195,12 +195,12 @@ export function cross(a: S[], b: T[]): Array<[S, T]>; * @param b Second input array. * @param reducer A reducer function taking as input an element from "a" and "b" and returning a reduced value. */ -export function cross(a: S[], b: T[], reducer: (a: S, b: T) => U): U[]; +export function cross(a: ArrayLike, b: ArrayLike, reducer: (a: S, b: T) => U): U[]; /** * Merges the specified arrays into a single array. */ -export function merge(arrays: T[][]): T[]; +export function merge(arrays: ArrayLike>): T[]; /** * For each adjacent pair of elements in the specified array, returns a new array of tuples of elements i and i - 1. @@ -208,7 +208,7 @@ export function merge(arrays: T[][]): T[]; * * @param array Array of input elements */ -export function pairs(array: T[]): Array<[T, T]>; +export function pairs(array: ArrayLike): Array<[T, T]>; /** * For each adjacent pair of elements in the specified array, in order, invokes the specified reducer function passing the element i and element i - 1. * Returns the resulting array of pair-wise reduced elements. @@ -217,17 +217,17 @@ export function pairs(array: T[]): Array<[T, T]>; * @param array Array of input elements * @param reducer A reducer function taking as input to adjecent elements of the input array and returning a reduced value. */ -export function pairs(array: T[], reducer: (a: T, b: T) => U): U[]; +export function pairs(array: ArrayLike, reducer: (a: T, b: T) => U): U[]; /** * Given the specified array, return an array corresponding to the list of indices in 'keys'. */ -export function permute(array: { [key: number]: T }, keys: number[]): T[]; +export function permute(array: { [key: number]: T }, keys: ArrayLike): T[]; /** * Given the specified object, return an array corresponding to the list of property names in 'keys'. */ -export function permute(object: { [key: string]: T }, keys: string[]): T[]; +export function permute(object: { [key: string]: T }, keys: ArrayLike): T[]; /** * Generates a 0-based numeric sequence. The output range does not include 'stop'. @@ -243,6 +243,15 @@ export function range(start: number, stop: number, step?: number): number[]; * Randomizes the order of the specified array using the Fisher–Yates shuffle. */ export function shuffle(array: T[], lo?: number, hi?: number): T[]; +export function shuffle(array: Int8Array, lo?: number, hi?: number): Int8Array; +export function shuffle(array: Uint8Array, lo?: number, hi?: number): Uint8Array; +export function shuffle(array: Uint8ClampedArray, lo?: number, hi?: number): Uint8ClampedArray; +export function shuffle(array: Int16Array, lo?: number, hi?: number): Int16Array; +export function shuffle(array: Uint16Array, lo?: number, hi?: number): Uint16Array; +export function shuffle(array: Int32Array, lo?: number, hi?: number): Int32Array; +export function shuffle(array: Uint32Array, lo?: number, hi?: number): Uint32Array; +export function shuffle(array: Float32Array, lo?: number, hi?: number): Float32Array; +export function shuffle(array: Float64Array, lo?: number, hi?: number): Float64Array; /** * Generate an array of approximately count + 1 uniformly-spaced, nicely-rounded values between start and stop (inclusive). @@ -289,14 +298,14 @@ export function tickStep(start: number, stop: number, count: number): number; /** * Transpose a matrix provided in Array of Arrays format. */ -export function transpose(matrix: T[][]): T[][]; +export function transpose(matrix: ArrayLike>): T[][]; /** * Returns an array of arrays, where the ith array contains the ith element from each of the argument arrays. * The returned array is truncated in length to the shortest array in arrays. If arrays contains only a single array, the returned array * contains one-element arrays. With no arguments, the returned array is empty. */ -export function zip(...arrays: T[][]): T[][]; +export function zip(...arrays: Array>): T[][]; // -------------------------------------------------------------------------------------- // Histogram @@ -310,20 +319,20 @@ export interface Bin extends Array { /** * Type definition for threshold generator which returns the count of recommended thresholds */ -export type ThresholdCountGenerator = (values: number[], min?: number, max?: number) => number; +export type ThresholdCountGenerator = (values: ArrayLike, min?: number, max?: number) => number; /** * Type definition for threshold generator which returns an array of recommended thresholds */ -export type ThresholdArrayGenerator = (values: Value[], min?: Value, max?: Value) => Value[]; +export type ThresholdArrayGenerator = (values: ArrayLike, min?: Value, max?: Value) => Value[]; export interface HistogramGenerator { - (data: Datum[]): Array>; - value(): (d: Datum, i: number, data: Datum[]) => Value; - value(valueAccessor: (d: Datum, i: number, data: Datum[]) => Value): this; - domain(): (values: Value[]) => [Value, Value]; + (data: ArrayLike): Array>; + value(): (d: Datum, i: number, data: ArrayLike) => Value; + value(valueAccessor: (d: Datum, i: number, data: ArrayLike) => Value): this; + domain(): (values: ArrayLike) => [Value, Value]; domain(domain: [Value, Value]): this; - domain(domainAccessor: (values: Value[]) => [Value, Value]): this; + domain(domainAccessor: (values: ArrayLike) => [Value, Value]): this; thresholds(): ThresholdCountGenerator | ThresholdArrayGenerator; /** * Divide the domain uniformly into approximately count bins. IMPORTANT: This threshold @@ -357,7 +366,7 @@ export interface HistogramGenerator { * @param thresholds Array of threshold values used for binning. The elements must * be of the same type as the materialized values of the histogram. */ - thresholds(thresholds: Value[]): this; + thresholds(thresholds: ArrayLike): this; /** * Set a threshold accessor function, which returns the array of values to be used as * thresholds in determining the bins. @@ -379,8 +388,8 @@ export function histogram(): HistogramGenera // Histogram Thresholds // -------------------------------------------------------------------------------------- -export function thresholdFreedmanDiaconis(values: number[], min: number, max: number): number; // of type ThresholdCountGenerator +export function thresholdFreedmanDiaconis(values: ArrayLike, min: number, max: number): number; // of type ThresholdCountGenerator -export function thresholdScott(values: number[], min: number, max: number): number; // of type ThresholdCountGenerator +export function thresholdScott(values: ArrayLike, min: number, max: number): number; // of type ThresholdCountGenerator -export function thresholdSturges(values: number[]): number; // of type ThresholdCountGenerator +export function thresholdSturges(values: ArrayLike): number; // of type ThresholdCountGenerator diff --git a/types/d3-axis/index.d.ts b/types/d3-axis/index.d.ts index 9cee537067..1c7820c809 100644 --- a/types/d3-axis/index.d.ts +++ b/types/d3-axis/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.0.4 +// Last module patch version validated against: 1.0.8 import { Selection, TransitionLike } from 'd3-selection'; @@ -82,6 +82,10 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * + * This method is also a convenience function for axis.tickArguments. + * * @param count Number of ticks that should be rendered * @param specifier An optional format specifier to customize how the tick values are formatted. */ @@ -91,6 +95,8 @@ export interface Axis { * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * Use with a TIME SCALE ONLY. * + * This method is also a convenience function for axis.tickArguments. + * * @param interval A time interval used to generate date-based ticks. This is typically a TimeInterval/CountableTimeInterval as defined * in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). * @param specifier An optional format specifier to customize how the tick values are formatted. @@ -99,17 +105,31 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. + * + * The meaning of the arguments depends on the axis’ scale type: most commonly, the arguments are a suggested count for the number of ticks + * (or a time interval for time scales), and an optional format specifier to customize how the tick values are formatted. + * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * This method is also a convenience function for axis.tickArguments. */ ticks(arg0: any, ...args: any[]): this; /** - * Get an array containing the currently set arguments to be passed into scale.ticks and scale.tickFormat. + * Get an array containing the currently set arguments to be passed into scale.ticks and scale.tickFormat, which defaults to the empty array. */ tickArguments(): any[]; /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * * @param args An array containing a single element representing the count, i.e. number of ticks to be rendered. */ tickArguments(args: [number]): this; @@ -117,6 +137,11 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * * @param args An array containing two elements. The first element represents the count, i.e. number of ticks to be rendered. The second * element is a string representing the format specifier to customize how the tick values are formatted. */ @@ -126,6 +151,8 @@ export interface Axis { * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * Use with a TIME SCALE ONLY. * + * See also axis.ticks. + * * @param args An array containing a single element representing a time interval used to generate date-based ticks. * This is typically a TimeInterval/CountableTimeInterval as defined in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). */ @@ -135,6 +162,8 @@ export interface Axis { * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * Use with a TIME SCALE ONLY. * + * See also axis.ticks. + * * @param args An array containing two elements. The first element represents a time interval used to generate date-based ticks. * This is typically a TimeInterval/CountableTimeInterval as defined in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). * The second element is a string representing the format specifier to customize how the tick values are formatted. @@ -144,6 +173,11 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * * @param args An array with arguments suitable for the scale to be used for tick generation */ tickArguments(args: any[]): this; diff --git a/types/d3-brush/d3-brush-tests.ts b/types/d3-brush/d3-brush-tests.ts index 2d9ee319aa..bce080f424 100644 --- a/types/d3-brush/d3-brush-tests.ts +++ b/types/d3-brush/d3-brush-tests.ts @@ -85,7 +85,6 @@ brush = brush.on('end', null); // re-apply brush.on('end', function(d, i, g) { - const that: SVGGElement = this; const datum: BrushDatum = d; const index: number = i; const group: SVGGElement[] | ArrayLike = g; diff --git a/types/d3-collection/d3-collection-tests.ts b/types/d3-collection/d3-collection-tests.ts index af9bf8d075..91a72479db 100644 --- a/types/d3-collection/d3-collection-tests.ts +++ b/types/d3-collection/d3-collection-tests.ts @@ -11,13 +11,13 @@ import { ascending } from 'd3-array'; // Preparatory steps -------------------------------------------------------------- -let keyValueObj = { +const keyValueObj = { a: 'test', b: 123, c: [true, true, false] }; -let keyValueObj2 = { +const keyValueObj2 = { a: 'test', b: 'same', c: 'type' @@ -29,7 +29,6 @@ let stringKVArray: Array<{ key: string, value: string }>; let anyKVArray: Array<{ key: string, value: any }>; let num: number; -let str: string; let booleanFlag: boolean; // --------------------------------------------------------------------- @@ -137,9 +136,9 @@ testObjKVArray = testObjMap.entries(); // each() -------------------------------------------------------------- testObjMap.each((value, key, map) => { - let v: TestObject = value; - let k: string = key; - let m: d3Collection.Map = map; + const v: TestObject = value; + const k: string = key; + const m: d3Collection.Map = map; console.log(v.val); }); @@ -169,9 +168,9 @@ basicSet = d3Collection.set(['foo', 'bar', 42]); // last element is coerced // from array without accessor basicSet = d3Collection.set(testObjArray, (value, index, array) => { - let v: TestObject = value; - let i: number = index; - let a: TestObject[] = array; + const v: TestObject = value; + const i: number = index; + const a: TestObject[] = array; return v.name; }); @@ -208,9 +207,9 @@ stringArray = basicSet.values(); // each() -------------------------------------------------------------- basicSet.each((value, valueRepeat, set) => { - let v: string = value; - let vr: string = valueRepeat; - let s: d3Collection.Set = set; + const v: string = value; + const vr: string = valueRepeat; + const s: d3Collection.Set = set; console.log(v); }); @@ -233,7 +232,7 @@ interface Yield { site: string; } -let raw: Yield[] = [ +const raw: Yield[] = [ { yield: 27.00, variety: 'Manchuria', year: 1931, site: 'University Farm' }, { yield: 48.87, variety: 'Manchuria', year: 1931, site: 'Waseca' }, { yield: 27.43, variety: 'Manchuria', year: 1931, site: 'Morris' }, @@ -279,8 +278,8 @@ nestL1Rollup = nestL1Rollup nestL2 = nestL2 .sortValues((a, b) => { - let val1: Yield = a; // data type Yield - let val2: Yield = b; // data type Yield + const val1: Yield = a; // data type Yield + const val2: Yield = b; // data type Yield return a.yield - b.yield; }); @@ -288,7 +287,7 @@ nestL2 = nestL2 nestL1Rollup = nestL1Rollup .rollup(values => { - let vs: Yield[] = values; // correct data array type + const vs: Yield[] = values; // correct data array type return vs.length; }); diff --git a/types/d3-contour/d3-contour-tests.ts b/types/d3-contour/d3-contour-tests.ts index 751dfe99c9..588750bf29 100644 --- a/types/d3-contour/d3-contour-tests.ts +++ b/types/d3-contour/d3-contour-tests.ts @@ -110,7 +110,7 @@ interface CustomDatum { // Get contour generator ------------------------------------------------------- -let contDensDefault: d3Contour.ContourDensity<[number, number]> = d3Contour.contourDensity(); +const contDensDefault: d3Contour.ContourDensity<[number, number]> = d3Contour.contourDensity(); let contDensCustom: d3Contour.ContourDensity = d3Contour.contourDensity(); // Configure contour generator ================================================= diff --git a/types/d3-dispatch/d3-dispatch-tests.ts b/types/d3-dispatch/d3-dispatch-tests.ts index 436bc3d6d4..a9f29ef75d 100644 --- a/types/d3-dispatch/d3-dispatch-tests.ts +++ b/types/d3-dispatch/d3-dispatch-tests.ts @@ -16,8 +16,6 @@ interface Datum { } let dispatch: d3Dispatch.Dispatch; -let copy: d3Dispatch.Dispatch; -let copy2: d3Dispatch.Dispatch; // Signature Tests ---------------------------------------- @@ -50,5 +48,5 @@ dispatch.apply('bar', document.body, [{ a: 3, b: 'test' }, 1]); dispatch.on('bar', null); // Copy dispatch ----------------------------------------------- -copy = dispatch.copy(); -// copy2 = dispatch.copy(); // test fails type mismatch of underlying event target +const copy: d3Dispatch.Dispatch = dispatch.copy(); +// const copy2: d3Dispatch.Dispatch = dispatch.copy(); // test fails type mismatch of underlying event target diff --git a/types/d3-drag/tslint.json b/types/d3-drag/tslint.json index 08b1465cd6..b8825c1674 100644 --- a/types/d3-drag/tslint.json +++ b/types/d3-drag/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { + // TODO + "no-this-assignment": false, "unified-signatures": false } } diff --git a/types/d3-dsv/d3-dsv-tests.ts b/types/d3-dsv/d3-dsv-tests.ts index 421add6e65..51127b7266 100644 --- a/types/d3-dsv/d3-dsv-tests.ts +++ b/types/d3-dsv/d3-dsv-tests.ts @@ -12,13 +12,13 @@ import * as d3Dsv from 'd3-dsv'; // Preperatory Steps // ------------------------------------------------------------------------------------------ -const csvTestString: string = '1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; -const tsvTestString: string = '1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; -const pipedTestString: string = '1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; +const csvTestString = '1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; +const tsvTestString = '1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; +const pipedTestString = '1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; -const csvTestStringWithHeader: string = 'Year,Make,Model,Length\n1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; -const tsvTestStringWithHeader: string = 'Year\tMake\tModel\tLength\n1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; -const pipedTestStringWithHeader: string = 'Year|Make|Model|Length\n1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; +const csvTestStringWithHeader = 'Year,Make,Model,Length\n1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; +const tsvTestStringWithHeader = 'Year\tMake\tModel\tLength\n1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; +const pipedTestStringWithHeader = 'Year|Make|Model|Length\n1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; interface ParsedTestObject { year: Date; diff --git a/types/d3-dsv/v0/tslint.json b/types/d3-dsv/v0/tslint.json index 3db14f85ea..bafaae7817 100644 --- a/types/d3-dsv/v0/tslint.json +++ b/types/d3-dsv/v0/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "dt-header": false + } +} diff --git a/types/d3-ease/d3-ease-tests.ts b/types/d3-ease/d3-ease-tests.ts index 67a0f32b1b..543f2fd375 100644 --- a/types/d3-ease/d3-ease-tests.ts +++ b/types/d3-ease/d3-ease-tests.ts @@ -8,7 +8,7 @@ import * as d3Ease from 'd3-ease'; -const t_in: number = 0.5; +const t_in = 0.5; let t_out: number; t_out = d3Ease.easeLinear(t_in); diff --git a/types/d3-force/tslint.json b/types/d3-force/tslint.json index 08b1465cd6..b8825c1674 100644 --- a/types/d3-force/tslint.json +++ b/types/d3-force/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { + // TODO + "no-this-assignment": false, "unified-signatures": false } } diff --git a/types/d3-format/d3-format-tests.ts b/types/d3-format/d3-format-tests.ts index 9c11d07c70..def8994b70 100644 --- a/types/d3-format/d3-format-tests.ts +++ b/types/d3-format/d3-format-tests.ts @@ -36,17 +36,17 @@ formatFn = d3Format.formatPrefix(',.0', 1e-6); specifier = d3Format.formatSpecifier('.0%'); -let fill: string = specifier.fill; -let align: '>' | '<' | '^' | '=' = specifier.align; -let sign: '-' | '+' | '(' | ' ' = specifier.sign; -let symbol: '$' | '#' | '' = specifier.symbol; -let zero: boolean = specifier.zero; -let width: number | undefined = specifier.width; -let comma: boolean = specifier.comma; -let precision: number = specifier.precision; -let type: 'e' | 'f' | 'g' | 'r' | 's' | '%' | 'p' | 'b' | 'o' | 'd' | 'x' | 'X' | 'c' | '' | 'n' = specifier.type; +const fill: string = specifier.fill; +const align: '>' | '<' | '^' | '=' = specifier.align; +const sign: '-' | '+' | '(' | ' ' = specifier.sign; +const symbol: '$' | '#' | '' = specifier.symbol; +const zero: boolean = specifier.zero; +const width: number | undefined = specifier.width; +const comma: boolean = specifier.comma; +const precision: number = specifier.precision; +const type: 'e' | 'f' | 'g' | 'r' | 's' | '%' | 'p' | 'b' | 'o' | 'd' | 'x' | 'X' | 'c' | '' | 'n' = specifier.type; -let formatString: string = specifier.toString(); +const formatString: string = specifier.toString(); // ---------------------------------------------------------------------- // Test Precision Suggestors @@ -85,16 +85,16 @@ localeDef = { percent : "\u202f%" }; -let decimal: string = localeDef.decimal; -let thousands: string = localeDef.thousands; -let grouping: number[] = localeDef.grouping; -let currency: [string, string] = localeDef.currency; -let numerals: string[] | undefined = localeDef.numerals; -let percent: string | undefined = localeDef.percent; +const decimal: string = localeDef.decimal; +const thousands: string = localeDef.thousands; +const grouping: number[] = localeDef.grouping; +const currency: [string, string] = localeDef.currency; +const numerals: string[] | undefined = localeDef.numerals; +const percent: string | undefined = localeDef.percent; localeObj = d3Format.formatLocale(localeDef); localeObj = d3Format.formatDefaultLocale(localeDef); -let formatFactory: (specifier: string) => ((n: number) => string) = localeObj.format; -let formatPrefixFactory: (specifier: string, value: number) => ((n: number) => string) = localeObj.formatPrefix; +const formatFactory: (specifier: string) => ((n: number) => string) = localeObj.format; +const formatPrefixFactory: (specifier: string, value: number) => ((n: number) => string) = localeObj.formatPrefix; diff --git a/types/d3-format/index.d.ts b/types/d3-format/index.d.ts index 34cf80c047..6592756ef1 100644 --- a/types/d3-format/index.d.ts +++ b/types/d3-format/index.d.ts @@ -112,8 +112,8 @@ export interface FormatSpecifier { comma: boolean; /** * Depending on the type, the precision either indicates the number of digits that follow the decimal point (types 'f' and '%'), - * or the number of significant digits (types ''​ (none), 'e', 'g', 'r', 's' and 'p'). If the precision is not specified, - * it defaults to 6 for all types except ''​ (none), which defaults to 12. + * or the number of significant digits (types '' (none), 'e', 'g', 'r', 's' and 'p'). If the precision is not specified, + * it defaults to 6 for all types except '' (none), which defaults to 12. * Precision is ignored for integer formats (types 'b', 'o', 'd', 'x', 'X' and 'c'). * * See precisionFixed and precisionRound for help picking an appropriate precision @@ -137,7 +137,7 @@ export interface FormatSpecifier { * 'c' - converts the integer to the corresponding unicode character before printing. * '' (none) - like g, but trim insignificant trailing zeros. * - * The type 'n' is also supported as shorthand for ',g'. For the 'g', 'n' and ​''(none) types, + * The type 'n' is also supported as shorthand for ',g'. For the 'g', 'n' and ''(none) types, * decimal notation is used if the resulting string would have precision or fewer digits; otherwise, exponent notation is used. */ type: 'e' | 'f' | 'g' | 'r' | 's' | '%' | 'p' | 'b' | 'o' | 'd' | 'x' | 'X' | 'c' | '' | 'n'; @@ -170,7 +170,7 @@ export function formatDefaultLocale(defaultLocale: FormatLocaleDefinition): Form * * Uses the current default locale. * - * The general form of a specifier is [​[fill]align][sign][symbol][0][width][,][.precision][type]. + * The general form of a specifier is [[fill]align][sign][symbol][0][width][,][.precision][type]. * For reference, an explanation of the segments of the specifier string, refer to the FormatSpecifier interface properties. * * @param specifier A Specifier string @@ -185,7 +185,7 @@ export function format(specifier: string): (n: number) => string; * * Uses the current default locale. * - * The general form of a specifier is [​[fill]align][sign][symbol][0][width][,][.precision][type]. + * The general form of a specifier is [[fill]align][sign][symbol][0][width][,][.precision][type]. * For reference, an explanation of the segments of the specifier string, refer to the FormatSpecifier interface properties. * * @param specifier A Specifier string @@ -197,7 +197,7 @@ export function formatPrefix(specifier: string, value: number): (n: number) => s * Parses the specified specifier, returning an object with exposed fields that correspond to the * format specification mini-language and a toString method that reconstructs the specifier. * - * The general form of a specifier is [​[fill]align][sign][symbol][0][width][,][.precision][type]. + * The general form of a specifier is [[fill]align][sign][symbol][0][width][,][.precision][type]. * For reference, an explanation of the segments of the specifier string, refer to the FormatSpecifier interface properties. * * @param specifier A specifier string. diff --git a/types/d3-geo/d3-geo-tests.ts b/types/d3-geo/d3-geo-tests.ts index 8b8f9557e9..f698193878 100644 --- a/types/d3-geo/d3-geo-tests.ts +++ b/types/d3-geo/d3-geo-tests.ts @@ -607,7 +607,7 @@ let customTransformProto: CustomTranformProto; customTransformProto = { point(x, y) { - return this.stream.point(x + this.a, -y); + this.stream.point(x + this.a, -y); }, a: 10 }; diff --git a/types/d3-geo/tslint.json b/types/d3-geo/tslint.json index 657f2f02f7..680a816ce2 100644 --- a/types/d3-geo/tslint.json +++ b/types/d3-geo/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { + // TODO + "no-this-assignment": false, "unified-signatures": false, "max-line-length": [false, 200] } diff --git a/types/d3-hexbin/index.d.ts b/types/d3-hexbin/index.d.ts index 61d7330ca6..dba33cb292 100644 --- a/types/d3-hexbin/index.d.ts +++ b/types/d3-hexbin/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for D3JS d3-hexbin module v0.2.1 // Project: https://github.com/d3/d3-hexbin/ -// Definitions by: UNCOVER TRUTH Inc. , Tom Wanzek +// Definitions by: UNCOVER TRUTH Inc. , Tom Wanzek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export interface HexbinBin extends Array { diff --git a/types/d3-hsv/d3-hsv-tests.ts b/types/d3-hsv/d3-hsv-tests.ts index 72e18145e6..0d3e564360 100644 --- a/types/d3-hsv/d3-hsv-tests.ts +++ b/types/d3-hsv/d3-hsv-tests.ts @@ -6,8 +6,8 @@ * are not intended as functional tests. */ -import {hsv, HSVColor} from 'd3-hsv'; -import {rgb, RGBColor} from 'd3-color'; +import { hsv, HSVColor } from 'd3-hsv'; +import { rgb, RGBColor } from 'd3-color'; let c: RGBColor; let cHSV: HSVColor; diff --git a/types/d3-hsv/index.d.ts b/types/d3-hsv/index.d.ts index c10fa6ee44..6a7a2c8560 100644 --- a/types/d3-hsv/index.d.ts +++ b/types/d3-hsv/index.d.ts @@ -5,7 +5,7 @@ // Last module patch version validated against: 0.0.3 -import {Color, RGBColor, ColorSpaceObject, ColorCommonInstance} from 'd3-color'; +import { Color, RGBColor, ColorSpaceObject, ColorCommonInstance } from 'd3-color'; export type ColorSpaceObjectWithHSV = ColorSpaceObject | HSVColor; diff --git a/types/d3-interpolate/d3-interpolate-tests.ts b/types/d3-interpolate/d3-interpolate-tests.ts index 5cbb6fe3a0..6baaf06092 100644 --- a/types/d3-interpolate/d3-interpolate-tests.ts +++ b/types/d3-interpolate/d3-interpolate-tests.ts @@ -44,7 +44,6 @@ let iString: Interpolator; let iDate: Interpolator; let iArrayNum: Interpolator; let iArrayStr: Interpolator; -let iArrayDate: Interpolator; let iArrayMixed: Interpolator<[Date, string]>; let iKeyVal: Interpolator<{ [key: string]: any }>; let iRGBColorObj: Interpolator; @@ -56,7 +55,6 @@ let arrNum: number[]; let arrStr: string[]; let objKeyVal: { [key: string]: any }; let objRGBColor: d3Color.RGBColor; -let objHSVColor: d3Hsv.HSVColor; let zoom: [number, number, number]; // test interpolate(a, b) signature ---------------------------------------------------- diff --git a/types/d3-path/d3-path-tests.ts b/types/d3-path/d3-path-tests.ts index b11a3405e3..6a7b6a3fa0 100644 --- a/types/d3-path/d3-path-tests.ts +++ b/types/d3-path/d3-path-tests.ts @@ -12,7 +12,7 @@ import * as d3Path from 'd3-path'; // Test create new path serializer // ----------------------------------------------------------------------------------------- -let context: d3Path.Path = d3Path.path(); +const context: d3Path.Path = d3Path.path(); // ----------------------------------------------------------------------------------------- // Test path serializer methods @@ -35,4 +35,4 @@ context.rect(60, 60, 100, 200); context.closePath(); -let pathString: string = context.toString(); +const pathString: string = context.toString(); diff --git a/types/d3-polygon/d3-polygon-tests.ts b/types/d3-polygon/d3-polygon-tests.ts index 748054b727..28e1e464e1 100644 --- a/types/d3-polygon/d3-polygon-tests.ts +++ b/types/d3-polygon/d3-polygon-tests.ts @@ -15,8 +15,8 @@ import * as d3Polygon from 'd3-polygon'; let num: number; let containsFlag: boolean; let point: [number, number] = [15, 15]; -let polygon: Array<[number, number]> = [[10, 10], [20, 20], [10, 30]]; -let pointArray: Array<[number, number]> = [[10, 10], [20, 20], [10, 30], [15, 15]]; +const polygon: Array<[number, number]> = [[10, 10], [20, 20], [10, 30]]; +const pointArray: Array<[number, number]> = [[10, 10], [20, 20], [10, 30], [15, 15]]; let hull: Array<[number, number]>; // ----------------------------------------------------------------------------- diff --git a/types/d3-quadtree/d3-quadtree-tests.ts b/types/d3-quadtree/d3-quadtree-tests.ts index 5fabc66961..eda00fe130 100644 --- a/types/d3-quadtree/d3-quadtree-tests.ts +++ b/types/d3-quadtree/d3-quadtree-tests.ts @@ -39,7 +39,7 @@ let testData: TestDatum[] = [ let node: d3Quadtree.QuadtreeInternalNode | d3Quadtree.QuadtreeLeaf; let numberAccessor: (d: TestDatum) => number; -let simpleTestData: Array<[number, number]> = [ +const simpleTestData: Array<[number, number]> = [ [10, 20], [30, 10], [15, 80], @@ -216,7 +216,7 @@ quadtree = quadtree.visitAfter((node, x0, y0, x1, y1) => { // Test QuadtreeLeaf ========================================================= -let leaf: d3Quadtree.QuadtreeLeaf; +declare const leaf: d3Quadtree.QuadtreeLeaf; let nextLeaf: d3Quadtree.QuadtreeLeaf | undefined; testDatum = leaf.data; @@ -225,7 +225,7 @@ nextLeaf = leaf.next ? leaf.next : undefined; // Test QuadtreeInternalNode ================================================= -let internalNode: d3Quadtree.QuadtreeInternalNode; +declare const internalNode: d3Quadtree.QuadtreeInternalNode; let quadNode: d3Quadtree.QuadtreeInternalNode | d3Quadtree.QuadtreeLeaf | undefined; quadNode = internalNode[0]; diff --git a/types/d3-queue/d3-queue-tests.ts b/types/d3-queue/d3-queue-tests.ts index 312bb0c358..f387ea990a 100644 --- a/types/d3-queue/d3-queue-tests.ts +++ b/types/d3-queue/d3-queue-tests.ts @@ -29,7 +29,7 @@ qWithResults = d3Queue.queue(3); function delayedHello(name: string, delay: number, callback: (error: any | null) => void) { setTimeout(() => { - console.log('Hello, ' + name + '!'); + console.log(`Hello, ${name}!`); callback(null); }, delay); } diff --git a/types/d3-queue/tslint.json b/types/d3-queue/tslint.json index 08b1465cd6..b8825c1674 100644 --- a/types/d3-queue/tslint.json +++ b/types/d3-queue/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { + // TODO + "no-this-assignment": false, "unified-signatures": false } } diff --git a/types/d3-request/d3-request-tests.ts b/types/d3-request/d3-request-tests.ts index 8d8061d76a..8b2130240a 100644 --- a/types/d3-request/d3-request-tests.ts +++ b/types/d3-request/d3-request-tests.ts @@ -16,7 +16,7 @@ import { DSVParsedArray, DSVRowString } from 'd3-dsv'; // Preparatory Steps // ------------------------------------------------------------------------------- -const url: string = 'http:// api.reddit.com'; +const url = 'http:// api.reddit.com'; interface RequestDatumGET { kind: 'Listing'; @@ -49,13 +49,12 @@ let listenerResult: (this: d3Request.Request, result: ResponseDatumGET[]) => voi // ------------------------------------------------------------------------------- // request to configure and send in follow-up -let request: d3Request.Request = d3Request.request(url); +const request: d3Request.Request = d3Request.request(url); // GET-request with callback, immediately sent -let requestWithCallback: d3Request.Request = d3Request.request(url, (error, xhr) => { - let x: XMLHttpRequest; +const requestWithCallback: d3Request.Request = d3Request.request(url, (error, xhr) => { if (!error) { - x = xhr; + const x: XMLHttpRequest = xhr; console.log(xhr.responseText); } }); @@ -65,36 +64,34 @@ let requestWithCallback: d3Request.Request = d3Request.request(url, (error, xhr) // ------------------------------------------------------------------------------- // Abort ----------------------------------------------------------------------- -let r1: d3Request.Request = request.abort(); +const r1: d3Request.Request = request.abort(); // Get ------------------------------------------------------------------------- // no arguments -let r2: d3Request.Request = d3Request.request(url) +const r2: d3Request.Request = d3Request.request(url) .get(); // with request datum -let r3: d3Request.Request = d3Request.request(url) +const r3: d3Request.Request = d3Request.request(url) .get({ kind: 'Listing' }); // with callback for response handling -let r4: d3Request.Request = d3Request.request(url) +const r4: d3Request.Request = d3Request.request(url) .response(xhr2Listing) .get((error, response) => { - let r: ResponseDatumGET[]; if (!error) { - r = response; + const r: ResponseDatumGET[] = response; console.log(r); } }); // with request datum and callback for response handling -let r5: d3Request.Request = d3Request.request(url) +const r5: d3Request.Request = d3Request.request(url) .response(xhr2Listing) .get({ kind: 'Listing' }, (error, response) => { - let r: ResponseDatumGET[]; if (!error) { - r = response; + const r: ResponseDatumGET[] = response; console.log(r); } }); @@ -102,20 +99,20 @@ let r5: d3Request.Request = d3Request.request(url) // Headers -------------------------------------------------------------------- // get -let acceptEncoding: string = request.header('Accept-Encoding'); +const acceptEncoding: string = request.header('Accept-Encoding'); // set -let r6: d3Request.Request = request.header('Accept-Encoding', 'gzip'); +const r6: d3Request.Request = request.header('Accept-Encoding', 'gzip'); // remove -let r7: d3Request.Request = request.header('Accept-Encoding', null); +const r7: d3Request.Request = request.header('Accept-Encoding', null); // Mime Type ------------------------------------------------------------------- // get let mimeType: string = request.mimeType(); // set -let r8: d3Request.Request = request.mimeType('application/json'); +const r8: d3Request.Request = request.mimeType('application/json'); // remove -let r9: d3Request.Request = request.mimeType(null); +const r9: d3Request.Request = request.mimeType(null); // Events - on ------------------------------------------------------------------ @@ -124,8 +121,8 @@ let r10: d3Request.Request = d3Request.request(url); // beforesent r10 = r10.on('beforesend', function(xhr) { - let that: d3Request.Request = this; - let x: XMLHttpRequest = xhr; + const that: d3Request.Request = this; + const x: XMLHttpRequest = xhr; // do something; }); @@ -134,8 +131,8 @@ listenerXhr = r10.on('beforesend'); // progress r10 = r10.on('progress', function(progEvent) { - let that: d3Request.Request = this; - let e: ProgressEvent = progEvent; + const that: d3Request.Request = this; + const e: ProgressEvent = progEvent; // do something; }); @@ -144,8 +141,8 @@ listenerProgress = r10.on('progress'); // error r10 = r10.on('error', function(error) { - let that: d3Request.Request = this; - let err: any = error; + const that: d3Request.Request = this; + const err: any = error; // do something; }); @@ -154,20 +151,20 @@ listenerError = r10.on('error'); // load r10 = r10.on('load', function(result) { - let that: d3Request.Request = this; - let res: ResponseDatumGET[] = result; + const that: d3Request.Request = this; + const res: ResponseDatumGET[] = result; // do something; }); r10 = r10.on('load', function(result: ResponseDatumGET[]) { - let that: d3Request.Request = this; - let res: ResponseDatumGET[] = result; + const that: d3Request.Request = this; + const res: ResponseDatumGET[] = result; // do something; }); // r10 = r10.on('load', function(result: number) { // fails, wrong argument type for callback -// let that: d3Request.Request = this; -// let res: number = result; +// const that: d3Request.Request = this; +// const res: number = result; // // do something; // }); @@ -176,16 +173,16 @@ listenerResult = r10.on('load'); // general (for unknown type additional event listener e.g. 'beforesent.custom' or 'load.custom') r10 = r10.on('progress.foo', function(progEvent: ProgressEvent) { - let that: d3Request.Request = this; - let e: any = ProgressEvent; + const that: d3Request.Request = this; + const e: any = ProgressEvent; // do something; }); listenerProgress = r10.on('progress.foo'); r10 = r10.on('error.foo', function(error) { - let that: d3Request.Request = this; - let err: any = error; + const that: d3Request.Request = this; + const err: any = error; // do something; }); @@ -194,95 +191,85 @@ listenerError = r10.on('error.foo'); // Password --------------------------------------------------------------------- // get -let password: string = request.password(); +const password: string = request.password(); // set -let r11: d3Request.Request = request.password('MyPassword'); +const r11: d3Request.Request = request.password('MyPassword'); // Post ------------------------------------------------------------------------- function xhr2Success(xhr: XMLHttpRequest): ResponseDatumPOST { - let result: ResponseDatumPOST; - - result = JSON.parse(xhr.responseText); - - return result; + return JSON.parse(xhr.responseText); } // no arguments -let r12: d3Request.Request = d3Request.request(url) +const r12: d3Request.Request = d3Request.request(url) .post(); // with request datum -let r13: d3Request.Request = d3Request.request(url) +const r13: d3Request.Request = d3Request.request(url) .post({ test: 'NewValue', value: 10 }); // with callback for response handling -let r14: d3Request.Request = d3Request.request(url).response(xhr2Success) +const r14: d3Request.Request = d3Request.request(url).response(xhr2Success) .post(function(error, response) { - let that: d3Request.Request = this; - let err: any = error; - let res: ResponseDatumPOST = response; + const that: d3Request.Request = this; + const err: any = error; + const res: ResponseDatumPOST = response; console.log('Success? ', res.success); }); -let r15: d3Request.Request = d3Request.request(url).response(xhr2Success) +const r15: d3Request.Request = d3Request.request(url).response(xhr2Success) .post({ test: 'NewValue', value: 10 }, function(error, response) { - let that: d3Request.Request = this; - let err: any = error; - let res: ResponseDatumPOST = response; + const that: d3Request.Request = this; + const err: any = error; + const res: ResponseDatumPOST = response; console.log('Success? ', res.success); }); // Response --------------------------------------------------------------------- function xhr2Listing(xhr: XMLHttpRequest): ResponseDatumGET[] { - let result: ResponseDatumGET[]; - - result = JSON.parse(xhr.responseText); - - return result; + return JSON.parse(xhr.responseText); } -let r16: d3Request.Request = d3Request.request(url) +const r16: d3Request.Request = d3Request.request(url) .response(xhr2Listing); // ResponseType ----------------------------------------------------------------- // get -let responseType: string = d3Request.request(url) +const responseType: string = d3Request.request(url) .responseType(); // set -let r17: d3Request.Request = d3Request.request(url) +const r17: d3Request.Request = d3Request.request(url) .responseType('application/json'); // Send ------------------------------------------------------------------------ // method only -let r18: d3Request.Request = d3Request.request(url) +const r18: d3Request.Request = d3Request.request(url) .send('GET'); // method and request datum -let r19: d3Request.Request = d3Request.request(url) +const r19: d3Request.Request = d3Request.request(url) .send('POST', { test: 'NewValue', value: 10 }); // method and callback for response handling -let r20: d3Request.Request = d3Request.request(url) +const r20: d3Request.Request = d3Request.request(url) .response(xhr2Listing) .send('GET', (error, response) => { - let r: ResponseDatumGET[]; if (!error) { - r = response; + const r: ResponseDatumGET[] = response; console.log(r); } }); // method,request datum and callback for response handling -let r21: d3Request.Request = d3Request.request(url) +const r21: d3Request.Request = d3Request.request(url) .response(xhr2Listing) .send('GET', { kind: 'Listing' }, (error, response) => { - let r: ResponseDatumGET[]; if (!error) { - r = response; + const r: ResponseDatumGET[] = response; console.log(r); } }); @@ -290,28 +277,28 @@ let r21: d3Request.Request = d3Request.request(url) // Timeout ----------------------------------------------------------------------- // get -let timeout: number = d3Request.request(url) +const timeout: number = d3Request.request(url) .timeout(); // set -let r22: d3Request.Request = d3Request.request(url) +const r22: d3Request.Request = d3Request.request(url) .timeout(500); // User---------------------------------------------------------------------------- // get -let user: string = request.user(); +const user: string = request.user(); // set -let r23: d3Request.Request = request.user('User'); +const r23: d3Request.Request = request.user('User'); // ------------------------------------------------------------------------------- // HTML Request // ------------------------------------------------------------------------------- -let html: d3Request.Request = d3Request.html(url); -let htmlWithCallback: d3Request.Request = d3Request.html(url, function(error, data) { - let that: d3Request.Request = this; - let err: any = error; - let d: DocumentFragment = data; +const html: d3Request.Request = d3Request.html(url); +const htmlWithCallback: d3Request.Request = d3Request.html(url, function(error, data) { + const that: d3Request.Request = this; + const err: any = error; + const d: DocumentFragment = data; console.log(d); }); @@ -319,11 +306,11 @@ let htmlWithCallback: d3Request.Request = d3Request.html(url, function(error, da // JSON Request // ------------------------------------------------------------------------------- -let json: d3Request.Request = d3Request.json(url); -let jsonWithCallback: d3Request.Request = d3Request.json(url, function(error, data) { - let that: d3Request.Request = this; - let err: any = error; - let d: ResponseDatumGET[] = data; +const json: d3Request.Request = d3Request.json(url); +const jsonWithCallback: d3Request.Request = d3Request.json(url, function(error, data) { + const that: d3Request.Request = this; + const err: any = error; + const d: ResponseDatumGET[] = data; console.log(d); }); @@ -331,11 +318,11 @@ let jsonWithCallback: d3Request.Request = d3Request.json(url // Text Request // ------------------------------------------------------------------------------- -let text: d3Request.Request = d3Request.text(url); -let textWithCallback: d3Request.Request = d3Request.text(url, function(error, data) { - let that: d3Request.Request = this; - let err: any = error; - let d: string = data; +const text: d3Request.Request = d3Request.text(url); +const textWithCallback: d3Request.Request = d3Request.text(url, function(error, data) { + const that: d3Request.Request = this; + const err: any = error; + const d: string = data; console.log(d); }); @@ -343,11 +330,11 @@ let textWithCallback: d3Request.Request = d3Request.text(url, function(error, da // XML Request // ------------------------------------------------------------------------------- -let xml: d3Request.Request = d3Request.xml(url); -let xmlWithCallback: d3Request.Request = d3Request.xml(url, function(error, data) { - let that: d3Request.Request = this; - let err: any = error; - let d: any = data; +const xml: d3Request.Request = d3Request.xml(url); +const xmlWithCallback: d3Request.Request = d3Request.xml(url, function(error, data) { + const that: d3Request.Request = this; + const err: any = error; + const d: any = data; console.log(d); }); @@ -359,32 +346,29 @@ let xmlWithCallback: d3Request.Request = d3Request.xml(url, function(error, data let csvRequest: d3Request.DsvRequest = d3Request.csv(url); // url and callback for response handling -let csvRequestWithCallback: d3Request.DsvRequest = d3Request.csv(url, function(error, data) { - let that: d3Request.Request = this; - let err: any = error; - let d: DSVParsedArray = data; +const csvRequestWithCallback: d3Request.DsvRequest = d3Request.csv(url, function(error, data) { + const that: d3Request.Request = this; + const err: any = error; + const d: DSVParsedArray = data; console.log(d); }); // url, row mapping function and callback for response handling -let csvRequestWithRowWithCallback: d3Request.DsvRequest = d3Request.csv(url, +const csvRequestWithRowWithCallback: d3Request.DsvRequest = d3Request.csv(url, (rawRow, index, columns) => { - let rr: DSVRowString = rawRow; - let i: number = index; - let cols: string[] = columns; - let mappedRow: ResponseDatumGET; - - mappedRow = { + const rr: DSVRowString = rawRow; + const i: number = index; + const cols: string[] = columns; + const mappedRow: ResponseDatumGET = { test: rr['test'], value: +rr['value'] }; - return mappedRow; }, function(error, data) { - let that: d3Request.Request = this; - let err: any = error; - let d: DSVParsedArray = data; + const that: d3Request.Request = this; + const err: any = error; + const d: DSVParsedArray = data; console.log(data); }); @@ -393,35 +377,32 @@ let csvRequestWithRowWithCallback: d3Request.DsvRequest = d3Request.csv = data; +const tsvRequestWithCallback: d3Request.DsvRequest = d3Request.tsv(url, function(error, data) { + const that: d3Request.Request = this; + const err: any = error; + const d: DSVParsedArray = data; console.log(d); }); // url, row mapping function and callback for response handling -let tsvRequestWithRowWithCallback: d3Request.DsvRequest = d3Request.tsv(url, +const tsvRequestWithRowWithCallback: d3Request.DsvRequest = d3Request.tsv(url, (rawRow, index, columns) => { - let rr: DSVRowString = rawRow; - let i: number = index; - let cols: string[] = columns; - let mappedRow: ResponseDatumGET; - - mappedRow = { + const rr: DSVRowString = rawRow; + const i: number = index; + const cols: string[] = columns; + const mappedRow: ResponseDatumGET = { test: rr['test'], value: +rr['value'] }; - return mappedRow; }, function(error, data) { - let that: d3Request.Request = this; - let err: any = error; - let d: DSVParsedArray = data; + const that: d3Request.Request = this; + const err: any = error; + const d: DSVParsedArray = data; console.log(data); }); @@ -433,16 +414,13 @@ let tsvRequestWithRowWithCallback: d3Request.DsvRequest = d3Request.tsv((rawRow, index, columns) => { - let rr: DSVRowString = rawRow; - let i: number = index; - let cols: string[] = columns; - let mappedRow: ResponseDatumGET; - - mappedRow = { + const rr: DSVRowString = rawRow; + const i: number = index; + const cols: string[] = columns; + const mappedRow: ResponseDatumGET = { test: rr['test'], value: +rr['value'] }; - return mappedRow; }); diff --git a/types/d3-request/tslint.json b/types/d3-request/tslint.json index da66196eee..70edbfa511 100644 --- a/types/d3-request/tslint.json +++ b/types/d3-request/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { + // TODO + "no-this-assignment": false, "unified-signatures": false, "max-line-length": [false, 145] } diff --git a/types/d3-sankey/d3-sankey-tests.ts b/types/d3-sankey/d3-sankey-tests.ts index abf61775b8..ace13d7e3c 100644 --- a/types/d3-sankey/d3-sankey-tests.ts +++ b/types/d3-sankey/d3-sankey-tests.ts @@ -168,7 +168,7 @@ let sGraph: d3Sankey.SankeyGraph; // Obtain SankeyLayout Generator // --------------------------------------------------------------------------- -let slgDefault: d3Sankey.SankeyLayout, {}, {}> = d3Sankey.sankey(); +const slgDefault: d3Sankey.SankeyLayout, {}, {}> = d3Sankey.sankey(); let slgDAG: d3Sankey.SankeyLayout = d3Sankey.sankey(); let slgDAGCustomId: d3Sankey.SankeyLayout = d3Sankey.sankey(); @@ -299,7 +299,7 @@ slgDAG = slgDAG.nodes(d => d.customNodes); // Get ----------------------------------------------------------------------- -let nodesAccessor: (d: DAG) => SNode[] = slgDAG.nodes(); +const nodesAccessor: (d: DAG) => SNode[] = slgDAG.nodes(); // --------------------------------------------------------------------------- // Links @@ -315,7 +315,7 @@ slgDAG = slgDAG.links(d => d.customLinks); // Get ----------------------------------------------------------------------- -let linksAccessor: (d: DAG) => SLink[] = slgDAG.links(); +const linksAccessor: (d: DAG) => SLink[] = slgDAG.links(); // --------------------------------------------------------------------------- // Compute Initial Layout @@ -344,7 +344,7 @@ pathGen = d3Sankey.sankeyLinkHorizontal(); // Render to svg path -let svgPathString: string | null = pathGen(sGraph.links[0]); +const svgPathString: string | null = pathGen(sGraph.links[0]); svgLinkPaths.attr('d', pathGen); // Render to canvas @@ -361,7 +361,7 @@ pathGen(sGraph.links[0]); // Sankey Node -------------------------------------------------------------- sNodes = sGraph.nodes; -let sNode = sNodes[0]; +const sNode = sNodes[0]; // User-specified extra properties: @@ -386,7 +386,7 @@ linksArrMaybe = sNode.targetLinks; // Sankey Link -------------------------------------------------------------- sLinks = sGraph.links; -let sLink = sLinks[0]; +const sLink = sLinks[0]; // User-specified extra properties: diff --git a/types/d3-sankey/index.d.ts b/types/d3-sankey/index.d.ts index 46a80b2671..a0ed07b615 100644 --- a/types/d3-sankey/index.d.ts +++ b/types/d3-sankey/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Tom Wanzek , Alex Ford // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 0.7 +// Last module patch version validated against: 0.7.1 import { Link } from 'd3-shape'; @@ -266,7 +266,7 @@ export interface SankeyLayout) => string | number): this; /** - * Return the current node alignment method, which defaults to d3.sankeyLeft. + * Return the current node alignment method, which defaults to d3.sankeyJustify. */ nodeAlign(): (node: SankeyNode, n: number) => number; /** diff --git a/types/d3-scale-chromatic/d3-scale-chromatic-tests.ts b/types/d3-scale-chromatic/d3-scale-chromatic-tests.ts index 1dac850043..f6b322b74d 100644 --- a/types/d3-scale-chromatic/d3-scale-chromatic-tests.ts +++ b/types/d3-scale-chromatic/d3-scale-chromatic-tests.ts @@ -11,50 +11,50 @@ import * as d3ScaleChromatic from 'd3-scale-chromatic'; // ----------------------------------------------------------------------- // Categorical // ----------------------------------------------------------------------- -let accent: string = d3ScaleChromatic.schemeAccent[0]; // #7fc97f -let dark: string = d3ScaleChromatic.schemeDark2[0]; // #1b9e77 -let paired: string = d3ScaleChromatic.schemePaired[0]; // #a6cee3 -let pastel1: string = d3ScaleChromatic.schemePastel1[0]; // #fbb4ae -let pastel2: string = d3ScaleChromatic.schemePastel2[0]; // #b3e2cd -let set1: string = d3ScaleChromatic.schemeSet1[0]; // #e41a1c -let set2: string = d3ScaleChromatic.schemeSet2[0]; // #66c2a5 -let set3: string = d3ScaleChromatic.schemeSet3[0]; // #8dd3c7 +const accent: string = d3ScaleChromatic.schemeAccent[0]; // #7fc97f +const dark: string = d3ScaleChromatic.schemeDark2[0]; // #1b9e77 +const paired: string = d3ScaleChromatic.schemePaired[0]; // #a6cee3 +const pastel1: string = d3ScaleChromatic.schemePastel1[0]; // #fbb4ae +const pastel2: string = d3ScaleChromatic.schemePastel2[0]; // #b3e2cd +const set1: string = d3ScaleChromatic.schemeSet1[0]; // #e41a1c +const set2: string = d3ScaleChromatic.schemeSet2[0]; // #66c2a5 +const set3: string = d3ScaleChromatic.schemeSet3[0]; // #8dd3c7 // ----------------------------------------------------------------------- // Diverging // ----------------------------------------------------------------------- -let BrBG: string = d3ScaleChromatic.interpolateBrBG(0); // rgb(84, 48, 5) -let PRGn: string = d3ScaleChromatic.interpolatePRGn(0); // rgb(64, 0, 75) -let PiYG: string = d3ScaleChromatic.interpolatePiYG(0); // rgb(142, 1, 82) -let PuOr: string = d3ScaleChromatic.interpolatePuOr(0); // rgb(127, 59, 8) -let RdBu: string = d3ScaleChromatic.interpolateRdBu(0); // rgb(103, 0, 31) -let RdGy: string = d3ScaleChromatic.interpolateRdGy(0); // rgb(103, 0, 31) -let RdYlBu: string = d3ScaleChromatic.interpolateRdYlBu(0); // rgb(103, 0, 31) -let RdYlGn: string = d3ScaleChromatic.interpolateRdYlGn(0); // rgb(103, 0, 31) -let Spectral: string = d3ScaleChromatic.interpolateSpectral(0); // rgb(158, 1, 66) +const BrBG: string = d3ScaleChromatic.interpolateBrBG(0); // rgb(84, 48, 5) +const PRGn: string = d3ScaleChromatic.interpolatePRGn(0); // rgb(64, 0, 75) +const PiYG: string = d3ScaleChromatic.interpolatePiYG(0); // rgb(142, 1, 82) +const PuOr: string = d3ScaleChromatic.interpolatePuOr(0); // rgb(127, 59, 8) +const RdBu: string = d3ScaleChromatic.interpolateRdBu(0); // rgb(103, 0, 31) +const RdGy: string = d3ScaleChromatic.interpolateRdGy(0); // rgb(103, 0, 31) +const RdYlBu: string = d3ScaleChromatic.interpolateRdYlBu(0); // rgb(103, 0, 31) +const RdYlGn: string = d3ScaleChromatic.interpolateRdYlGn(0); // rgb(103, 0, 31) +const Spectral: string = d3ScaleChromatic.interpolateSpectral(0); // rgb(158, 1, 66) // ----------------------------------------------------------------------- // Sequential // ----------------------------------------------------------------------- -let Blue: string = d3ScaleChromatic.interpolateBlues(1); // rgb(8, 48, 107) -let Green: string = d3ScaleChromatic.interpolateGreens(1); // rgb(0, 68, 27) -let Grey: string = d3ScaleChromatic.interpolateGreys(1); // rgb(0, 0, 0) -let Orange: string = d3ScaleChromatic.interpolateOranges(1); // rgb(127, 39, 4) -let Purple: string = d3ScaleChromatic.interpolatePurples(1); // rgb(63, 0, 125) -let Red: string = d3ScaleChromatic.interpolateReds(1); // rgb(103, 0, 13) +const Blue: string = d3ScaleChromatic.interpolateBlues(1); // rgb(8, 48, 107) +const Green: string = d3ScaleChromatic.interpolateGreens(1); // rgb(0, 68, 27) +const Grey: string = d3ScaleChromatic.interpolateGreys(1); // rgb(0, 0, 0) +const Orange: string = d3ScaleChromatic.interpolateOranges(1); // rgb(127, 39, 4) +const Purple: string = d3ScaleChromatic.interpolatePurples(1); // rgb(63, 0, 125) +const Red: string = d3ScaleChromatic.interpolateReds(1); // rgb(103, 0, 13) // ----------------------------------------------------------------------- // Sequential(Multi-Hue) // ----------------------------------------------------------------------- -let BuGn: string = d3ScaleChromatic.interpolateBuGn(1); // rgb(0, 68, 27) -let BuPu: string = d3ScaleChromatic.interpolateBuPu(1); // rgb(77, 0, 75) -let GnBu: string = d3ScaleChromatic.interpolateGnBu(1); // rgb(8, 64, 129) -let OrRd: string = d3ScaleChromatic.interpolateOrRd(1); // rgb(127, 0, 0) -let PuBuGn: string = d3ScaleChromatic.interpolatePuBuGn(1); // rgb(1, 70, 54) -let PuBu: string = d3ScaleChromatic.interpolatePuBu(1); // rgb(2, 56, 88) -let PuRd: string = d3ScaleChromatic.interpolatePuRd(1); // rgb(103, 0, 31) -let RdPu: string = d3ScaleChromatic.interpolateRdPu(1); // rgb(73, 0, 106) -let YlGnBu: string = d3ScaleChromatic.interpolateYlGnBu(1); // rgb(8, 29, 88) -let YlGn: string = d3ScaleChromatic.interpolateYlGn(1); // rgb(0, 69, 41) -let YlOrBr: string = d3ScaleChromatic.interpolateYlOrBr(1); // rgb(102, 37, 6) -let YlOrRd: string = d3ScaleChromatic.interpolateYlOrRd(1); // rgb(128, 0, 38) +const BuGn: string = d3ScaleChromatic.interpolateBuGn(1); // rgb(0, 68, 27) +const BuPu: string = d3ScaleChromatic.interpolateBuPu(1); // rgb(77, 0, 75) +const GnBu: string = d3ScaleChromatic.interpolateGnBu(1); // rgb(8, 64, 129) +const OrRd: string = d3ScaleChromatic.interpolateOrRd(1); // rgb(127, 0, 0) +const PuBuGn: string = d3ScaleChromatic.interpolatePuBuGn(1); // rgb(1, 70, 54) +const PuBu: string = d3ScaleChromatic.interpolatePuBu(1); // rgb(2, 56, 88) +const PuRd: string = d3ScaleChromatic.interpolatePuRd(1); // rgb(103, 0, 31) +const RdPu: string = d3ScaleChromatic.interpolateRdPu(1); // rgb(73, 0, 106) +const YlGnBu: string = d3ScaleChromatic.interpolateYlGnBu(1); // rgb(8, 29, 88) +const YlGn: string = d3ScaleChromatic.interpolateYlGn(1); // rgb(0, 69, 41) +const YlOrBr: string = d3ScaleChromatic.interpolateYlOrBr(1); // rgb(102, 37, 6) +const YlOrRd: string = d3ScaleChromatic.interpolateYlOrRd(1); // rgb(128, 0, 38) diff --git a/types/d3-selection-multi/index.d.ts b/types/d3-selection-multi/index.d.ts index da3c64e5e3..4dd2a47c46 100644 --- a/types/d3-selection-multi/index.d.ts +++ b/types/d3-selection-multi/index.d.ts @@ -5,8 +5,8 @@ // Last module patch version validated against: 1.0.0 -import {Selection, BaseType, ArrayLike, ValueFn} from 'd3-selection'; -import {Transition} from 'd3-transition'; +import { Selection, BaseType, ArrayLike, ValueFn } from 'd3-selection'; +import { Transition } from 'd3-transition'; /** * An object mapping attribute (or style or property) names to value accessors diff --git a/types/d3-selection-multi/tslint.json b/types/d3-selection-multi/tslint.json index 08b1465cd6..b8825c1674 100644 --- a/types/d3-selection-multi/tslint.json +++ b/types/d3-selection-multi/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { + // TODO + "no-this-assignment": false, "unified-signatures": false } } diff --git a/types/d3-selection/d3-selection-tests.ts b/types/d3-selection/d3-selection-tests.ts index baae76bad2..e2a4d6ffd9 100644 --- a/types/d3-selection/d3-selection-tests.ts +++ b/types/d3-selection/d3-selection-tests.ts @@ -484,7 +484,7 @@ body = body const datum: BodyDatum = d; const index: number = i; const group: HTMLBodyElement[] | d3Selection.ArrayLike = g; - return '
      Body Background Color: ' + this.bgColor + ', Foo Datum: ' + d.foo + '
      '; // this context HTMLBodyElement, datum BodyDatum + return `
      Body Background Color: ${this.bgColor}, Foo Datum: ${d.foo}
      `; // this context HTMLBodyElement, datum BodyDatum }); // --------------------------------------------------------------------------------------- @@ -993,7 +993,7 @@ let customListener: (this: HTMLBodyElement, finalOpponent: string) => string; customListener = finalOpponent => { const e = d3Selection.event; - return e.team + ' defeated ' + finalOpponent + ' in the EURO 2016 Cup. Who would have thought!!!'; + return `${e.team} defeated ${finalOpponent} in the EURO 2016 Cup. Who would have thought!!!`; }; const resultText: string = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); diff --git a/types/d3-selection/tslint.json b/types/d3-selection/tslint.json index 08b1465cd6..b8825c1674 100644 --- a/types/d3-selection/tslint.json +++ b/types/d3-selection/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { + // TODO + "no-this-assignment": false, "unified-signatures": false } } diff --git a/types/d3-shape/d3-shape-tests.ts b/types/d3-shape/d3-shape-tests.ts index 6e0fa97d96..4199d2f170 100644 --- a/types/d3-shape/d3-shape-tests.ts +++ b/types/d3-shape/d3-shape-tests.ts @@ -447,8 +447,8 @@ let lineRadial: d3Shape.LineRadial = d3Shape.lineRadial = defaultLineRadial; -let radialLine: d3Shape.RadialLine = lineRadial; +const defaultRadialLine: d3Shape.RadialLine<[number, number]> = defaultLineRadial; +const radialLine: d3Shape.RadialLine = lineRadial; defaultLineRadial = d3Shape.radialLine(); lineRadial = d3Shape.radialLine(); @@ -685,8 +685,8 @@ let areaRadial: d3Shape.AreaRadial = d3Shape.areaRadial = defaultAreaRadial; -let radialArea: d3Shape.RadialArea = areaRadial; +const defaultRadialArea: d3Shape.RadialArea<[number, number]> = defaultAreaRadial; +const radialArea: d3Shape.RadialArea = areaRadial; defaultAreaRadial = d3Shape.radialArea(); areaRadial = d3Shape.radialArea(); @@ -1319,10 +1319,10 @@ customSymbol = d3Shape.symbolTriangle; customSymbol = d3Shape.symbolWye; // ----------------------------------------------------------------------------------- -// Test pointRadius +// Test pointRadial // ----------------------------------------------------------------------------------- -let coordinatates: [number, number] = d3Shape.pointRadius(0, 12); +const coordinatates: [number, number] = d3Shape.pointRadial(0, 12); // ----------------------------------------------------------------------------------- // Test Stacks diff --git a/types/d3-shape/index.d.ts b/types/d3-shape/index.d.ts index 010c2108e9..27a92a79fe 100644 --- a/types/d3-shape/index.d.ts +++ b/types/d3-shape/index.d.ts @@ -2436,7 +2436,7 @@ export const symbolTriangle: SymbolType; export const symbolWye: SymbolType; // ----------------------------------------------------------------------------------- -// pointRadius +// pointRadial // ----------------------------------------------------------------------------------- /** @@ -2444,7 +2444,7 @@ export const symbolWye: SymbolType; * @param angle Angle in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. * @param radius Radius. */ -export function pointRadius(angle: number, radius: number): [number, number]; +export function pointRadial(angle: number, radius: number): [number, number]; // ----------------------------------------------------------------------------------- // STACKS diff --git a/types/d3-shape/tslint.json b/types/d3-shape/tslint.json index 604d5950cf..108ab49c45 100644 --- a/types/d3-shape/tslint.json +++ b/types/d3-shape/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { + // TODO + "no-this-assignment": false, "unified-signatures": false, "callable-types": false } diff --git a/types/d3-time-format/d3-time-format-tests.ts b/types/d3-time-format/d3-time-format-tests.ts index 547a77aabe..eb569dd779 100644 --- a/types/d3-time-format/d3-time-format-tests.ts +++ b/types/d3-time-format/d3-time-format-tests.ts @@ -12,8 +12,6 @@ import * as d3TimeFormat from 'd3-time-format'; // Preparatory Steps // ---------------------------------------------------------------------- -let num: number; - let formatFn: (n: Date) => string; let parseFn: (dateString: string) => (Date | null); @@ -38,21 +36,21 @@ parseFn = d3TimeFormat.utcParse('.%L'); // iso ------------------------------------------------------------------ -let dateString: string = d3TimeFormat.isoFormat(new Date(2016, 6, 6)); -let date: Date = d3TimeFormat.isoParse('2016-07-08T14:06:41.386Z'); +const dateString: string = d3TimeFormat.isoFormat(new Date(2016, 6, 6)); +const date: Date = d3TimeFormat.isoParse('2016-07-08T14:06:41.386Z'); // ---------------------------------------------------------------------- // Test Locale Definition // ---------------------------------------------------------------------- -let dateTimeSpecifier: string = localeDef.dateTime; -let dateSpecifier: string = localeDef.date; -let timeSpecifier: string = localeDef.time; -let periods: [string, string] = localeDef.periods; -let days: [string, string, string, string, string, string, string] = localeDef.days; -let shortDays: [string, string, string, string, string, string, string] = localeDef.shortDays; -let months: [string, string, string, string, string, string, string, string, string, string, string, string] = localeDef.months; -let shortMonths: [string, string, string, string, string, string, string, string, string, string, string, string] = localeDef.shortMonths; +const dateTimeSpecifier: string = localeDef.dateTime; +const dateSpecifier: string = localeDef.date; +const timeSpecifier: string = localeDef.time; +const periods: [string, string] = localeDef.periods; +const days: [string, string, string, string, string, string, string] = localeDef.days; +const shortDays: [string, string, string, string, string, string, string] = localeDef.shortDays; +const months: [string, string, string, string, string, string, string, string, string, string, string, string] = localeDef.months; +const shortMonths: [string, string, string, string, string, string, string, string, string, string, string, string] = localeDef.shortMonths; localeDef = { dateTime: '%a %b %e %X %Y', diff --git a/types/d3-time/d3-time-tests.ts b/types/d3-time/d3-time-tests.ts index a99cd818a0..57905d5286 100644 --- a/types/d3-time/d3-time-tests.ts +++ b/types/d3-time/d3-time-tests.ts @@ -11,9 +11,9 @@ import * as d3Time from 'd3-time'; let countableI: d3Time.CountableTimeInterval; let simpleI: d3Time.TimeInterval; let dateArray: Date[]; -let start: Date = new Date(2014, 1, 1, 6, 0, 0, 0); -let end: Date = new Date(2016, 6, 13, 1, 25, 15, 500); -let inBetween: Date = new Date(2015, 6, 13, 1, 30, 5, 700); +const start: Date = new Date(2014, 1, 1, 6, 0, 0, 0); +const end: Date = new Date(2016, 6, 13, 1, 25, 15, 500); +const inBetween: Date = new Date(2015, 6, 13, 1, 30, 5, 700); let resultDate: Date; let count: number; @@ -75,7 +75,7 @@ simpleI = countableI.filter((d: Date) => d.getMonth() === 2); count = countableI.count(start, end); // let countableIOrNull: d3Time.CountableTimeInterval | null = countableI.every(10); // Test fails, since .every(...) return Interval and not CountableInterval -let simpleIOrNull: d3Time.TimeInterval | null = countableI.every(10); +const simpleIOrNull: d3Time.TimeInterval | null = countableI.every(10); resultDate = simpleI.floor(inBetween); resultDate = simpleI.round(inBetween); diff --git a/types/d3-time/index.d.ts b/types/d3-time/index.d.ts index 5e2b66718f..3d88edbf27 100644 --- a/types/d3-time/index.d.ts +++ b/types/d3-time/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.0.4 +// Last module patch version validated against: 1.0.7 // --------------------------------------------------------------- // Interfaces @@ -151,6 +151,8 @@ export interface CountableTimeInterval extends TimeInterval { * * This method can be used in conjunction with interval.range to ensure that two overlapping ranges are consistent. * + * The returned filtered interval does not support interval.count. See also interval.filter. + * * @param step Number of steps. */ every(step: number): TimeInterval | null; diff --git a/types/d3-timer/d3-timer-tests.ts b/types/d3-timer/d3-timer-tests.ts index d3e755ede1..042fc11072 100644 --- a/types/d3-timer/d3-timer-tests.ts +++ b/types/d3-timer/d3-timer-tests.ts @@ -9,7 +9,7 @@ import * as d3Timer from 'd3-timer'; // Test now definition -let now: number = d3Timer.now(); +const now: number = d3Timer.now(); // Test timer and timerFlush definitions ------------ diff --git a/types/d3-tip/index.d.ts b/types/d3-tip/index.d.ts index e820e8120f..5a70a6cf4d 100644 --- a/types/d3-tip/index.d.ts +++ b/types/d3-tip/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Gert Braspenning // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {Primitive} from "d3"; +import { Primitive } from "d3"; declare module "d3" { type TooltipDirection = ("n" | "s" | "e" | "w" | "nw" | "ne" | "sw" | "se"); diff --git a/types/d3-transition/tslint.json b/types/d3-transition/tslint.json index 08b1465cd6..b8825c1674 100644 --- a/types/d3-transition/tslint.json +++ b/types/d3-transition/tslint.json @@ -1,6 +1,8 @@ { "extends": "dtslint/dt.json", "rules": { + // TODO + "no-this-assignment": false, "unified-signatures": false } } diff --git a/types/d3-voronoi/d3-voronoi-tests.ts b/types/d3-voronoi/d3-voronoi-tests.ts index 7dea86241e..434055dc4d 100644 --- a/types/d3-voronoi/d3-voronoi-tests.ts +++ b/types/d3-voronoi/d3-voronoi-tests.ts @@ -24,7 +24,7 @@ interface VoronoiTestDatum { y: number; } -let testData: VoronoiTestDatum[] = [ +const testData: VoronoiTestDatum[] = [ { x: 10, y: 10 }, { x: 20, y: 10 }, { x: 10, y: 20 }, @@ -84,7 +84,7 @@ pointPair = [[10, 10], [50, 50]]; // VoronoiPolygon ------------------------------------------------------- -let voronoiPolygon: d3Voronoi.VoronoiPolygon; +declare const voronoiPolygon: d3Voronoi.VoronoiPolygon; voronoiPolygon[0][0] = 10; // x-coordinate of first point voronoiPolygon[0][1] = 10; // y-coordinate of first point @@ -183,7 +183,7 @@ cell = cells[0]; site = cell.site; -numArray = cell.halfEdges; +numArray = cell.halfedges; // VoronoiSite interface =============================================== @@ -229,7 +229,6 @@ testDatum = link.target; // find() =============================================================== let nearestSite: d3Voronoi.VoronoiSite | null; -let wrongSiteDataType: d3Voronoi.VoronoiSite<[number, number]> | null; // Without search radius nearestSite = voronoiDiagram.find(10, 50); @@ -238,4 +237,4 @@ nearestSite = voronoiDiagram.find(10, 50); nearestSite = voronoiDiagram.find(10, 50, 20); // wrong data type -// wrongSiteDataType = voronoiDiagram.find(10, 50); // fails, due to data type mismatch +// const wrongSiteDataType: d3Voronoi.VoronoiSite<[number, number]> | null; = voronoiDiagram.find(10, 50); // fails, due to data type mismatch diff --git a/types/d3-voronoi/index.d.ts b/types/d3-voronoi/index.d.ts index 1a529e4a71..c3dc03c9de 100644 --- a/types/d3-voronoi/index.d.ts +++ b/types/d3-voronoi/index.d.ts @@ -69,7 +69,7 @@ export interface VoronoiSite extends VoronoiPoint { /** * A Voronoi Cell in the diagram is an object with the following properties: - * site and halfEdges + * site and halfedges * * The generic refers to the type of the data for the corresponding element. */ @@ -81,7 +81,7 @@ export interface VoronoiCell { /** * An array of indexes into diagram.edges representing the cell’s polygon. */ - halfEdges: number[]; + halfedges: number[]; } /** diff --git a/types/d3-zoom/d3-zoom-tests.ts b/types/d3-zoom/d3-zoom-tests.ts index 185b9fd45a..02f7120e79 100644 --- a/types/d3-zoom/d3-zoom-tests.ts +++ b/types/d3-zoom/d3-zoom-tests.ts @@ -385,6 +385,106 @@ svgZoom.translateBy( return 30; }); +// translateTo() ------------------------------------------------------------------------------------- + +// use on selection +svgZoom.translateTo(svgOverlay, 20, 50); +// svgZoom.translateTo(groupsSelection, 20, 50); // fails, as groupSelection mismachtes DOM Element type and datum type + +svgZoom.translateTo( + svgOverlay, + 20, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }); +svgZoom.translateTo( + svgOverlay, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }, + 50); +svgZoom.translateTo( + svgOverlay, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }); + +// use on transition +svgZoom.translateTo(svgOverlayTransition, 20, 50); +// svgZoom.translateTo(groupsTransition, 20, 50); // fails, as groupTransition mismachtes DOM Element type and datum type + +svgZoom.translateTo( + svgOverlayTransition, + 20, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }); +svgZoom.translateTo( + svgOverlayTransition, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }, + 50); +svgZoom.translateTo( + svgOverlayTransition, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }); + // scaleBy() ------------------------------------------------------------------------------------- // use on selection diff --git a/types/d3-zoom/index.d.ts b/types/d3-zoom/index.d.ts index a0980344bb..a633644ded 100644 --- a/types/d3-zoom/index.d.ts +++ b/types/d3-zoom/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for d3JS d3-zoom module 1.3 +// Type definitions for d3JS d3-zoom module 1.5 // Project: https://github.com/d3/d3-zoom/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.3.0 +// Last module patch version validated against: 1.5.0 import { ArrayLike, Selection, TransitionLike, ValueFn } from 'd3-selection'; import { ZoomView, ZoomInterpolator } from 'd3-interpolate'; @@ -127,7 +127,7 @@ export interface ZoomBehavior, x: number, y: number): void; /** * Translates the current zoom transform of the selected elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param x A value function which is evaluated for each selected element, @@ -156,13 +156,13 @@ export interface ZoomBehavior, x: ValueFn, y: number): void; /** * Translates the current zoom transform of the selected elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided as a constant for all elements. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param x Amount of translation in x-direction. @@ -173,13 +173,13 @@ export interface ZoomBehavior, x: number, y: ValueFn): void; /** * Translates the current zoom transform of the selected elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param x A value function which is evaluated for each selected element, @@ -192,13 +192,13 @@ export interface ZoomBehavior, x: ValueFn, y: ValueFn): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided as a constant for all elements. * y is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x Amount of translation in x-direction. @@ -207,13 +207,13 @@ export interface ZoomBehavior, x: number, y: number): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x A value function which is evaluated for each selected element, @@ -224,13 +224,13 @@ export interface ZoomBehavior, x: ValueFn, y: number): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided as a constant for all elements. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x Amount of translation in x-direction. @@ -241,13 +241,13 @@ export interface ZoomBehavior, x: number, y: ValueFn): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x A value function which is evaluated for each selected element, @@ -260,24 +260,158 @@ export interface ZoomBehavior, x: ValueFn, y: ValueFn): void; /** - * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided as a constant for all elements. + * + * @param selection A D3 selection of elements. + * @param x Target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(selection: Selection, x: number, y: number): void; + /** + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided as a constant for all elements. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param selection A D3 selection of elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(selection: Selection, x: ValueFn, y: number): void; + /** + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param selection A D3 selection of elements. + * @param x Target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(selection: Selection, x: number, y: ValueFn): void; + /** + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param selection A D3 selection of elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(selection: Selection, x: ValueFn, y: ValueFn): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided as a constant for all elements. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x Target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(transition: TransitionLike, x: number, y: number): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided as a constant for all elements. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(transition: TransitionLike, x: ValueFn, y: number): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x Target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(transition: TransitionLike, x: number, y: ValueFn): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(transition: TransitionLike, x: ValueFn, y: ValueFn): void; + + /** + * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param k Scale factor. */ scaleBy(selection: Selection, k: number): void; /** - * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param k A value function which is evaluated for each selected element, @@ -286,24 +420,24 @@ export interface ZoomBehavior, k: ValueFn): void; /** - * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param k Scale factor. */ scaleBy(transition: TransitionLike, k: number): void; /** - * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param k A value function which is evaluated for each selected element, @@ -318,7 +452,7 @@ export interface ZoomBehavior, Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/dagre/index.d.ts b/types/dagre/index.d.ts index 7408d145cf..6f008ad1c8 100644 --- a/types/dagre/index.d.ts +++ b/types/dagre/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for dagre 0.7 // Project: https://github.com/cpettitt/dagre -// Definitions by: Qinfeng Chen +// Definitions by: Qinfeng Chen , Lisa Vallfors // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace dagre; @@ -11,16 +11,39 @@ export namespace graphlib { edge(id: any): any; nodes(): string[]; node(id: any): any; - setDefaultEdgeLabel(callback: () => void): Graph; - setEdge(sourceId: string, targetId: string, options?: { [key: string]: any }): Graph; - setGraph(options: { [key: string]: any }): Graph; + setDefaultEdgeLabel(callback: string|(() => string|void)): Graph; + setDefaultNodeLabel(callback: string|(() => string|void)): Graph; + setEdge(sourceId: string, targetId: string, options?: { [key: string]: any }, value?: string): Graph; + setEdge(params: {v: string, w: string, name?: string}, value?: string): Graph; + setGraph(label: GraphLabel): Graph; setNode(id: string, node: { [key: string]: any }): Graph; + graph(): GraphLabel; + + constructor(opt?: {directed?: boolean, multigraph?: boolean, compound?: boolean}); + setParent(name: string, parentName: string): void; + hasNode(name: string): boolean; } } +export interface GraphLabel { + width?: number; + height?: number; + compound?: boolean; + rankdir?: string; + align?: string; + nodesep?: number; + edgesep?: number; + ranksep?: number; + marginx?: number; + marginy?: number; + acyclicer?: string; + ranker?: string; +} + export function layout(graph: graphlib.Graph): void; export interface Edge { v: string; w: string; + name?: string; } diff --git a/types/dargs/dargs-tests.ts b/types/dargs/dargs-tests.ts new file mode 100644 index 0000000000..86ded8a0a8 --- /dev/null +++ b/types/dargs/dargs-tests.ts @@ -0,0 +1,29 @@ +import dargs = require('dargs'); + +const input = { + _: ['some', 'option'], + foo: 'bar', + hello: true, + cake: false, + camelCase: 5, + multiple: ['value', 'value2'], + pieKind: 'cherry', + sad: ':(' +}; + +const excludes = ['sad', /.*Kind$/]; +const includes = ['camelCase', 'multiple', 'sad', /^pie.*/]; +const aliases = {file: 'f'}; + +// $ExpectType string[] +dargs(input, {excludes}); +dargs(input, {excludes, includes}); +dargs(input, {includes}); +dargs({ + foo: 'bar', + hello: true, + file: 'baz' +}, {aliases}); +dargs({foo: 'bar'}, {useEquals: false}); +dargs({foo: 'bar'}, {ignoreFalse: true}); +dargs({fooBar: 'baz'}, {allowCamelCase: true}); diff --git a/types/dargs/index.d.ts b/types/dargs/index.d.ts new file mode 100644 index 0000000000..62ad42a9c1 --- /dev/null +++ b/types/dargs/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for dargs 5.1 +// Project: https://github.com/sindresorhus/dargs#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = dargs; + +declare function dargs(input: object, options?: dargs.Options): string[]; + +declare namespace dargs { + interface Options { + excludes?: ReadonlyArray; + includes?: ReadonlyArray; + aliases?: { [key: string]: string }; + useEquals?: boolean; + ignoreFalse?: boolean; + allowCamelCase?: boolean; + } +} diff --git a/types/dargs/tsconfig.json b/types/dargs/tsconfig.json new file mode 100644 index 0000000000..fd5bee5051 --- /dev/null +++ b/types/dargs/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dargs-tests.ts" + ] +} diff --git a/types/dargs/tslint.json b/types/dargs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dargs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/datatables.net-rowreorder/datatables.net-rowreorder-tests.ts b/types/datatables.net-rowreorder/datatables.net-rowreorder-tests.ts new file mode 100644 index 0000000000..bb0926bfda --- /dev/null +++ b/types/datatables.net-rowreorder/datatables.net-rowreorder-tests.ts @@ -0,0 +1,14 @@ +$(document).ready(() => { + const config: DataTables.Settings = { + // reorder extension options + rowReorder: { + dataSrc: "somesrc", + editor: {}, + enable: true, + formOptions: {}, + selector: "someselector", + snapX: true, + update: true, + }, + }; +}); diff --git a/types/datatables.net-rowreorder/index.d.ts b/types/datatables.net-rowreorder/index.d.ts new file mode 100644 index 0000000000..110da7a747 --- /dev/null +++ b/types/datatables.net-rowreorder/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for JQuery DataTables RowReorder extension 1.1 +// Project: http://datatables.net/extensions/rowreorder/ +// Definitions by: Vincent Biret +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// +/// + +declare namespace DataTables { + interface Settings { + /** + * Enable and configure the RowReorder extension for DataTables + */ + rowReorder?: RowReorderSettings; + } + + interface RowReorderSettings { + /** + * Configure the data point that will be used for the reordering data + */ + dataSrc?: string; + /** + * Attach an Editor instance for database updating + */ + editor?: any; + /** + * Enable / disable RowReorder's user interaction + */ + enable?: boolean; + /** + * Set the options for the Editor form when submitting data + */ + formOptions?: any; + /** + * Define the selector used to pick the elements that will start a drag + */ + selector?: string; + /** + * Horizontal position control of the row being dragged + */ + snapX?: number | boolean; + /** + * Control automatic of data when a row is dropped + */ + update?: boolean; + } +} diff --git a/types/datatables.net-rowreorder/tsconfig.json b/types/datatables.net-rowreorder/tsconfig.json new file mode 100644 index 0000000000..c0b35cadfe --- /dev/null +++ b/types/datatables.net-rowreorder/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "datatables.net-rowreorder-tests.ts" + ] +} \ No newline at end of file diff --git a/types/datatables.net-rowreorder/tslint.json b/types/datatables.net-rowreorder/tslint.json new file mode 100644 index 0000000000..21764ccb0d --- /dev/null +++ b/types/datatables.net-rowreorder/tslint.json @@ -0,0 +1,5 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + } +} \ No newline at end of file diff --git a/types/datatables.net/datatables.net-tests.ts b/types/datatables.net/datatables.net-tests.ts index 8ec7ecb084..f4e322dcfc 100644 --- a/types/datatables.net/datatables.net-tests.ts +++ b/types/datatables.net/datatables.net-tests.ts @@ -12,6 +12,7 @@ $(document).ready(function () { "loadingRecords": "Loading...", "processing": "Processing...", "search": "Search:", + "searchPlaceholder": "Default text", "zeroRecords": "No matching records found", "paginate": { "first": "First", @@ -413,6 +414,7 @@ $(document).ready(function () { var modifier: DataTables.ObjectSelectorModifier = { order: "current", search: "none", + searchPlaceholder: "Default text", page: "all", }; diff --git a/types/datatables.net/index.d.ts b/types/datatables.net/index.d.ts index 68e26ee048..85f6d05857 100644 --- a/types/datatables.net/index.d.ts +++ b/types/datatables.net/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for JQuery DataTables 1.10.9 // Project: http://www.datatables.net -// Definitions by: Kiarash Ghiaseddin , Omid Rad , Armin Sander +// Definitions by: Kiarash Ghiaseddin , Omid Rad , Armin Sander , Denise Mauldin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -145,6 +145,11 @@ declare namespace DataTables { */ search?: string; + /** + * The searchPlaceholder modifier provides the ability to provide informational text for an input control when it has no value. + */ + searchPlaceholder?: string; + /** * The page modifier allows you to control if the selector should consider all data in the table, regardless of paging, or if only the rows in the currently disabled page should be used. * Values: 'all', 'current' @@ -1316,7 +1321,12 @@ declare namespace DataTables { /** * Set an initial filter in DataTables and / or filtering options. Since: 1.10 */ - search?: SearchSettings; + search?: SearchSettings | boolean; + + /** + * Set placeholder attribute for input type="text" tag elements. Since: 1.10 + */ + searchPlaceholder?: SearchSettings; /** * Define an initial search for individual columns. Since: 1.10 @@ -1642,6 +1652,11 @@ declare namespace DataTables { * Set an initial filtering condition on the table. Since: 1.10 */ search?: string; + + /** + * Set a placeholder attribute for input type="text" tag elements. Since: 1.10.1 + */ + searchPlaceholder?: string; } //#endregion "other-settings" @@ -1720,6 +1735,7 @@ declare namespace DataTables { loadingRecords?: string; processing?: string; search?: string; + searchPlaceholder?: string; zeroRecords?: string; paginate?: LanguagePaginateSettings; aria?: LanguageAriaSettings; diff --git a/types/datejs/index.d.ts b/types/datejs/index.d.ts index d7c1854253..1863dc2a6f 100644 --- a/types/datejs/index.d.ts +++ b/types/datejs/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for DateJS // Project: http://www.datejs.com/ -// Definitions by: David Khristepher Santos +// Definitions by: David Khristepher Santos // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped //NOTE: This definition file is for the library located at http://datejs.googlecode.com/svn/ and documented at https://code.google.com/p/datejs/wiki/APIDocumentation diff --git a/types/datejs/sugarpak.d.ts b/types/datejs/sugarpak.d.ts index b4077960ad..b389f2c723 100644 --- a/types/datejs/sugarpak.d.ts +++ b/types/datejs/sugarpak.d.ts @@ -1,6 +1,6 @@ // Type definitions for DateJS - SugarPak Extensions // Project: http://www.datejs.com/ -// Definitions by: David Khristepher Santos +// Definitions by: David Khristepher Santos // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** SugarPak.js - Domain Specific Language - Syntactical Sugar */ diff --git a/types/daterangepicker/index.d.ts b/types/daterangepicker/index.d.ts index 3846ea2472..f01ffd59a3 100644 --- a/types/daterangepicker/index.d.ts +++ b/types/daterangepicker/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for Date Range Picker v2.1.19 +// Type definitions for Date Range Picker v2.1.25 // Project: http://www.daterangepicker.com/ -// Definitions by: SirMartin +// Definitions by: SirMartin +// Steven Masala // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -24,6 +25,10 @@ declare namespace daterangepicker { startDate: moment.Moment; endDate: moment.Moment; + + setStartDate(date: Date | moment.Moment | string): void; + setEndDate(date: Date | moment.Moment | string): void; + remove(): void; } interface DatepickerEventObject extends JQueryEventObject { diff --git a/types/db-migrate-pg/index.d.ts b/types/db-migrate-pg/index.d.ts index 6a72fd1109..09cba26317 100644 --- a/types/db-migrate-pg/index.d.ts +++ b/types/db-migrate-pg/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for db-migrate-pg // Project: https://github.com/db-migrate/pg -// Definitions by: nickiannone +// Definitions by: nickiannone // Definitions: https://github.com/nickiannone/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/deasync/deasync-tests.ts b/types/deasync/deasync-tests.ts new file mode 100644 index 0000000000..982e34c338 --- /dev/null +++ b/types/deasync/deasync-tests.ts @@ -0,0 +1,24 @@ +import * as deasync from "deasync"; + +function asyncFunction(input: number, cb: (res: number) => void) {} +function handle(res: number) {} + +// base case +asyncFunction(42, handle); + +// deasync +const wrapped = deasync(asyncFunction); +handle(wrapped(42)); + +// deasync.loopWhile +let done = false; +asyncFunction(42, () => { + done = true; +}); +deasync.loopWhile(() => !done); + +// deasync.runLoopOnce +deasync.runLoopOnce(); + +// deasync.sleep +deasync.sleep(100); diff --git a/types/deasync/index.d.ts b/types/deasync/index.d.ts new file mode 100644 index 0000000000..20440203e7 --- /dev/null +++ b/types/deasync/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for deasync 0.1 +// Project: https://github.com/abbr/deasync +// Definitions by: Matt Rollins +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = deasync; + +declare function deasync(fn: (...args: any[]) => void): (...args: any[]) => any; +declare namespace deasync { + function loopWhile(pred: () => boolean): void; + function runLoopOnce(): void; + function sleep(ms: number): void; +} diff --git a/types/deasync/tsconfig.json b/types/deasync/tsconfig.json new file mode 100644 index 0000000000..5b96318954 --- /dev/null +++ b/types/deasync/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "deasync-tests.ts" + ] +} diff --git a/types/deasync/tslint.json b/types/deasync/tslint.json new file mode 100644 index 0000000000..c6c6df5352 --- /dev/null +++ b/types/deasync/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} diff --git a/types/debessmann/debessmann-tests.ts b/types/debessmann/debessmann-tests.ts index 802257992e..ab135de254 100644 --- a/types/debessmann/debessmann-tests.ts +++ b/types/debessmann/debessmann-tests.ts @@ -1,9 +1,9 @@ -import {DM, Event, EventId} from 'debessmann'; +import { DM, Event, EventId } from 'debessmann'; -let eventId: EventId = {seq: 0, time: new Date()}; -let e: Event = {_id: eventId, headers: {header1: 'header1Val'}}; +const eventId: EventId = {seq: 0, time: new Date()}; +const e: Event = {_id: eventId, headers: {header1: 'header1Val'}}; -let dm: DM = { +const dm: DM = { init(endpoint: string, auth: string): void { }, send(data: Event): void { diff --git a/types/debug/debug-tests.ts b/types/debug/debug-tests.ts index fc8d3c5e56..73a16fe782 100644 --- a/types/debug/debug-tests.ts +++ b/types/debug/debug-tests.ts @@ -12,6 +12,7 @@ log("Formatted test (%d arg)", 1); log("Formatted %s (%d args)", "test", 2); log("Enabled?: %s", debug.enabled("DefinitelyTyped:log")); +log("Name Enabled: %s", debug.names.some(name => name.test("DefinitelyTyped:log"))); log("Namespace: %s", log.namespace); var error:debug.IDebugger = debug("DefinitelyTyped:error"); diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 45d3ad02f3..8987b13a26 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for debug // Project: https://github.com/visionmedia/debug -// Definitions by: Seon-Wook Park , Gal Talmor +// Definitions by: Seon-Wook Park +// Gal Talmor +// John McLaughlin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var debug: debug.IDebug; @@ -16,8 +18,8 @@ declare namespace debug { enable: (namespaces: string) => void, enabled: (namespaces: string) => boolean, - names: string[], - skips: string[], + names: RegExp[], + skips: RegExp[], formatters: IFormatters } diff --git a/types/decamelize/decamelize-tests.ts b/types/decamelize/decamelize-tests.ts index af35c41943..836c67e64c 100644 --- a/types/decamelize/decamelize-tests.ts +++ b/types/decamelize/decamelize-tests.ts @@ -1,5 +1,4 @@ - import decamelize = require('decamelize'); decamelize('unicornRainbow'); -decamelize('unicornRainbow', '-'); \ No newline at end of file +decamelize('unicornRainbow', '-'); diff --git a/types/decamelize/index.d.ts b/types/decamelize/index.d.ts index 5ee1f76f35..e159cd43bb 100644 --- a/types/decamelize/index.d.ts +++ b/types/decamelize/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for decamelize +// Type definitions for decamelize 1.2 // Project: https://github.com/sindresorhus/decamelize // Definitions by: Sam Verschueren // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = decamelize; declare function decamelize(input: string, separator?: string): string; -declare namespace decamelize { } -export = decamelize; +declare namespace decamelize {} diff --git a/types/decamelize/tsconfig.json b/types/decamelize/tsconfig.json index ac086e266d..31205a3949 100644 --- a/types/decamelize/tsconfig.json +++ b/types/decamelize/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "decamelize-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/decamelize/tslint.json b/types/decamelize/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/decamelize/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/decay/decay-tests.ts b/types/decay/decay-tests.ts index 20f33210ac..af45c63923 100644 --- a/types/decay/decay-tests.ts +++ b/types/decay/decay-tests.ts @@ -1,4 +1,4 @@ -import {redditHot, hackerHot, wilsonScore} from 'decay'; +import { redditHot, hackerHot, wilsonScore } from 'decay'; const upvotes = 42; const downvotes = 12; diff --git a/types/decimal.js/index.d.ts b/types/decimal.js/index.d.ts index 69521a46cc..27f4213612 100644 --- a/types/decimal.js/index.d.ts +++ b/types/decimal.js/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for decimal.js // Project: http://mikemcl.github.io/decimal.js -// Definitions by: Joseph Rossi +// Definitions by: Joseph Rossi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var Decimal: decimal.IDecimalStatic; diff --git a/types/decorum/decorum-tests.ts b/types/decorum/decorum-tests.ts index 8cd03e046c..d6f2565fa5 100644 --- a/types/decorum/decorum-tests.ts +++ b/types/decorum/decorum-tests.ts @@ -1,4 +1,4 @@ -import {Required} from 'decorum'; +import { Required } from 'decorum'; import {Email} from 'decorum'; import {MinLength} from 'decorum'; import {MaxLength} from 'decorum'; diff --git a/types/deep-diff/index.d.ts b/types/deep-diff/index.d.ts index f07fc39ef6..de17a03bc8 100644 --- a/types/deep-diff/index.d.ts +++ b/types/deep-diff/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for deep-diff // Project: https://github.com/flitbit/diff/ -// Definitions by: ZauberNerd +// Definitions by: ZauberNerd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace deepDiff { diff --git a/types/deep-equal/index.d.ts b/types/deep-equal/index.d.ts index d9c4b5f6cf..7451fbc255 100644 --- a/types/deep-equal/index.d.ts +++ b/types/deep-equal/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for deep-equal 1.0 // Project: https://github.com/substack/node-deep-equal -// Definitions by: remojansen , Jay Anslow +// Definitions by: remojansen , Jay Anslow // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface DeepEqualOptions { diff --git a/types/defaults/index.d.ts b/types/defaults/index.d.ts index 024df0558b..717f80a5a7 100644 --- a/types/defaults/index.d.ts +++ b/types/defaults/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for defaults 1.0.3 // Project: https://github.com/tmpvar/defaults/ -// Definitions by: Ibtihel CHNAB +// Definitions by: Ibtihel CHNAB // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare function defaults(options: any, defaultOptions: any): any; diff --git a/types/define-lazy-prop/define-lazy-prop-tests.ts b/types/define-lazy-prop/define-lazy-prop-tests.ts new file mode 100644 index 0000000000..31efb3f861 --- /dev/null +++ b/types/define-lazy-prop/define-lazy-prop-tests.ts @@ -0,0 +1,10 @@ +import defineLazyProp = require('define-lazy-prop'); + +const unicorn = { + foo: 'bar' +}; + +const rainbowUnicorn = defineLazyProp(unicorn, 'rainbow', () => 1); + +rainbowUnicorn.rainbow; // $ExpectType number +rainbowUnicorn.foo; // $ExpectType string diff --git a/types/define-lazy-prop/index.d.ts b/types/define-lazy-prop/index.d.ts new file mode 100644 index 0000000000..4cffe79a66 --- /dev/null +++ b/types/define-lazy-prop/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for define-lazy-prop 1.0 +// Project: https://github.com/sindresorhus/define-lazy-prop#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export = defineLazyProp; + +declare function defineLazyProp(obj: O, prop: P, fn: () => T): O & {[K in P]: T}; diff --git a/types/define-lazy-prop/tsconfig.json b/types/define-lazy-prop/tsconfig.json new file mode 100644 index 0000000000..3a5611afb1 --- /dev/null +++ b/types/define-lazy-prop/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "define-lazy-prop-tests.ts" + ] +} diff --git a/types/define-lazy-prop/tslint.json b/types/define-lazy-prop/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/define-lazy-prop/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/defined/defined-tests.ts b/types/defined/defined-tests.ts new file mode 100644 index 0000000000..5a9d055114 --- /dev/null +++ b/types/defined/defined-tests.ts @@ -0,0 +1,7 @@ +import defined = require('defined'); + +const opts = { x: undefined, y : false, w : 4 }; +// $ExpectType number | boolean | undefined +defined(opts.x, opts.y, opts.w, 100); +// $ExpectType any +defined(opts.x, opts.y, opts.w, 100); diff --git a/types/defined/index.d.ts b/types/defined/index.d.ts new file mode 100644 index 0000000000..1e7f4afc6a --- /dev/null +++ b/types/defined/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for defined 1.0 +// Project: https://github.com/substack/defined +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = defined; + +declare function defined(...args: T[]): T; +declare function defined(...args: any[]): any; diff --git a/types/defined/tsconfig.json b/types/defined/tsconfig.json new file mode 100644 index 0000000000..63c6202b4c --- /dev/null +++ b/types/defined/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "defined-tests.ts" + ] +} diff --git a/types/defined/tslint.json b/types/defined/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/defined/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/deku/index.d.ts b/types/deku/index.d.ts index ff5a68f8bb..595e2521e9 100644 --- a/types/deku/index.d.ts +++ b/types/deku/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for deku v2.0 // Project: https://github.com/anthonyshort/deku -// Definitions by: Sho Fuji +// Definitions by: Sho Fuji // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = deku; diff --git a/types/del/del-tests.ts b/types/del/del-tests.ts index 09702c4b39..fc6c63b6fa 100644 --- a/types/del/del-tests.ts +++ b/types/del/del-tests.ts @@ -3,8 +3,10 @@ import del = require("del"); let paths = ["build", "dist/**/*.js"]; del(["tmp/*.js", "!tmp/unicorn.js"]); - del(["tmp/*.js", "!tmp/unicorn.js"], {force: true}); +del(["tmp/*.js", "!tmp/unicorn.js"], {dryRun: true}); +del(["tmp/*.js", "!tmp/unicorn.js"], {concurrency: 20}); +del(["tmp/*.js", "!tmp/unicorn.js"], {cwd: ''}); del(["tmp/*.js", "!tmp/unicorn.js"]).then((paths: string[]) => { console.log('Deleted files/folders:\n', paths.join('\n')); @@ -15,9 +17,10 @@ del(["tmp/*.js", "!tmp/unicorn.js"], {force: true}).then((paths: string[]) => { }); del("tmp/*.js"); - del("tmp/*.js", {force: true}); - +del("tmp/*.js", {dryRun: true}); +del("tmp/*.js", {concurrency: 20}); +del("tmp/*.js", {cwd: ''}); del("tmp/*.js").then((paths: string[]) => { console.log('Deleted files/folders:\n', paths.join('\n')); }); @@ -27,11 +30,10 @@ del("tmp/*.js", {force: true}).then((paths: string[]) => { }); paths = del.sync(["tmp/*.js", "!tmp/unicorn.js"]); - paths = del.sync(["tmp/*.js", "!tmp/unicorn.js"], {force: true}); paths = del.sync("tmp/*.js"); - paths = del.sync("tmp/*.js", {force: true}); - paths = del.sync("tmp/*.js", {dryRun: true}); +paths = del.sync("tmp/*.js", {concurrency: 20}); +paths = del.sync("tmp/*.js", {cwd: ''}); diff --git a/types/del/index.d.ts b/types/del/index.d.ts index 50634e39eb..e3c250e69b 100644 --- a/types/del/index.d.ts +++ b/types/del/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for del 2.2 +// Type definitions for del 3.0 // Project: https://github.com/sindresorhus/del -// Definitions by: Asana , Aya Morisawa +// Definitions by: Asana +// Aya Morisawa +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import glob = require("glob"); @@ -13,6 +15,7 @@ declare namespace del { interface Options extends glob.IOptions { force?: boolean; dryRun?: boolean; + concurrency?: number; } } diff --git a/types/del/tsconfig.json b/types/del/tsconfig.json index dd4981bd08..ba10982e67 100644 --- a/types/del/tsconfig.json +++ b/types/del/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "del-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/del/tslint.json b/types/del/tslint.json index 3db14f85ea..26bcea6634 100644 --- a/types/del/tslint.json +++ b/types/del/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "dt-header": false + } +} diff --git a/types/del/v2/del-tests.ts b/types/del/v2/del-tests.ts new file mode 100644 index 0000000000..09702c4b39 --- /dev/null +++ b/types/del/v2/del-tests.ts @@ -0,0 +1,37 @@ +import del = require("del"); + +let paths = ["build", "dist/**/*.js"]; + +del(["tmp/*.js", "!tmp/unicorn.js"]); + +del(["tmp/*.js", "!tmp/unicorn.js"], {force: true}); + +del(["tmp/*.js", "!tmp/unicorn.js"]).then((paths: string[]) => { + console.log('Deleted files/folders:\n', paths.join('\n')); +}); + +del(["tmp/*.js", "!tmp/unicorn.js"], {force: true}).then((paths: string[]) => { + console.log('Deleted files/folders:\n', paths.join('\n')); +}); + +del("tmp/*.js"); + +del("tmp/*.js", {force: true}); + +del("tmp/*.js").then((paths: string[]) => { + console.log('Deleted files/folders:\n', paths.join('\n')); +}); + +del("tmp/*.js", {force: true}).then((paths: string[]) => { + console.log('Deleted files/folders:\n', paths.join('\n')); +}); + +paths = del.sync(["tmp/*.js", "!tmp/unicorn.js"]); + +paths = del.sync(["tmp/*.js", "!tmp/unicorn.js"], {force: true}); + +paths = del.sync("tmp/*.js"); + +paths = del.sync("tmp/*.js", {force: true}); + +paths = del.sync("tmp/*.js", {dryRun: true}); diff --git a/types/del/v2/index.d.ts b/types/del/v2/index.d.ts new file mode 100644 index 0000000000..50634e39eb --- /dev/null +++ b/types/del/v2/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for del 2.2 +// Project: https://github.com/sindresorhus/del +// Definitions by: Asana , Aya Morisawa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import glob = require("glob"); + +declare function del(patterns: string | string[], options?: del.Options): Promise; + +declare namespace del { + function sync(patterns: string | string[], options?: Options): string[]; + + interface Options extends glob.IOptions { + force?: boolean; + dryRun?: boolean; + } +} + +export = del; diff --git a/types/del/v2/tsconfig.json b/types/del/v2/tsconfig.json new file mode 100644 index 0000000000..4ec5576309 --- /dev/null +++ b/types/del/v2/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "del": ["del/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "del-tests.ts" + ] +} diff --git a/types/del/v2/tslint.json b/types/del/v2/tslint.json new file mode 100644 index 0000000000..65c83fb1e3 --- /dev/null +++ b/types/del/v2/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "dt-header": false + } +} diff --git a/types/delaunator/tslint.json b/types/delaunator/tslint.json index 3db14f85ea..f2ffe2445b 100644 --- a/types/delaunator/tslint.json +++ b/types/delaunator/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-duplicate-imports": false + } +} diff --git a/types/delay/delay-tests.ts b/types/delay/delay-tests.ts new file mode 100644 index 0000000000..9714bfd86d --- /dev/null +++ b/types/delay/delay-tests.ts @@ -0,0 +1,47 @@ +import delay = require('delay'); + +delay(200) + .then(() => { + }); + +let str: string; +let num: number; +Promise.resolve(delay(100)) + .then(() => { + }); + +Promise.resolve("foo") + .then(delay(100)) + .then(result => { + str = result; + }); + +Promise.resolve('foo') + .then(delay(100, 10)) + .then(result => { + num = result; + }); + +Promise.resolve('foo') + .then(delay.reject(100)) + .then(x => 10) + .catch(err => { + }); + +Promise.resolve('foo') + .then(delay.reject(100, 'bar')) + .then(x => 10) + .catch(err => { + }); + +(async () => { + const delaying = delay(1000); + delaying.cancel(); + try { + await delaying; + } catch (err) { + // `err` is an instance of `delay.CancelError` + } +})(); + +throw new delay.CancelError('bar'); diff --git a/types/delay/index.d.ts b/types/delay/index.d.ts new file mode 100644 index 0000000000..f84c7ab5e4 --- /dev/null +++ b/types/delay/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for delay 2.0 +// Project: https://github.com/sindresorhus/delay#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export = delay; + +declare function delay(ms: number): delay.PDelayedPassThroughThunk; +declare function delay(ms: number, value: T): delay.PDelayedThunk; + +declare namespace delay { + function reject(ms: number, rejectionValue?: any): PDelayedThunk; + + class CancelError extends Error { + readonly name: 'CancelError'; + constructor(message?: string); + } + + type PDelayedThunk = ((value: any) => DelayedPromiseLike) & DelayedPromiseLike; + + type PDelayedPassThroughThunk = ((value: TValue) => DelayedPromiseLike) & DelayedPromiseLike; + + interface DelayedPromiseLike { + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, + onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise; + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise; + cancel(): void; + } +} diff --git a/types/delay/tsconfig.json b/types/delay/tsconfig.json new file mode 100644 index 0000000000..2004ba50ba --- /dev/null +++ b/types/delay/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "delay-tests.ts" + ] +} diff --git a/types/delay/tslint.json b/types/delay/tslint.json new file mode 100644 index 0000000000..21fecfef93 --- /dev/null +++ b/types/delay/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "await-promise": false + } +} diff --git a/types/denodeify/index.d.ts b/types/denodeify/index.d.ts index d5283bf777..4c180e63d8 100644 --- a/types/denodeify/index.d.ts +++ b/types/denodeify/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for denodeify 1.2.1 // Project: https://github.com/matthew-andrews/denodeify -// Definitions by: joaomoreno +// Definitions by: joaomoreno // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/depd/index.d.ts b/types/depd/index.d.ts index 147393a332..0db1d877f6 100644 --- a/types/depd/index.d.ts +++ b/types/depd/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for depd 1.1.0 // Project: https://github.com/dougwilson/nodejs-depd -// Definitions by: Zhiyuan Wang +// Definitions by: Zhiyuan Wang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/destroy-on-hwm/destroy-on-hwm-tests.ts b/types/destroy-on-hwm/destroy-on-hwm-tests.ts new file mode 100644 index 0000000000..9c32a27e26 --- /dev/null +++ b/types/destroy-on-hwm/destroy-on-hwm-tests.ts @@ -0,0 +1,10 @@ +import { PassThrough } from 'stream'; +import destroyOnHWM = require('destroy-on-hwm'); + +const stream = new PassThrough(); + +destroyOnHWM(stream); // $ExpectType PassThrough +destroyOnHWM(stream, function(stream) { + this; // $ExpectType PassThrough + stream; // $ExpectType PassThrough +}); diff --git a/types/destroy-on-hwm/index.d.ts b/types/destroy-on-hwm/index.d.ts new file mode 100644 index 0000000000..5c5dcb43e9 --- /dev/null +++ b/types/destroy-on-hwm/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for destroy-on-hwm 1.0 +// Project: https://github.com/stream-utils/destroy-on-hwm +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// +import { Writable } from 'stream'; + +export = destroyOnHwm; + +declare function destroyOnHwm(stream: T, callback?: (this: T, stream: T) => void): T; diff --git a/types/destroy-on-hwm/tsconfig.json b/types/destroy-on-hwm/tsconfig.json new file mode 100644 index 0000000000..9bcad7ee9b --- /dev/null +++ b/types/destroy-on-hwm/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "destroy-on-hwm-tests.ts" + ] +} diff --git a/types/destroy-on-hwm/tslint.json b/types/destroy-on-hwm/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/destroy-on-hwm/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/destroy/destroy-tests.ts b/types/destroy/destroy-tests.ts new file mode 100644 index 0000000000..15dbe62e32 --- /dev/null +++ b/types/destroy/destroy-tests.ts @@ -0,0 +1,9 @@ +import destroy = require('destroy'); +import * as fs from 'fs'; + +const stream = fs.createReadStream('package.json'); + +// $ExpectType ReadStream +destroy(stream); +// $ExpectType WriteStream +destroy(process.stderr); diff --git a/types/destroy/index.d.ts b/types/destroy/index.d.ts new file mode 100644 index 0000000000..7427655ace --- /dev/null +++ b/types/destroy/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for destroy 1.0 +// Project: https://github.com/stream-utils/destroy +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import { Stream } from 'stream'; + +export = destroy; + +declare function destroy(stream: T): T; diff --git a/types/destroy/tsconfig.json b/types/destroy/tsconfig.json new file mode 100644 index 0000000000..197ac0c669 --- /dev/null +++ b/types/destroy/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "destroy-tests.ts" + ] +} diff --git a/types/destroy/tslint.json b/types/destroy/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/destroy/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/detect-indent/detect-indent-tests.ts b/types/detect-indent/detect-indent-tests.ts index 166b89d1ec..dc962b86fc 100644 --- a/types/detect-indent/detect-indent-tests.ts +++ b/types/detect-indent/detect-indent-tests.ts @@ -1,7 +1,9 @@ +import detectIndent = require('detect-indent'); -import di = require('detect-indent'); +const indent = detectIndent('').indent || ' '; -var str: string; - -str = di(str); -str = di(str, str); +const indentInfo = detectIndent(''); +indentInfo; // $ExpectType IndentInfo +const num: number = indentInfo.amount; +const str: string = indentInfo.indent; +const type: 'space' | 'tab' | null = indentInfo.type; diff --git a/types/detect-indent/index.d.ts b/types/detect-indent/index.d.ts index 15e82d0015..7c1838ce10 100644 --- a/types/detect-indent/index.d.ts +++ b/types/detect-indent/index.d.ts @@ -1,11 +1,17 @@ -// Type definitions for detect-indent 0.1.3 +// Type definitions for detect-indent 5.0 // Project: https://github.com/sindresorhus/detect-indent // Definitions by: Bart van der Schoor +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +export = detectIndent; -interface DetectIndent { - (dir: string, alt?: string): string; +declare function detectIndent(str: string): detectIndent.IndentInfo; + +declare namespace detectIndent { + interface IndentInfo { + amount: number; + type: 'tab' | 'space' | null; + indent: string; + } } -declare var _: DetectIndent; -export = _; diff --git a/types/detect-indent/tsconfig.json b/types/detect-indent/tsconfig.json index 4eae731f48..07d6d5adc2 100644 --- a/types/detect-indent/tsconfig.json +++ b/types/detect-indent/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "detect-indent-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/detect-indent/tslint.json b/types/detect-indent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/detect-indent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/detect-indent/v0/detect-indent-tests.ts b/types/detect-indent/v0/detect-indent-tests.ts new file mode 100644 index 0000000000..4bb8171494 --- /dev/null +++ b/types/detect-indent/v0/detect-indent-tests.ts @@ -0,0 +1,6 @@ +import di = require('detect-indent'); + +let str = ''; + +str = di(str); +str = di(str, str); diff --git a/types/detect-indent/v0/index.d.ts b/types/detect-indent/v0/index.d.ts new file mode 100644 index 0000000000..17e8459281 --- /dev/null +++ b/types/detect-indent/v0/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for detect-indent 0.1 +// Project: https://github.com/sindresorhus/detect-indent +// Definitions by: Bart van der Schoor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type DetectIndent = (dir: string, alt?: string) => string; + +declare const _: DetectIndent; +export = _; diff --git a/types/detect-indent/v0/tsconfig.json b/types/detect-indent/v0/tsconfig.json new file mode 100644 index 0000000000..f80769f598 --- /dev/null +++ b/types/detect-indent/v0/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "detect-indent": ["detect-indent/v0"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "detect-indent-tests.ts" + ] +} diff --git a/types/detect-indent/v0/tslint.json b/types/detect-indent/v0/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/detect-indent/v0/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/detect-newline/detect-newline-tests.ts b/types/detect-newline/detect-newline-tests.ts new file mode 100644 index 0000000000..b660d01ffc --- /dev/null +++ b/types/detect-newline/detect-newline-tests.ts @@ -0,0 +1,7 @@ +import detectNewline = require('detect-newline'); + +const res1 = detectNewline('foo\nbar\nbaz\r\n'); +res1; // $ExpectType "\r\n" | "\n" | null + +const res2 = detectNewline.graceful('foo\nbar\nbaz\r\n'); +res2; // $ExpectType "\r\n" | "\n" diff --git a/types/detect-newline/index.d.ts b/types/detect-newline/index.d.ts new file mode 100644 index 0000000000..4a7aaad673 --- /dev/null +++ b/types/detect-newline/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for detect-newline 2.1 +// Project: https://github.com/sindresorhus/detect-newline#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = detectNewline; + +declare function detectNewline(str: string): '\r\n' | '\n' | null; + +declare namespace detectNewline { + function graceful(str: string): '\r\n' | '\n'; +} diff --git a/types/detect-newline/tsconfig.json b/types/detect-newline/tsconfig.json new file mode 100644 index 0000000000..bbb57f1823 --- /dev/null +++ b/types/detect-newline/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "detect-newline-tests.ts" + ] +} diff --git a/types/detect-newline/tslint.json b/types/detect-newline/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/detect-newline/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/detect-port/detect-port-tests.ts b/types/detect-port/detect-port-tests.ts index 759313665b..afd532ead0 100644 --- a/types/detect-port/detect-port-tests.ts +++ b/types/detect-port/detect-port-tests.ts @@ -1,6 +1,6 @@ import * as detect from "detect-port"; -const port: number = 8000; +const port = 8000; /** * callback usage diff --git a/types/dhtmlxgantt/index.d.ts b/types/dhtmlxgantt/index.d.ts index f94ba88a33..53626662ec 100644 --- a/types/dhtmlxgantt/index.d.ts +++ b/types/dhtmlxgantt/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for dhtmlxGantt 4.0.0 // Project: http://dhtmlx.com/docs/products/dhtmlxGantt -// Definitions by: Maksim Kozhukh , Christophe Camicas +// Definitions by: Maksim Kozhukh , Christophe Camicas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/dhtmlxscheduler/index.d.ts b/types/dhtmlxscheduler/index.d.ts index 2a5ff01c87..96c9670a4d 100644 --- a/types/dhtmlxscheduler/index.d.ts +++ b/types/dhtmlxscheduler/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for dhtmlxScheduler 4.3.0 // Project: http://dhtmlx.com/docs/products/dhtmlxScheduler -// Definitions by: Maksim Kozhukh +// Definitions by: Maksim Kozhukh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface SchedulerCallback { (...args: any[]): any } diff --git a/types/di-lite/di-lite-tests.ts b/types/di-lite/di-lite-tests.ts index efe45738ae..37d220fc6d 100644 --- a/types/di-lite/di-lite-tests.ts +++ b/types/di-lite/di-lite-tests.ts @@ -7,13 +7,13 @@ interface Dependency { function doTest(test: (ctx: any, ...obj: Dependency[]) => void) { // create di context var ctx = di.createContext(), - A: Dependency = () => { - this.dependencies = "b, c"; + A: Dependency = { + dependencies: "b, c", }, - B: Dependency = () => { - this.dependencies = "c"; + B: Dependency = { + dependencies: "c", }, - C: Dependency = () => {}; + C: Dependency = {}; // register a class with an unique name ctx.register("a", A); diff --git a/types/diacritics/diacritics-tests.ts b/types/diacritics/diacritics-tests.ts new file mode 100644 index 0000000000..c6419c8593 --- /dev/null +++ b/types/diacritics/diacritics-tests.ts @@ -0,0 +1,12 @@ +import * as diacritics from "diacritics"; + +const replacementListItem = diacritics.replacementList[1]; + +// tslint:disable-next-line:no-unused-expression +replacementListItem.base === "0"; +replacementListItem.chars === "\u07C0"; + +const mapItem = diacritics.diacriticsMap["A"]; + +// tslint:disable-next-line:no-unused-expression +diacritics.remove("foo") === "bar"; diff --git a/types/diacritics/index.d.ts b/types/diacritics/index.d.ts new file mode 100644 index 0000000000..c25988cb37 --- /dev/null +++ b/types/diacritics/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for diacritics 1.3 +// Project: https://github.com/andrewrk/node-diacritics +// Definitions by: Oto Ciulis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function remove(str: string): string; +export const replacementList: Array<{ + base: string; + chars: string; +}>; + +export const diacriticsMap: { + [key: string]: string; +}; diff --git a/types/diacritics/tsconfig.json b/types/diacritics/tsconfig.json new file mode 100644 index 0000000000..c5df557fe5 --- /dev/null +++ b/types/diacritics/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "diacritics-tests.ts" + ] +} \ No newline at end of file diff --git a/types/diacritics/tslint.json b/types/diacritics/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/diacritics/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/diff/diff-tests.ts b/types/diff/diff-tests.ts index e1b1025495..e787c44f48 100644 --- a/types/diff/diff-tests.ts +++ b/types/diff/diff-tests.ts @@ -1,14 +1,13 @@ -// tslint:disable:no-var only-arrow-functions import jsdiff = require('diff'); -var one = 'beep boop'; -var other = 'beep boob blah'; +const one = 'beep boop'; +const other = 'beep boob blah'; -var diff = jsdiff.diffChars(one, other); +let diff = jsdiff.diffChars(one, other); -diff.forEach(function(part) { - var mark = part.added ? '+' : +diff.forEach(part => { + const mark = part.added ? '+' : part.removed ? '-' : ' '; - console.log(mark + " " + part.value); + console.log(`${mark} ${part.value}`); }); // -------------------------- @@ -23,8 +22,8 @@ class LineDiffWithoutWhitespace extends jsdiff.Diff { } } -var obj = new LineDiffWithoutWhitespace(true); -var diff = obj.diff(one, other); +const obj = new LineDiffWithoutWhitespace(true); +diff = obj.diff(one, other); printDiff(diff); function printDiff(diff: jsdiff.IDiffResult[]) { @@ -50,7 +49,7 @@ function printDiff(diff: jsdiff.IDiffResult[]) { } function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { - var verifyPatch = jsdiff.parsePatch( + const verifyPatch = jsdiff.parsePatch( jsdiff.createTwoFilesPatch("oldFile.ts", "newFile.ts", oldStr, newStr, "old", "new", { context: 1 })); if (JSON.stringify(verifyPatch) !== JSON.stringify(uniDiff)) { @@ -58,7 +57,7 @@ function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUni } } function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUniDiff) { - var verifyApply = [ + const verifyApply = [ jsdiff.applyPatch(oldStr, uniDiff), jsdiff.applyPatch(oldStr, [uniDiff]) ]; @@ -83,7 +82,7 @@ function verifyApplyMethods(oldStr: string, newStr: string, uniDiff: jsdiff.IUni }); } -verifyPatchMethods(one, other, uniDiff); -var uniDiff = jsdiff.structuredPatch("oldFile.ts", "newFile.ts", one, other, +const uniDiff = jsdiff.structuredPatch("oldFile.ts", "newFile.ts", one, other, "old", "new", { context: 1 }); +verifyPatchMethods(one, other, uniDiff); verifyApplyMethods(one, other, uniDiff); diff --git a/types/diff/index.d.ts b/types/diff/index.d.ts index 03228269e0..49975756f4 100644 --- a/types/diff/index.d.ts +++ b/types/diff/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for diff 3.2 // Project: https://github.com/kpdecker/jsdiff -// Definitions by: vvakame +// Definitions by: vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 diff --git a/types/diff2html/index.d.ts b/types/diff2html/index.d.ts index 398cb1aba1..ce2522d444 100644 --- a/types/diff2html/index.d.ts +++ b/types/diff2html/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for diff2html // Project: https://github.com/rtfpessoa/diff2html -// Definitions by: rtfpessoa +// Definitions by: rtfpessoa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Diff2Html { diff --git a/types/dockerode/dockerode-tests.ts b/types/dockerode/dockerode-tests.ts index ef2ed924d1..14ea3ca639 100644 --- a/types/dockerode/dockerode-tests.ts +++ b/types/dockerode/dockerode-tests.ts @@ -74,6 +74,10 @@ docker.buildImage('archive.tar', { t: 'imageName' }, (err, response) => { // NOOP }); +docker.buildImage({context: '.', src: ['Dockerfile', 'test.sh']}, { t: 'imageName' }, (err, response) => { + // NOOP +}); + docker.createContainer({ Tty: true }, (err, container) => { container.start((err, data) => { // NOOP diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index 1b456e8f45..aa6c03bf29 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for dockerode 2.4 // Project: https://github.com/apocas/dockerode -// Definitions by: Carl Winkler , Nicolas Laplante +// Definitions by: Carl Winkler +// Nicolas Laplante +// ByeongHun Yoo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -427,6 +429,15 @@ declare namespace Dockerode { GlobalIPv6PrefixLen: number; MacAddress: string; } + }; + Node?: { + ID: string; + IP: string; + Addr: string; + Name: string; + Cpus: number; + Memory: number; + Labels: any; } }; } @@ -795,6 +806,11 @@ declare namespace Dockerode { tail?: number; timestamps?: boolean; } + + interface ImageBuildContext { + context: string; + src: string[]; + } } type Callback = (error?: any, result?: T) => void; @@ -821,9 +837,9 @@ declare class Dockerode { checkAuth(options: any, callback: Callback): void; checkAuth(options: any): Promise; - buildImage(file: string | NodeJS.ReadableStream, options: {}, callback: Callback): void; - buildImage(file: string | NodeJS.ReadableStream, callback: Callback): void; - buildImage(file: string | NodeJS.ReadableStream, options?: {}): Promise; + buildImage(file: string | NodeJS.ReadableStream | Dockerode.ImageBuildContext, options: {}, callback: Callback): void; + buildImage(file: string | NodeJS.ReadableStream | Dockerode.ImageBuildContext, callback: Callback): void; + buildImage(file: string | NodeJS.ReadableStream | Dockerode.ImageBuildContext, options?: {}): Promise; getContainer(id: string): Dockerode.Container; diff --git a/types/dockerode/tslint.json b/types/dockerode/tslint.json index 3db14f85ea..aac1f69ee8 100644 --- a/types/dockerode/tslint.json +++ b/types/dockerode/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "await-promise": false + } +} diff --git a/types/docopt/index.d.ts b/types/docopt/index.d.ts index a40904bf76..8d8b23a0c0 100644 --- a/types/docopt/index.d.ts +++ b/types/docopt/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Docopt v0.6.2 // Project: http://docopt.org/ -// Definitions by: Giovanni Bassi +// Definitions by: Giovanni Bassi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** diff --git a/types/documentdb-server/documentdb-server-tests.ts b/types/documentdb-server/documentdb-server-tests.ts index aa5c45b73d..d4e8e7f40c 100644 --- a/types/documentdb-server/documentdb-server-tests.ts +++ b/types/documentdb-server/documentdb-server-tests.ts @@ -20,10 +20,12 @@ function filter() { .value(); if (!result.isAccepted) throw new Error("The call was not accepted"); // Example 3: get document (person) with id = 1 and delete it. - var result: IQueryResponse = __.filter(function (doc: any) { return doc.id === 1; }, function (err: IFeedCallbackError, feed: Array, options: IFeedCallbackOptions) { - if (err) throw err; - if (!__.deleteDocument(feed[0].getSelfLink())) throw new Error("deleteDocument was not accepted"); - }); + var result: IQueryResponse = __.filter( + function (doc: any) { return doc.id === 1; }, + function (err: IFeedCallbackError, feed: Array, options: IFeedCallbackOptions) { + if (err) throw err; + if (!__.deleteDocument(feed[0].getSelfLink())) throw new Error("deleteDocument was not accepted"); + }); if (!result.isAccepted) throw new Error("The call was not accepted"); } function flatten() { @@ -103,7 +105,7 @@ function value() { // Samples taken from https://github.com/Azure/azure-documentdb-js-server/tree/master/samples /** * This script called as stored procedure to import lots of documents in one batch. -* The script sets response body to the number of docs imported and is called multiple times +* The script sets response body to the number of docs imported and is called multiple times * by the client until total number of docs desired by the client is imported. * @param {Object[]} docs - Array of documents to import. */ @@ -127,7 +129,7 @@ function bulkImport(docs: Array) { tryCreate(docs[count], callback); // Note that there are 2 exit conditions: - // 1) The createDocument request was not accepted. + // 1) The createDocument request was not accepted. // In this case the callback will not be called, we just call setBody and we are done. // 2) The callback was called docs.length times. // In this case all documents were created and we don't need to call tryCreate anymore. Just call setBody and we are done. @@ -135,7 +137,7 @@ function bulkImport(docs: Array) { var isAccepted = collection.createDocument(collectionLink, doc, callback); // If the request was accepted, callback will be called. - // Otherwise report current count back to the client, + // Otherwise report current count back to the client, // which will call the script again with remaining set of docs. // This condition will happen when this stored procedure has been running too long // and is about to get cancelled by the server. This will allow the calling client @@ -164,7 +166,7 @@ function bulkImport(docs: Array) { * This is executed as stored procedure to count the number of docs in the collection. * To avoid script timeout on the server when there are lots of documents (100K+), the script executed in batches, * each batch counts docs to some number and returns continuation token. -* The script is run multiple times, starting from empty continuation, +* The script is run multiple times, starting from empty continuation, * then using continuation returned by last invocation script until continuation returned by the script is null/empty string. * * @param {String} filterQuery - Optional filter for query (e.g. "SELECT * FROM docs WHERE docs.category = 'food'"). @@ -172,7 +174,7 @@ function bulkImport(docs: Array) { */ function count(filterQuery: string, continuationToken: string) { var collection: ICollection = getContext().getCollection(); - var maxResult: number = 25; // MAX number of docs to process in one batch, when reached, return to client/request continuation. + var maxResult: number = 25; // MAX number of docs to process in one batch, when reached, return to client/request continuation. // intentionally set low to demonstrate the concept. This can be much higher. Try experimenting. // We've had it in to the high thousands before seeing the stored proceudre timing out. @@ -186,7 +188,7 @@ function count(filterQuery: string, continuationToken: string) { var responseOptions: Object = { continuation: nextContinuationToken, pageSize: maxResult }; // In case the server is running this script for long time/near timeout, it would return false, - // in this case we set the response to current continuation token, + // in this case we set the response to current continuation token, // and the client will run this script again starting from this continuation. // When the client calls this script 1st time, is passes empty continuation token. if (result >= maxResult || !query(responseOptions)) { @@ -210,7 +212,7 @@ function count(filterQuery: string, continuationToken: string) { // Increament the number of documents counted so far. result += docFeed.length; - // If there is continuation, call query again with it, + // If there is continuation, call query again with it, // otherwise we are done, in which case set continuation to null. if (responseOptions.continuation) { tryQuery(responseOptions.continuation); @@ -324,7 +326,7 @@ function orderBy(filterQuery: string, orderByFieldName: string, continuationToke break; } } - + // Now next batch to return to client has i elements. // Slice the continuationResult if needed and discard the end. var partialResult: Array = continuationResult; @@ -341,7 +343,7 @@ function orderBy(filterQuery: string, orderByFieldName: string, continuationToke /** * This is run as stored procedure and does the following: -* - get 1st document in the collection, convert to JSON, prepend string specified by the prefix parameter +* - get 1st document in the collection, convert to JSON, prepend string specified by the prefix parameter * and set response to the result of that. * * @param {String} prefix - The string to prepend to the 1st document in collection. @@ -750,8 +752,8 @@ function updateSproc(id: string, update: Object) { /** * A DocumentDB stored procedure that upserts a given document (insert new or update if present) using its id property.
      - * This implementation tries to create, and if the create fails then query for the document with the specified document's id, then replace it. - * Use this sproc if creates are more common than replaces, otherwise use "upsertOptimizedForReplace" + * This implementation tries to create, and if the create fails then query for the document with the specified document's id, then replace it. + * Use this sproc if creates are more common than replaces, otherwise use "upsertOptimizedForReplace" * * @function * @param {Object} document - A document that should be upserted into this collection. @@ -820,7 +822,7 @@ function upsert(document: IDocumentMeta) { /** * A DocumentDB stored procedure that upserts a given document (insert new or update if present) using its id property.
      * This implementation queries for the document's id, and creates if absent and replaces if found. - * Use this sproc if replaces are more common than creates, otherwise use "upsert" + * Use this sproc if replaces are more common than creates, otherwise use "upsert" * * @function * @param {Object} document - A document that should be upserted into this collection. @@ -941,17 +943,17 @@ function updateMetadata() { // for 1st document use doc.Size, for all the rest see if it's less than last min. if (metaDoc.minSize == 0) metaDoc.minSize = doc.size; else metaDoc.minSize = Math.min(metaDoc.minSize, doc.size); - + // Update metaDoc.maxSize. metaDoc.maxSize = Math.max(metaDoc.maxSize, doc.size); // Update metaDoc.totalSize. metaDoc.totalSize += doc.size; - + // Update/replace the metadata document in the store. var isAccepted: boolean = collection.replaceDocument(metaDoc._self, metaDoc, function (err: IRequestCallbackError) { if (err) throw err; - // Note: in case concurrent updates causes conflict with ErrorCode.RETRY_WITH, we can't read the meta again + // Note: in case concurrent updates causes conflict with ErrorCode.RETRY_WITH, we can't read the meta again // and update again because due to Snapshot isolation we will read same exact version (we are in same transaction). // We have to take care of that on the client side. }); diff --git a/types/documentdb-server/index.d.ts b/types/documentdb-server/index.d.ts index 907fbd3d8c..974c0661fa 100644 --- a/types/documentdb-server/index.d.ts +++ b/types/documentdb-server/index.d.ts @@ -36,6 +36,8 @@ interface IQueryAPI { * @param options Optional query options. Should not be used in a chained call. * @param callback Optional callback for the operation. If no callback is provided, any error in the operation will be thrown and the result document set will be written to the Response body. Should not be used in a chained call. */ + filter(predicate: (document: Object) => boolean, + callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; filter(predicate: (document: Object) => boolean, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; @@ -49,6 +51,8 @@ interface IQueryAPI { * @param options Optional query options. Should not be used in a chained call. * @param callback Optional callback for the operation. If no callback is provided, any error in the operation will be thrown and the result document set will be written to the Response body. Should not be used in a chained call. */ + map(predicate: (document: Object) => Object, + callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; map(predicate: (document: Object) => Object, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; @@ -62,6 +66,8 @@ interface IQueryAPI { * @param options Optional query options. Should not be used in a chained call. * @param callback Optional callback for the operation. If no callback is provided, any error in the operation will be thrown and the result document set will be written to the Response body. Should not be used in a chained call. */ + pluck(propertyName: string, + callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; pluck(propertyName: string, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; @@ -75,6 +81,8 @@ interface IQueryAPI { * @param options Optional query options. Should not be used in a chained call. * @param callback Optional callback for the operation. If no callback is provided, any error in the operation will be thrown and the result document set will be written to the Response body. Should not be used in a chained call. */ + flatten(isShallow?: boolean, + callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; flatten(isShallow?: boolean, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; @@ -88,16 +96,12 @@ interface IQueryAPI { * @param options Optional query options. Should not be used in a chained call. * @param Optional callback for the operation. If no callback is provided, any error in the operation will be thrown and the result document set will be written to the Response body. Should not be used in a chained call. */ - sortBy(predicate: (document: Object) => string, + sortBy(predicate: (document: Object) => string | number, + callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; + sortBy(predicate: (document: Object) => string | number, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; - sortBy(predicate: (document: Object) => number, - options?: IFeedOptions, - callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; - sortBy(predicate: (document: Object) => string, - options?: IFeedOptions, - callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; - sortBy(predicate: (document: Object) => number, + sortBy(predicate: (document: Object) => string | number, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; /** @@ -107,16 +111,12 @@ interface IQueryAPI { * @param options Optional query options. Should not be used in a chained call. * @param callback Optional callback for the operation. If no callback is provided, any error in the operation will be thrown and the result document set will be written to the Response body. Should not be used in a chained call. */ - sortByDescending(predicate: (document: Object) => string, + sortByDescending(predicate: (document: Object) => string | number, + callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; + sortByDescending(predicate: (document: Object) => string | number, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; - sortByDescending(predicate: (document: Object) => number, - options?: IFeedOptions, - callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; - sortByDescending(predicate: (document: Object) => string, - options?: IFeedOptions, - callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; - sortByDescending(predicate: (document: Object) => number, + sortByDescending(predicate: (document: Object) => string | number, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; /** @@ -125,19 +125,20 @@ interface IQueryAPI { * @param options Optional query options for the entire chained call. * @param callback Optional callback for the operation. If no callback is provided, any error in the operation will be thrown and the result document set will be written to the Response body. */ + value(callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; value(options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; value(options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): IQueryResponse; } - + /** * Stored procedures and triggers are registered for a particular collection. The Collection object supports create, read, update and delete (CRUD) and query operations on documents and attachments in the current collection. * All collection operations are completed asynchronously. You can provide a callback to handle the result of the operation, and to perform error handling if necessary. * Stored procedures and triggers are executed in a time-limited manner. Long-running stored procedures and triggers are defensively timed out and all transactions performed are rolled back. * We stop queuing collection operations if the stored procedure is close to timing out. You can inspect the boolean return value of all collection operations to see if an operation was not queued and handle this situation gracefully. */ -interface ICollection extends IQueryAPI { +interface ICollection extends IQueryAPI { /** Opening call to start a chained query. Should be used in conjunction with the closing value call to perform chained queries. */ chain(): IQueryResponse; @@ -148,11 +149,14 @@ interface ICollection extends IQueryAPI { * @param options optional create options * @param callback optional callback for the operation. If no callback is provided, any error in the operation will be thrown. */ + createAttachment(documentLink: string, + body: IAttachment, + callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; createAttachment(documentLink: string, body: IAttachment, options?: ICreateOptions, callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; - + /** * Create a document under the collection. * @param collectionLink resource link of the collection under which the document will be created @@ -160,37 +164,44 @@ interface ICollection extends IQueryAPI { * @param optional create options * @param optional callback for the operation. If no callback is provided, any error in the operation will be thrown. */ + createDocument(collectionLink: string, + body: Object, + callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; createDocument(collectionLink: string, body: Object, options?: ICreateOptions, callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; - + /** * Delete an attachment. * @param attachmentLink resource link of the attachment to be deleted * @param options optional delete options. * @param callback optional callback for the operation. If no callback is provided, any error in the operation will be thrown. */ + deleteAttachment(attachmentLink: string, + callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; deleteAttachment(attachmentLink: string, options?: IDeleteOptions, callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; - + /** * Delete a document. * @param documentLink resource link of the document to delete * @param options optional delete options * @param callback optional callback for the operation. If no callback is provided, any error in the operation will be thrown. */ + deleteDocument(documentLink: string, + callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; deleteDocument(documentLink: string, options?: IDeleteOptions, callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; - + /** Get alt link (name-based link) of current collection. */ getAltLink(): string; /** Get self link of current collection. */ getSelfLink(): string; - + /** * Execute a SQL query on the attachments for the document. * @param documentLink resource link of the document whose attachments are being queried @@ -199,14 +210,13 @@ interface ICollection extends IQueryAPI { * @param callback optional callback for the operation. If no callback is provided, any error in the operation will be thrown. */ queryAttachments(documentLink: string, - query: string, - options?: IFeedOptions, + query: string | IParameterizedQuery, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): boolean; queryAttachments(documentLink: string, - query: IParameterizedQuery, + query: string | IParameterizedQuery, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): boolean; - + /** * Execute a SQL query on the documents of the collection. * @param collectionLink resource link of the collection whose documents are being queried @@ -214,6 +224,9 @@ interface ICollection extends IQueryAPI { * @param options optional query options. * @param callback optional callback for the operation. If no callback is provided, any error in the operation will be thrown. */ + queryDocuments(collectionLink: string, + filterQuery: string, + callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): boolean; queryDocuments(collectionLink: string, filterQuery: string, options?: IFeedOptions, @@ -222,6 +235,9 @@ interface ICollection extends IQueryAPI { filterQuery: string, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): boolean; + queryDocuments(collectionLink: string, + filterQuery: IParameterizedQuery, + callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): boolean; queryDocuments(collectionLink: string, filterQuery: IParameterizedQuery, options?: IFeedOptions, @@ -230,53 +246,61 @@ interface ICollection extends IQueryAPI { filterQuery: IParameterizedQuery, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): boolean; - + /** * Read an Attachment. * @param attachmenLink resource link of the attachment to read * @param options optional read options * @param callback optional callback for the operation. If no callback is provided, any error in the operation will be thrown. */ + readAttachment(attachmenLink: string, + callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; readAttachment(attachmenLink: string, options?: IReadOptions, callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; - + /** * Get all attachments for the document. * @param documentLink resource link of the document whose attachments are being read * @param options optional read feed options * @param callback optional callback for the operation. If no callback is provided, any error in the operation will be thrown. */ + readAttachments(documentLink: string, + callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): boolean; readAttachments(documentLink: string, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): boolean; - + /** * Read a document. * @param documentLink resource link of the document to read * @param options optional read options * @param callback optional callback for the operation. If no callback is provided, any error in the operation will be thrown. */ + readDocument(documentLink: string, + callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; readDocument(documentLink: string, options?: IReadOptions, callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; readDocument(documentLink: string, options?: IReadOptions, callback?: (error: IRequestCallbackError, resources: T, options: IRequestCallbackOptions) => void): boolean; - + /** * Get all documents for the collection. * @param collectionLink resource link of the collection whose documents are being read * @param options optional read feed options * @param callback optional callback for the operation. If no callback is provided, any error in the operation will be thrown. */ + readDocuments(collectionLink: string, + callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): boolean; readDocuments(collectionLink: string, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): boolean; readDocuments(collectionLink: string, options?: IFeedOptions, callback?: (error: IFeedCallbackError, resources: Array, options: IFeedCallbackOptions) => void): boolean; - + /** * Replace an attachment. * @param attachmentLink resource link of the attachment to be replaced @@ -284,11 +308,14 @@ interface ICollection extends IQueryAPI { * @param options optional replace options * @param callback optional callback for the operation. If no callback is provided, any error in the operation will be thrown. */ + replaceAttachment(attachmentLink: string, + attachment: Object, + callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; replaceAttachment(attachmentLink: string, attachment: Object, options?: IReplaceOptions, callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; - + /** * Replace a document. * @param documentLink resource link of the document @@ -296,12 +323,15 @@ interface ICollection extends IQueryAPI { * @param options optional replace options * @param callback optional callback for the operation. If no callback is provided, any error in the operation will be thrown. */ + replaceDocument(documentLink: string, + document: Object, + callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; replaceDocument(documentLink: string, document: Object, options?: IReplaceOptions, callback?: (error: IRequestCallbackError, resources: Object, options: IRequestCallbackOptions) => void): boolean; } - + /** Options associated with a create operation. */ interface ICreateOptions { /** Specifies indexing directives. */ @@ -309,7 +339,7 @@ interface ICreateOptions { /** Disables automatic generation of "id" field of the document to be created (if it is not provided) */ disableAutomaticIdGeneration?: string; } - + /** Options associated with a delete operation. */ interface IDeleteOptions { /** @@ -318,7 +348,7 @@ interface IDeleteOptions { */ etag?: string; } - + /** Will contain error information if an error occurs, undefined otherwise. */ interface IFeedCallbackError { /** The HTTP response code corresponding to the error. */ @@ -326,7 +356,7 @@ interface IFeedCallbackError { /** A string containing the error information. */ body: string; } - + /** Information associated with the response to the operation. */ interface IFeedCallbackOptions { /** Opaque token for continuing the read feed or query. */ @@ -336,7 +366,7 @@ interface IFeedCallbackOptions { /** Comma delimited string containing the collection's maximum quota metrics (storage, number of stored procedure, triggers and UDFs). */ maxCollectionSizeInMB: string; } - + /** Options associated with a read feed or query operation. */ interface IFeedOptions { /** @@ -360,13 +390,13 @@ interface IQueryResponse extends IQueryAPI { /** True if the query has been queued, false if it is not queued because of a pending timeout. */ isAccepted: boolean; } - + /** Options associated with a read operation. */ interface IReadOptions { /** The conditional HTTP method ifNoneMatch value. */ ifNoneMatch?: string; } - + /** Options associated with a replace operation. */ interface IReplaceOptions { /** Specifies indexing directives. */ @@ -377,7 +407,7 @@ interface IReplaceOptions { */ etag?: string; } - + /** Will contain error information if an error occurs, undefined otherwise. */ interface IRequestCallbackError { /** The HTTP response code corresponding to the error. */ @@ -385,7 +415,7 @@ interface IRequestCallbackError { /** A string containing the error information. */ body: string; } - + /** Information associated with the response to the operation. */ interface IRequestCallbackOptions { /** Comma delimited string containing the collection's current quota metrics (storage, number of stored procedure, triggers and UDFs) after completion of the operation. */ @@ -411,7 +441,7 @@ interface IDocumentMeta extends Object { _etag?: string; _attachments?: string; } - + /** * The Request object represents the request message that was sent to the server. This includes information about HTTP headers and the body of the HTTP request sent to the server. * For triggers, the request represents the operation that is executing when the trigger is run. For example, if the trigger is being run ("triggered") on the creation of a document, then @@ -445,7 +475,7 @@ interface IRequest { */ setValue(key: string, value: string): void; } - + /** * The Response object represents the response message that will be sent from the server in response to the requested operation. This includes information about the HTTP headers and body of the response from the server. * The Response object is not present in pre-triggers because they are run before the response is generated. diff --git a/types/documentdb/documentdb-tests.ts b/types/documentdb/documentdb-tests.ts index 3395716305..3ad362e4a0 100644 --- a/types/documentdb/documentdb-tests.ts +++ b/types/documentdb/documentdb-tests.ts @@ -240,3 +240,15 @@ const rpr2 = new ddb.RangePartitionResolver((obj: any) => obj.foo, [ partitionKe const rangePartitionKey1: any = rpr1.getPartitionKey(document1); const rangeCollectionLink1: string = rpr1.resolveForCreate(hashPartitionKey1); const rangeCollectionLinks1: string[] = rpr1.resolveForRead(hashPartitionKey1); + +/** UriFactory methods */ +const dbUri = ddb.UriFactory.createDatabaseUri('dbfoo'); +const colUri = ddb.UriFactory.createDocumentCollectionUri('dbfoo', 'colbar'); +const docUri = ddb.UriFactory.createDocumentUri('dbfoo', 'colbar', 'doc1'); +const permUri = ddb.UriFactory.createPermissionUri('dbfoo', 'userId', 'permission1'); +const sprocUri = ddb.UriFactory.createStoredProcedureUri('dbfoo', 'colbar', 'sproc1'); +const triggerUri = ddb.UriFactory.createTriggerUri('dbfoo', 'colbar', 'trigger1'); +const udfUri = ddb.UriFactory.createUserDefinedFunctionUri('dbfoo', 'colbar', 'udf1'); +const conflictUri = ddb.UriFactory.createConflictUri('dbfoo', 'colbar', 'conflict1'); +const attachUri = ddb.UriFactory.createAttachmentUri('dbfoo', 'colbar', 'doc1', 'attachment1'); +const partitionKeyRangeUri = ddb.UriFactory.createPartitionKeyRangesUri('dbfoo', 'colbar'); diff --git a/types/documentdb/index.d.ts b/types/documentdb/index.d.ts index 7e73926c7f..140470fbda 100644 --- a/types/documentdb/index.d.ts +++ b/types/documentdb/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for DocumentDB 1.10 // Project: https://github.com/Azure/azure-documentdb-node -// Definitions by: Noel Abrahams , Brett Gutstein , Chris Stone +// Definitions by: Noel Abrahams , Brett Gutstein , Chris Stone , Yifan Wu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/documentdb /// @@ -1340,6 +1340,109 @@ export class DocumentClient { getWriteEndpoint(callback: RequestCallback): void; } +export class UriFactory { + /** + * Given a database id, this creates a database link. + * @param {string} databaseId -The database id + * @returns {string} -A database link in the format of dbs/{0} with {0} being a Uri escaped version of the databaseId + * @description Would be used when creating or deleting a DocumentCollection or a User in Azure DocumentDB database service + */ + static createDatabaseUri(databaseId: string): string; + /** + * Given a database and collection id, this creates a collection link. + * @param {string} databaseId -The database id + * @param {string} collectionId -The collection id + * @returns {string} A collection link in the format of dbs/{0}/colls/{1} with {0} being a Uri escaped version of the databaseId and {1} being collectionId + * @description Would be used when updating or deleting a DocumentCollection, creating a Document, a StoredProcedure, a + * Trigger, a UserDefinedFunction, or when executing a query with CreateDocumentQuery in Azure DocumentDB database service. + */ + static createDocumentCollectionUri(databaseId: string, collectionId: string): string; + /** + * Given a database and collection id, this creates a collection link. + * @param {string} databaseId -The database id + * @param {string} collectionId -The collection id + * @param {string} documentId -The document id + * @returns {string} -A document link in the format of dbs/{0}/colls/{1}/docs/{2} with {0} + * being a Uri escaped version of the databaseId, {1} being collectionId and {2} being the documentId + * @description Would be used when creating an Attachment, or when replacing or deleting a Document in Azure DocumentDB database service + */ + static createDocumentUri(databaseId: string, collectionId: string, documentId: string): string; + /** + * Given a database, collection and document id, this creates a document link. + * @param {string} databaseId -The database Id + * @param {string} userId -The user Id + * @param {string} permissionId - The permissionId + * @returns {string} A permission link in the format of dbs/{0}/users/{1}/permissions/{2} with {0} being a Uri escaped version of the databaseId, {1} being userId and {2} being permissionId + * @description Would be used when replacing or deleting a Permission in Azure DocumentDB database service. + */ + static createPermissionUri(databaseId: string, userId: string, permissionId: string): string; + + /** + * Given a database, collection and stored proc id, this creates a stored proc link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} storedProcedureId -The stored procedure Id + * @returns {string} -A stored procedure link in the format of dbs/{0}/colls/{1}/sprocs/{2} + * with {0} being a Uri escaped version of the databaseId, + * {1} being collectionId and {2} being the storedProcedureId + * @description Would be used when replacing, executing, or deleting a StoredProcedure in Azure DocumentDB database service. + */ + static createStoredProcedureUri(databaseId: string, collectionId: string, storedProcedureId: string): string; + + /** + * @summary Given a database, collection and trigger id, this creates a trigger link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} triggerId -The trigger Id + * @returns {string} -A trigger link in the format of dbs/{0}/colls/{1}/triggers/{2} + * with {0} being a Uri escaped version of the databaseId, + * {1} being collectionId and {2} being the triggerId + * @description Would be used when replacing, executing, or deleting a Trigger in Azure DocumentDB database service + */ + static createTriggerUri(databaseId: string, collectionId: string, triggerId: string): string; + + /** + * @summary Given a database, collection and udf id, this creates a udf link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} udfId -The User Defined Function Id + * @returns {string} -A udf link in the format of dbs/{0}/colls/{1}/udfs/{2} with {0} being a Uri escaped version of the databaseId, {1} being collectionId and {2} being the udfId + * @description Would be used when replacing, executing, or deleting a UserDefinedFunction in Azure DocumentDB database service + */ + static createUserDefinedFunctionUri(databaseId: string, collectionId: string, udfId: string): string; + + /** + * @summary + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} conflictId -The conflict Id + * @returns {string} -A conflict link in the format of dbs/{0}/colls/{1}/conflicts/{2} + * with {0} being a Uri escaped version of the databaseId, {1} being collectionId and {2} being the conflictId + * @description Would be used when creating a Conflict in Azure DocumentDB database service. + */ + static createConflictUri(databaseId: string, collectionId: string, conflictId: string): string; + + /** + * @summary Given a database, collection and conflict id, this creates a conflict link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} documentId -The document Id\ + * @param {string} attachmentId -The attachment Id + * @returns {string} -A conflict link in the format of dbs/{0}/colls/{1}/conflicts/{2} with {0} being a Uri escaped version of the databaseId, + * {1} being collectionId and {2} being the conflictId + * @description Would be used when creating a Conflict in Azure DocumentDB database service. + */ + static createAttachmentUri(databaseId: string, collectionId: string, documentId: string, attachmentId: string): string; + + /** + * @summary Given a database and collection, this creates a partition key ranges link in the Azure DocumentDB database service. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @returns {string} -A partition key ranges link in the format of dbs/{0}/colls/{1}/pkranges with {0} being a Uri escaped version of the databaseId and {1} being collectionId + */ + static createPartitionKeyRangesUri(databaseId: string, collectionId: string): string; +} + export type MediaReadMode = 'Buffered' | 'Streamed'; export type ConsistencyLevel = 'Strong' | 'BoundedStaleness' | 'Session' | 'Eventual'; export type IndexingMode = 'Consistent' | 'Lazy'; diff --git a/types/dojo/dojox.gfx3d.d.ts b/types/dojo/dojox.gfx3d.d.ts index 42483ab8d4..6d584c4b50 100644 --- a/types/dojo/dojox.gfx3d.d.ts +++ b/types/dojo/dojox.gfx3d.d.ts @@ -23,8 +23,8 @@ declare namespace dojox { * * */ - class object { - constructor(); + const object: { new(): objectInstance }; + interface objectInstance { /** * multiplies the existing matrix with an argument on left side * (matrix * this.matrix) @@ -2529,7 +2529,7 @@ declare namespace dojox { * @param outline */ class BinarySearchTree { - constructor(obj: dojox.gfx3d.object, outline: any); + constructor(obj: dojox.gfx3d.objectInstance, outline: any); /** * * @param obj @@ -3240,7 +3240,7 @@ declare module "dojox/gfx3d" { export=exp; } declare module "dojox/gfx3d/object" { - var exp: dojox.gfx3d.object + var exp: dojox.gfx3d.objectInstance; export=exp; } declare module "dojox/gfx3d/gradient" { diff --git a/types/dojo/dojox.lang.d.ts b/types/dojo/dojox.lang.d.ts index 4774941552..fa6b9ae07c 100644 --- a/types/dojo/dojox.lang.d.ts +++ b/types/dojo/dojox.lang.d.ts @@ -6293,7 +6293,7 @@ declare namespace dojox { * * */ - interface object { + interface objectInstance { /** * builds a function from a snippet, returns a string, which * represents the function. @@ -12082,7 +12082,7 @@ declare module "dojox/lang/functional/listcomp" { export=exp; } declare module "dojox/lang/functional/object" { - var exp: dojox.lang.functional.object + var exp: dojox.lang.functional.objectInstance export=exp; } declare module "dojox/lang/functional/zip" { diff --git a/types/dom-inputevent/tslint.json b/types/dom-inputevent/tslint.json index 3db14f85ea..b63c1c3846 100644 --- a/types/dom-inputevent/tslint.json +++ b/types/dom-inputevent/tslint.json @@ -1 +1,7 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // TODO + "no-boolean-literal-compare": false + } +} diff --git a/types/dompurify/dompurify-tests.ts b/types/dompurify/dompurify-tests.ts index eb07cfcf14..356225b7c3 100644 --- a/types/dompurify/dompurify-tests.ts +++ b/types/dompurify/dompurify-tests.ts @@ -3,55 +3,60 @@ import dompurify = require('dompurify'); dompurify.sanitize(''); -dompurify.addHook('beforeSanitizeElements', (el, data, config) => { - return el; -}); +dompurify.addHook('beforeSanitizeElements', (el, data, config) => undefined); //examples from the DOMPurify README let dirty = '

      Totally safe

      Totally not safe

      '; +let str: string; +let elem: HTMLElement; +let frag: DocumentFragment; // allow only -dompurify.sanitize(dirty, {ALLOWED_TAGS: ['b']}); +str = dompurify.sanitize(dirty, { ALLOWED_TAGS: ['b'] }); // allow only and with style attributes (for whatever reason) -dompurify.sanitize(dirty, {ALLOWED_TAGS: ['b', 'q'], ALLOWED_ATTR: ['style']}); +str = dompurify.sanitize(dirty, { ALLOWED_TAGS: ['b', 'q'], ALLOWED_ATTR: ['style'] }); // leave all as it is but forbid