diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index df45a8a9e7..7e3c9ccc69 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -9,6 +9,7 @@ /types/absolute/ @AyaMorisawa /types/abstract-leveldown/ @MeirionHughes @danwbyrne /types/acc-wizard/ @cyrilschumacher +/types/accept/ @feinoujc /types/accept-language-parser/ @kampfgnom /types/accepts/ @bomret @brikou /types/accounting/ @gerich-home @chrisleck @@ -159,7 +160,7 @@ /types/ansi-escapes/ @jacobbubu /types/ansi-regex/ @mvachhar /types/ansi-styles/ @brynbellomy @plylrnsdy -/types/ansicolors/ @rogierschouten +/types/ansicolors/ @balupton /types/antlr4/ @mcchatman8009 /types/antlr4-autosuggest/ @jonfreedman /types/any-db/ @rogierschouten @@ -175,6 +176,7 @@ /types/apollo-codegen/ @bradleyayers @kostspielig /types/apollo-upload-client/ @Slessi /types/apostrophe/ @afholderman +/types/app-module-path/ @darkwebdev /types/app-root-dir/ @chenyang-biu /types/app-root-path/ @shantmarouti /types/appdmg/ @unindented @@ -212,7 +214,7 @@ /types/asenv/ @remisery /types/asn1js/ @microshine /types/aspnet-identity-pw/ @jt000 -/types/assert/ @nicoabie +/types/assert/ @nicoabie @LinusU /types/assert-equal-jsx/ @seryl /types/assert-plus/ @KostyaTretyak /types/assertsharp/ @brunolm @@ -231,6 +233,7 @@ /types/atlaskit__inline-edit/ @lstanden /types/atlaskit__layer/ @lstanden /types/atlaskit__single-select/ @lstanden +/types/atlaskit__tree/ @benhjames /types/atlassian-crowd-client/ @mtgto /types/atmosphere.js/ @toedter @Mory1879 @Scipion /types/atob/ @johngeorgewright @@ -254,6 +257,7 @@ /types/autoprefixer/ @odnamrataizem @murt /types/autosize/ @kingdango @keika299 @NeekSandhu /types/autosuggest-highlight/ @senukartur +/types/await-timeout/ @szhu /types/awesomplete/ @webbiesdk @bmdixon @tbekolay @chrislopresto /types/aws-iot-device-sdk/ @niik @mlamp /types/aws-lambda/ @skarum @tobyhede @buggy @y13i @wwwy3y3 @OrthoDex @MichaelMarner @daniel-cottone @kostya-misura @coderbyheart @palmithor @daniloraisi @simonbuchan @Haydabase @repl-chris @aneilbaboo @jeznag @louislarry @dpapukchiev @ohookins @trevor-leach @jagregory @@ -279,20 +283,19 @@ /types/babel__code-frame/ @mohsen1 @ForbesLindesay /types/babel__core/ @yortus @marvinhagemeister @mgroenhoff /types/babel__generator/ @yortus @johnnyestilles @mgroenhoff -/types/babel__parser/ @yortus @marvinhagemeister @mgroenhoff /types/babel__template/ @yortus @marvinhagemeister @mgroenhoff /types/babel__traverse/ @yortus @marvinhagemeister @rpetrich @mgroenhoff /types/babelify/ @TeamworkGuy2 @marvinhagemeister /types/babylon/ @yortus @marvinhagemeister /types/babylon-walk/ @czbuchi /types/babyparse/ @cdiddy77 -/types/backbone/ @borisyankov @nvivo @kenjiru +/types/backbone/ @borisyankov @nvivo @kenjiru @jjoekoullas /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 @razorness @confususs +/types/backbone.marionette/ @zhamid @nvivo @sventschui @razorness @confususs @jjoekoullas /types/backbone.paginator/ @Nyamazing /types/backbone.radio/ @alphaleonis /types/backgrid/ @jlujan @@ -301,6 +304,7 @@ /types/backoff/ @BendingBender /types/baconjs/ @alexander-matsievsky @gekkio /types/bagpipes/ @micmro +/types/baidu-app/ @taoqf /types/barbellweights/ @evelijn /types/barcode/ @pvomhoff /types/bardjs/ @TepigMC @@ -329,7 +333,7 @@ /types/better-curry/ @pocesar /types/better-queue/ @maozedong /types/better-scroll/ @stoneChen @cnjack -/types/better-sqlite3/ @Morfent @matrumz +/types/better-sqlite3/ @Morfent @matrumz @sant123 /types/bezier-easing/ @ptlis /types/bezier-js/ @danmarshall @Epskampie /types/bgiframe/ @sumegizoltan @@ -340,7 +344,7 @@ /types/bignum/ @Patman64 /types/bigscreen/ @dduugg /types/bin-pack/ @orentrutner -/types/binary-parser/ @riggs @dolanmiu +/types/binary-parser/ @riggs @dolanmiu @yuhr /types/bind-ponyfill/ @skysteve /types/bindings/ @unindented /types/bintrees/ @CjS77 @@ -352,7 +356,7 @@ /types/bitcoinjs-lib/ @mhegazy @dlebrecht @rbuckton @micksatana @youssefgh @kento1218 /types/bitcore-lib/ @lautarodragan /types/bittorrent-protocol/ @feross @tlaziuk -/types/bitwise-xor/ @rogierschouten +/types/bitwise-xor/ @rogierschouten @BendingBender /types/bl/ @Bartvds @reconbot /types/blacklist/ @mhegazy /types/blazy/ @julienpa @@ -425,6 +429,7 @@ /types/browser-resolve/ @marionebl /types/browser-sync/ @joeskeen @aznnomness /types/browserify/ @AndrewGaspar @jvilk @leonard-thieu @LinusU +/types/browserslist/ @davecardwell /types/bs58/ @chrootsu /types/bson/ @horiuchi @CaselIT /types/btoa/ @johngeorgewright @@ -438,7 +443,7 @@ /types/bufferstream/ @Bartvds /types/builtin-modules/ @ajafff /types/bull/v2/ @bgrieder @JProgrammer -/types/bull/ @bgrieder @JProgrammer @marshall007 @weeco @blaugold @iamolegga @koblas @bondz @wuha-team @aleccool213 @danmana +/types/bull/ @bgrieder @JProgrammer @marshall007 @weeco @blaugold @iamolegga @koblas @bondz @wuha-team @aleccool213 @danmana @kjellmorten @pc-jedi /types/bump-regex/ @silkentrance /types/bunnymq/ @cyrilschumacher /types/bunyan/ @amikhalev @@ -457,6 +462,7 @@ /types/bytewise/ @danwbyrne /types/c3/ @mcliment @gerinjacob @denyo @dmitryshindin @timn /types/cache-manager/ @GausSim +/types/cached-path-relative/ @TeamworkGuy2 /types/cal-heatmap/ @RetroChrisB /types/caller/ @ignocide /types/callsite/ @newclear @@ -468,6 +474,7 @@ /types/camo/ @lucasmciruzzi /types/cancan/ @Vincent-Pang /types/caniuse-api/ @davecardwell +/types/caniuse-lite/ @mutech /types/cannon/ @clark-stevenson @Gelio /types/canvas-confetti/ @matracey /types/canvas-gauges/ @Mikhus @@ -482,10 +489,12 @@ /types/cassandra-driver/ @Svjard @pc-jedi /types/catbox/v7/ @jasonswearingen @AJamesPhillips /types/catbox/ @jasonswearingen @AJamesPhillips @saboya +/types/catbox-memory/ @SimonSchick /types/catbox-redis/ @SimonSchick /types/cbor/ @pushplay /types/ccap/ @taoqf /types/cesium/ @Zuzon @hnipps @szechyjs @golyalpha +/types/cfn-response/ @ivoisbelongtous /types/chai/v2/ @Bartvds @AGBrown /types/chai/ @jedmao @Bartvds @AGBrown @olivr70 @mwistrand @joshuakgoldberg @shaunluttin @Naktibalda @micksatana @ErikSchierboom /types/chai-arrays/ @clementprevot @@ -520,7 +529,7 @@ /types/check-types/ @idchlife /types/checkstyle-formatter/ @mhegazy /types/checksum/ @rogierschouten -/types/cheerio/ @blittle @wmaurer @umarniz @LiJinyao @chennakrishna8 +/types/cheerio/ @blittle @wmaurer @umarniz @LiJinyao @chennakrishna8 @AzSiAz /types/chess.js/ @JacobFischer /types/chessboardjs/ @sliverb @davidmpaz /types/chmodr/ @BendingBender @@ -538,7 +547,8 @@ /types/circuit-breaker-js/ @DeTeam /types/circular-json/ @jpevarnek /types/ckeditor/v2/ @wittwert -/types/ckeditor/ @wittwert @stuartlong +/types/ckeditor/ @wittwert @stuartlong @viktorpegy +/types/ckeditor__ckeditor5-utils/ @denisname /types/clamp-js/ @Hikariii /types/clamp-js-main/ @sinziananicolae /types/classnames/ @adidahiya @JKillian @seansfkelley @mradamczyk @marvinhagemeister @@ -552,6 +562,7 @@ /types/clearbladejs-server/ @ClearBlade /types/cleave.js/ @clentfort @jasongi-at-sportsbet @sashashakun /types/cli/ @kayahr +/types/cli-box/ @athasach /types/cli-color/ @ChaosinaCan /types/cli-interact/ @ffflorian /types/cli-progress/ @mhegazy @@ -579,7 +590,7 @@ /types/co-body/ @geoffreak /types/co-views/ @devlee @geoffreak /types/code/ @prashaantt -/types/codemirror/ @mihailik @nrbernard @Pr1st0n @rileymiller +/types/codemirror/ @mihailik @nrbernard @Pr1st0n @rileymiller @toddself /types/codependency/ @morphatic /types/coffeeify/ @tkQubo /types/coinbase/ @rogierschouten @@ -598,9 +609,10 @@ /types/com.darktalker.cordova.screenshot/ @akarienta /types/com.wikitude.phonegap.wikitudeplugin/ @zbarbuto /types/combine-source-map/ @TeamworkGuy2 -/types/combined-stream/ @felixge @tlaziuk +/types/combined-stream/ @felixge @tlaziuk @konpikwastaken /types/combokeys/ @iclanton /types/cometd/ @derekcicerone @unindented @alxHenry +/types/command-exists/ @BendingBender /types/command-line-args/v4/ @CzBuCHi @75lb /types/command-line-args/ @75lb /types/command-line-commands/ @CzBuCHi @@ -610,9 +622,10 @@ /types/commercetools__enzyme-extensions/ @screendriver /types/common-errors/ @icopp /types/common-prefix/ @seangenabe -/types/common-tags/ @zuzusik @tzupengwang +/types/common-tags/ @zuzusik @tzupengwang @BendingBender /types/commondir/ @leonard-thieu /types/commonmark/ @nicojs @leonard-thieu +/types/compare-func/ @fennibay /types/compare-version/ @jpevarnek /types/compare-versions/ @LogvinovLeon /types/complex/ @AyaMorisawa @pavasich @@ -644,7 +657,7 @@ /types/connect-mongo/ @Syati /types/connect-mongodb-session/ @NattapongSiri /types/connect-pg-simple/ @pasieronen -/types/connect-redis/ @xstoudi @morcerf +/types/connect-redis/ @xstoudi /types/connect-slashes/ @samherrmann /types/connect-timeout/ @cyrilschumacher /types/consola/ @Jungwoo-An @@ -662,7 +675,7 @@ /types/convert-layout/ @xeningem /types/convert-source-map/ @AndrewGaspar @mgroenhoff @TeamworkGuy2 /types/convict/ @Nemo157 @vesse @elyscape @vanthiyathevan -/types/cookie/ @pine613 +/types/cookie/ @pine /types/cookie-parser/ @santialbo @BendingBender /types/cookie-session/ @borislavjivkov /types/cookie-signature/ @lith-light-g @@ -706,7 +719,8 @@ /types/countdown/ @gjuchault /types/counterpart/ @santiagodoldan /types/countries-and-timezones/ @zero51 -/types/country-list/ @iRoachie +/types/country-list/v1/ @iRoachie +/types/country-list/ @iRoachie @Kimahriman /types/country-select-js/ @humrochagf /types/countup.js/ @shermendev /types/coverup/ @bevalorous @@ -717,6 +731,8 @@ /types/cradle/ @panuhorsmalahti /types/crc/ @YuJianrong /types/create-error/ @tkrotoff +/types/create-hash/ @BendingBender +/types/create-hmac/ @BendingBender /types/create-react-class/ @jgoz /types/create-subscription/ @Asana @vsiao /types/createjs/ @evilangelist @gyohk @@ -731,20 +747,24 @@ /types/crossfilter/ @schmuli @iebaker @nordfjord /types/crossroads/ @diullei /types/crpc/ @0xdeafcafe +/types/crumb/ @lenovouser @SimonSchick /types/cryptiles/ @awendland /types/crypto-js/ @misak113 /types/crypto-random-string/ @MrManny /types/cryptojs/ @giabao +/types/cryptr/ @rrogowski /types/cson/ @stpettersens +/types/cson-parser/ @lenovouser /types/csprng/ @winksaville /types/csrf/ @markis /types/css/ @ilich /types/css-font-loading-module/ @slikts /types/css-modules/ @NeekSandhu /types/css-to-style/ @bengry +/types/css-tree/ @erik-kallen /types/cssbeautify/ @rictic /types/cssnano/ @odnamrataizem -/types/csso/ @screendriver +/types/csso/ @screendriver @erik-kallen /types/csurf/ @horiuchi /types/csv-parse/ @davidm77 @obi-jan-kenobi /types/csv-stringify/ @rogierschouten @arjenvanderende @@ -777,7 +797,7 @@ /types/d3-delaunay/ @BTOdell /types/d3-dispatch/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-drag/ @tomwanzek @gustavderdrache @borisyankov -/types/d3-dsv/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-dsv/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-ease/ @tomwanzek @gustavderdrache @borisyankov /types/d3-fetch/ @ledragon /types/d3-force/ @tomwanzek @gustavderdrache @borisyankov @@ -843,7 +863,8 @@ /types/dd-trace/ @ColinBradley @alloy /types/deasync/ @Sicilica /types/debessmann/ @vkorehov -/types/debounce/ @denis-sokolov @joshuakgoldberg +/types/debounce/ @denis-sokolov @joshuakgoldberg @wcarson +/types/debounce-promise/ @whtsky /types/debug/ @swook @galtalmor @zamb3zi @brasten /types/decamelize/ @samverschueren /types/decay/ @enaeseth @@ -876,10 +897,13 @@ /types/depd/ @danny8002 @BendingBender /types/dependency-tree/ @joscha /types/deployjava/ @cyrilschumacher +/types/deprecate/ @Toilal +/types/deps-sort/ @TeamworkGuy2 /types/derhuerst__cli-on-key/ @jacobbubu /types/destroy/ @BendingBender /types/destroy-on-hwm/ @BendingBender -/types/detect-browser/ @rogierschouten +/types/detect-browser/ @rogierschouten @carusology +/types/detect-character-encoding/ @BendingBender /types/detect-hover/ @thomastilkema /types/detect-indent/v0/ @Bartvds /types/detect-indent/ @Bartvds @BendingBender @@ -901,17 +925,21 @@ /types/di-lite/ @dcrusader /types/diacritics/ @otociulis /types/dialogflow/ @dyladan +/types/dicer/ @GoupilRobin @BendingBender /types/diff/ @vvakame @szdc @moc-yuto /types/diff2html/ @rtfpessoa +/types/diffie-hellman/ @BendingBender /types/digibyte/ @lautarodragan @werewolfe +/types/dinero.js/ @BendingBender /types/dir-resolve/ @andy-ms /types/discontinuous-range/ @OiCMudkips +/types/discord-rpc/ @jasonhaxstuff /types/discourse-sso/ @championswimmer /types/dispatchr/ @Ragg- /types/disposable-email-domains/ @geoffreak /types/dnssd/ @angelmerino @Maxr1998 /types/doccookies/ @jonegerton -/types/dockerode/ @seikho @nlaplante @isac322 @lazarusx @meisenzahl @thegecko +/types/dockerode/ @seikho @nlaplante @isac322 @lazarusx @meisenzahl @thegecko @CameronDiver /types/docopt/ @giggio /types/doctrine/ @rictic /types/document-promises/ @NotWoods @@ -923,6 +951,7 @@ /types/dom-clipboard-api/ @43081j /types/dom-inputevent/ @diagramatics /types/dom-loaded/ @ltetzlaff +/types/dom-mediacapture-record/ @eliasmeire /types/dom-to-image/ @JipSterk /types/dom4/ @adidahiya @giladgray /types/domo/ @Steve-Fenton @@ -937,7 +966,7 @@ /types/dotdir-regex/ @mrmlnc /types/dotdotdot/ @milanjaros /types/dotenv/v2/ @jussikinnula @borekb @enaeseth -/types/dotenv/ @jussikinnula @borekb @enaeseth +/types/dotenv/ @jussikinnula @borekb @enaeseth @maxbeatty /types/dotenv-safe/ @krenor /types/dotenv-webpack/ @karol-majewski /types/dotfile-regex/ @mrmlnc @@ -984,7 +1013,7 @@ /types/easy-xapi/ @DeadAlready /types/easy-xapi-utils/ @DeadAlready /types/ebongarde-root/ @Ebongarde -/types/echarts/ @xieisabug @AntiMoron @liveangela @Ovilia +/types/echarts/ @xieisabug @AntiMoron @liveangela @Ovilia @iRON5 /types/ecma-proposal-math-extensions/ @ksm2 /types/ecurve/ @mhegazy /types/ed25519/ @erikma @@ -1018,7 +1047,7 @@ /types/electron-winstaller/ @shiftkey @unindented /types/elegant-spinner/ @danwbyrne /types/element-ready/ @BendingBender -/types/element-resize-detector/ @saranshkataria +/types/element-resize-detector/ @saranshkataria @franklixuefei /types/element-resize-event/ @rogierschouten @plgregoire /types/elementtree/ @dwieeb /types/elliptic/ @danwbyrne @@ -1062,6 +1091,7 @@ /types/emoji-regex/ @iKBAHT /types/emojione/ @dbrgn /types/empower/ @vvakame +/types/empty-dir/ @BendingBender /types/emscripten/ @zakki @periklis /types/encoding-down/ @MeirionHughes @danwbyrne /types/end-of-stream/ @strax @@ -1079,6 +1109,7 @@ /types/enzyme-adapter-react-15/ @tkrotoff /types/enzyme-adapter-react-15.4/ @nali /types/enzyme-adapter-react-16/ @tkrotoff +/types/enzyme-async-helpers/ @kimehrenpohl /types/enzyme-redux/ @knegusen /types/enzyme-to-json/ @joscha /types/eonasdan-bootstrap-datetimepicker/ @ToastHawaii @@ -1137,17 +1168,21 @@ /types/exit/ @Bartvds /types/exit-hook/ @BendingBender /types/exorcist/ @TeamworkGuy2 +/types/expand-tilde/ @carnesen /types/expect/ @jmreidy @merrywhether /types/expect-puppeteer/ @JoshuaKGoldberg @tkrotoff /types/expect.js/ @teppeis /types/expectations/ @vvakame /types/expired-storage/ @intolerance +/types/expirymanager/ @DanielRose /types/expo/v23/ @KonstantinKai /types/expo/v24/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger /types/expo/v25/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov /types/expo/v26/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @tinaroh /types/expo/v27/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo -/types/expo/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo +/types/expo/v30/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo +/types/expo/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo @levansuper @ihmpavel +/types/expo-localization/ @burtek /types/expo__status-bar-height/ @dawnmist /types/expo__vector-icons/ @incleaf /types/express/ @borisyankov @@ -1188,6 +1223,7 @@ /types/express-redis-cache/ @ajliv /types/express-route-fs/ @kripod /types/express-routemap/ @icopp +/types/express-routes-versioning/ @weffe /types/express-sanitized/ @cjbarth /types/express-serve-static-core/ @borisyankov @19majkel94 @kacepe @micksatana @samijaber /types/express-session/ @horiuchi @jacobbogers @builtinnya @ry7n @@ -1195,6 +1231,8 @@ /types/express-socket.io-session/ @AylaJK /types/express-to-koa/ @xiaohanzhang /types/express-unless/ @wokim +/types/express-version-request/ @weffe +/types/express-version-route/ @weffe /types/express-wechat-access/ @simmons8616 /types/express-winston/ @bricka /types/express-ws/ @ajliv @@ -1226,11 +1264,11 @@ /types/fancy-log/ @pine /types/fancybox/ @borisyankov /types/farbtastic/ @EnableSoftware -/types/fast-diff/ @djrenren /types/fast-levenshtein/ @mizunashi-mana /types/fast-list/ @BendingBender /types/fast-stats/ @rogierschouten /types/fastclick/ @shinnn +/types/fastify-accepts/ @leomelzer /types/fastify-cors/ @jannikkeye /types/fastify-jwt/ @jannikkeye /types/fastify-multipart/ @jannikkeye @@ -1283,13 +1321,15 @@ /types/finalhandler/ @chrootsu /types/finch/ @DavidSichau /types/find/ @andypyrope +/types/find-package-json/ @BendingBender /types/find-parent-dir/ @ikatyang /types/find-process/ @buaban /types/find-project-root/ @ikatyang /types/find-root/ @Alorel /types/find-up/ @BendingBender -/types/find-versions/ @LogvinovLeon +/types/find-versions/ @LogvinovLeon @carnesen /types/findup-sync/ @Bartvds @ngbrown +/types/fined/ @BendingBender /types/fingerprintjs/ @zaneli /types/fingerprintjs2/ @curtstate /types/firebase-client/ @fpsscarecrow @@ -1301,7 +1341,9 @@ /types/first-mate/ @GlenCFL /types/fixed-data-table/ @pepaar @stephenjelfs /types/fixed-data-table-2/ @ilivit +/types/flagged-respawn/ @BendingBender /types/flat/ @chrootsu +/types/fleximap/ @DanielRose /types/flexslider/ @diullei /types/flickity/ @clmcgrath @wagich /types/flight/ @jonathanhedren @@ -1309,6 +1351,7 @@ /types/flipsnap/ @kubosho @gsino @mayuki /types/float-regex/ @wanganjun /types/flot/ @burlandm @Anticom @admiralsmaster +/types/flowdoc/ @animify /types/flowjs/ @ryan10132 /types/fluent-ffmpeg/ @tcaesvk @DingWeizhe @mabidina /types/flush-write-stream/ @djcsdy @@ -1374,6 +1417,7 @@ /types/fusioncharts/ @rohitkr @shivarajkv /types/fuzzaldrin/ @mhegazy /types/fuzzaldrin-plus/ @jeancroy @jkillian @reyronald +/types/fuzzy-search/ @alex-deas @BendingBender /types/fuzzyset/ @lgrignon @narainsagar /types/fuzzyset.js/ @lgrignon @narainsagar /types/fxn/ @charrondev @@ -1547,6 +1591,7 @@ /types/getos/ @BendingBender /types/gettext.js/ @jucrouzet /types/gh-pages/ @DanielRosenwasser +/types/ghauth/ @Leko /types/gifffer/ @gatimus /types/gijgo/ @atatanasov /types/giraffe/ @darthapo @@ -1555,11 +1600,17 @@ /types/git-config/ @stpettersens /types/git-remote-origin-url/ @janslow /types/git-rev-sync/ @khoi-fish +/types/git-root-dir/ @ffflorian /types/git-url-parse/ @ajafff +/types/gitconfiglocal/ @ffflorian /types/github-url-to-object/ @ajafff /types/github-username-regex/ @BehindTheMath -/types/gitlab/ @yanqing6628780 @Arylo /types/gl-matrix/ @mattijskneppers @tatchx @nbabanov @auzmartist @surtr-isaz +/types/gl-react/ @jussikinnula +/types/gl-react-dom/ @jussikinnula +/types/gl-react-expo/ @jussikinnula +/types/gl-react-headless/ @jussikinnula +/types/gl-react-native/ @jussikinnula /types/gl-shader/ @MathiasPaumgarten /types/gl-texture2d/ @MathiasPaumgarten /types/gldatepicker/ @qcz @@ -1585,12 +1636,12 @@ /types/google-apps-script-oauth2/ @dhayab /types/google-cloud__datastore/ @beaulac @ogawa0071 @ThomasdenH /types/google-cloud__pubsub/ @pheromonez @LunaPg @msiviero -/types/google-cloud__storage/ @blove @nbperry @welkie @ogawa0071 /types/google-earth/ @icholy /types/google-images/ @dolanmiu /types/google-libphonenumber/ @leonyu @winfinit /types/google-map-react/ @honzabrecka /types/google-maps/ @DeividasBakanas @GiedriusGrabauskas +/types/google-maps-react/ @gburgett @jpowell /types/google-protobuf/ @marcuslongmuir /types/google-translate-api/ @maple3142 /types/google.analytics/ @tyler-murphy @@ -1598,7 +1649,7 @@ /types/google.fonts/ @danmarshall /types/google.geolocation/ @vbortone /types/google.picker/ @grapswiz -/types/google.visualization/ @danludwig @gmoore-sjcorg @danmana @mlcheng @IvanBisultanov @glebm +/types/google.visualization/ @danludwig @gmoore-sjcorg @danmana @mlcheng @IvanBisultanov @glebm @shrujalshah28 /types/google__maps/ @indrimuska /types/googlemaps/ @cgwrench @nertzy @xaolas @mrmcnerd @martincostello @svenkreiss @bolatovumar @gauthierm /types/googlemaps.infobubble/ @Dashue @@ -1616,6 +1667,7 @@ /types/graphql-date/ @enaeseth /types/graphql-deduplicator/ @lfades /types/graphql-depth-limit/ @eritikass +/types/graphql-fields/ @feinoujc /types/graphql-iso-date/ @jwaldrip /types/graphql-list-fields/ @filipows /types/graphql-query-complexity/ @abhikmitra @@ -1678,6 +1730,7 @@ /types/gulp-jasmine/ @andypyrope /types/gulp-jasmine-browser/ @tkrotoff /types/gulp-json-editor/ @peterjuras +/types/gulp-json-validator/ @pe8ter /types/gulp-jsonmin/ @romain-faust /types/gulp-jsonminify/ @pine /types/gulp-jspm/ @peterjuras @@ -1722,12 +1775,14 @@ /types/halogen/ @steller /types/hammerjs/ @milkisevil @codler /types/handlebars/ @borisyankov @evil-shrike +/types/handlebars-helpers/ @Toilal /types/hapi/v8/ @jasonswearingen /types/hapi/v12/ @jasonswearingen /types/hapi/v15/ @jasonswearingen /types/hapi/v16/ @jasonswearingen @AJamesPhillips /types/hapi/ @rafaelsouzaf @jhsimms @SimonSchick /types/hapi-auth-basic/ @AJamesPhillips @saboya +/types/hapi-auth-cookie/ @lenovouser @SimonSchick @Mutmatt /types/hapi-auth-jwt2/v7/ @warrenseymour /types/hapi-auth-jwt2/ @warrenseymour @SimonSchick /types/hapi-decorators/ @kenhowardpdx @@ -1764,6 +1819,7 @@ /types/hexo-fs/ @segayuu /types/hexo-log/ @segayuu /types/hexo-util/ @segayuu +/types/hibp/ @lenovouser /types/highcharts/ @damianog @baltie @AlbertOzimek @hanssens /types/highcharts-ng/ @scatcher /types/highland/ @Bartvds @hgwood @iwllyu @alvis @notbobthebuilder @@ -1821,6 +1877,7 @@ /types/humanparser/ @MichalPodeszwa /types/humps/ @nikeee /types/hyco-ws/ @mrcabellom +/types/hyper-aws4/ @bambutz /types/hyperscript/ @spacejack @jmfirth /types/hypertext-application-language/ @maks3w /types/hystrixjs/ @igorsechyn @@ -1867,7 +1924,7 @@ /types/images/ @DingWeizhe /types/imagesloaded/ @coldacid @apexskier /types/imap/ @psnider -/types/imap-simple/ @pushplay +/types/imap-simple/ @pushplay @iaarnio /types/imgur-rest-api/ @lukewestby /types/imperium/ @gaetansenn /types/impress/ @borisyankov @@ -1881,7 +1938,7 @@ /types/inflected/ @dsci /types/inflection/ @shiwano /types/inherits/ @chrootsu -/types/ini/ @marcinporebski +/types/ini/ @marcinporebski @carnesen /types/iniparser/ @chrootsu /types/init-package-json/ @kfarnung /types/inline-css/ @philipisapain @@ -1890,33 +1947,38 @@ /types/inquirer-npm-name/ @manuth /types/insert-module-globals/ @leonard-thieu /types/insight/ @vvakame +/types/instabug-reactnative/ @pengcao1 /types/integer/ @Morfent /types/intercom-client/ @jineshshah36 @peping /types/intercom-web/ @fongandrew @salbahra @onatm /types/intercomjs/ @spencerwi /types/internal-ip/ @BendingBender +/types/interpret/ @BendingBender /types/intl/ @RagibHasin /types/intl-locales-supported/ @Slessi /types/intl-messageformat/ @mhegazy /types/intl-relativeformat/ @mohsen1 -/types/intl-tel-input/ @fdnhkj @leonard-thieu +/types/intl-tel-input/v13/ @fdnhkj @leonard-thieu +/types/intl-tel-input/ @fdnhkj @leonard-thieu @molnarm /types/into-stream/ @BendingBender /types/intrinsic-scale/ @shalomdotnet /types/intro.js/ @anahkiasen /types/invariant/ @bennett000 /types/inversify-devtools/ @inversify +/types/iobroker/ @AlCalzone /types/ion-rangeslider/v1/ @dduugg @Karel-van-de-Plassche /types/ion-rangeslider/ @Karel-van-de-Plassche /types/ioredis/v3/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot -/types/ioredis/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot @funthing @iamolegga +/types/ioredis/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot @funthing @iamolegga @tingwai-to /types/iota.lib.js/ @fogsh /types/ip/ @codeanimal /types/ip-address/ @icopp @danwbyrne /types/ip-regex/ @unindented /types/ipcheck/ @bengry /types/irc/ @phillips1012 +/types/iri/ @BendingBender /types/iron/ @simonschick @rafaelsouzaf -/types/is/ @cabralRodrigo +/types/is/ @cabralRodrigo @gricey432 /types/is-absolute-url/ @mhegazy /types/is-alphanumerical/ @vutran /types/is-archive/ @mhegazy @@ -1936,10 +1998,12 @@ /types/is-my-json-valid/ @kruncher /types/is-negated-glob/ @ajafff /types/is-number/ @harryshipton +/types/is-obj/ @forivall /types/is-object/ @wbhob /types/is-path-cwd/ @DanielRosenwasser /types/is-path-in-cwd/ @mhegazy /types/is-promise/ @DanielRosenwasser +/types/is-regexp/ @forivall /types/is-relative-url/ @mhegazy /types/is-root/ @mhegazy /types/is-root-path/ @mhegazy @@ -1975,7 +2039,9 @@ /types/jade/ @panuhorsmalahti /types/jalaali-js/ @alitaheri /types/japanese-holidays/ @syamatoo -/types/jasmine/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software @Engineer2B +/types/jasmine/v1/ @borisyankov +/types/jasmine/v2/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software @Engineer2B @cyungmann +/types/jasmine/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software @Engineer2B @cyungmann @Roaders /types/jasmine-ajax/ @lgrignon /types/jasmine-data-provider/ @tlaziuk /types/jasmine-data_driven_tests/ @AnthonyMacKinnon @@ -1991,7 +2057,7 @@ /types/jasminewd2/ @sjelin @gkalpak /types/java/ @jimlloyd @hrl7 @darti /types/java-applet/ @cyrilschumacher -/types/javascript-astar/ @ptlis +/types/javascript-astar/ @ptlis @lazerwalker /types/javascript-bignum/ @sandersn /types/javascript-obfuscator/ @sanex3339 /types/javascript-state-machine/ @borisyankov @mdocter @MrBigDog2U @samael65535 @taoqf @@ -2021,10 +2087,11 @@ /types/jexl/ @m-tomczyk /types/jfs/ @tlaziuk /types/jira-client/ @KOPTE3 @orta +/types/jju/ @ecraig12345 @rlidwka /types/jjv/ @Nemo157 /types/jjve/ @Nemo157 /types/jmespath/ @pushplay -/types/johnny-five/ @nakakura @ujvzolee @workshop2 +/types/johnny-five/ @nakakura @ujvzolee @workshop2 @xtrimsystems /types/joi/v6/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW /types/joi/v10/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @aconanlai /types/joi/v13/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @dankraus @wanganjun @rafaelkallis @aconanlai @zaphoyd @thewillg @SimonSchick @@ -2173,7 +2240,7 @@ /types/js-sha512/ @nicojs /types/js-string-escape/ @viralpickaxe /types/js-to-java/ @skyitachi -/types/js-url/ @pine613 +/types/js-url/ @pine /types/js-yaml/ @Bartvds @sclausen /types/js.spec/ @mattbishop /types/jsbn/ @Evgenus @al2xed @@ -2201,6 +2268,7 @@ /types/json-rpc-random-id/ @micahriggan /types/json-rpc-ws/ @npenin @mlamp /types/json-schema/ @bcherny @cyrilletuzi @lucianbuzzo @rolandjitsu +/types/json-server/ @jeremyben /types/json-socket/ @svi3c /types/json-stable-stringify/ @mhfrantz /types/json-stringify-safe/ @BendingBender @@ -2208,6 +2276,7 @@ /types/json2md/ @MartynasZilinskas /types/json3/ @NN--- /types/json5/ @Esemesek +/types/json_ml/ @pluma /types/jsonata/ @nick121212 /types/jsoneditor/ @alejo90 @errietta /types/jsoneditor-for-react/ @joshuakgoldberg @@ -2225,7 +2294,7 @@ /types/jsonwebtoken/ @SomaticIT @danielheim @brikou @vpk @rlgod /types/jsonwebtoken-promisified/ @SomaticIT @danielheim @brikou @aneilbaboo /types/jspath/ @dex4er -/types/jspdf/ @amberjs +/types/jspdf/ @amberjs @lleios @jemerald /types/jsqrcode/ @lordazzi /types/jsrender/ @zakki /types/jsreport-core/ @taoqf @@ -2253,6 +2322,7 @@ /types/jui-grid/ @easylogic /types/just-debounce-it/ @azizhk /types/just-extend/ @pe8ter +/types/just-pick/ @pe8ter /types/jweixin/ @taoqf @gomydodo /types/jwplayer/ @martinduparc @kutomer @philippguertler @danielmcgraw @bpdsw /types/jws/ @JustinBeckwith @@ -2268,7 +2338,7 @@ /types/karma/ @tkrotoff @43081j @devoto13 /types/karma-chai/ @JayAndCatchFire /types/karma-chai-sinon/ @vasek17 -/types/karma-coverage/ @tkrotoff +/types/karma-coverage/ @tkrotoff @devoto13 /types/karma-fixture/ @evictor @afshawnlotfi /types/karma-jasmine/ @michelsalib /types/karma-viewport/ @karak @@ -2276,9 +2346,11 @@ /types/katex/ @mrand01 /types/kcors/ @Xstoudi @izayoiko /types/kdbush/ @DenisCarriere @chrfrasco +/types/kdbxweb/ @Roang-zero1 /types/keen-tracking/ @rui-ferreira /types/kefir/ @AyaMorisawa @HitoriSensei /types/kendo-ui/ @telerik +/types/kerberos/ @velezsarain /types/keyboardjs/ @vbortone @piranha771 @teoxoy /types/keycloak-connect/ @gstamac /types/keygrip/ @jkeylu @@ -2293,10 +2365,10 @@ /types/klaw/ @mceachen /types/klaw-sync/ @shiftkey /types/kms-json/ @sunnyone -/types/knex/ @tkQubo @MeLlamoPablo @mastermatt @micksatana @shreyjain1994 +/types/knex/ @tkQubo @MeLlamoPablo @mastermatt @micksatana @shreyjain1994 @joelshepherd /types/knex-postgis/ @vesse /types/knockback/ @borisyankov -/types/knockout/ @borisyankov @Igorbek @moonpyk @EnableSoftware @BenjaminEckardt @ffMathy @ltlombardi +/types/knockout/ @borisyankov @Igorbek @moonpyk @EnableSoftware @BenjaminEckardt @ffMathy @ltlombardi @Retsam /types/knockout-amd-helpers/ @DavidSichau /types/knockout-secure-binding/ @pine613 /types/knockout-transformations/ @johnnyreilly @Nemo157 @@ -2317,7 +2389,8 @@ /types/koa/ @DavidCai1993 @jkeylu @brikou /types/koa-basic-auth/ @Tobias4872 /types/koa-better-body/ @danwbyrne -/types/koa-bodyparser/ @hellopao @anup-2s +/types/koa-bodyparser/ @hellopao @anup-2s @hirochachacha +/types/koa-bouncer/ @maruware /types/koa-bunyan-logger/ @sjmcdowall /types/koa-cache-control/ @pe8ter /types/koa-compose/ @jkeylu @@ -2332,9 +2405,10 @@ /types/koa-hbs/ @jcbmln @mudkipme /types/koa-helmet/ @me /types/koa-html-minifier/ @romain-faust -/types/koa-joi-router/ @wingsbob @move-zig +/types/koa-joi-router/ @wingsbob @move-zig @hirochachacha /types/koa-json/ @brooklyndev /types/koa-json-error/ @mudkipme +/types/koa-log/ @havenchyk /types/koa-logger/ @geoffreak @tlaziuk /types/koa-logger-winston/ @stevehipwell /types/koa-morgan/ @vesse @@ -2343,14 +2417,16 @@ /types/koa-passport/ @horiuchi @tlaziuk @brendtumi /types/koa-pino-logger/ @khell /types/koa-pug/ @Xstoudi +/types/koa-qs/ @RemyJeancolas /types/koa-range/ @strax /types/koa-ratelimit/ @OutdatedVersion +/types/koa-ratelimit-lru/ @danwbyrne /types/koa-redis/ @nsimmons /types/koa-redis-cache/ @dimamukhin /types/koa-requestid/ @sjmcdowall /types/koa-response-time/ @thorsedeke @sjmcdowall /types/koa-route/ @migstopheles @jacogr -/types/koa-router/ @hellopao @schfkt @JounQin @romain-faust +/types/koa-router/ @hellopao @schfkt @JounQin @romain-faust @Guillaume-Mayer @falinor /types/koa-send/ @pe8ter @tlaziuk /types/koa-session/ @kerol2r20 @tlaziuk /types/koa-session-minimal/ @longztian @@ -2358,6 +2434,7 @@ /types/koa-static/ @hellopao @tlaziuk /types/koa-static-cache/ @JounQin /types/koa-static-server/ @wulunyi +/types/koa-useragent/ @rvboris /types/koa-views/ @brooklyndev /types/koa-webpack/ @malj @leebenson @miZyind @tlaziuk /types/koa-websocket/ @moimael @jacogr @zdila @Kroisse @@ -2387,6 +2464,7 @@ /types/lazy-value/ @ikatyang /types/lazy.js/ @Bartvds @miso440 /types/lazypipe/ @tomc974 +/types/ldap-filters/ @pluma /types/ldapjs/ @cvillemure @peterkooijmans /types/leadfoot/ @theintern /types/leaflet/v0/ @rgripper @@ -2441,6 +2519,7 @@ /types/libxmljs/ @fdecampredon @ComFreek /types/libxslt/ @alejo90 /types/license-checker/ @rogierschouten @unindented +/types/liftoff/ @BendingBender /types/lil-uuid/ @Pr1st0n /types/lime-js/ @arthur-xavier /types/line-by-line/ @etomsen @@ -2450,6 +2529,8 @@ /types/lingui__macro/ @huan086 /types/lingui__react/ @huan086 /types/linkify-it/ @praxxis +/types/linkifyjs/ @szhu +/types/list-stream/ @IanStorm /types/listr/ @durad /types/lls/ @borislavjivkov /types/load-json-file/ @SamVerschueren @@ -2767,6 +2848,7 @@ /types/lokijs/ @TeamworkGuy2 @thomasconner /types/lolex/ @Nemo157 @joshuakgoldberg @rogierschouten /types/long/ @peterkooijmans +/types/looks-same/ @xcatliu /types/loopback/ @kattsushi @enko @sequoia @drmikecrowe @karimsa /types/loopback-boot/ @kattsushi /types/lorem-ipsum/ @durad @@ -2778,12 +2860,12 @@ /types/lozad/ @plantain-00 /types/lru-cache/ @Bartvds @BendingBender /types/lscache/ @Chris-Martinezz -/types/ltx/ @PJakcson +/types/ltx/ @PJakcson @BendingBender /types/luaparse/ @stpettersens /types/lunr/v0/ @sebastian-lenz /types/lunr/ @seantanly /types/lusca/ @crutchcorn -/types/luxon/ @colbydehart @FourwingsY @jsiebern +/types/luxon/ @colbydehart @FourwingsY @jsiebern @mastermatt /types/lwip/ @AyaMorisawa /types/lz-string/ @M0ns1gn0r /types/lzma-native/ @leshow @@ -2793,19 +2875,21 @@ /types/mailcheck/ @pocesar /types/maildev/ @cyrilschumacher @zbarbuto /types/mailgen/ @vothanhkiet @jordanfarrer -/types/mailgun-js/ @sampsonjoliver +/types/mailgun-js/ @sampsonjoliver @andipaetzold /types/mailparser/ @psnider /types/main-bower-files/ @k-kagurazaka /types/make-dir/ @ikatyang @BendingBender /types/maker.js/ @danmarshall /types/makeup-expander/ @darkwebdev /types/makeup-floating-label/ @darkwebdev +/types/makeup-keyboard-trap/ @darkwebdev +/types/makeup-prevent-scroll-keys/ @darkwebdev /types/makeup-screenreader-trap/ @darkwebdev /types/mali-compose/ @danwbyrne /types/mali-onerror/ @danwbyrne /types/mandrill-api/ @pocesar /types/map-obj/ @BendingBender -/types/mapbox/ @anahkiasen +/types/mapbox/ @anahkiasen @Fluccioni /types/mapbox-gl/ @dobrud @patrickr /types/mapbox-gl-leaflet/ @agorshkov23 /types/mapbox__geo-viewport/ @fnberta @@ -2822,7 +2906,7 @@ /types/markdown-it-lazy-headers/ @knom /types/markdown-pdf/ @MonsieurMan /types/markdownlint/ @ark120202 -/types/marked/ @worr @BendingBender @CrossR +/types/marked/ @worr @BendingBender @CrossR @mwickett /types/marker-animate-unobtrusive/ @viskin /types/markerclustererplus/ @enanox @mxl /types/markitup/ @drillbits @@ -2868,12 +2952,13 @@ /types/materialize-css/ @huww98 @MaximBalaganskiy @MonizDave @broccoliarchy /types/math3d/ @laszlojakab @jimsmart /types/mathjax/ @rolandzwaga -/types/mathjs/ @siavol @andnp @bradbesserman +/types/mathjs/ @siavol @andnp @bradbesserman @pawkrol /types/matter-js/ @piranha771 @hasparus -/types/maxmind/ @geoffreak +/types/mcrypt/ @pluma /types/mcustomscrollbar/ @flurg /types/md5/ @arcdev1 @jprogrammer /types/md5-file/ @BamButz +/types/mdast/ @lujun2 /types/mdns/ @reppners /types/mdurl/ @rokt33r /types/media-typer/ @BendingBender @@ -2892,6 +2977,7 @@ /types/memwatch-next/ @cyrilschumacher /types/meow/ @KnisterPeter @praxxis @bitjson /types/merge-descriptors/ @danny8002 +/types/merge-env/ @BendingBender /types/merge-stream/ @k-kagurazaka @tomxtobin @daniel-zazula @djcsdy /types/merge2/ @tkrotoff @smac89 /types/merkle/ @kerol2r20 @@ -2945,12 +3031,12 @@ /types/mixpanel/ @hjellek @Manduro /types/mixto/ @vvakame /types/mjml/ @aahoughton @marpstar +/types/mjml-react/ @henrinormak /types/mkdirp/ @Bartvds @mrmlnc /types/mkdirp-promise/ @pluma /types/mkpath/ @optical /types/ml-levenberg-marquardt/ @m93a /types/mobx-apollo/ @pselden -/types/mobx-cookie/ @t49tran /types/mobx-devtools-mst/ @pluma /types/mocha/ @kazimanzurrashid @otiai10 @jt000 @enlight @cspotcode @1999 /types/mocha-each/ @magnostherobot @@ -2964,6 +3050,7 @@ /types/mock-require/ @gDelgado14 /types/mockdate/ @brunolm /types/mockery/ @jt000 +/types/mockingoose/ @hirochachacha /types/modernizr/ @borisyankov @theodorejb @leonyu @lucax88x @nhardy /types/modesl/ @neeschit /types/module-alias/ @KevinRamharak @@ -2982,7 +3069,7 @@ /types/money-math/ @taoqf /types/mongo-sanitize/ @CedricCazin /types/mongodb/v2/ @CaselIT @alanmarcell @bitjson @dante-101 @mcortesi -/types/mongodb/ @CaselIT @alanmarcell @bitjson @dante-101 @mcortesi @EnricoPicci @AJCStriker @julien-c @daprahamian @denys-bushulyak @BastienAr @sindbach @geraldinelemeur @jishi @various89 @angela-1 @lirbank @hector7 @floric +/types/mongodb/ @CaselIT @alanmarcell @bitjson @dante-101 @mcortesi @EnricoPicci @AJCStriker @julien-c @daprahamian @denys-bushulyak @BastienAr @sindbach @geraldinelemeur @jishi @various89 @angela-1 @lirbank @hector7 @floric @erikc5000 /types/mongodb-memory-server/ @dmitryrogozhny /types/mongodb-uri/ @mernxl /types/mongoose/v4/ @simonxca @horiuchi @sindrenm @lukasz-zak @@ -3040,6 +3127,7 @@ /types/murmurhash3js/ @dlee-nvisia /types/musicmetadata/ @Xstoudi /types/mustache/ @markashleybell @manuth +/types/mustache-express/ @BendingBender /types/mutexify/ @maistho /types/mv/ @nenadalm /types/mysql/ @wjohnsto @kacepe @kpping @jdmunro @@ -3078,6 +3166,8 @@ /types/nes/ @NoHomey @saboya /types/nested-error-stacks/ @woutervh- /types/net-keepalive/ @hertzg +/types/netease-captcha/ @norubidium +/types/netlify-identity-widget/ @nkprince007 /types/netmask/ @mhfrantz /types/network-interfaces/ @anderswestberg /types/new-relic-browser/ @renehamburger @piotrkubisa @@ -3112,7 +3202,8 @@ /types/ngtoaster/ @btesser /types/ngwysiwyg/ @patrick-mackay /types/nightmare/ @horiuchi @samyang-au @Bleser92 -/types/nightwatch/ @rkavalap @schlesiger +/types/nightwatch/ @rkavalap @schlesiger @ClaytonAstrom +/types/nise/ @a-tarasyuk /types/nivo-slider/ @AndersonFriaca /types/noble/ @swook @shantanubhadoria @lukel99 @bioball @keton @thegecko /types/nock/ @bonnici @horiuchi @afharo @mastermatt @damour @paambaati @@ -3123,7 +3214,7 @@ /types/node/v7/ @Microsoft @DefinitelyTyped @parambirs @tellnes @WilcoBakker @eps1lon @KSXGitHub @Archcry /types/node/v8/ @Microsoft @DefinitelyTyped @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @eps1lon @Hannes-Magnusson-CK @jkomyno @hoo29 @n-e @brunoscheufler @KSXGitHub @islishude @r3nya /types/node/v9/ @Microsoft @DefinitelyTyped @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @eps1lon @Hannes-Magnusson-CK @jkomyno @ajafff @hoo29 @n-e @brunoscheufler @mohsen1 @KSXGitHub @a-tarasyuk @islishude @r3nya @eyqs -/types/node/ @Microsoft @DefinitelyTyped @jkomyno @a-tarasyuk @alvis @r3nya @brunoscheufler @smac89 @tellnes @DeividasBakanas @eyqs @Flarna @Hannes-Magnusson-CK @KSXGitHub @hoo29 @kjin @ajafff @islishude @mwiktorczyk @matthieusieben @mohsen1 @n-e @octo-sniffle @parambirs @eps1lon @SimonSchick @ThomasdenH @WilcoBakker @wwwy3y3 @ZaneHannanAU @jeremiergz +/types/node/ @Microsoft @DefinitelyTyped @jkomyno @a-tarasyuk @alvis @r3nya @brunoscheufler @smac89 @tellnes @DeividasBakanas @eyqs @Flarna @Hannes-Magnusson-CK @KSXGitHub @hoo29 @kjin @ajafff @islishude @mwiktorczyk @matthieusieben @mohsen1 @n-e @octo-sniffle @parambirs @eps1lon @SimonSchick @ThomasdenH @WilcoBakker @wwwy3y3 @ZaneHannanAU @jeremiergz @samuela /types/node-7z/ @erkie /types/node-array-ext/ @Beng89 /types/node-cache/ @chrootsu @dthunell @useltmann @@ -3137,7 +3228,7 @@ /types/node-emoji/ @jonestristand @styu /types/node-fetch/ @torstenwerner @nikcorg /types/node-fibers/ @caryhaynie -/types/node-forge/ @westy92 @flynetworks @a-k-g @rafal2228 @beenotung @joeflateau +/types/node-forge/ @westy92 @flynetworks @a-k-g @rafal2228 @beenotung @joeflateau @Apologiz @timhwang21 /types/node-gcm/ @horiuchi /types/node-geocoder/ @rosek86 /types/node-getopt/ @kcauchy @@ -3212,7 +3303,7 @@ /types/ns-api/ @Archcry /types/nslog/ @unindented /types/nsqjs/ @cezaryrk -/types/nuka-carousel/ @Romic @altaudio +/types/nuka-carousel/ @Romic @altaudio @matt-sungwook /types/number-is-nan/ @mhegazy /types/number-to-words/ @frederickfogerty /types/numeral/ @vbortone @BehindTheMath @klujanrosas @@ -3226,8 +3317,9 @@ /types/nwmatcher/ @woutervh- /types/o.js/ @IceOnFire @bradzacher @janhommes @jcchalte /types/oauth/ @nonAlgebraic @EduardoAC +/types/oauth-shim/ @BendingBender /types/oauth.js/ @nobuoka -/types/oauth2-server/ @vangorra @cirick @d-fischer +/types/oauth2-server/ @vangorra @cirick @d-fischer @rvitorsantos /types/oauth2orize/ @wokim @heycalmdown @stevehipwell /types/obelisk.js/ @bdrupieski /types/obj-file-parser/ @benc-uk @@ -3248,6 +3340,7 @@ /types/observe-js/ @herrmanno /types/oclazyload/ @rolandzwaga /types/odata/ @janhommes @jcchalte +/types/oembed-parser/ @BendingBender /types/ofe/ @Morfent /types/office-js/ @OfficeDev @LanceEA @Zlatkovsky @kbrandl @Rick-Kirkham @AlexJerabek @ElizabethSamuel-MSFT /types/office-runtime/ @Zlatkovsky @mscharlock @@ -3271,17 +3364,18 @@ /types/opener/ @tikurahul /types/openfin/v17/ @chrisbarker /types/openfin/v29/ @chrisbarker @rdepena -/types/openfin/ @chrisbarker @rdepena @whyn07m3 +/types/openfin/v34/ @chrisbarker @rdepena @whyn07m3 +/types/openfin/ @chrisbarker @rdepena @whyn07m3 @licui3936 /types/openjscad/ @danmarshall /types/openlayers/v2/ @bolhovsky /types/openlayers/v3/ @osechet @matthiasdailey-ccri /types/openlayers/ @osechet @wb14123 @ailrun @mylen @iamthechad @danmana @yairtawil @pierremarc @hauke96 @gberaudo -/types/openpgp/ @errietta @damonpam +/types/openpgp/ @errietta @damonpam @po5i /types/openstack-wrapper/ @sanjaymadane /types/opentok/ @westy92 @CatGuardian /types/opentype.js/ @danmarshall @edzis /types/opn/ @shinnn @SomaticIT @tlent -/types/opossum/ @quinnlangille @lance +/types/opossum/ @quinnlangille @merufm @lance /types/optics-agent/ @crevil /types/optimist/ @soywiz @chbrown /types/optimize-css-assets-webpack-plugin/ @odnamrataizem @@ -3310,7 +3404,7 @@ /types/p-cancelable/ @BendingBender /types/p-catch-if/ @LinusU /types/p-debounce/ @BendingBender -/types/p-defer/ @SamVerschueren +/types/p-defer/ @SamVerschueren @BendingBender /types/p-do-whilst/ @BendingBender /types/p-each-series/ @BendingBender /types/p-event/ @BendingBender @@ -3326,6 +3420,7 @@ /types/p-one/ @BendingBender /types/p-progress/ @icopp /types/p-props/ @BendingBender +/types/p-queue/v2/ @BendingBender @evanshortiss /types/p-queue/ @BendingBender @evanshortiss /types/p-reduce/ @BendingBender /types/p-reflect/ @BendingBender @@ -3337,6 +3432,7 @@ /types/p-throttle/ @BendingBender /types/p-timeout/ @BendingBender /types/p-try/ @BendingBender @LinusU +/types/p-wait-for/v1/ @BendingBender /types/p-wait-for/ @BendingBender /types/p-whilst/ @BendingBender /types/p2/ @clark-stevenson @@ -3358,7 +3454,8 @@ /types/parity-pmd/ @leovujanic @jewbre /types/parity-pmr/ @leovujanic /types/parity-poe/ @leovujanic -/types/parse/ @dpoetzsch @jaeggerr @flavionegrao @wesleygrimes @owsas +/types/parse/v1/ @dpoetzsch @jaeggerr @flavionegrao @wesleygrimes @owsas +/types/parse/ @dpoetzsch @jaeggerr @flavionegrao @wesleygrimes @owsas @agoldis /types/parse-git-config/ @leonard-thieu @deltaidea /types/parse-github-url/ @ajafff /types/parse-glob/ @glen-84 @@ -3382,9 +3479,10 @@ /types/parsimmon/ @Bartvds @mizunashi-mana @bcherny @bvanreeven @leonard-thieu @MrJohz /types/passport/ @horiuchi @enaeseth @theigor @tlaziuk @danielpa9708 /types/passport-anonymous/ @0x6368656174 -/types/passport-auth0/ @johnbendi @iamvishnusankar +/types/passport-auth0/ @johnbendi @iamvishnusankar @duncanhall /types/passport-azure-ad/ @ShekharNain /types/passport-beam/ @AtlasDev +/types/passport-bnet/ @ivan94 /types/passport-cognito/ @mbutsykin /types/passport-discord/ @kzay /types/passport-facebook/ @staticfunction @lucasmacosta @@ -3403,7 +3501,7 @@ /types/passport-oauth2/ @pasieronen @WangZishi @EduardoAC /types/passport-oauth2-client-password/ @akaNightmare /types/passport-remember-me-extended/ @AylaJK -/types/passport-saml/ @cjbarth @dassennato +/types/passport-saml/ @cjbarth @dassennato @ksamborski /types/passport-steam/ @kzay /types/passport-strategy/ @liorm /types/passport-twitter/ @staticfunction @@ -3425,6 +3523,7 @@ /types/paypal-rest-sdk/ @trainerbill /types/pbf/ @cschwarz /types/pbkdf2/ @timonegk +/types/pdf2image/ @taoqf /types/pdfjs-dist/ @jbaldwin /types/pdfkit/ @erichillah /types/pdfmake/ @m1llen1um @radziksh @evolkmann @@ -3467,13 +3566,13 @@ /types/picturefill/ @alaz /types/pidusage/ @cyrilschumacher @mx601595686 /types/pify/ @samverschueren @mad-mike @c7hm4r -/types/pigpio/ @manerfan +/types/pigpio/ @manerfan @erikma /types/pigpio-dht/ @erikma /types/pikaday/ @MidnightDesign @wake42 @mezoistvan /types/pikaday-time/ @Sayan751 /types/pinkyswear/ @chances /types/pino/v3/ @psnider -/types/pino/ @psnider @BendingBender @screendriver @paambaati @alferpal +/types/pino/ @psnider @BendingBender @screendriver @paambaati @alferpal @mortiy /types/pino-http/ @screendriver /types/pino-multi-stream/ @JakeGinnivan /types/pinterest-sdk/ @adamburmister @@ -3483,6 +3582,7 @@ /types/pixi.js/ @clark-stevenson /types/pkg-conf/ @jorgegonzalez /types/pkg-dir/ @NK-WEB-Git +/types/pkg-up/ @forivall /types/pkijs/ @microshine /types/platform/ @JakeH /types/playcanvas/ @Neoflash1979 @@ -3503,6 +3603,12 @@ /types/podcast/ @nikeee /types/podium/ @AJamesPhillips /types/point-in-polygon/ @dyst5422 @kogai +/types/pollyjs__adapter/ @feinoujc +/types/pollyjs__adapter-fetch/ @feinoujc +/types/pollyjs__core/ @feinoujc +/types/pollyjs__persister/ @feinoujc +/types/pollyjs__persister-fs/ @feinoujc +/types/pollyjs__utils/ @feinoujc /types/polyfill-service/ @Alorel /types/polylabel/ @DenisCarriere /types/polyline/ @Kern0 @@ -3513,7 +3619,11 @@ /types/postal/ @lokeshpeta @myitcv /types/postcss-calc/ @huan086 /types/postcss-icss-values/ @huan086 +/types/postcss-modules-extract-imports/ @huan086 +/types/postcss-modules-local-by-default/ @huan086 /types/postcss-modules-resolve-imports/ @huan086 +/types/postcss-modules-scope/ @huan086 +/types/postcss-url/ @lenovouser /types/postman-collection/ @kbuzby /types/postmark/ @benbayard @jineshshah36 /types/pouch-redux-middleware/ @charrondev @@ -3563,21 +3673,23 @@ /types/promise-ftp/ @coolreader18 /types/promise-ftp-common/ @coolreader18 /types/promise-map-limit/ @kohlmannj +/types/promise-memoize/ @forivall /types/promise-pg/ @coldacid -/types/promise-polyfill/ @skysteve +/types/promise-polyfill/ @skysteve @djcsdy /types/promise-pool/ @vilic /types/promise-queue/ @LachlanStuart /types/promise-retry/ @shirakaba /types/promise-sftp/ @coolreader18 /types/promise-timeout/ @Aankhen /types/promise.prototype.finally/ @slavik57 @BendingBender +/types/promised-ldap/ @pluma /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/prompts/ @Berkays +/types/prompts/ @Berkays @danielpa9708 /types/prop-types/ @DovydasNavickas @ferdaber /types/proper-lockfile/ @qlonik /types/properties-reader/ @Goldsmith42 @@ -3610,12 +3722,13 @@ /types/ptomasroos__react-native-multi-slider/ @Slessi /types/pty.js/ @enlight /types/public-ip/ @BendingBender -/types/pubnub/ @bitbankinc @rollymaduk @vitosamson +/types/pubnub/ @bitbankinc @rollymaduk @vitosamson @FlorianDr /types/pubsub-js/ @borisyankov /types/pug/ @TonyPythoneer @19majkel94 /types/pulltorefreshjs/ @DanielRosenwasser @humpedli /types/pump/ @tlaziuk /types/pumpify/ @JustinBeckwith @aoberoi +/types/punycode/ @yavanosta /types/pupa/ @nju33 /types/puppeteer/v0/ @marvinhagemeister @cdeutsch /types/puppeteer/ @marvinhagemeister @cdeutsch @ksm2 @SimonSchick @@ -3651,13 +3764,22 @@ /types/qwest/ @lindsayevans /types/r-script/ @NaridaL /types/rabbit.js/ @wokim +/types/rabbitmq-schema/ @rulezzz1987 /types/radium/ @alexgorbatchev @nupplaphil @asvetliakov /types/radius/ @codeanimal +/types/radix64/ @huan086 /types/ramda/ @donnut @tycho01 @mdekrey @mrdziuban @sbking @afharo @teves-castro @1M0reBug @hojberg @samsonkeung @angeloocana @raynerd @googol @moshensky @ethanresnick @leighman @CaptJakk @deftomat @deptno @blimusiek @biern @rayhaneh @rgm @drewwyatt +/types/random-boolean/ @BendingBender +/types/random-float/ @BendingBender +/types/random-int/ @BendingBender +/types/random-item/ @BendingBender /types/random-js/ @pistacchio /types/random-number/ @OpenByteDev +/types/random-obj-key/ @BendingBender +/types/random-obj-prop/ @BendingBender /types/random-seed/ @endel /types/random-string/ @stpettersens +/types/randombytes/ @BendingBender /types/randomcolor/ @feitzi @BradyLiles /types/range-parser/ @tlaziuk /types/rangyinputs/ @ersimont @@ -3681,9 +3803,11 @@ /types/raygun4js/ @xt0rted @BenjaminHarding @UberMouse /types/rbac-a/ @tlaziuk /types/rc/ @DanielRosenwasser +/types/rc-progress/ @jussikinnula /types/rc-select/ @DenisTirilis /types/rc-slider/ @mantasmarcinkus @mattoni @paustint @j-fro @Deanna2 /types/rc-time-picker/ @Hoff97 +/types/rc-tooltip/ @rhysd @ahstro @vsaarinen /types/rc-tree/ @johnnyreilly @Methuselah96 /types/rcloader/ @panuhorsmalahti /types/rdf-data-model/ @rubensworks @@ -3691,8 +3815,8 @@ /types/rdflib/ @cenotelie /types/re-base/ @jordandrako /types/reach__router/ @kingdaro -/types/react/v15/ @bbenezech @pzavolinsky @digiguru @ericanderson @morcerf @tkrotoff @DovydasNavickas @onigoetz -/types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @morcerf @tkrotoff @DovydasNavickas @onigoetz @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei +/types/react/v15/ @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz +/types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei @Kovensky /types/react-adal/ @dkorolev1 /types/react-albus/ @sseppola @conradreuter @kuirak /types/react-alert/v2/ @ssyrell @@ -3708,7 +3832,8 @@ /types/react-avatar-editor/ @diogocorrea @gabsprates /types/react-beautiful-dnd/ @varHarrie @bradleyayers @paustint @marknelissen /types/react-better-password/ @mhuynh1 -/types/react-big-calendar/ @piotrwitek @paustint @pikpok @eps1lon @strongpauly +/types/react-big-calendar/ @piotrwitek @paustint @pikpok @eps1lon @strongpauly @janb87 +/types/react-blessed/ @me /types/react-body-classname/ @mhegazy /types/react-bootstrap/ @walkerburgin @vsiao @danilojrr @Batbold-Gansukh @octatone @chengsieuly @mretolaza @katbusch @vitosamson @LKay @aaronbeall @jrakotoharisoa @r3nya @t49tran /types/react-bootstrap-date-picker/ @LKay @ssi-hu-antal-bodnar @@ -3720,6 +3845,7 @@ /types/react-breadcrumbs-dynamic/ @mitsuruog /types/react-broadcast/ @kandros /types/react-burger-menu/ @radziksh +/types/react-cache/ @skovy /types/react-calendar-heatmap/ @9renpoto /types/react-calendar-timeline/ @radziksh @acemac /types/react-cartographer/ @trevonmckay @@ -3738,6 +3864,7 @@ /types/react-countup/ @danielbrodin /types/react-credit-cards/ @vstrimaitis @olefrank /types/react-cropper/ @stepancar +/types/react-css-collapse/ @dford07 /types/react-css-modules/ @KostyaEsmukov @skirsdeda /types/react-css-transition-replace/ @LKay /types/react-currency-formatter/ @pastushenkoy @Jeka-Vasiliev @@ -3748,7 +3875,7 @@ /types/react-data-grid/ @SupernaviX @KieranPeat @martinnov92 @baso53 /types/react-datagrid/ @stephenjelfs /types/react-date-range/ @Junbong -/types/react-datepicker/ @radziksh @andrewBalekha @smrq @Rogach @royxue @KoalaHuman @seansfkelley +/types/react-datepicker/ @radziksh @andrewBalekha @smrq @Rogach @royxue @KoalaHuman @seansfkelley @justingrant @jakeboone02 /types/react-daterange-picker/ @uncovertruth @MartynasZilinskas @donaldtf @vladflorescu94 /types/react-dates/ @ArturAmpilogov @NathanNZ /types/react-daum-postcode/ @Sa-ryong @@ -3775,7 +3902,7 @@ /types/react-file-reader-input/ @dmitryrogozhny @alitaheri /types/react-flag-icon-css/ @jonfreedman /types/react-flags-select/ @senukartur -/types/react-flatpickr/ @begincalendar +/types/react-flatpickr/ @begincalendar @snaveevans /types/react-flex/ @pushplay /types/react-flexr/ @pushplay /types/react-fontawesome/ @timurrustamov @dublicator @vincaslt @gavingregory @@ -3814,17 +3941,17 @@ /types/react-infinite/ @rhysd /types/react-infinite-calendar/ @christianchown /types/react-infinite-scroll-component/ @sroy3 @burtek @davidkevork @JoshuaScript -/types/react-infinite-scroller/ @Lapanti @psrebniak @WrathZA +/types/react-infinite-scroller/ @Lapanti @psrebniak @WrathZA @daggerjames /types/react-input-autosize/ @jsonunger @franklixuefei /types/react-input-calendar/ @stepancar /types/react-input-mask/v1/ @apare /types/react-input-mask/ @apare @dima7a14 /types/react-instantsearch/ @gburgett @jpowell -/types/react-instantsearch-core/ @gburgett @jpowell +/types/react-instantsearch-core/ @gburgett @jpowell @davidfurlong /types/react-instantsearch-dom/ @gburgett @jpowell /types/react-instantsearch-native/ @gburgett @jpowell /types/react-intl/v1/ @bgrieder -/types/react-intl/ @bgrieder @cdroulers @gyzerok @tillwolff @LKay @bhouser @kristerkari @formatlos @lukyth +/types/react-intl/ @bgrieder @cdroulers @gyzerok @tillwolff @LKay @bhouser @kristerkari @formatlos @lukyth @obedm503 /types/react-intl-redux/ @LKay /types/react-is/ @AviVahl @christianchown /types/react-is-deprecated/ @seansfkelley @@ -3833,11 +3960,12 @@ /types/react-json/ @spielc /types/react-json-pretty/ @LKay /types/react-json-tree/ @gnestor -/types/react-jsonschema-form/ @iamdanfox @iplus26 @KurtPreston @phbou72 @LucianBuzzo @sthenault @sbusch +/types/react-jsonschema-form/ @iamdanfox @iplus26 @phbou72 @LucianBuzzo @sthenault @sbusch /types/react-jss/ @eps1lon /types/react-lazyload/ @m0a /types/react-lazylog/ @benjaminRomano /types/react-leaflet/ @danzel @davschne @yuit +/types/react-leaflet-markercluster/ @Kimahriman /types/react-lifecycle-component/ @pixelshaded /types/react-list/ @buptyyf @tomshen /types/react-loadable/ @Kovensky @odensc @ianks @tlaziuk @iMobs @@ -3865,16 +3993,18 @@ /types/react-native-communications/ @huhuanming @PaitoAnderson /types/react-native-custom-tabs/ @philnova /types/react-native-datepicker/ @jacobbaskin -/types/react-native-dialog/ @MrLuje +/types/react-native-dialog/ @MrLuje @stackbuilders @ibarrae /types/react-native-dialogflow/ @jasonmerino /types/react-native-doc-viewer/ @iRoachie /types/react-native-document-picker/ @plantain-00 +/types/react-native-draggable-flatlist/ @stackbuilders @ibarrae /types/react-native-drawer/ @jnbt @suniahk /types/react-native-drawer-layout/ @jmfirth /types/react-native-elevated-view/ @fhelwanger /types/react-native-fabric/ @josephroque /types/react-native-fbsdk/ @ifiokjr /types/react-native-fetch-blob/ @MNBuyskih +/types/react-native-flip-card/ @imjakechapman /types/react-native-fs/ @pocesar @josephroque /types/react-native-google-signin/ @j-fro @bm-software @christianchown @echentw /types/react-native-htmlview/ @ifiokjr @@ -3903,6 +4033,7 @@ /types/react-native-referrer/ @christianchown /types/react-native-restart/ @christianchown /types/react-native-safari-view/ @mrand01 +/types/react-native-safe-area/ @pvinis /types/react-native-scaled-image/ @Jaeger25 /types/react-native-scrollable-tab-view/ @CaiHuan @egorshulga /types/react-native-sensor-manager/ @SahinVardar @@ -3927,7 +4058,7 @@ /types/react-native-version-number/ @VincentLanglet /types/react-native-video/ @huhuanming /types/react-navigation/v1/ @huhuanming @mhcgrq @fangpenlin @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @YourGamesBeOver @ArmandoAssuncao @cliedeman @Slessi -/types/react-navigation/ @huhuanming @mhcgrq @fangpenlin @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @YourGamesBeOver @ArmandoAssuncao @cliedeman @Slessi @magrinj @TizioFittizio @stigi @LinusU @jshosomichi @jakebooyah @brunoro @DenisFrezzato @mickaelw @maxdavidson @jkillian +/types/react-navigation/ @huhuanming @mhcgrq @fangpenlin @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @YourGamesBeOver @ArmandoAssuncao @cliedeman @magrinj @TizioFittizio @stigi @LinusU @jshosomichi @jakebooyah @brunoro @DenisFrezzato @mickaelw @maxdavidson @alechill @builtbyproxy @jkillian @jeroenvervaeke @chagasaway /types/react-navigation-material-bottom-tabs/ @iRoachie /types/react-no-ssr/ @rafalfilipek /types/react-notification-system/ @GiedriusGrabauskas @DeividasBakanas @LKay @sztobar @@ -3941,7 +4072,8 @@ /types/react-overlays/ @aaronbeall @vitosamson /types/react-owl-carousel/ @tbounsiar @igorissen @KennethanCeyer /types/react-paginate/v4/ @deevus @wouterhardeman @pegel03 @archy-bold -/types/react-paginate/ @deevus @wouterhardeman @pegel03 @archy-bold @yasupeke +/types/react-paginate/v5/ @deevus @wouterhardeman @pegel03 @archy-bold @yasupeke +/types/react-paginate/ @deevus @wouterhardeman @pegel03 @archy-bold @yasupeke @sugarshin /types/react-places-autocomplete/ @guilhermehubner @r3nya /types/react-plotly.js/ @jonfreedman /types/react-pointable/ @istefo @mdibyo @@ -3955,7 +4087,7 @@ /types/react-recaptcha/ @mhegazy @zzanol /types/react-reconciler/ @Methuselah96 /types/react-redux/v5/ @tkqubo @thasner @kenzierocks @clayne11 @tansongyang @nicholasboll @mdibyo @pdeva -/types/react-redux/ @tkqubo @kenzierocks @clayne11 @tansongyang @nicholasboll @mdibyo @pdeva @kallikrein @val1984 @jrakotoharisoa @apapirovski +/types/react-redux/ @tkqubo @kenzierocks @clayne11 @tansongyang @nicholasboll @mdibyo @pdeva @kallikrein @val1984 @jrakotoharisoa @apapirovski @surgeboris /types/react-redux-epic/ @forabi /types/react-redux-i18n/ @clementdevos /types/react-redux-toastr/ @Smiche @artyomsv @kulmajaba @@ -3970,7 +4102,7 @@ /types/react-router/v3/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @ssorallen @gillchristian @nulladdict /types/react-router/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @tkrotoff @huy-nguyen @grmiade @DaIgeb @egorshulga @neuoy @rraina @pret-a-porter @t49tran @8enSmith /types/react-router-bootstrap/ @vlesierse @LKay @olmobrutall -/types/react-router-config/ @lith-light-g @johnnyreilly +/types/react-router-config/ @lith-light-g @johnnyreilly @NullMDR /types/react-router-dom/ @tkrotoff @huy-nguyen @p-jackson @johnnyreilly /types/react-router-hash-link/ @zoompie /types/react-router-native/ @ezintz @fhelwanger @@ -3989,7 +4121,7 @@ /types/react-show-more/ @naortor /types/react-side-effect/ @remojansen @0xcaff /types/react-sidebar/ @jeroenvervaeke -/types/react-sketchapp/ @ricokahler @DomiR +/types/react-sketchapp/ @ricokahler @DomiR @saschazar21 /types/react-slick/ @andrewBalekha @GiedriusGrabauskas @r3nya /types/react-slider/ @jsonunger /types/react-smooth-scrollbar/ @asvetliakov @@ -4000,12 +4132,13 @@ /types/react-sparklines/ @henrinormak /types/react-spinkit/v1/ @tkqubo @mleko @pelotom /types/react-spinkit/ @tkqubo @mleko @pelotom @zzanol +/types/react-splitter-layout/ @snaptags /types/react-star-rating-component/ @marpstar /types/react-sticky/ @curtisw0 @ajhyndman /types/react-sticky-box/ @koss-lebedev /types/react-sticky-el/ @jbraithwaite /types/react-stickynode/ @tstirrat -/types/react-stripe-elements/ @dan-j @santiagodoldan @sonnysangha @9y5 @thchia +/types/react-stripe-elements/ @dan-j @santiagodoldan @sonnysangha @9y5 @thchia @yhnavein /types/react-svg-inline/ @kiyopikko /types/react-svg-pan-zoom/ @huy-nguyen /types/react-swf/ @stepancar @@ -4013,7 +4146,7 @@ /types/react-swipeable/ @GiedriusGrabauskas @mctep @horiuchi /types/react-swipeable-views/ @mxl @DeividasBakanas /types/react-syntax-highlighter/ @NoHomey @ajgamble-milner -/types/react-table/ @royxue @psakalo @Havret @andys8 +/types/react-table/ @royxue @psakalo @Havret @andys8 @Gelio /types/react-table-filter/ @gjsln /types/react-tabs/ @danez @Equationist /types/react-tag-autocomplete/ @jlismore @@ -4043,9 +4176,9 @@ /types/react-user-tour/ @ccancellieri /types/react-vertical-timeline-component/ @stephane-monnot /types/react-virtual-keyboard/ @bsurai -/types/react-virtualized/ @kaoDev @guntherjh @wasd171 @szabolcsx @kraenhansen @Stevearzh @mgoszcz2 @brandonhall +/types/react-virtualized/ @kaoDev @guntherjh @wasd171 @szabolcsx @kraenhansen @Stevearzh @mgoszcz2 @brandonhall @sbusch /types/react-virtualized-select/ @seansfkelley -/types/react-visibility-sensor/ @JRasmusBm +/types/react-visibility-sensor/ @JRasmusBm @gcangussu /types/react-webcam/ @squat /types/react-weui/ @tairan /types/react-widgets/ @rogierschouten @sanyatuning @frodehansen2 @r3nya @MBillemaz @georg94 @@ -4057,7 +4190,7 @@ /types/reactable/ @spielc /types/reactcss/ @chrisgervang @LKay /types/reactstrap/v4/ @alihammad @mfal @danilobjr @fabiopaiva -/types/reactstrap/ @alihammad @mfal @danilobjr @FaithForHumans @KurtPreston @timc13 @patrickrgaffney @prabodht +/types/reactstrap/ @alihammad @mfal @danilobjr @FaithForHumans @timc13 @patrickrgaffney @prabodht /types/read/ @timjk /types/read-chunk/ @crispybee /types/read-package-tree/ @mgroenhoff @@ -4068,14 +4201,15 @@ /types/readline-sync/ @jonestristand /types/readline-transform/ @dex4er /types/reapop/ @Barrokgl -/types/rebass/ @ryee-dev +/types/rebass/ @ryee-dev @jamesmckenzie /types/rebass__grid/ @antonvasin @vittorio @lhache @lavoaster /types/recaptcha2/ @l-jonas /types/recase/ @18steps -/types/recharts/ @mthmulders @rapmue @royxue @ZheyangSong @richbai90 @caspeco-dan @pkeuter @jrsaunde @paulmelnikow @crusectrl @apalugniok +/types/recharts/ @mthmulders @rapmue @royxue @ZheyangSong @richbai90 @caspeco-dan @pkeuter @jrsaunde @paulmelnikow @crusectrl @apalugniok @RobertStigsson /types/recharts-scale/ @johnnyreilly +/types/rechoir/ @BendingBender /types/recluster/ @dex4er -/types/recompose/ @iskandersierra @mrapogee @clayne11 @Pajn @lucasterra @brian-lives-outdoors +/types/recompose/ @iskandersierra @clayne11 @Pajn @lucasterra @brian-lives-outdoors @TiuSh /types/reconnect-core/ @thw0rted /types/reconnectingwebsocket/ @nguarracino /types/recorder-js/ @higuri @@ -4084,7 +4218,7 @@ /types/redis/ @soywiz @CodeAnimal @MugeSo @UppaJung @Rokt33r @43081j @barnski @1pete /types/redis-errors/ @43081j /types/redis-mock/ @BendingBender -/types/redis-rate-limiter/ @westy92 +/types/redis-rate-limiter/ @westy92 @nodify-at /types/redis-scripto/ @westy92 /types/redlock/v2/ @chrootsu /types/redlock/ @chrootsu @BendingBender @@ -4102,7 +4236,7 @@ /types/redux-devtools-dock-monitor/ @mc-petry /types/redux-devtools-log-monitor/ @mc-petry /types/redux-doghouse/ @BendingBender -/types/redux-first-router/ @Valbrand @viggyfresh @janb87 @corydeppen @jscinoz @surgeboris +/types/redux-first-router/ @Valbrand @viggyfresh @janb87 @corydeppen @jscinoz @surgeboris @geirsagberg /types/redux-first-router-link/ @janb87 /types/redux-first-router-restore-scroll/ @icopp /types/redux-first-routing/ @tlaziuk @@ -4111,7 +4245,7 @@ /types/redux-form/ @carsonf @aikoven @LKay @bancek @alsiola @tehbi4 @huwmartin @ethanresnick @reggino @maddijoyce @smifun /types/redux-immutable/v3/ @oizie @sebald @gavingregory /types/redux-immutable/ @oizie @sebald @gavingregory @lukyth -/types/redux-immutable-state-invariant/ @remojansen @highflying +/types/redux-immutable-state-invariant/ @remojansen @highflying @mihai-dinculescu /types/redux-infinite-scroll/ @silkyfray /types/redux-injectable-store/ @unindented /types/redux-localstorage/ @LKay @@ -4129,7 +4263,8 @@ /types/redux-promise-middleware/ @ianks /types/redux-recycle/ @LKay /types/redux-router/ @stepancar -/types/redux-saga-tester/ @BenLorantfy +/types/redux-saga-tester/ @BenLorantfy @lawsumisu +/types/redux-sentry-middleware/ @dolezel /types/redux-shortcuts/ @tstirrat /types/redux-socket.io/ @snakeego /types/redux-storage/ @asvetliakov @@ -4212,8 +4347,10 @@ /types/riot-route/ @karak /types/riotcontrol/ @chrootsu /types/riotjs/ @vvakame +/types/ripemd160/ @BendingBender /types/rison/ @impworks /types/rivets/ @TrevorDev @matjanos +/types/rmc-drawer/ @Hoff97 /types/rmfr/ @pluma /types/roads/ @dancespiele /types/roads-server/ @dancespiele @@ -4221,8 +4358,9 @@ /types/roll/ @icopp /types/rolling-rate-limiter/ @l-jonas /types/rollup-plugin-json/ @asmockler @hotell +/types/roman-numerals/ @pluma /types/ronomon__crypto-async/ @BendingBender -/types/rosie/ @abner @subvertallchris @abukurov +/types/rosie/ @abner @subvertallchris @abukurov @adam187 /types/roslib/ @Pro @skycoop @dgorobopec /types/rot-js/ @atiaxi /types/round-to/ @seangenabe @@ -4278,11 +4416,18 @@ /types/sanitize-filename/ @Nemo157 /types/sanitize-html/ @rogierschouten @afshin @BehindTheMath @biermeester @WillGibson @sirMerr /types/sap__xsenv/ @mad-mike +/types/sasl-anonymous/ @BendingBender +/types/saslmechanisms/ @BendingBender +/types/sass/ @lenovouser /types/sass-graph/ @marvinhagemeister /types/sass-webpack-plugin/ @AepKill /types/sat/ @omni360 /types/satnav/ @DotNetNerd /types/saywhen/ @SeanSobey +/types/sc-auth/ @DanielRose +/types/sc-broker/ @DanielRose +/types/sc-broker-cluster/ @DanielRose +/types/sc-channel/ @DanielRose /types/scalike/ @ryoppy /types/schedule/ @Methuselah96 /types/scheduler/ @Methuselah96 @@ -4367,7 +4512,9 @@ /types/session-file-store/ @blendsdk @rokt33r /types/set-cookie-parser/ @nickp10 /types/set-value/ @DanielRosenwasser +/types/setasap/ @djcsdy /types/settings/ @shreyjain1994 +/types/sha.js/ @BendingBender /types/sha1/ @arcdev1 /types/sha256/ @nhardy /types/shallow-equals/ @rsolomon @@ -4391,6 +4538,7 @@ /types/shot/ @AJamesPhillips @SimonSchick /types/should-sinon/ @Arylo /types/showdown/ @cbowdon @tan9 @arielsaldana +/types/shpjs/ @littlebtc /types/shrink-ray/ @forabi /types/shuffle-seed/ @LeartS /types/siema/ @Irmiz @0x6368656174 @samnau @@ -4407,7 +4555,7 @@ /types/simple-lru/ @NN--- /types/simple-mock/ @leonyu /types/simple-oauth2/v1/ @mad-mike @troy-lamerton @netux -/types/simple-oauth2/ @mad-mike @troy-lamerton @netux +/types/simple-oauth2/ @mad-mike @troy-lamerton @netux @LinusU /types/simple-peer/ @tlaziuk /types/simple-url-cache/ @a-lucas /types/simple-websocket/ @dex4er @@ -4420,7 +4568,7 @@ /types/sindresorhus__df/ @whatknight /types/single-line-log/ @ffflorian /types/single-spa-react/ @Garrett-Smith-iq -/types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j @joshuakgoldberg @gjednaszewski +/types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j @joshuakgoldberg @gjednaszewski @johnjesse /types/sinon-as-promised/ @igrayson /types/sinon-chai/v2/ @kazimanzurrashid @jedmao /types/sinon-chai/ @kazimanzurrashid @jedmao @elpdpt @@ -4437,7 +4585,7 @@ /types/sjcl/ @Evgenus /types/skatejs/ @Hotell /types/ski/ @AyaMorisawa -/types/skyway/ @nakakura +/types/skyway/ @nakakura @izmhr /types/slack-mock/ @kkalavantavanich /types/slack-node/ @geoffreak /types/slack-winston/ @BlueHatbRit @@ -4448,18 +4596,21 @@ /types/slate-html-serializer/ @YangusKhan /types/slate-irc/ @elisee /types/slate-plain-serializer/ @YangusKhan @mkiefel -/types/slate-react/ @andykent @majelbstoat @JanLoebel @PatrickSachs @YangusKhan @isubasti @sgreav +/types/slate-react/ @andykent @majelbstoat @JanLoebel @PatrickSachs @YangusKhan @isubasti @sgreav @Kornil /types/sleep/ @rajarz +/types/slice-ansi/ @dwieeb /types/slickgrid/ @jbaldwin /types/slideout/ @ToastHawaii /types/slimerjs/ @alexwall /types/slocket/ @BendingBender /types/slug/ @mhegazy /types/smart-fox-server/ @ChanceM +/types/smooth-scroll/ @andreiho /types/smoothscroll-polyfill/ @kryops /types/smtp-server/v1/ @markisme @Taisiias /types/smtp-server/ @markisme @Taisiias @dex4er /types/smtpapi/ @a-morales +/types/snakecase-keys/ @BendingBender /types/snappy/ @reconbot /types/snapsvg/ @lhk @mattanja @kant2002 /types/snazzy-info-window/ @milosd92 @@ -4474,6 +4625,9 @@ /types/socket.io-parser/ @plantain-00 /types/socket.io-redis/ @nupplaphil @seeLuck /types/socket.io.users/ @kataras +/types/socketcluster/ @DanielRose +/types/socketcluster-client/ @DanielRose +/types/socketcluster-server/ @DanielRose /types/socketio-jwt/ @ehallander9591 /types/socketio-jwt-auth/ @codeanimal /types/socketio-wildcard/ @BendingBender @@ -4485,6 +4639,7 @@ /types/solution-center-communicator/ @dami-gg /types/sonic-boom/ @alferpal /types/sort-array/ @mrmlnc +/types/sort-object-keys/ @forivall /types/sortablejs/ @Maw-Fox @maartenstaa /types/soundmanager2/ @elton2048 /types/soupbintcp/ @jewbre @@ -4502,7 +4657,7 @@ /types/spdy/ @tony19 /types/speakeasy/ @legendecas @mrOlorin @xeoneux /types/speakingurl/ @Goldsmith42 -/types/spectacle/ @zmaybury +/types/spectacle/ @zmaybury @kale-stew /types/spectrum/ @M-Zuber @Ailrun /types/split/ @marcinporebski /types/split.js/ @icholy @@ -4514,6 +4669,7 @@ /types/sprintf/ @soywiz @BendingBender /types/sprintf-js/ @jasonswearingen @BendingBender @cdagli /types/sql-bricks/ @adn05 @paleo +/types/sql-template/ @q42jaap /types/sql.js/ @Hozuki /types/sqlanywhere/ @pkeuter /types/sqlite3/ @nmalaguti @dpyro @BehindTheMath @@ -4521,8 +4677,8 @@ /types/squirejs/ @bradleyayers /types/srp/ @Patman64 /types/ssh-key-decrypt/ @BendingBender -/types/ssh2/ @tkQubo @rbuckton @wrboyce -/types/ssh2-sftp-client/ @igrayson @ascariandrea @kartik2406 +/types/ssh2/ @tkQubo @rbuckton @wrboyce @lucasmotta +/types/ssh2-sftp-client/ @igrayson @ascariandrea @kartik2406 @viamuli /types/ssh2-streams/ @rbuckton /types/sshpk/ @mabels /types/stack-mapper/ @rogierschouten @@ -4552,9 +4708,9 @@ /types/sticky-cluster/ @paustint /types/stompit/ @DanielRose /types/stompjs/ @jimic @Dr4k4n -/types/stoppable/ @EricByers +/types/stoppable/ @EricByers @jplusje /types/storage-helper/ @ajafff -/types/store/ @vbortone @harry0000 @Ky6uk +/types/store/ @vbortone @harry0000 @Ky6uk @igl00 /types/storybook-addon-jsx/ @jameslnewell /types/storybook-readme/ @lonyele /types/storybook__addon-a11y/ @hyunseob @@ -4566,10 +4722,10 @@ /types/storybook__addon-knobs/ @joscha @martynaskadisa @amacleay /types/storybook__addon-links/ @joscha @jessepinho /types/storybook__addon-notes/ @joscha @amacleay -/types/storybook__addon-options/ @joscha @simonhn @amacleay +/types/storybook__addon-options/ @joscha @simonhn @amacleay @gaetanmaisse @adam187 /types/storybook__addon-storyshots/ @bradleyayers -/types/storybook__react/ @joscha @wapgear -/types/storybook__react-native/ @joscha @wapgear @alechill @iRoachie +/types/storybook__react/ @joscha @wapgear @dandean +/types/storybook__react-native/ @joscha @wapgear @alechill @iRoachie @ceyhuno /types/storybook__vue/ @pntgupta /types/stream-array/ @Tyler-Murphy /types/stream-buffers/ @Jason3S @@ -4584,6 +4740,7 @@ /types/stream-to-array/v0/ @Bartvds /types/stream-to-array/ @Bartvds @BendingBender /types/stream-to-promise/ @Alorel +/types/stream-to-string/ @BendingBender /types/streaming-json-stringify/ @BendingBender /types/streamjs/ @erosb /types/streamtest/ @lummish @@ -4606,7 +4763,7 @@ /types/stripe-checkout/ @cgwrench /types/stripe-v2/ @ejsmith @amritk @adamcmiel @jleider @galuszkak /types/stripe-v3/ @ejsmith @amritk @adamcmiel @jleider @galuszkak -/types/stripejs/ @RobinvanTienhoven +/types/stripejs/ @RobinvanTienhoven @mattferderer /types/strong-cluster-control/ @shuntksh /types/strong-error-handler/ @blankstar85 /types/strong-log-transformer/ @azasypkin @@ -4614,7 +4771,7 @@ /types/strophe.js/ @DavidKDeutsch /types/structured-source/ @azu /types/styled-components/v3/ @Igorbek @Igmat -/types/styled-components/ @Igorbek @Igmat @lavoaster +/types/styled-components/ @Igorbek @Igmat @lavoaster @Kovensky /types/styled-jsx/ @R1ZZU /types/styled-react-modal/ @Lavoaster /types/styled-system/ @maxdeviant @phobon @zephraph @damassi @alloy @maoueh @lavoaster @jschuler @@ -4634,7 +4791,7 @@ /types/sumo-logger/ @forabi @clementallen /types/suncalc/ @horiuchi /types/superagent/v2/ @varju @NicoZelaya @mxl -/types/superagent/ @NicoZelaya @mxl @paplorinc @shreyjain1994 @zopf @beeequeue +/types/superagent/ @NicoZelaya @mxl @paplorinc @shreyjain1994 @zopf @beeequeue @lukaselmer /types/superagent-bunyan/ @bricka /types/superagent-no-cache/ @mxl /types/superagent-prefix/ @mxl @@ -4658,7 +4815,7 @@ /types/sw-precache/ @JounQin /types/sw-precache-webpack-plugin/ @JounQin /types/swag/ @shiwano -/types/swagger-express-middleware/ @alexandreroba +/types/swagger-express-middleware/ @alexandreroba @tromgy /types/swagger-express-mw/ @micmro /types/swagger-express-validator/ @pinguet62 /types/swagger-hapi/ @micmro @@ -4690,8 +4847,9 @@ /types/tabbable/ @mokkan /types/table/ @evanshortiss @mrmlnc /types/tableau/ @protip +/types/tableify/ @forivall /types/tabris-plugin-firebase/ @eclipsesource -/types/tabtab/ @vojtechhabarta +/types/tabtab/ @vojtechhabarta @kamontat /types/tabulator/ @euginio /types/tail/ @spacejack /types/tapable/v0/ @e-cloud @@ -4721,7 +4879,7 @@ /types/tether-drop/ @adidahiya /types/tether-shepherd/ @mtgibbs /types/text-buffer/ @GlenCFL -/types/text-encoding/ @pine613 @mohsen1 @nwmqpa +/types/text-encoding/ @pine @mohsen1 @nwmqpa /types/text-encoding-utf-8/ @trxcllnt /types/text-table/ @saadq /types/textarea-caret/ @shiftkey @@ -4732,7 +4890,8 @@ /types/theming/ @eps1lon /types/theo/ @petekp /types/thepiratebay/ @jsorrell -/types/three/ @gyohk @florentpoujol @SereznoKot @omni360 @ivoisbelongtous @piranha771 @qszhusightp @nakakura @s093294 @Pro @efokschaner @PsychoSTS @dhritzkiv @apurvaojas @NotWoods @sethk @elk941 @Methuselah96 @Dukuo @JulianSSS @devilsparta +/types/three/ @gyohk @florentpoujol @SereznoKot @omni360 @ivoisbelongtous @piranha771 @qszhusightp @nakakura @s093294 @Pro @efokschaner @PsychoSTS @dhritzkiv @apurvaojas @NotWoods @sethk @elk941 @Methuselah96 @Dukuo @JulianSSS @devilsparta @KonstantinLukaschenko +/types/three-tds-loader/ @KonstantinLukaschenko @sschoensee /types/thrift/ @kamek-pf @kevin-greene-ck @jessezhang91 /types/throng/ @cyrilschumacher @tatethurston /types/throttle/ @BendingBender @@ -4742,6 +4901,7 @@ /types/through2/ @Bartvds @jedmao @valotas @TeamworkGuy2 @Alorel /types/through2-concurrent/ @Alorel /types/through2-map/ @LucasHill +/types/tildify/ @BendingBender /types/tile-reduce/ @DenisCarriere /types/tilebelt/ @DenisCarriere /types/time-span/ @BendingBender @mdvorscak @@ -4749,6 +4909,8 @@ /types/timelinejs3/ @MikeMatusz /types/timer-machine/ @dolanmiu /types/timezone-js/ @bonnici +/types/timing-safe-equal/ @BendingBender +/types/timsort/ @Vunovati /types/tinajs__tina/ @Jimexist /types/tinajs__tina-redux/ @Jimexist /types/tinder/ @pingec @@ -4773,7 +4935,7 @@ /types/toastr/ @borisyankov /types/tocktimer/ @evanshortiss /types/tokgen/ @l-jonas -/types/toobusy-js/ @atd-schubert +/types/toobusy-js/ @atd-schubert @BendingBender /types/tooltipster/ @stephenlautier @pjmagee @VorobeY1326 @leonard-thieu @janhi @joeskeen /types/topojson/ @ricardo-mello @chenzhutian @denisname /types/topojson-client/ @denisname @ricardo-mello @@ -4787,7 +4949,7 @@ /types/tough-cookie/ @leonard-thieu @LiJinyao @no2chem /types/tough-cookie-filestore/ @friedow /types/traceback/ @misak113 -/types/tracking/ @pimterry +/types/tracking/ @pimterry @bratter /types/transducers-js/ @colinkahn @dphilipson @NaridaL /types/transducers.js/ @dphilipson /types/transliteration/ @tony19 @@ -4806,13 +4968,14 @@ /types/tspromise/ @soywiz /types/ttf2woff2/ @ThomasdenH /types/tunnel/ @BendingBender -/types/tus-js-client/ @kevhiggins +/types/tus-js-client/ @kevhiggins @Acconut /types/tv4/ @Bartvds @psnider /types/tween.js/ @Amos47 @sunetos @jzarnikov @alexburner /types/tweenjs/ @evilangelist @jcyuan /types/tweezer.js/ @praxxis /types/twig/ @soywiz @enko /types/twilio/ @nickiannone @ashleybrener +/types/twilio-common/ @gatimus /types/twilio-video/ @minddocdev @darioblanco /types/twit/ @Volox @sapphiredev @abraham @siwalikm @plhery /types/twitch-ext/ @beheh @@ -4857,7 +5020,9 @@ /types/uniqid/ @idchlife /types/unique-hash-stream/ @BendingBender /types/unique-random/ @Kuniwak -/types/unist/ @bizen241 +/types/unique-random-array/ @BendingBender +/types/unist/ @bizen241 @lujun2 @hrajchert @wooorm @rokt33r +/types/unist-util-is/ @rokt33r /types/unity-webapi/ @jmvrbanac /types/universal-analytics/ @Bartvds @DarkerTV /types/universal-cookie/ @tomi @@ -4905,6 +5070,7 @@ /types/uuid-validate/ @HiromiShikata /types/uws/ @plantain-00 @orblazer /types/v-chart-plugin/ @natemara +/types/v8flags/ @BendingBender /types/valdr/ @ilbertz /types/valdr-message/ @ilbertz /types/valerie/ @conficient @@ -4920,7 +5086,6 @@ /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 @@ -4928,7 +5093,8 @@ /types/vexdb/ @MayorMonty /types/vexflow/ @rquiring @sebastianhaas @bohoffi @sschmidTU /types/vfile/ @bizen241 @rokt33r -/types/vfile-location/ @ikatyang +/types/vfile-location/ @ikatyang @rokt33r +/types/vfile-message/ @rokt33r /types/victory/ @asvetliakov @snerks @Havret @alredyExist /types/video.js/ @vbortone @scleriot @SWBennett06 @IgelCampus @giofreitas @gjanblaszczyk @sroucheray @AkxeOne @meikidd /types/viewability-helper/ @lironzluf @@ -4944,7 +5110,7 @@ /types/vinyl-paths/ @tkQubo /types/virtual-dom/ @chbrown /types/virtual-keyboard/ @bsurai -/types/vis/ @MichaelBitard @macleodbroad-wf @adripanico @seveves @kaktus40 @mmaitre314 @supercargo @takato1314 @alex-kachura @dcop @avrahamcool +/types/vis/ @MichaelBitard @macleodbroad-wf @adripanico @seveves @kaktus40 @mmaitre314 @supercargo @takato1314 @alex-kachura @dcop @avrahamcool @divideby /types/vision/v4/ @jasonswearingen @AJamesPhillips /types/vision/ @jasonswearingen @AJamesPhillips @lenovouser /types/vitalsigns/ @cyrilschumacher @@ -4963,7 +5129,8 @@ /types/vue-scrollto/ @vincekovacs /types/vue-select/ @silh /types/vue2-datepicker/ @ChristianStornowski -/types/vuex-i18n/ @jaeggerr @noamkfir +/types/vuelidate/ @janesser +/types/vuex-i18n/ @jaeggerr @noamkfir @barahliush /types/w2ui/ @Ptival /types/w3c-generic-sensor/ @kenchris /types/w3c-image-capture/ @cosium @@ -4984,17 +5151,19 @@ /types/watson-developer-cloud/ @waldo000000 @Naktibalda /types/wavesurfer.js/ @higuri /types/waypoints/ @dominikbulaj @Koloto @evil-shrike +/types/wcag-contrast/ @plantain-00 /types/wcwidth/ @rokt33r /types/weak/ @int0h /types/weapp-api/ @vargeek /types/web-animations-js/ @kritollm /types/web-bluetooth/ @urish /types/web-push/ @paullessing +/types/web-resource-inliner/ @BendingBender /types/web3/ @simon-jentzsch @nitzantomer @zurbo @yxliang01 @phra @naddison36 @icaroharry @linusnorton @jpeletier @anneau @matrushka @andrevmatos @levino @zlumer @archangel-irk @sogasg @donamk @dkent600 @nerddan /types/web3-eth-abi/ @LogvinovLeon /types/web3-provider-engine/ @LogvinovLeon /types/webappsec-credential-management/ @iainmcgin -/types/webassembly-js-api/ @periklis +/types/webassembly-js-api/ @periklis @chicoxyzzy /types/webassembly-web-api/ @jhenninger /types/webcl/ @NCARalph /types/webcomponents.js/ @adidahiya @@ -5061,6 +5230,7 @@ /types/wicg-mediasession/ @jucrouzet /types/wif/ @danwbyrne /types/wiiu/ @mzsm +/types/wikidata-sdk/ @kamontat /types/window-or-global/ @vvakame /types/window-size/ @pmkary /types/windows-1251/ @RomanGolovanov @@ -5113,7 +5283,8 @@ /types/xmldom/ @tkqubo /types/xmlpoke/ @garthk /types/xmltojson/ @traviscrowe -/types/xmpp__jid/ @PJakcson +/types/xmpp__jid/ @PJakcson @BendingBender +/types/xmpp__xml/ @BendingBender /types/xregexp/ @Bartvds @jfahrenkrug @sigo /types/xrm/v7/ @daryllabar /types/xrm/v8/ @6ix4our @mattngan @markusmauch @daryllabar @clownwilleatme @mariusagur @@ -5137,7 +5308,8 @@ /types/yayson/ @Codesleuth /types/yazl/ @taoqf @seangenabe /types/ydn-db/ @yathit @gabrielmaldi -/types/yeoman-generator/ @armorik83 @janslow @ikatyang +/types/yeoman-assert/ @Toilal +/types/yeoman-generator/ @armorik83 @janslow @ikatyang @tasadar2 /types/yeoman-test/ @ikatyang /types/yesql/ @Sumolari /types/yoctodelay/ @seangenabe @@ -5146,10 +5318,10 @@ /types/yog2-kernel/ @ssddi456 /types/yoga-layout/ @tnobody /types/yosay/ @armorik83 -/types/youtube/ @DazWilkin @JoshuaKGoldberg @eliotfallon213 @terrymun +/types/youtube/ @DazWilkin @JoshuaKGoldberg @eliotfallon213 @terrymun @paulhobbel /types/youtube-dl/ @bsurai /types/yui/ @giabao -/types/yup/ @dhardtke @vtserman @MoretonBayRC @sseppola @YashdalfTheGray +/types/yup/ @dhardtke @vtserman @MoretonBayRC @sseppola @YashdalfTheGray @vincentjames501 /types/z-schema/ @pgonzal /types/zapier-platform-core/ @bradleyayers /types/zeit__next-typescript/ @icopp @@ -5172,5 +5344,6 @@ /types/zmq/ @davemckeown /types/zookeeper/ @xialeistudio /types/zopflipng-bin/ @hikoma +/types/zrender/ @iRON5 /types/zui/ @yuanxu /types/zxcvbn/ @mtraynham diff --git a/README.md b/README.md index 9a31d73da1..a9be0471a1 100644 --- a/README.md +++ b/README.md @@ -169,8 +169,14 @@ If a package was never on DefinitelyTyped, it does not need to be added to `notN #### Lint -To lint a package, just add a `tslint.json` to that package containing `{ "extends": "dtslint/dt.json" }`. All new packages must be linted. -If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example: +All new packages must be linted. To lint a package, add a `tslint.json` to that package containing +```js +{ + "extends": "dtslint/dt.json" +} +``` + +This should be the only content in a finished project's `tslint.json` file. If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example: ```js { @@ -336,3 +342,6 @@ This project is licensed under the MIT license. Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file. [![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) + +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) Are packages being published to npm in less than 10,000 seconds on average? +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Has typescript-bot been active on DefinitelyTyped in the last two hours? diff --git a/notNeededPackages.json b/notNeededPackages.json index cf5c9449d7..c64738aa8d 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -642,6 +642,12 @@ "sourceRepoURL": "https://github.com/jdalrymple/node-gitlab", "asOfVersion": "2.0.0" }, + { + "libraryName": "Google Cloud Storage", + "typingsPackageName": "google-cloud__storage", + "sourceRepoURL": "https://github.com/googleapis/nodejs-storage", + "asOfVersion": "2.3.0" + }, { "libraryName": "graphene-pk11", "typingsPackageName": "graphene-pk11", @@ -1656,6 +1662,12 @@ "sourceRepoURL": "https://github.com/ansman/validate.js", "asOfVersion": "0.11.0" }, + { + "libraryName": "vega", + "typingsPackageName": "vega", + "sourceRepoURL": "https://github.com/vega/vega", + "asOfVersion": "3.2.0" + }, { "libraryName": "vso-node-api", "typingsPackageName": "vso-node-api", diff --git a/package.json b/package.json index 09fe064d48..caf101cbc6 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,6 @@ }, "devDependencies": { "dtslint": "github:Microsoft/dtslint#production", - "types-publisher": "Microsoft/types-publisher#production" + "types-publisher": "github:Microsoft/types-publisher#production" } } diff --git a/types/accept/accept-tests.ts b/types/accept/accept-tests.ts new file mode 100644 index 0000000000..011216ede4 --- /dev/null +++ b/types/accept/accept-tests.ts @@ -0,0 +1,29 @@ +import * as accept from 'accept'; + +accept.charsets("iso-8859-5, unicode-1-1;q=0.8"); // charset === "iso-8859-5" +accept.charset("iso-8859-5, unicode-1-1;q=0.8", ["unicode-1-1"]); // charset === "unicode-1-1" + +accept.encoding("gzip, deflate, sdch"); // encoding === "gzip" +accept.encoding("gzip, deflate, sdch", ["deflate", "identity"]); + +const encodings = accept.encodings("compress;q=0.5, gzip;q=1.0"); // encodings === ["gzip", "compress", "identity"] +encodings.lastIndexOf(''); + +accept.language("en;q=0.7, en-GB;q=0.8"); +accept.language("en;q=0.7, en-GB;q=0.8", ["en-gb"]); // language === "en-GB" +const languages = accept.languages("da, en;q=0.7, en-GB;q=0.8"); // languages === ["da", "en-GB", "en"] +languages.lastIndexOf(''); + +const mediaTypes = accept.mediaTypes("text/plain, application/json;q=0.5, text/html, */*;q=0.1"); +// mediaTypes === ["text/plain", "text/html", "application/json", "*/*"] +mediaTypes.lastIndexOf(''); +const headers = { + accept: 'text/plain, application/json;q=0.5, text/html, */*;q=0.1', + 'accept-language': 'da, en;q=0.7, en-GB;q=0.8' +}; + +const all = accept.parseAll(headers); +all.charsets.length; +all.encodings.length; +all.languages.length; +all.mediaTypes.length; diff --git a/types/accept/index.d.ts b/types/accept/index.d.ts new file mode 100644 index 0000000000..b067ea4306 --- /dev/null +++ b/types/accept/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for accept 3.1 +// Project: https://github.com/hapijs/accept#readme +// Definitions by: feinoujc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export function charset(charsetHeader?: string, preferences?: string[]): string; +export function charsets(charsetHeader?: string): string[]; +export function encoding(encodingHeader?: string, preferences?: string[]): string; +export function encodings(encodingHeader?: string): string[]; +export function language(languageHeader?: string, preferences?: string[]): string; +export function languages(languageHeader?: string): string[]; +export function mediaTypes(mediaTypeHeader?: string): string[]; +export function parseAll( + headers: Record +): { + charsets: string[]; + encodings: string[]; + languages: string[]; + mediaTypes: string[]; +}; diff --git a/types/accept/tsconfig.json b/types/accept/tsconfig.json new file mode 100644 index 0000000000..cb192697d5 --- /dev/null +++ b/types/accept/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "accept-tests.ts" + ] +} diff --git a/types/accept/tslint.json b/types/accept/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/accept/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ali-oss/Cluster.d.ts b/types/ali-oss/Cluster.d.ts deleted file mode 100644 index 60886fca36..0000000000 --- a/types/ali-oss/Cluster.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { - ACLType, - CopyAndPutMetaResult, - CopyObjectOptions, - DeleteMultiOptions, - DeleteMultiResult, - GetObjectOptions, - GetObjectResult, - GetStreamOptions, - GetStreamResult, - HeadObjectOptions, - HeadObjectResult, - ListObjectResult, - ListObjectsQuery, - NormalSuccessResponse, - PutObjectOptions, - PutObjectResult, - PutStreamOptions, - RequestOptions, - SignatureUrlOptions, - UserMeta -} from "./index"; - -export interface ClusterType { - host: string; - accessKeyId: string; - accessKeySecret: string; -} - -export interface ClusterOptions { - clusters: ClusterType[]; - schedule?: string; -} - -export class Cluster { - constructor(options: ClusterOptions) - - list(query: ListObjectsQuery | null, options: RequestOptions): Promise; - - put(name: string, file: any, options?: PutObjectOptions): Promise; - - putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }>; - - head(name: string, options?: HeadObjectOptions): Promise; - - get(name: string, file?: any, options?: GetObjectOptions): Promise; - - getStream(name?: string, options?: GetStreamOptions): Promise; - - delete(name: string, options?: RequestOptions): Promise; - - copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise; - - putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise; - - deleteMulti(names: string[], options?: DeleteMultiOptions): Promise; - - signatureUrl(name: string, options?: SignatureUrlOptions): string; - - putACL(name: string, acl: ACLType, options?: RequestOptions): Promise; - - restore(name: string, options?: RequestOptions): Promise; -} diff --git a/types/ali-oss/ImageClient.d.ts b/types/ali-oss/ImageClient.d.ts deleted file mode 100644 index 850213083c..0000000000 --- a/types/ali-oss/ImageClient.d.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { NormalSuccessResponse, RequestOptions } from "./index"; - -export interface ImageClientOptions { - imageHost: string; // your image service domain that binding to a OSS bucket - accessKeyId: string; // access key you create on aliyun console website - accessKeySecret: string; // access secret you create - bucket: string; // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. - region?: string; // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou - internal?: boolean; // access OSS with aliyun internal network or not, default is false If your servers are running on aliyun too, you can set true to save lot of money. - timeout?: string | number; // instance level timeout for all operations, default is 60s -} - -export interface ImageGetOptions { - timeout?: number; - headers?: object; -} - -export interface StyleData { - Name: string; // style name - Content: string; // style content - CreateTime: string; // style create time - LastModifyTime: string; // style last modify time -} -export class ImageClient { - constructor(options: ImageClientOptions) - - /** - * Get an image from the image channel. - */ - get(name: string, file?: any, options?: ImageGetOptions): Promise<{ content: any, res: NormalSuccessResponse }>; - - /** - * Get an image read stream. - */ - getStream(name: string, options?: ImageGetOptions): Promise<{ stream: any, res: NormalSuccessResponse }>; - - /** - * Get a image exif info by image object name from the image channel. - */ - getExif(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; - - /** - * Get a image info and exif info by image object name from the image channel. - */ - getInfo(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; - - /** - * todo - */ - putStyle(name: string, style: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; - - /** - * Get a style by name from the image channel. - */ - getStyle(name: string, options?: RequestOptions): Promise<{ data: StyleData, res: NormalSuccessResponse}>; - - /** - * Get all styles from the image channel. - */ - listStyle(options?: RequestOptions): Promise; - - /** - * todo - */ - deleteStyle(styleName: string, options?: RequestOptions): Promise; - - /** - * Create a signature url for directly download. - */ - signatureUrl(name: string, options?: { expires?: string, timeout?: string }): string; -} diff --git a/types/ali-oss/ali-oss-tests.ts b/types/ali-oss/ali-oss-tests.ts index 96f817cca8..dc751b8d44 100644 --- a/types/ali-oss/ali-oss-tests.ts +++ b/types/ali-oss/ali-oss-tests.ts @@ -1,34 +1,25 @@ -import OSS from "ali-oss"; +import * as OSS from 'ali-oss'; -const client = new OSS({ +const ossOptions: OSS.Options = { accessKeyId: 'your access key', accessKeySecret: 'your access secret', bucket: 'your bucket name', region: 'oss-cn-hangzhou' -}); +}; -const ImageClient = OSS.ImageClient({ - imageHost: 'host', - accessKeySecret: "secret", - accessKeyId: 'id', - bucket: "", - internal: false, - region: "", - timeout: 2000 -}); +const client = new OSS(ossOptions); -const cluster = OSS.Cluster({ - clusters: [ - { - accessKeyId: 'id', - accessKeySecret: 'secret', - host: "" - }, - { - accessKeyId: 'id', - accessKeySecret: 'secret', - host: "" - }, - ], - schedule: 'masterSlave', -}); +const clusterOptions: OSS.ClusterOptions = { + clusters: [], +}; + +const clusterClient = new OSS.Cluster(clusterOptions); + +const imageOptions: OSS.ImageClientOptions = { + imageHost: 'xxxx', + accessKeyId: 'xxxx', + accessKeySecret: 'xxxx', + bucket: 'xxxx' +}; + +const imageClient = new OSS.ImageClient(imageOptions); diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts index c3fa0dd10b..13f7f56ff9 100644 --- a/types/ali-oss/index.d.ts +++ b/types/ali-oss/index.d.ts @@ -4,442 +4,555 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as ImageClientDefinition from './ImageClient'; -import * as ClusterDefinition from "./Cluster"; +export = OSS; -export * from './ImageClient'; -export * from './Cluster'; +// basic OSS +declare namespace OSS { + interface Options { + accessKeyId: string; // access secret you create + accessKeySecret: string; // access secret you create + stsToken?: string; // used by temporary authorization + bucket?: string; // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. + endpoint?: string; // oss region domain. It takes priority over region. + region?: string; // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou. + internal?: boolean; // access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save lot of money. + secure?: boolean; // instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol. + timeout?: string | number; // instance level timeout for all operations, default is 60s + } -export interface Options { - accessKeyId: string; // access secret you create - accessKeySecret: string; // access secret you create - stsToken?: string; // used by temporary authorization - bucket?: string; // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. - endpoint?: string; // oss region domain. It takes priority over region. - region?: string; // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou. - internal?: boolean; // access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save lot of money. - secure?: boolean; // instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol. - timeout?: string | number; // instance level timeout for all operations, default is 60s -} + interface Bucket { + name: string; + region: string; + creationDate: string; + StorageClass: StorageType; + } -export interface Bucket { - name: string; - region: string; - creationDate: string; - StorageClass: StorageType; -} + type StorageType = "Standard" | "IA" | "Archive"; -export type StorageType = "Standard" | "IA" | "Archive"; + type ACLType = "public-read-write" | "public-read" | "and private"; -export type ACLType = "public-read-write" | "public-read" | "and private"; + type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT"; -export type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT"; + interface RequestOptions { + // the operation timeout + timeout?: number; + } -export interface RequestOptions { - // the operation timeout - timeout?: number; -} + type RuleStatusType = "Enabled" | "Disabled"; -export type RuleStatusType = "Enabled" | "Disabled"; + interface LifecycleRule { + id?: string; // rule id, if not set, OSS will auto create it with random string. + prefix: string; // store prefix + status: RuleStatusType; // rule status, allow values: Enabled or Disabled + days?: number | string; // expire after the days + date: string; // expire date, e.g.: 2022-10-11T00:00:00.000Z date and days only set one. + } -export interface LifecycleRule { - id?: string; // rule id, if not set, OSS will auto create it with random string. - prefix: string; // store prefix - status: RuleStatusType; // rule status, allow values: Enabled or Disabled - days?: number | string; // expire after the days - date: string; // expire date, e.g.: 2022-10-11T00:00:00.000Z date and days only set one. -} + interface CORSRule { + allowedOrigin: string | string[]; // configure for Access-Control-Allow-Origin header + allowedMethod: string | string[]; // configure for Access-Control-Allow-Methods header + allowedHeader?: string | string[]; // configure for Access-Control-Allow-Headers header + exposeHeader?: string | string[]; // configure for Access-Control-Expose-Headers header + maxAgeSeconds?: string | string[]; // configure for Access-Control-Max-Age header + } -export interface CORSRule { - allowedOrigin: string | string[]; // configure for Access-Control-Allow-Origin header - allowedMethod: string | string[]; // configure for Access-Control-Allow-Methods header - allowedHeader?: string | string[]; // configure for Access-Control-Allow-Headers header - exposeHeader?: string | string[]; // configure for Access-Control-Expose-Headers header - maxAgeSeconds?: string | string[]; // configure for Access-Control-Max-Age header -} + interface OwnerType { + id: string; + displayName: string; + } -export interface OwnerType { - id: string; - displayName: string; -} + interface ObjectMeta { + name: string; // object name on oss + lastModified: string; // object last modified GMT date, e.g.: 2015-02-19T08:39:44.000Z + etag: string; // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" + type: string; // object type, e.g.: Normal + size: number; // object size, e.g.: 344606 + storageClass: StorageType; + owner: OwnerType; + } -export interface ObjectMeta { - name: string; // object name on oss - lastModified: string; // object last modified GMT date, e.g.: 2015-02-19T08:39:44.000Z - etag: string; // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" - type: string; // object type, e.g.: Normal - size: number; // object size, e.g.: 344606 - storageClass: StorageType; - owner: OwnerType; -} + interface NormalSuccessResponse { + // response status + status: number; + // response headers + headers: object; // todo the object in detail + // response size + size: number; + // request total use time (ms) + rt: number; + } -export interface NormalSuccessResponse { - // response status - status: number; - // response headers - headers: object; // todo the object in detail - // response size - size: number; - // request total use time (ms) - rt: number; -} + interface UserMeta { + uid: number; + pid: number; + } -export interface UserMeta { - uid: number; - pid: number; -} + interface ObjectCallback { + url: string; // After a file is uploaded successfully, the OSS sends a callback request to this URL. + host?: string; // The host header value for initiating callback requests. + body: string; // The value of the request body when a callback is initiated, for example, key=$(key)&etag=$(etag)&my_var=$(x:my_var). + contentType?: string; // The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value. + customValue?: object; + headers?: object; // extra headers, detail see RFC 2616 + } -export interface ObjectCallback { - url: string; // After a file is uploaded successfully, the OSS sends a callback request to this URL. - host?: string; // The host header value for initiating callback requests. - body: string; // The value of the request body when a callback is initiated, for example, key=$(key)&etag=$(etag)&my_var=$(x:my_var). - contentType?: string; // The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value. - customValue?: object; - headers?: object; // extra headers, detail see RFC 2616 -} + interface ModifyData { + lastModified: string; // object last modified GMT string + etag: string; // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" + } -export interface ModifyData { - lastModified: string; // object last modified GMT string - etag: string; // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" -} + interface Checkpoint { + file: any; // The file object selected by the user, if the browser is restarted, it needs the user to manually trigger the settings + name: string; // object key + fileSize: number; + partSize: number; + uploadId: string; + doneParts: Array<{ number: number, etag: string }>; + } -export interface Checkpoint { - file: any; // The file object selected by the user, if the browser is restarted, it needs the user to manually trigger the settings - name: string; // object key - fileSize: number; - partSize: number; - uploadId: string; - doneParts: Array<{ number: number, etag: string }>; -} + interface ObjectPart { + PartNumber: number; + LastModified: any; // {Date} Time when a part is uploaded. + ETag: string; + size: number; + } -export interface ObjectPart { - PartNumber: number; - LastModified: any; // {Date} Time when a part is uploaded. - ETag: string; - size: number; -} + interface Upload { + name: string; + uploadId: string; + initiated: any; + } -export interface Upload { - name: string; - uploadId: string; - initiated: any; -} + interface Channel { + Name: string; + Description: string; + Status: string; + LastModified: string; + PublishUrls: string[]; + PlayUrls: string[]; + } -export interface Channel { - Name: string; - Description: string; - Status: string; - LastModified: string; - PublishUrls: string[]; - PlayUrls: string[]; -} - -export interface ChannelHistory { - StartTime: string; // - EndTime: string; - RemoteAddr: string; // the remote addr -} + interface ChannelHistory { + StartTime: string; // + EndTime: string; + RemoteAddr: string; // the remote addr + } // parameters type -export interface ListBucketsQueryType { - prefix?: string; // search buckets using prefix key - marker?: string; // search start from marker, including marker key - 'max-keys'?: string | number; // max buckets, default is 100, limit to 1000 + interface ListBucketsQueryType { + prefix?: string; // search buckets using prefix key + marker?: string; // search start from marker, including marker key + 'max-keys'?: string | number; // max buckets, default is 100, limit to 1000 + } + + interface PutBucketOptions { + timeout: number; + storageClass: StorageType; + } + + interface PutBucketWebsiteConfig { + index: string; // default page, e.g.: index.html + error?: string; // error page, e.g.: 'error.html' + } + + interface ListObjectsQuery { + prefix?: string; // search object using prefix key + marker?: string; // search start from marker, including marker key + delimiter?: string; // delimiter search scope e.g. / only search current dir, not including subdir + 'max-keys': string | number; // max objects, default is 100, limit to 1000 + } + + interface ListObjectResult { + objects: ObjectMeta[]; + prefixes: string[]; + isTruncated: boolean; + nextMarker: string; + res: NormalSuccessResponse; + } + + interface PutObjectOptions { + timeout?: number; // the operation timeout + mime?: string; // custom mime, will send with Content-Type entity header + meta?: UserMeta; // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 } + callback: ObjectCallback; + } + + interface PutObjectResult { + name: string; + data: object; + res: NormalSuccessResponse; + } + + interface PutStreamOptions { + contentLength?: number; // the stream length, chunked encoding will be used if absent + timeout: number; // the operation timeout + mime: string; // custom mime, will send with Content-Type entity header + meta: UserMeta; + callback: ObjectCallback; + } + + interface AppendObjectOptions { + position?: string; // specify the position which is the content length of the latest object + timeout?: number; // the operation timeout + mime?: string; // custom mime, will send with Content-Type entity header + meta?: UserMeta; + headers?: object; + } + + interface AppendObjectResult { + name: string; + url: string; // the url of oss + res: NormalSuccessResponse; + nextAppendPosition: string; // the next position + } + + interface HeadObjectOptions { + timeout?: number; + headers?: object; + } + + interface HeadObjectResult { + status: number; // response status, maybe 200 or 304 + meta: UserMeta; + res: NormalSuccessResponse; + } + + interface GetObjectOptions { + timeout?: number; + process?: string; // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} + headers?: object; + } + + interface GetObjectResult { + content?: any; // file content buffer if file parameter is null or ignore + res: NormalSuccessResponse; + } + + interface GetStreamOptions { + timeout?: number; + process?: string; // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} + headers?: object; + } + + interface GetStreamResult { + stream?: any; // readable stream instance if response status is not 200, stream will be null. + res: NormalSuccessResponse; + } + + interface CopyObjectOptions { + timeout?: number; + meta?: UserMeta; + headers?: object; + } + + interface CopyAndPutMetaResult { + data: ModifyData; + res: NormalSuccessResponse; + } + + interface DeleteMultiOptions { + quite?: boolean; // quite mode or verbose mode, default is false + timeout?: number; + } + + interface DeleteMultiResult { + deleted?: string[]; // deleted object names list + res: NormalSuccessResponse; + } + + interface ResponseHeaderType { + 'content-type'?: string; + 'content-disposition'?: string; + 'cache-control'?: string; + } + + interface SignatureUrlOptions { + expires?: number; // after expires seconds, the url will become invalid, default is 1800 + method?: HTTPMethods; // the HTTP method, default is 'GET' + 'Content-Type'?: string; // set the request content type + process?: string; + response?: ResponseHeaderType; // set the response headers for download + callback?: ObjectCallback; + } + + interface GetACLResult { + acl: ACLType; + res: NormalSuccessResponse; + } + + interface InitMultipartUploadOptions { + timeout?: number; + mime?: string; // Mime file type + meta?: UserMeta; + headers?: object; + } + + interface InitMultipartUploadResult { + res: { status: number, headers: object, size: number, rt: number }; + bucket: string; // bucket name + name: string; // object name store on OSS + uploadId: string; // upload id, use for uploadPart, completeMultipart + } + + interface UploadPartResult { + name: string; + etag: string; + res: NormalSuccessResponse; + } + + interface CompleteMultipartUploadOptions { + timeout?: number; + callback?: ObjectCallback; + headers?: object; + } + + interface CompleteMultipartUploadResult { + bucket: string; + name: string; + etag: string; + data: object; + res: NormalSuccessResponse; + } + + interface MultipartUploadOptions { + parallel?: number; // the number of parts to be uploaded in parallel + partSize?: number; // the suggested size for each part + progress?: (...args: any[]) => any; // the progress callback called after each successful upload of one part + checkpoint?: Checkpoint; // the checkpoint to resume upload, if this is provided, it will continue the upload from where interrupted, otherwise a new multipart upload will be created. + meta?: UserMeta; + mime?: string; + callback?: ObjectCallback; + headers?: object; + timeout?: number; + copyheaders?: object; // {Object} only uploadPartCopy api used, detail + } + + interface MultipartUploadResult { + bucket: string; + name: string; + etag: string; + data: object; + res: NormalSuccessResponse; + } + + interface MultipartUploadCopyResult { + bucket: string; + name: string; + etag: string; + res: NormalSuccessResponse; + } + + interface MultipartUploadCopySourceData { + sourceKey: string; // the source object name + sourceBucketName: string; // sourceData. the source bucket name + startOffset: number; // data copy start byte offset, e.g: 0 + endOffset: number; // data copy end byte offset, e.g: 102400 + } + + interface ListPartsQuery { + 'max-parts': number; // The maximum part number in the response of the OSS. default value: 1000. + 'part-number-marker': number; // Starting position of a specific list. A part is listed only when the part number is greater than the value of this parameter. + 'encoding-type': string; // Specify the encoding of the returned content and the encoding type. Optional value: url + } + + interface ListPartsResult { + uploadId: string; + bucket: string; + name: string; + PartNumberMarker: number; + nextPartNumberMarker: number; + maxParts: number; + isTruncated: boolean; + parts: ObjectPart[]; + res: NormalSuccessResponse; + } + + interface ListUploadsQuery { + prefix?: string; + 'max-uploads'?: number; + 'key-marker'?: string; + 'upload-id-marker'?: string; + } + + interface ListUploadsResult { + res: NormalSuccessResponse; + bucket: string; + nextKeyMarker: any; + nextUploadIdMarker: any; + isTruncated: boolean; + uploads: Upload[]; + } + + interface PutChannelConf { + Description?: string; + Status?: string; + Target?: { + Type: string, + FragDuration: number, + FragCount: number, + PlaylistName: string + }; + } + + interface PutChannelResult { + publishUrls: string[]; + playUrls: string[]; + res: NormalSuccessResponse; + } + + interface GetChannelResult { + Status: string; + ConnectedTime?: string; + RemoteAddr?: string; + Video?: object; + Audio?: object; + res: NormalSuccessResponse; + } + + interface ListChannelsQuery { + prefix: string; // the channel id prefix (returns channels with this prefix) + marker: string; // the channel id marker (returns channels after this id) + 'max-keys ': number; // max number of channels to return + } + + interface ListChannelsResult { + channels: Channel[]; + nextMarker: string | null; + isTruncated: boolean; + res: NormalSuccessResponse; + } + + interface ChannelHistoryResult { + records: ChannelHistory; + res: NormalSuccessResponse; + } + + interface GetRtmpUrlOptions { + expires?: number; // the expire time in seconds of the url + params?: object; // the additional parameters for url, e.g.: {playlistName: 'play.m3u8'} + timeout?: number; // the operation timeout + } } -export interface PutBucketOptions { - timeout: number; - storageClass: StorageType; +/// cluster +declare namespace OSS { + interface ClusterType { + host: string; + accessKeyId: string; + accessKeySecret: string; + } + + interface ClusterOptions { + clusters: ClusterType[]; + schedule?: string; + } + + class Cluster { + constructor(options: ClusterOptions) + + list(query: ListObjectsQuery | null, options: RequestOptions): Promise; + + put(name: string, file: any, options?: PutObjectOptions): Promise; + + putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }>; + + head(name: string, options?: HeadObjectOptions): Promise; + + get(name: string, file?: any, options?: GetObjectOptions): Promise; + + getStream(name?: string, options?: GetStreamOptions): Promise; + + delete(name: string, options?: RequestOptions): Promise; + + copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise; + + putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise; + + deleteMulti(names: string[], options?: DeleteMultiOptions): Promise; + + signatureUrl(name: string, options?: SignatureUrlOptions): string; + + putACL(name: string, acl: ACLType, options?: RequestOptions): Promise; + + restore(name: string, options?: RequestOptions): Promise; + } } -export interface PutBucketWebsiteConfig { - index: string; // default page, e.g.: index.html - error?: string; // error page, e.g.: 'error.html' +// image +declare namespace OSS { + interface ImageClientOptions { + imageHost: string; // your image service domain that binding to a OSS bucket + accessKeyId: string; // access key you create on aliyun console website + accessKeySecret: string; // access secret you create + bucket: string; // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. + region?: string; // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou + internal?: boolean; // access OSS with aliyun internal network or not, default is false If your servers are running on aliyun too, you can set true to save lot of money. + timeout?: string | number; // instance level timeout for all operations, default is 60s + } + + interface ImageGetOptions { + timeout?: number; + headers?: object; + } + + interface StyleData { + Name: string; // style name + Content: string; // style content + CreateTime: string; // style create time + LastModifyTime: string; // style last modify time + } + + class ImageClient { + constructor(options: ImageClientOptions) + + /** + * Get an image from the image channel. + */ + get(name: string, file?: any, options?: ImageGetOptions): Promise<{ content: any, res: NormalSuccessResponse }>; + + /** + * Get an image read stream. + */ + getStream(name: string, options?: ImageGetOptions): Promise<{ stream: any, res: NormalSuccessResponse }>; + + /** + * Get a image exif info by image object name from the image channel. + */ + getExif(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; + + /** + * Get a image info and exif info by image object name from the image channel. + */ + getInfo(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; + + /** + * todo + */ + putStyle(name: string, style: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; + + /** + * Get a style by name from the image channel. + */ + getStyle(name: string, options?: RequestOptions): Promise<{ data: StyleData, res: NormalSuccessResponse}>; + + /** + * Get all styles from the image channel. + */ + listStyle(options?: RequestOptions): Promise; + + /** + * todo + */ + deleteStyle(styleName: string, options?: RequestOptions): Promise; + + /** + * Create a signature url for directly download. + */ + signatureUrl(name: string, options?: { expires?: string, timeout?: string }): string; + } } -export interface ListObjectsQuery { - prefix?: string; // search object using prefix key - marker?: string; // search start from marker, including marker key - delimiter?: string; // delimiter search scope e.g. / only search current dir, not including subdir - 'max-keys': string | number; // max objects, default is 100, limit to 1000 -} - -export interface ListObjectResult { - objects: ObjectMeta[]; - prefixes: string[]; - isTruncated: boolean; - nextMarker: string; - res: NormalSuccessResponse; -} - -export interface PutObjectOptions { - timeout?: number; // the operation timeout - mime?: string; // custom mime, will send with Content-Type entity header - meta?: UserMeta; // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 } - callback: ObjectCallback; -} - -export interface PutObjectResult { - name: string; - data: object; - res: NormalSuccessResponse; -} - -export interface PutStreamOptions { - contentLength?: number; // the stream length, chunked encoding will be used if absent - timeout: number; // the operation timeout - mime: string; // custom mime, will send with Content-Type entity header - meta: UserMeta; - callback: ObjectCallback; -} - -export interface AppendObjectOptions { - position?: string; // specify the position which is the content length of the latest object - timeout?: number; // the operation timeout - mime?: string; // custom mime, will send with Content-Type entity header - meta?: UserMeta; - headers?: object; -} - -export interface AppendObjectResult { - name: string; - url: string; // the url of oss - res: NormalSuccessResponse; - nextAppendPosition: string; // the next position -} - -export interface HeadObjectOptions { - timeout?: number; - headers?: object; -} - -export interface HeadObjectResult { - status: number; // response status, maybe 200 or 304 - meta: UserMeta; - res: NormalSuccessResponse; -} - -export interface GetObjectOptions { - timeout?: number; - process?: string; // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} - headers?: object; -} - -export interface GetObjectResult { - content?: any; // file content buffer if file parameter is null or ignore - res: NormalSuccessResponse; -} - -export interface GetStreamOptions { - timeout?: number; - process?: string; // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} - headers?: object; -} - -export interface GetStreamResult { - stream?: any; // readable stream instance if response status is not 200, stream will be null. - res: NormalSuccessResponse; -} - -export interface CopyObjectOptions { - timeout?: number; - meta?: UserMeta; - headers?: object; -} - -export interface CopyAndPutMetaResult { - data: ModifyData; - res: NormalSuccessResponse; -} - -export interface DeleteMultiOptions { - quite?: boolean; // quiet mode or verbose mode, default is false - timeout?: number; -} - -export interface DeleteMultiResult { - deleted?: string[]; // deleted object names list - res: NormalSuccessResponse; -} - -export interface ResponseHeaderType { - 'content-type'?: string; - 'content-disposition'?: string; - 'cache-control'?: string; -} - -export interface SignatureUrlOptions { - expires?: number; // after expires seconds, the url will become invalid, default is 1800 - method?: HTTPMethods; // the HTTP method, default is 'GET' - 'Content-Type'?: string; // set the request content type - process?: string; - response?: ResponseHeaderType; // set the response headers for download - callback?: ObjectCallback; -} - -export interface GetACLResult { - acl: ACLType; - res: NormalSuccessResponse; -} - -export interface InitMultipartUploadOptions { - timeout?: number; - mime?: string; // Mime file type - meta?: UserMeta; - headers?: object; -} - -export interface InitMultipartUploadResult { - res: { status: number, headers: object, size: number, rt: number }; - bucket: string; // bucket name - name: string; // object name store on OSS - uploadId: string; // upload id, use for uploadPart, completeMultipart -} - -export interface UploadPartResult { - name: string; - etag: string; - res: NormalSuccessResponse; -} - -export interface CompleteMultipartUploadOptions { - timeout?: number; - callback?: ObjectCallback; - headers?: object; -} - -export interface CompleteMultipartUploadResult { - bucket: string; - name: string; - etag: string; - data: object; - res: NormalSuccessResponse; -} - -export interface MultipartUploadOptions { - parallel?: number; // the number of parts to be uploaded in parallel - partSize?: number; // the suggested size for each part - progress?: (...args: any[]) => any; // the progress callback called after each successful upload of one part - checkpoint?: Checkpoint; // the checkpoint to resume upload, if this is provided, it will continue the upload from where interrupted, otherwise a new multipart upload will be created. - meta?: UserMeta; - mime?: string; - callback?: ObjectCallback; - headers?: object; - timeout?: number; - copyheaders?: object; // {Object} only uploadPartCopy api used, detail -} - -export interface MultipartUploadResult { - bucket: string; - name: string; - etag: string; - data: object; - res: NormalSuccessResponse; -} - -export interface MultipartUploadCopyResult { - bucket: string; - name: string; - etag: string; - res: NormalSuccessResponse; -} - -export interface MultipartUploadCopySourceData { - sourceKey: string; // the source object name - sourceBucketName: string; // sourceData. the source bucket name - startOffset: number; // data copy start byte offset, e.g: 0 - endOffset: number; // data copy end byte offset, e.g: 102400 -} - -export interface ListPartsQuery { - 'max-parts': number; // The maximum part number in the response of the OSS. default value: 1000. - 'part-number-marker': number; // Starting position of a specific list. A part is listed only when the part number is greater than the value of this parameter. - 'encoding-type': string; // Specify the encoding of the returned content and the encoding type. Optional value: url -} - -export interface ListPartsResult { - uploadId: string; - bucket: string; - name: string; - PartNumberMarker: number; - nextPartNumberMarker: number; - maxParts: number; - isTruncated: boolean; - parts: ObjectPart[]; - res: NormalSuccessResponse; -} - -export interface ListUploadsQuery { - prefix?: string; - 'max-uploads'?: number; - 'key-marker'?: string; - 'upload-id-marker'?: string; -} - -export interface ListUploadsResult { - res: NormalSuccessResponse; - bucket: string; - nextKeyMarker: any; - nextUploadIdMarker: any; - isTruncated: boolean; - uploads: Upload[]; -} - -export interface PutChannelConf { - Description?: string; - Status?: string; - Target?: { - Type: string, - FragDuration: number, - FragCount: number, - PlaylistName: string - }; -} - -export interface PutChannelResult { - publishUrls: string[]; - playUrls: string[]; - res: NormalSuccessResponse; -} - -export interface GetChannelResult { - Status: string; - ConnectedTime?: string; - RemoteAddr?: string; - Video?: object; - Audio?: object; - res: NormalSuccessResponse; -} - -export interface ListChannelsQuery { - prefix: string; // the channel id prefix (returns channels with this prefix) - marker: string; // the channel id marker (returns channels after this id) - 'max-keys ': number; // max number of channels to return -} - -export interface ListChannelsResult { - channels: Channel[]; - nextMarker: string | null; - isTruncated: boolean; - res: NormalSuccessResponse; -} - -export interface ChannelHistoryResult { - records: ChannelHistory; - res: NormalSuccessResponse; -} - -export interface GetRtmpUrlOptions { - expires?: number; // the expire time in seconds of the url - params?: object; // the additional parameters for url, e.g.: {playlistName: 'play.m3u8'} - timeout?: number; // the operation timeout -} - -export default class OSS { - // the image client - static ImageClient: (options: ImageClientDefinition.ImageClientOptions) => ImageClientDefinition.ImageClient; - static Cluster: (options: ClusterDefinition.ClusterOptions) => ClusterDefinition.Cluster; - - constructor(options: Options) +declare class OSS { + constructor(options: OSS.Options) /******************************************* the bucket operations *************************************************/ @@ -447,12 +560,12 @@ export default class OSS { /** * List buckets in this account. */ - listBuckets(query: ListBucketsQueryType | null, options?: RequestOptions): Promise; + listBuckets(query: OSS.ListBucketsQueryType | null, options?: OSS.RequestOptions): Promise; /** * Create a new bucket. */ - putBucket(name: string, options?: PutBucketOptions): Promise<{ bucket: string, res: NormalSuccessResponse }>; + putBucket(name: string, options?: OSS.PutBucketOptions): Promise<{ bucket: string, res: OSS.NormalSuccessResponse }>; /** * Use the bucket. @@ -462,7 +575,7 @@ export default class OSS { /** * Delete an empty bucket. */ - deleteBucket(name: string, options?: RequestOptions): Promise; + deleteBucket(name: string, options?: OSS.RequestOptions): Promise; /** * Get bucket information,include CreationDate、ExtranetEndpoint、IntranetEndpoint、Location、Name、StorageClass、 Owner、AccessControlList @@ -478,114 +591,114 @@ export default class OSS { /** * Update the bucket ACL. */ - putBucketACL(name: string, acl: ACLType, options?: RequestOptions): Promise; + putBucketACL(name: string, acl: OSS.ACLType, options?: OSS.RequestOptions): Promise; /** * Get the bucket ACL. * acl - acl settings string */ - getBucketACL(name: string, options?: RequestOptions): Promise<{ acl: string, res: NormalSuccessResponse }>; + getBucketACL(name: string, options?: OSS.RequestOptions): Promise<{ acl: string, res: OSS.NormalSuccessResponse }>; // logging operations /** * Update the bucket logging settings. Log file will create every one hour and name format: -YYYY-mm-DD-HH-MM-SS-UniqueString. */ - putBucketLogging(name: string, prefix?: string, options?: RequestOptions): Promise; + putBucketLogging(name: string, prefix?: string, options?: OSS.RequestOptions): Promise; /** * Get the bucket logging settings. */ - getBucketLogging(name: string, options?: RequestOptions): Promise<{ enable: boolean, prefix: string | null, res: NormalSuccessResponse }>; + getBucketLogging(name: string, options?: OSS.RequestOptions): Promise<{ enable: boolean, prefix: string | null, res: OSS.NormalSuccessResponse }>; /** * Delete the bucket logging settings. */ - deleteBucketLogging(name: string, options?: RequestOptions): Promise; + deleteBucketLogging(name: string, options?: OSS.RequestOptions): Promise; // Website operations /** * Set the bucket as a static website. */ - putBucketWebsite(name: string, config: PutBucketWebsiteConfig): Promise; + putBucketWebsite(name: string, config: OSS.PutBucketWebsiteConfig): Promise; /** * Get the bucket website config. */ - getBucketWebsite(name: string, options?: RequestOptions): Promise<{ index: string, error: string, res: NormalSuccessResponse }>; + getBucketWebsite(name: string, options?: OSS.RequestOptions): Promise<{ index: string, error: string, res: OSS.NormalSuccessResponse }>; /** * Delete the bucket website config. */ - deleteBucketWebsite(name: string, options?: RequestOptions): Promise; + deleteBucketWebsite(name: string, options?: OSS.RequestOptions): Promise; // referer operations /** * Set the bucket request Referer white list. */ - putBucketReferer(name: string, allowEmpty: boolean, referers: string[], options?: RequestOptions): Promise; + putBucketReferer(name: string, allowEmpty: boolean, referers: string[], options?: OSS.RequestOptions): Promise; /** * Get the bucket request Referer white list. */ - getBucketReferer(name: string, options?: RequestOptions): Promise<{ allowEmpty: boolean, referers: string[], res: NormalSuccessResponse }>; + getBucketReferer(name: string, options?: OSS.RequestOptions): Promise<{ allowEmpty: boolean, referers: string[], res: OSS.NormalSuccessResponse }>; /** * Delete the bucket request Referer white list. */ - deleteBucketReferer(name: string, options?: RequestOptions): Promise; + deleteBucketReferer(name: string, options?: OSS.RequestOptions): Promise; // lifecycle operations /** * Set the bucket object lifecycle. */ - putBucketLifecycle(name: string, rules: LifecycleRule[], options?: RequestOptions): Promise; + putBucketLifecycle(name: string, rules: OSS.LifecycleRule[], options?: OSS.RequestOptions): Promise; /** * Get the bucket object lifecycle. */ - getBucketLifecycle(name: string, options?: RequestOptions): Promise<{ rules: LifecycleRule[], res: NormalSuccessResponse }>; + getBucketLifecycle(name: string, options?: OSS.RequestOptions): Promise<{ rules: OSS.LifecycleRule[], res: OSS.NormalSuccessResponse }>; /** * Delete the bucket object lifecycle. */ - deleteBucketLifecycle(name: string, options?: RequestOptions): Promise; + deleteBucketLifecycle(name: string, options?: OSS.RequestOptions): Promise; // CORS operations /** * Set CORS rules of the bucket object */ - putBucketCORS(name: string, rules: CORSRule[], options?: RequestOptions): Promise; + putBucketCORS(name: string, rules: OSS.CORSRule[], options?: OSS.RequestOptions): Promise; /** * Get CORS rules of the bucket object. */ - getBucketCORS(name: string): Promise<{ rules: CORSRule[], res: NormalSuccessResponse }>; + getBucketCORS(name: string): Promise<{ rules: OSS.CORSRule[], res: OSS.NormalSuccessResponse }>; /** * Delete CORS rules of the bucket object. */ - deleteBucketCORS(name: string): Promise; + deleteBucketCORS(name: string): Promise; /********************************************************** Object operations ********************************************/ /** * List objects in the bucket. */ - list(query: ListObjectsQuery | null, options: RequestOptions): Promise; + list(query: OSS.ListObjectsQuery | null, options: OSS.RequestOptions): Promise; /** * Add an object to the bucket. */ - put(name: string, file: any, options?: PutObjectOptions): Promise; + put(name: string, file: any, options?: OSS.PutObjectOptions): Promise; /** * Add a stream object to the bucket. */ - putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }>; + putStream(name: string, stream: any, options?: OSS.PutStreamOptions): Promise<{ name: string, res: OSS.NormalSuccessResponse }>; /** * Append an object to the bucket, it's almost same as put, but it can add content to existing object rather than override it. */ - append(name: string, file: any, options?: AppendObjectOptions): Promise; + append(name: string, file: any, options?: OSS.AppendObjectOptions): Promise; /** * Get the Object url. If provide baseUrl, will use baseUrl instead the default endpoint. @@ -600,67 +713,67 @@ export default class OSS { /** * Head an object and get the meta info. */ - head(name: string, options?: HeadObjectOptions): Promise; + head(name: string, options?: OSS.HeadObjectOptions): Promise; /** * Get an object from the bucket. */ - get(name: string, file?: any, options?: GetObjectOptions): Promise; + get(name: string, file?: any, options?: OSS.GetObjectOptions): Promise; /** * Get an object read stream. */ - getStream(name?: string, options?: GetStreamOptions): Promise; + getStream(name?: string, options?: OSS.GetStreamOptions): Promise; /** * Delete an object from the bucket. */ - delete(name: string, options?: RequestOptions): Promise; + delete(name: string, options?: OSS.RequestOptions): Promise; /** * Copy an object from sourceName to name. */ - copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise; + copy(name: string, sourceName: string, options?: OSS.CopyObjectOptions): Promise; /** * Set an exists object meta. */ - putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise; + putMeta(name: string, meta: OSS.UserMeta, options: OSS.RequestOptions): Promise; /** * Delete multi objects in one request. */ - deleteMulti(names: string[], options?: DeleteMultiOptions): Promise; + deleteMulti(names: string[], options?: OSS.DeleteMultiOptions): Promise; /** * Create a signature url for download or upload object. When you put object with signatureUrl ,you need to pass Content-Type.Please look at the example. */ - signatureUrl(name: string, options?: SignatureUrlOptions): string; + signatureUrl(name: string, options?: OSS.SignatureUrlOptions): string; /** * Set object's ACL. */ - putACL(name: string, acl: ACLType, options?: RequestOptions): Promise; + putACL(name: string, acl: OSS.ACLType, options?: OSS.RequestOptions): Promise; /** * Get object's ACL. */ - getACL(name: string, options?: RequestOptions): Promise; + getACL(name: string, options?: OSS.RequestOptions): Promise; /** * Restore Object. */ - restore(name: string, options?: RequestOptions): Promise; + restore(name: string, options?: OSS.RequestOptions): Promise; /** * multi upload */ - initMultipartUpload(name: string, options?: InitMultipartUploadOptions): Promise; + initMultipartUpload(name: string, options?: OSS.InitMultipartUploadOptions): Promise; /** * After initiating a Multipart Upload event, you can upload data in parts based on the specified object name and Upload ID. */ - uploadPart(name: string, uploadId: string, partNo: number, file: any, start: number, end: number, options?: RequestOptions): Promise; + uploadPart(name: string, uploadId: string, partNo: number, file: any, start: number, end: number, options?: OSS.RequestOptions): Promise; /** * Using Upload Part Copy, you can copy data from an existing object and upload a part of the data. @@ -673,7 +786,7 @@ export default class OSS { range: string, sourceData: { sourceKey: string, sourceBucketName: string }, options: { timeout?: number, headers?: object } - ): Promise; + ): Promise; /** * After uploading all data parts, you must call the Complete Multipart Upload API to complete Multipart Upload for the entire file. @@ -682,79 +795,79 @@ export default class OSS { name: string, uploadId: string, parts: Array<{ number: number, etag: string }>, - options?: CompleteMultipartUploadOptions - ): Promise; + options?: OSS.CompleteMultipartUploadOptions + ): Promise; /** * Upload file with OSS multipart. */ - multipartUpload(name: string, file: any, options: MultipartUploadOptions): Promise; + multipartUpload(name: string, file: any, options: OSS.MultipartUploadOptions): Promise; /** * Copy file with OSS multipart. * this function contains head, initMultipartUpload, uploadPartCopy, completeMultipartUpload. * When copying a file larger than 1 GB, you should use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object. */ - multipartUploadCopy(name: string, sourceData: MultipartUploadCopySourceData, options?: MultipartUploadOptions): Promise; + multipartUploadCopy(name: string, sourceData: OSS.MultipartUploadCopySourceData, options?: OSS.MultipartUploadOptions): Promise; /** * The ListParts command can be used to list all successfully uploaded parts mapped to a specific upload ID, i.e.: those not completed and not aborted. */ - listParts(name: string, uploadId: string, query?: ListPartsQuery, options?: RequestOptions): Promise; + listParts(name: string, uploadId: string, query?: OSS.ListPartsQuery, options?: OSS.RequestOptions): Promise; /** * List on-going multipart uploads, i.e.: those not completed and not aborted. */ - listUploads(query: ListUploadsQuery, options?: RequestOptions): Promise; + listUploads(query: OSS.ListUploadsQuery, options?: OSS.RequestOptions): Promise; /** * Abort a multipart upload for object. */ - abortMultipartUpload(name: string, uploadId: string, options?: RequestOptions): Promise; + abortMultipartUpload(name: string, uploadId: string, options?: OSS.RequestOptions): Promise; /************************************************ RTMP Operations *************************************************************/ /** * Create a live channel. */ - putChannel(id: string, conf: PutChannelConf, options?: RequestOptions): Promise; + putChannel(id: string, conf: OSS.PutChannelConf, options?: OSS.RequestOptions): Promise; /** * Get live channel info. */ - getChannel(id: string, options?: RequestOptions): Promise<{ data: PutChannelConf, res: NormalSuccessResponse }>; + getChannel(id: string, options?: OSS.RequestOptions): Promise<{ data: OSS.PutChannelConf, res: OSS.NormalSuccessResponse }>; /** * Delete a live channel. */ - deleteChannel(id: string, options?: RequestOptions): Promise; + deleteChannel(id: string, options?: OSS.RequestOptions): Promise; /** * Change the live channel status. */ - putChannelStatus(id: string, status?: string, options?: RequestOptions): Promise; + putChannelStatus(id: string, status?: string, options?: OSS.RequestOptions): Promise; /** * Get the live channel status. */ - getChannelStatus(id: string, options?: RequestOptions): Promise; + getChannelStatus(id: string, options?: OSS.RequestOptions): Promise; /** * List channels. */ - listChannels(query: ListChannelsQuery, options?: RequestOptions): Promise; + listChannels(query: OSS.ListChannelsQuery, options?: OSS.RequestOptions): Promise; /** * Get the live channel history. */ - getChannelHistory(id: string, options?: RequestOptions): Promise; + getChannelHistory(id: string, options?: OSS.RequestOptions): Promise; /** * Create a VOD playlist for the channel. */ - createVod(id: string, name: string, time: { startTime: number, endTime: number }, options?: RequestOptions): Promise; + createVod(id: string, name: string, time: { startTime: number, endTime: number }, options?: OSS.RequestOptions): Promise; /** * Get signatured rtmp url for publishing. */ - getRtmpUrl(channelId?: string, options?: GetRtmpUrlOptions): string; + getRtmpUrl(channelId?: string, options?: OSS.GetRtmpUrlOptions): string; } diff --git a/types/ali-oss/tsconfig.json b/types/ali-oss/tsconfig.json index 62f030a4fd..6a0fb7441b 100644 --- a/types/ali-oss/tsconfig.json +++ b/types/ali-oss/tsconfig.json @@ -18,8 +18,6 @@ }, "files": [ "index.d.ts", - "ImageClient.d.ts", - "Cluster.d.ts", "ali-oss-tests.ts" ] } diff --git a/types/ali-oss/tslint.json b/types/ali-oss/tslint.json index f93cf8562a..8192d88dd1 100644 --- a/types/ali-oss/tslint.json +++ b/types/ali-oss/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-mergeable-namespace": false + } } diff --git a/types/amqp-connection-manager/index.d.ts b/types/amqp-connection-manager/index.d.ts index ab69aadeb1..e2907b67ee 100644 --- a/types/amqp-connection-manager/index.d.ts +++ b/types/amqp-connection-manager/index.d.ts @@ -136,7 +136,16 @@ export interface ChannelWrapper extends EventEmitter { * Setup functions should, ideally, not throw errors, but if they do then the ChannelWrapper will emit an 'error' event. * @param func */ - addSetup(func: SetupFunc): Promise; + addSetup(func: SetupFunc): Promise; + + /** + * Remove a setup function added with `addSetup`. If there is currently a + * connection, `teardown(channel, [cb])` will be run immediately, and the + * returned Promise will not resolve until it completes. + * @param func + * @param [tearDown] + */ + removeSetup(func: SetupFunc, tearDown?: SetupFunc): Promise; /** * @see amqplib diff --git a/types/analytics-node/index.d.ts b/types/analytics-node/index.d.ts index 6834087ff7..cc9e5386e2 100644 --- a/types/analytics-node/index.d.ts +++ b/types/analytics-node/index.d.ts @@ -22,8 +22,8 @@ declare namespace AnalyticsNode { }, timestamp?: Date; messageId?: string; - anonymousId: string | number; - userId: string | number; + anonymousId?: string | number; + userId?: string | number; } interface Data { @@ -47,7 +47,8 @@ declare namespace AnalyticsNode { /* The identify method lets you tie a user to their actions and record traits about them. */ identify(message: { - userId: string | number; + userId?: string | number; + anonymousId?: string | number; traits?: Object; timestamp?: Date; context?: Object; @@ -56,7 +57,8 @@ declare namespace AnalyticsNode { /* The track method lets you record the actions your users perform. */ track(message: { - userId: string | number; + userId?: string | number; + anonymousId?: string | number; event: string; properties?: Object; timestamp?: Date; @@ -67,7 +69,8 @@ declare namespace AnalyticsNode { /* The page method lets you record page views on your website, along with optional extra information about the page being viewed. */ page(message: { - userId: string | number; + userId?: string | number; + anonymousId?: string | number; category?: string; name?: string; properties?: Object; @@ -79,19 +82,20 @@ declare namespace AnalyticsNode { /* alias is how you associate one identity with another. */ alias(message: { previousId: string | number; - userId: string | number; + userId?: string | number; + anonymousId?: string | number; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; /* Group calls can be used to associate individual users with shared accounts or companies. */ group(message: { - userId: string | number; + userId?: string | number; + anonymousId?: string | number; groupId: string | number; traits?: Object; context?: Object; timestamp?: Date; - anonymous_id?: string | number; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; diff --git a/types/angular-agility/tslint.json b/types/angular-agility/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-agility/tslint.json +++ b/types/angular-agility/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular-locker/tslint.json b/types/angular-locker/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-locker/tslint.json +++ b/types/angular-locker/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index db74c97d10..9202829175 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -153,6 +153,10 @@ declare module 'angular' { defaultFontSet(name: string): IIconProvider; } + interface IInkRippleProvider { + disableInkRipple(): void; + } + type IMedia = (media: string) => boolean; interface ISidenavObject { diff --git a/types/angular-odata-resources/tslint.json b/types/angular-odata-resources/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-odata-resources/tslint.json +++ b/types/angular-odata-resources/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular-ui-tree/tslint.json b/types/angular-ui-tree/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-ui-tree/tslint.json +++ b/types/angular-ui-tree/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular/test/jquery3-merging-tests.ts b/types/angular/test/jquery3-merging-tests.ts index 507c58b67e..da61a6f0bc 100644 --- a/types/angular/test/jquery3-merging-tests.ts +++ b/types/angular/test/jquery3-merging-tests.ts @@ -94,8 +94,6 @@ function JQuery() { } function bind() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').bind('myEvent', 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -104,14 +102,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('p').bind('myEvent', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('p').bind('myEvent', function(event) { // TODO: $ExpectType HTMLElement @@ -120,14 +110,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('p').bind('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('p').bind('myEvent', false); @@ -139,12 +121,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }); @@ -164,27 +140,15 @@ function JQuery() { } function off() { - function defaultContext_defaultData(this: HTMLElement, event: JQueryEventObject) { } + function defaultData(this: HTMLElement, event: JQueryEventObject) { } - function defaultContext_customData(this: HTMLElement, event: JQueryEventObject) { } - - function customContext_defaultData(this: I1, event: JQueryEventObject) { } - - function customContext_customData(this: I1, event: JQueryEventObject) { } - - interface I1 { kind: 'I1'; } + function customData(this: HTMLElement, event: JQueryEventObject) { } // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_defaultData); + $('table').off('myEvent', 'td', 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); + $('table').off('myEvent', 'td', customData); // $ExpectType JQuery $('table').off('myEvent', 'td', false); @@ -193,16 +157,10 @@ function JQuery() { $('table').off('myEvent', 'td'); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_defaultData); + $('table').off('myEvent', defaultData); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_customData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_customData); + $('table').off('myEvent', customData); // $ExpectType JQuery $('table').off('myEvent', false); @@ -213,19 +171,15 @@ function JQuery() { // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }, 'td'); // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }); // $ExpectType JQuery @@ -236,8 +190,6 @@ function JQuery() { } function on() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('table').on('myEvent', 'td', 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -246,14 +198,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', 'td', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', null, 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -262,14 +206,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', null, 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', 'td', function(event) { // TODO: $ExpectType HTMLElement @@ -278,14 +214,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', 'td', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', 'td', false); @@ -297,14 +225,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', 3, function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', function(event) { // TODO: $ExpectType HTMLElement @@ -313,14 +233,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', false); @@ -332,12 +244,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td', 'myData'); @@ -349,12 +255,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, null, 'myData'); @@ -366,12 +266,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td'); @@ -383,12 +277,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 3); @@ -400,19 +288,11 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }); } function one() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('table').one('myEvent', 'td', 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -421,14 +301,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', 'td', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', null, 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -437,14 +309,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', null, 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', 'td', function(event) { // TODO: $ExpectType HTMLElement @@ -453,14 +317,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', 'td', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', 'td', false); @@ -472,14 +328,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', 3, function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', function(event) { // TODO: $ExpectType HTMLElement @@ -488,14 +336,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', false); @@ -507,12 +347,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td', 'myData'); @@ -524,12 +358,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, null, 'myData'); @@ -541,12 +369,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td'); @@ -558,12 +380,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 3); @@ -575,12 +391,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }); } diff --git a/types/angularfire/tslint.json b/types/angularfire/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angularfire/tslint.json +++ b/types/angularfire/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ansi/ansi-tests.ts b/types/ansi/ansi-tests.ts index b2625defa5..0c033c6839 100644 --- a/types/ansi/ansi-tests.ts +++ b/types/ansi/ansi-tests.ts @@ -22,7 +22,7 @@ Object.keys({ }).forEach((color) => { const cname = color.replace(/([a-z])([A-Z])/g, (_: string, l: string, u: string): string => `${l} ${u.toLowerCase()}`); - ((<(...anything: any[]) => ansi.Cursor> cursor[color])() + ((cursor[color] as (...anything: any[]) => ansi.Cursor)() .bold() .bg)[color === 'blue' || color === 'brightBlue' ? 'black' : 'blue']() .write( diff --git a/types/ansicolors/index.d.ts b/types/ansicolors/index.d.ts index 6750283895..dd1a872e57 100644 --- a/types/ansicolors/index.d.ts +++ b/types/ansicolors/index.d.ts @@ -1,8 +1,45 @@ // Type definitions for ansicolors // Project: https://github.com/thlorenz/ansicolors -// Definitions by: rogierschouten +// Definitions by: Benjamin Arthur Lupton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare var colors: { [index: string]: (s: string) => string; }; -export = colors; +interface Colors extends String { + (value: string): string + white: this + black: this + blue: this + cyan: this + green: this + magenta: this + red: this + yellow: this + brightBlack: this + brightRed: this + brightGreen: this + brightYellow: this + brightBlue: this + brightMagenta: this + brightCyan: this + brightWhite: this + bgBlack: this + bgRed: this + bgGreen: this + bgYellow: this + bgBlue: this + bgMagenta: this + bgCyan: this + bgWhite: this + bgBrightBlack: this + bgBrightRed: this + bgBrightGreen: this + bgBrightYellow: this + bgBrightBlue: this + bgBrightMagenta: this + bgBrightCyan: this + bgBrightWhite: this + open: this + close: this + colors: this +} +declare const colors: Colors +export default colors diff --git a/types/applicationinsights-js/applicationinsights-js-tests.ts b/types/applicationinsights-js/applicationinsights-js-tests.ts index c2adb63a30..de6de9a2c6 100644 --- a/types/applicationinsights-js/applicationinsights-js-tests.ts +++ b/types/applicationinsights-js/applicationinsights-js-tests.ts @@ -47,7 +47,8 @@ appInsights = { startTrackEvent(name: string) { return null; }, stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, - trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) { return null; }, + trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, + resultCode: number, properties?: { [name: string]: string }, measurements?: { [name: string]: number }) { return null; }, trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null; }, trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null; }, trackTrace(message: string, properties?: { [name: string]: string; }, severityLevel?: AI.SeverityLevel) { return null; }, @@ -86,7 +87,7 @@ appInsights.trackTrace("message", null); appInsights.trackTrace("message", { a: '1', b: '2' }, AI.SeverityLevel.Error); // trackDependency -appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null); +appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null, {prop1: 'abc'}, {meas1: 4.5}); // flush appInsights.flush(); diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index 5fbbc3a0f5..002a950637 100644 --- a/types/applicationinsights-js/index.d.ts +++ b/types/applicationinsights-js/index.d.ts @@ -670,14 +670,16 @@ declare module Microsoft.ApplicationInsights { context: ITelemetryContext; queue: Array<() => void>; /** - * Starts timing how long the user views a page or other item. Call this when the page opens. - * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. + * Starts the timer for tracking a page load time. Use this instead of `trackPageView` if you want to control when the page view timer starts and stops, + * but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call `stopTrackPage` to log the end of the page view + * and send the event. * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title. */ startTrackPage(name?: string): any; /** - * Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes. - * @param name The string you used as the name in startTrackPage. Defaults to the document title. + * Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements. + * The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`. + * @param name The string you used as the name in `startTrackPage`. Defaults to the document title. * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. @@ -689,7 +691,7 @@ declare module Microsoft.ApplicationInsights { measurements?: { [name: string]: number }): any; /** * Logs that a page or other item was viewed. - * @param name The string you used as the name in startTrackPage. Defaults to the document title. + * @param name The string you used as the name in `startTrackPage`. Defaults to the document title. * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. @@ -701,13 +703,13 @@ declare module Microsoft.ApplicationInsights { properties?: { [name: string]: string }, measurements?: { [name: string]: number }, duration?: number): any; /** - * Start timing an extended event. Call {@link stopTrackEvent} to log the event when it ends. + * Start timing an extended event. Call `stopTrackEvent` to log the event when it ends. * @param name A string that identifies this event uniquely within the document. */ startTrackEvent(name: string): any; /** - * Log an extended event that you started timing with {@link startTrackEvent}. - * @param name The string you used to identify this event in startTrackEvent. + * Log an extended event that you started timing with `startTrackEvent`. + * @param name The string you used to identify this event in `startTrackEvent`. * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. */ @@ -734,8 +736,11 @@ declare module Microsoft.ApplicationInsights { * @param totalTime total request time * @param success indicates if the request was sessessful * @param resultCode response code returned by the dependency request + * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. */ - trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number): any; + trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, + properties?: { [name: string]: string }, measurements?: { [name: string]: number }): any; /** * Log an exception you have caught. * @param exception An Error from a catch clause, or the string error message. diff --git a/types/arangodb/arangodb-tests.ts b/types/arangodb/arangodb-tests.ts index e049a2374d..c2ade4d0bb 100644 --- a/types/arangodb/arangodb-tests.ts +++ b/types/arangodb/arangodb-tests.ts @@ -16,6 +16,9 @@ coll.save({ username: "user" }); const doc = coll.any(); console.log(doc.username); +const coll2 = db._collection(coll.name()); +console.log(coll2 === coll); + const users = coll as ArangoDB.Collection; const admin = users.firstExample({ username: "admin" })!; users.update(admin, { password: md5("hunter2") }); diff --git a/types/arangodb/index.d.ts b/types/arangodb/index.d.ts index 238cea2379..c5e83a1cfc 100644 --- a/types/arangodb/index.d.ts +++ b/types/arangodb/index.d.ts @@ -619,6 +619,7 @@ declare namespace ArangoDB { interface Collection { // Collection + name(): string; checksum( withRevisions?: boolean, withData?: boolean @@ -1503,16 +1504,7 @@ declare module "@arangodb/foxx/queues" { function deleteQueue(name: string): boolean; function get(name: string): Queue; - export { - createQueue as create, - deleteQueue as delete, - get, - JobOptions, - Job, - Queue, - QueueItem, - Script, - }; + export { createQueue as create, deleteQueue as delete, get, JobOptions, Job, Queue, QueueItem, Script, }; } declare module "@arangodb/foxx/graphql" { diff --git a/types/assert/assert-tests.ts b/types/assert/assert-tests.ts index 22248c18bd..3f795f0552 100644 --- a/types/assert/assert-tests.ts +++ b/types/assert/assert-tests.ts @@ -5,6 +5,7 @@ assert(true, "it's working"); assert.ok(true, "inner functions work as well"); assert.throws(() => {}); +assert.throws(() => {}, /Regex test/); assert.throws(() => {}, () => {}, "works wonderfully"); assert['fail'](true, true, "works like a charm"); diff --git a/types/assert/index.d.ts b/types/assert/index.d.ts index d79805f5af..f04158bbd3 100644 --- a/types/assert/index.d.ts +++ b/types/assert/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for commonjs-assert 1.4 // Project: https://github.com/browserify/commonjs-assert // Definitions by: Nico Gallinal +// Linus Unnebäck // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare function assert(value: any, message?: string): void; @@ -23,10 +24,10 @@ declare namespace assert { function notStrictEqual(actual: any, expected: any, message?: string): void; function throws(block: () => void, message?: string): void; - function throws(block: () => void, error: () => void | ((err: any) => boolean) | RegExp, message?: string): void; + function throws(block: () => void, error: (() => void) | ((err: any) => boolean) | RegExp, message?: string): void; function doesNotThrow(block: () => void, message?: string): void; - function doesNotThrow(block: () => void, error: () => void | ((err: any) => boolean) | RegExp, message?: string): void; + function doesNotThrow(block: () => void, error: (() => void) | ((err: any) => boolean) | RegExp, message?: string): void; function ifError(value: any): void; diff --git a/types/async/test/index.ts b/types/async/test/index.ts index 0081dd3dcd..574a5ed8b9 100644 --- a/types/async/test/index.ts +++ b/types/async/test/index.ts @@ -390,22 +390,22 @@ async.auto({ get_data: function (callback: AsyncResultCallback) { }, make_folder: function (callback: AsyncResultCallback) { }, //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { + write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { callback(null, filename); - }], + } as any], //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { }] + email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { } as any] }); async.auto({ get_data: function (callback: AsyncResultCallback) { }, make_folder: function (callback: AsyncResultCallback) { }, //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { + write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { callback(null, filename); - }], + } as any], //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { }] + email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { } as any] }, function (err, results) { console.log('finished auto'); }); @@ -421,11 +421,11 @@ async.auto({ get_data: function (callback: AsyncResultCallback) { }, make_folder: function (callback: AsyncResultCallback) { }, //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { + write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { callback(null, filename); - }], + } as any], //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { }] + email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { } as any] }, 1, function (err, results) { console.log('finished auto'); }); diff --git a/types/atlaskit__tree/atlaskit__tree-tests.tsx b/types/atlaskit__tree/atlaskit__tree-tests.tsx new file mode 100644 index 0000000000..b99647a7c6 --- /dev/null +++ b/types/atlaskit__tree/atlaskit__tree-tests.tsx @@ -0,0 +1,42 @@ +import Tree from "@atlaskit/tree"; + +import * as React from "react"; +import { render } from "react-dom"; + +declare const container: Element; + +render( +
} + onExpand={() => {}} + onCollapse={() => {}} + onDragStart={() => {}} + onDragEnd={() => {}} + offsetPerLevel={20} + isDragEnabled + isNestingEnabled + />, + container +); + +// Check that default props work too. +render(
} />, container); diff --git a/types/atlaskit__tree/index.d.ts b/types/atlaskit__tree/index.d.ts new file mode 100644 index 0000000000..4d6a952b76 --- /dev/null +++ b/types/atlaskit__tree/index.d.ts @@ -0,0 +1,153 @@ +// Type definitions for @atlaskit/tree 4.1 +// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/ +// Definitions by: Ben James +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +import { Component, ReactNode } from "react"; + +import { + DraggingStyle, + DraggableProvidedDragHandleProps, + DraggableStateSnapshot, + NotDraggingStyle +} from "react-beautiful-dnd"; + +export type ItemId = any; + +export type Path = number[]; + +export interface TreeData { + rootId: ItemId; + items: { [key: string]: TreeItem; [key: number]: TreeItem }; +} + +export type TreeItemData = any; + +export interface TreeItem { + id: ItemId; + children: ItemId[]; + hasChildren?: boolean; + isExpanded?: boolean; + isChildrenLoading?: boolean; + data?: TreeItemData; +} + +export interface TreeSourcePosition { + parentId: ItemId; + index: number; +} + +export interface TreeDestinationPosition { + parentId: ItemId; + index?: number; +} + +type Omit = Pick>; + +interface TreeDraggingStyle extends Omit { + paddingLeft: number; + transition: "none" | string; +} + +type TreeDraggableStyle = NotDraggingStyle | TreeDraggingStyle; + +interface TreeDraggableProps { + // Props that can be spread onto the element directly + // inline style + style?: TreeDraggableStyle; + // used for shared global styles + "data-react-beautiful-dnd-draggable": string; +} + +interface TreeDraggableProvided { + draggableProps: TreeDraggableProps; + // will be null if the draggable is disabled + dragHandleProps?: DraggableProvidedDragHandleProps; + // The following props will be removed once we move to react 16 + innerRef: (element?: HTMLElement) => void; +} + +export interface RenderItemParams { + item: TreeItem; + depth: number; + onExpand: (itemId: ItemId) => void; + onCollapse: (itemId: ItemId) => void; + provided: TreeDraggableProvided; + snapshot: DraggableStateSnapshot; +} + +interface TreeItemMutation { + id?: ItemId; + children?: ItemId[]; + hasChildren?: boolean; + isExpanded?: boolean; + isChildrenLoading?: boolean; + data?: TreeItemData; +} + +export function mutateTree( + tree: TreeData, + itemId: ItemId, + mutation: TreeItemMutation +): TreeData; + +export function moveItemOnTree( + tree: TreeData, + from: TreeSourcePosition, + to: TreeDestinationPosition +): TreeData; + +interface TreeProps { + /** The tree data structure. */ + tree: TreeData; + /** Function that will be called when a parent item needs to be expanded. */ + onExpand: (itemId: ItemId, path: Path) => void; + /** Function that will be called when a parent item needs to be collapsed. */ + onCollapse: (itemId: ItemId, path: Path) => void; + /** Function that will be called when the user starts dragging. */ + onDragStart: (itemId: ItemId) => void; + /** Function that will be called when the user finishes dragging. */ + onDragEnd: ( + sourcePosition: TreeSourcePosition, + destinationPosition: TreeDestinationPosition | undefined + ) => void; + /** Function that will be called to render a single item. */ + renderItem: (itemProps: RenderItemParams) => ReactNode; + /** Number of pixel is used to scaffold the tree by the consumer. */ + offsetPerLevel: number; + /** Boolean to turn on drag&drop re-ordering on the tree */ + isDragEnabled: boolean; + /** Boolean to turn on hovering while dragging */ + isNestingEnabled: boolean; +} + +interface FlattenedItem { + item: TreeItem; + path: Path; +} + +type FlattenedTree = FlattenedItem[]; + +interface TreeState { + /** The flattened tree data structure transformed from props.tree */ + flattenedTree: FlattenedTree; + // Id of the currently dragged item + draggedItemId: ItemId; +} + +declare class Tree extends Component { + static defaultProps: { + tree: { children: [] }; + onExpand: () => void; + onCollapse: () => void; + onDragStart: () => void; + onDragEnd: () => void; + renderItem: () => void; + offsetPerLevel: 35; + isDragEnabled: false; + isNestingEnabled: false; + }; +} + +export default Tree; diff --git a/types/atlaskit__tree/tsconfig.json b/types/atlaskit__tree/tsconfig.json new file mode 100644 index 0000000000..b6d581fa0d --- /dev/null +++ b/types/atlaskit__tree/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "paths": { + "@atlaskit/tree": ["atlaskit__tree"] + } + }, + "files": ["index.d.ts", "atlaskit__tree-tests.tsx"] +} diff --git a/types/atlaskit__tree/tslint.json b/types/atlaskit__tree/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/atlaskit__tree/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/atom/atom-tests.ts b/types/atom/atom-tests.ts index 6acca94fc5..9a04b9c7b6 100644 --- a/types/atom/atom-tests.ts +++ b/types/atom/atom-tests.ts @@ -557,8 +557,8 @@ function testDesializerManager() { } function isStorableClass(o: object): o is StorableClass { - if (typeof o === "object" && ( o).name && - ( o).name === "test") { + if (typeof o === "object" && (o as StorableClass).name && + (o as StorableClass).name === "test") { return true; } else { return false; diff --git a/types/babel__core/babel__core-tests.ts b/types/babel__core/babel__core-tests.ts index a873c3392f..ba51ac21be 100644 --- a/types/babel__core/babel__core-tests.ts +++ b/types/babel__core/babel__core-tests.ts @@ -7,15 +7,18 @@ const options: babel.TransformOptions = { babel.transform("code();", options, (err, result) => { const { code, map, ast } = result!; + const { body } = ast!.program; }); const transformSyncResult = babel.transformSync("code();", options); if (transformSyncResult) { const { code, map, ast } = transformSyncResult; + const { body } = ast!.program; } babel.transformFile("filename.js", options, (err, result) => { const { code, map, ast } = result!; + const { body } = ast!.program; }); babel.transformFileSync("filename.js", options)!.code; @@ -25,7 +28,14 @@ const parsedAst = babel.parse(sourceCode, options); babel.transformFromAst(parsedAst!, sourceCode, options, (err, result) => { const { code, map, ast } = result!; + const { body } = ast!.program; }); const transformFromAstSyncResult = babel.transformFromAstSync(parsedAst!, sourceCode, options); const { code, map, ast } = transformFromAstSyncResult!; +const { body } = ast!.program; + +babel.transformFromAstAsync(parsedAst!, sourceCode, options).then(transformFromAstAsyncResult => { + const { code, map, ast } = transformFromAstAsyncResult!; + const { body } = ast!.program; +}); diff --git a/types/babel__core/index.d.ts b/types/babel__core/index.d.ts index 85a89392af..eb39d90a58 100644 --- a/types/babel__core/index.d.ts +++ b/types/babel__core/index.d.ts @@ -349,7 +349,7 @@ export function transformFromAstSync(ast: Node, code?: string, opts?: TransformO /** * Given an AST, transform it. */ -export function transformFromAstSync(ast: Node, code?: string, opts?: TransformOptions): Promise; +export function transformFromAstAsync(ast: Node, code?: string, opts?: TransformOptions): Promise; // A babel plugin is a simple function which must return an object matching // the following interface. Babel will throw if it finds unknown properties. @@ -365,7 +365,7 @@ export interface PluginObj { } export interface BabelFileResult { - ast?: Node | null; + ast?: t.File | null; code?: string | null; ignored?: boolean; map?: { diff --git a/types/babel__traverse/babel__traverse-tests.ts b/types/babel__traverse/babel__traverse-tests.ts index 5b4fbbef5f..70f8c5f0b6 100644 --- a/types/babel__traverse/babel__traverse-tests.ts +++ b/types/babel__traverse/babel__traverse-tests.ts @@ -4,10 +4,14 @@ import * as t from "@babel/types"; // Examples from: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md const MyVisitor: Visitor = { Identifier: { - enter() { + enter(path) { + // $ExpectType NodePath + path; console.log("Entered!"); }, - exit() { + exit(path) { + // $ExpectType NodePath + path; console.log("Exited!"); } } @@ -89,7 +93,8 @@ const v1: Visitor = { const id = path.scope.generateUidIdentifierBasedOnNode(path.node.id!); path.remove(); - path.scope.parent.push({ id, init: path.node }); + path.scope.parent.push({ id }); + path.scope.parent.push({ id, init: t.stringLiteral('foo'), kind: "const" }); path.scope.rename("n", "x"); path.scope.rename("n"); @@ -104,7 +109,44 @@ const BindingKindTest: Visitor = { kind === 'const'; kind === 'let'; kind === 'var'; - // The following should fail when uncommented - // kind === 'anythingElse'; + // $ExpectError + kind === 'anythingElse'; }, }; + +interface SomeVisitorState { someState: string; } + +const VisitorStateTest: Visitor = { + enter(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + exit(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + Identifier(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + FunctionDeclaration: { + enter(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + exit(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + } + } +}; diff --git a/types/babel__traverse/index.d.ts b/types/babel__traverse/index.d.ts index 465a60464f..89e242129b 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -90,11 +90,16 @@ export class Scope { removeData(key: string): void; - push(opts: any): void; + push(opts: { + id: t.LVal, + init?: t.Expression, + unique?: boolean, + kind?: "var" | "let" | "const", + }): void; getProgramParent(): Scope; - getFunctionParent(): Scope; + getFunctionParent(): Scope | null; getBlockParent(): Scope; @@ -138,17 +143,17 @@ export class Binding { constantViolations: NodePath[]; } -export type Visitor = VisitNodeObject & { - [P in Node["type"]]?: VisitNode>; +export type Visitor = VisitNodeObject & { + [Type in Node["type"]]?: VisitNode>; }; -export type VisitNode = VisitNodeFunction | VisitNodeObject; +export type VisitNode = VisitNodeFunction | VisitNodeObject; -export type VisitNodeFunction = (this: T, path: NodePath

, state: any) => void; +export type VisitNodeFunction = (this: S, path: NodePath

, state: S) => void; -export interface VisitNodeObject { - enter?(path: NodePath, state: any): void; - exit?(path: NodePath, state: any): void; +export interface VisitNodeObject { + enter?: VisitNodeFunction; + exit?: VisitNodeFunction; } export class NodePath { diff --git a/types/backbone-fetch-cache/backbone-fetch-cache-tests.ts b/types/backbone-fetch-cache/backbone-fetch-cache-tests.ts index 072e3c29ce..6c2d852961 100644 --- a/types/backbone-fetch-cache/backbone-fetch-cache-tests.ts +++ b/types/backbone-fetch-cache/backbone-fetch-cache-tests.ts @@ -64,7 +64,7 @@ const modelOpts: Backbone.ModelFetchWithCacheOptions = { context: {}, }; -const hoge = new Backbone.Model; +const hoge = new Backbone.Model() as Backbone.ModelWithCache; hoge.fetch(modelOpts); const collectionOpts: Backbone.CollectionFetchWithCacheOptions = { @@ -76,5 +76,5 @@ const collectionOpts: Backbone.CollectionFetchWithCacheOptions = { prefillSuccess: (self: any) => { }, }; -const fuga = new Backbone.Collection; +const fuga = new Backbone.Collection() as Backbone.CollectionWithCache; fuga.fetch(collectionOpts); diff --git a/types/backbone-relational/index.d.ts b/types/backbone-relational/index.d.ts index a1c8c3eefb..403759ac97 100644 --- a/types/backbone-relational/index.d.ts +++ b/types/backbone-relational/index.d.ts @@ -122,7 +122,19 @@ declare module 'backbone' { } - export class Store extends Events { + export class Store implements Events { + on(eventName: string, callback?: (...args: any[]) => void, context?: any): any; + on(eventMap: EventsHash): any; + on(eventName: any, callback?: any, context?: any): any; + off(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + trigger(eventName: string, ...args: any[]): any; + bind(eventName: string, callback: (...args: any[]) => void, context?: any): any; + unbind(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + once(events: string, callback: (...args: any[]) => void, context?: any): any; + listenTo(object: any, events: string, callback: (...args: any[]) => void): any; + listenToOnce(object: any, events: string, callback: (...args: any[]) => void): any; + stopListening(object?: any, events?: string, callback?: (...args: any[]) => void): any; + initializeRelation(model, relation, options); addModelScope(scope:any):void; diff --git a/types/backbone.marionette/index.d.ts b/types/backbone.marionette/index.d.ts index 609bf37b67..4edaba87b7 100644 --- a/types/backbone.marionette/index.d.ts +++ b/types/backbone.marionette/index.d.ts @@ -407,9 +407,21 @@ export interface ObjectOptions extends RadioMixinOptions { * A base class which other classes can extend from. Object incorporates many * backbone conventions and utilities like initialize and Backbone.Events. */ -export class Object extends Backbone.Events implements CommonMixin, RadioMixin { +export class Object implements CommonMixin, RadioMixin, Backbone.Events { constructor(options?: ObjectOptions); + on(eventName: string, callback?: (...args: any[]) => void, context?: any): any; + on(eventMap: EventsHash): any; + on(eventName: any, callback?: any, context?: any): any; + off(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + trigger(eventName: string, ...args: any[]): any; + bind(eventName: string, callback: (...args: any[]) => void, context?: any): any; + unbind(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + once(events: string, callback: (...args: any[]) => void, context?: any): any; + listenTo(object: any, events: string, callback: (...args: any[]) => void): any; + listenToOnce(object: any, events: string, callback: (...args: any[]) => void): any; + stopListening(object?: any, events?: string, callback?: (...args: any[]) => void): any; + /** * Receives a hash of event names and functions and/or function names, * and returns the same hash with the function names replaced with the diff --git a/types/backbone.paginator/backbone.paginator-tests.ts b/types/backbone.paginator/backbone.paginator-tests.ts index f24e2855f5..0c1b0cf9a8 100644 --- a/types/backbone.paginator/backbone.paginator-tests.ts +++ b/types/backbone.paginator/backbone.paginator-tests.ts @@ -70,8 +70,8 @@ namespace InitializingWithOptions { }); var testCollection6 = new TestCollection([ - {}, - {}, + {} as TestModel, + {} as TestModel, ]); } diff --git a/types/backbone.radio/index.d.ts b/types/backbone.radio/index.d.ts index 12fc6d384f..ac953aa00b 100644 --- a/types/backbone.radio/index.d.ts +++ b/types/backbone.radio/index.d.ts @@ -71,7 +71,18 @@ declare module "backbone" { stopReplying(commandName?: string, callback?: (...args: any[]) => any, context?: any): Requests; } - class Channel extends Backbone.Events implements Commands, Requests { + class Channel implements Commands, Requests, Backbone.Events { + on(eventName: string, callback?: (...args: any[]) => void, context?: any): any; + on(eventMap: EventsHash): any; + on(eventName: any, callback?: any, context?: any): any; + off(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + trigger(eventName: string, ...args: any[]): any; + bind(eventName: string, callback: (...args: any[]) => void, context?: any): any; + unbind(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + once(events: string, callback: (...args: any[]) => void, context?: any): any; + listenTo(object: any, events: string, callback: (...args: any[]) => void): any; + listenToOnce(object: any, events: string, callback: (...args: any[]) => void): any; + stopListening(object?: any, events?: string, callback?: (...args: any[]) => void): any; channelName: string; reset(): Channel; diff --git a/types/backbone/backbone-tests.ts b/types/backbone/backbone-tests.ts index 65a1463978..563c21634c 100644 --- a/types/backbone/backbone-tests.ts +++ b/types/backbone/backbone-tests.ts @@ -1,6 +1,6 @@ function test_events() { - var object = new Backbone.Events(); + var object = Backbone.Events; object.on("alert", (eventName: string) => alert("Triggered " + eventName)); object.trigger("alert", "an event"); diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index 81bce43606..a881284c8f 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Boris Yankov // Natan Vivo // kenjiru +// jjoekoullas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -91,24 +92,37 @@ declare namespace Backbone { } interface EventsHash { - [selector: string]: string | {(eventObject: JQueryEventObject): void}; + [selector: string]: string | {(eventObject: JQuery.TriggeredEvent): void}; } - class Events { + export const Events: Events; + interface Events { + on(eventName: string, callback?: (...args: any[]) => void, context?: any): any; + on(eventMap: EventsHash): any; + off(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + trigger(eventName: string, ...args: any[]): any; + bind(eventName: string, callback: (...args: any[]) => void, context?: any): any; + unbind(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + + once(events: string, callback: (...args: any[]) => void, context?: any): any; + listenTo(object: any, events: string, callback: (...args: any[]) => void): any; + listenToOnce(object: any, events: string, callback: (...args: any[]) => void): any; + stopListening(object?: any, events?: string, callback?: (...args: any[]) => void): any; + } + + class ModelBase implements Events { on(eventName: string, callback?: Function, context?: any): any; on(eventMap: EventsHash): any; - off(eventName?: string, callback?: Function, context?: any): any; - trigger(eventName: string, ...args: any[]): any; - bind(eventName: string, callback: Function, context?: any): any; - unbind(eventName?: string, callback?: Function, context?: any): any; + on(eventName: any, callback?: any, context?: any): any + off(eventName?: string, callback?: Function, context?: any): any + trigger(eventName: string, ...args: any[]): any + bind(eventName: string, callback: Function, context?: any): any + unbind(eventName?: string, callback?: Function, context?: any): any + once(events: string, callback: Function, context?: any): any + listenTo(object: any, events: string, callback: Function):any + listenToOnce(object: any, events: string, callback: Function): any + stopListening(object?: any, events?: string, callback?: Function): any - once(events: string, callback: Function, context?: any): any; - listenTo(object: any, events: string, callback: Function): any; - listenToOnce(object: any, events: string, callback: Function): any; - stopListening(object?: any, events?: string, callback?: Function): any; - } - - class ModelBase extends Events { parse(response: any, options?: any): any; toJSON(options?: any): any; sync(...arg: any[]): JQueryXHR; @@ -353,7 +367,7 @@ declare namespace Backbone { without(...values: TModel[]): TModel[]; } - class Router extends Events { + class Router extends EventSignatures { /** * Do not use, prefer TypeScript's extend functionality. @@ -382,7 +396,7 @@ declare namespace Backbone { var history: History; - class History extends Events { + class History extends EventSignatures { handlers: any[]; interval: number; @@ -419,7 +433,7 @@ declare namespace Backbone { attributes?: {[id: string]: any}; } - class View extends Events { + class View extends EventSignatures { /** * Do not use, prefer TypeScript's extend functionality. @@ -471,3 +485,21 @@ declare namespace Backbone { function noConflict(): typeof Backbone; var $: JQueryStatic; } + +/** + * This is not for external use and is only here as a convenient way to + * specify signatures for internal implementers of Backbone.Events + */ +declare abstract class EventSignatures implements Backbone.Events { + on(eventName: string, callback?: (...args: any[]) => void, context?: any): any; + on(eventMap: Backbone.EventsHash): any; + off(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + trigger(eventName: string, ...args: any[]): any; + bind(eventName: string, callback: (...args: any[]) => void, context?: any): any; + unbind(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + + once(events: string, callback: (...args: any[]) => void, context?: any): any; + listenTo(object: any, events: string, callback: (...args: any[]) => void): any; + listenToOnce(object: any, events: string, callback: (...args: any[]) => void): any; + stopListening(object?: any, events?: string, callback?: (...args: any[]) => void): any; +} \ No newline at end of file diff --git a/types/baconjs/baconjs-tests.ts b/types/baconjs/baconjs-tests.ts index 2755bec595..b7d6db4c0f 100644 --- a/types/baconjs/baconjs-tests.ts +++ b/types/baconjs/baconjs-tests.ts @@ -120,7 +120,7 @@ function CommonMethodsInEventStreamsAndProperties() { Bacon.fromArray([1, 2, 3]).withStateMachine(0, (sum, event) => { if (event.hasValue()) { // had to cast to `number` because event:Bacon.Next|Bacon.Error<{}> - return [sum + event.value(), []]; + return [sum + (event.value() as number), []]; } else if (event.isEnd()) { return [undefined, [new Bacon.Next(sum), event]]; @@ -140,8 +140,8 @@ function CommonMethodsInEventStreamsAndProperties() { { // This is handy for keeping track whether we are currently awaiting an AJAX response: - var ajaxRequest = >{}, - ajaxResponse = >{}, + var ajaxRequest = {} as Bacon.Observable, + ajaxResponse = {} as Bacon.Observable, showAjaxIndicator = ajaxRequest.awaiting(ajaxResponse); } diff --git a/types/baidu-app/baidu-app-tests.ts b/types/baidu-app/baidu-app-tests.ts new file mode 100644 index 0000000000..9987a650ee --- /dev/null +++ b/types/baidu-app/baidu-app-tests.ts @@ -0,0 +1,2007 @@ +(() => { + swan.request({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址 + method: 'GET', + dataType: 'json', + data: { + key: 'value' + }, + header: { + 'content-type': 'application/json' // 默认值 + }, + success(res) { + console.log(res.data); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + const requestTask = swan.request({ + url: 'test.php', // 仅为示例,并非真实的接口地址 + data: { + x: '', + y: '' + }, + header: { + 'content-type': 'application/json' + }, + success(res) { + console.log(res.data); + } + }); + // 取消请求任务 + requestTask.abort(); +})(); + +(() => { + swan.chooseImage({ + success(res) { + swan.uploadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址 + filePath: res.tempFilePaths[0], // 要上传文件资源的路径 + name: 'myfile', + success(res) { + console.log(res.statusCode); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + } + }); +})(); + +(() => { + const uploadTask = swan.uploadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 开发者服务器 url + filePath: '', // res.tempFilePaths[0], // 要上传文件资源的路径 + name: 'myfile', + success(res) { + console.log(res.statusCode); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + uploadTask.onProgressUpdate(res => { + console.log('上传进度', res.progress); + console.log('已经上传的数据长度', res.totalBytesSent); + console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend); + }); + + uploadTask.abort(); // 取消上传任务 +})(); + +(() => { + swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源 + success(res) { + // 下载成功 + if (res.statusCode === 200) { + console.log("临时文件路径" + res.tempFilePath); + } + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const downloadTask = swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源 + success(res) { + console.log(res.tempFilePath); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + downloadTask.onProgressUpdate(res => { + console.log('下载进度', res.progress); + console.log('已经下载的数据长度', res.totalBytesWritten); + console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite); + }); + + downloadTask.abort(); // 取消下载任务 +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen((res) => { + console.log('WebSocket连接已打开!', res.header); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' // 仅为示例,并非真实的服务地址 + }); + swan.onSocketError((res) => { + console.log('WebSocket连接打开失败,请检查!'); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen(() => { + swan.sendSocketMessage({ + data: 'baidu' + }); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen(() => { + swan.sendSocketMessage({ + data: 'baidu' + }); + }); + swan.onSocketMessage((res) => { + console.log('收到服务器内容:', res.data); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com', + success(res) { + swan.closeSocket(); + } + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + + swan.onSocketClose((res) => { + console.log('WebSocket 已关闭!'); + }); + + swan.onSocketOpen(() => { + swan.closeSocket(); + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrIdCard({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrBankCard({ + image, + success(res) { + console.log(res.result.bank_name); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrDrivingLicense({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrVehicleLicense({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); +})(); + +(() => { + swan.ai.textReview({ + content: '', + success(res) { + console.log(res.result.spam); // 0 表示审核通过 + } + }); +})(); + +(() => { + swan.ai.textToAudio({ + ctp: '1', + lan: 'zh', + tex: '这是一段测试文字', + success(res) { + console.log(res.filePath); + } + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.imageAudit({ + image, + success(res) { + console.log(res.conclusionType); // 1 为合规 + } + }); + } + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.advancedGeneralIdentify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.objectDetectIdentify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.carClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.dishClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.logoClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.animalClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.plantClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); +})(); + +(() => { + const voiceRecognizer = swan.ai.getVoiceRecognizer(); + + voiceRecognizer.onStart(() => { + console.log('voice start'); + }); + voiceRecognizer.onRecognize(res => { + console.log('voice recognize', res); + }); + voiceRecognizer.onFinish(res => { + console.log('voice end', res); + }); + voiceRecognizer.onError(err => { + console.log('voice error', err); + }); + + const options = { + mode: 'dnn', + longSpeech: false + }; + + voiceRecognizer.start(options); +})(); + +(() => { + swan.chooseImage({ + count: 1, + sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 + sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 + success(res) { + // 成功则返回图片的本地文件路径列表 tempFilePaths + console.log(res.tempFilePaths); + // 文件列表对象 + console.log(res.tempFiles); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.previewImage({ + current: '', // 当前显示图片的http链接 + urls: [], // 需要预览的图片http链接列表 + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + swan.getImageInfo({ + src: '/xxx/xxx.jpg', + success(res) { + // 成功则返回图片高,宽,本地路径 + console.log(res.width); + console.log(res.height); + console.log(res.path); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + swan.saveImageToPhotosAlbum({ + filePath: '/xxx/xxx.jpg', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const recorderManager = swan.getRecorderManager(); + + recorderManager.onStart(() => { + // 开始录音事件 + console.log('recorder start'); + }); + recorderManager.onPause(() => { + // 暂停录音事件 + console.log('recorder pause'); + }); + recorderManager.onStop((res) => { + // 停止录音事件 + console.log('recorder stop', res); + const { tempFilePath } = res; + }); + + const options = { + duration: 10000, + sampleRate: 44100, + numberOfChannels: 1, + encodeBitRate: 96000, + format: 'aac' + }; + + recorderManager.start(options); +})(); + +(() => { + const backgroundAudioManager = swan.getBackgroundAudioManager(); + + backgroundAudioManager.title = '此时此刻'; + backgroundAudioManager.epname = '此时此刻'; + backgroundAudioManager.singer = '许巍'; + backgroundAudioManager.coverImgUrl = 'xxx'; + backgroundAudioManager.src = 'xxx'; +})(); + +(() => { + const innerAudioContext = swan.createInnerAudioContext(); + innerAudioContext.src = 'xxx'; + innerAudioContext.autoplay = true; + innerAudioContext.seek({ + position: 10 + }); + innerAudioContext.onPlay((res) => { + console.log('开始播放'); + }); +})(); + +(() => { + Page({ + data: { + sourceType: ['album', 'camera'], + compressed: false, + maxDuration: 60, + src: '' + }, + + chooseVideo() { + const self = this; + swan.chooseVideo({ + sourceType: this.getData('sourceType'), + compressed: this.getData('compressed'), + maxDuration: this.getData('maxDuration'), + success(res) { + // 成功返回选定视频的临时文件路径 + self.setData('src', res.tempFilePath); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + } + }); + swan.saveVideoToPhotosAlbum({ + filePath: 'bdfile://xxx', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const myVideo = swan.createVideoContext('myVideo'); + myVideo.play(); +})(); + +(() => { + swan.chooseImage({ + count: 1, + success(res) { + const tempFilePaths = res.tempFilePaths; + swan.saveFile({ + tempFilePath: tempFilePaths[0], + success(res) { + const savedFilePath = res.savedFilePath; + } + }); + } + }); + swan.getFileInfo({ + filePath: 'bdfile://somefile', + success(res) { + console.log(res.size); + console.log(res.digest); + } + }); + swan.getSavedFileList({ + success(res) { + const fileList = res.fileList; + } + }); + swan.getSavedFileInfo({ + filePath: 'bdfile://somefile', + success(res) { + console.log(res.size); + console.log(res.createTime); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.getSavedFileList({ + success(res) { + if (res.fileList.length > 0) { + swan.removeSavedFile({ + filePath: res.fileList[0].filePath, + success(res) { + console.log(res.filePath); + } + }); + } + } + }); +})(); + +(() => { + swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx.pdf', + success(res) { + const filePath = res.tempFilePath; + swan.openDocument({ + filePath, + success(res) { + console.log('打开文档成功'); + } + }); + } + }); +})(); + +(() => { + swan.setStorage({ + key: 'key', + data: 'value' + }); +})(); + +(() => { + try { + swan.setStorageSync('key', 'value'); + } catch (e) { + } + swan.getStorage({ + key: 'key', + success(res) { + console.log(res.data); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + const result = swan.getStorageSync('key'); + } catch (e) { + } + swan.getStorageInfo({ + success(res) { + console.log(res.keys); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + const result = swan.getStorageInfoSync(); + console.log(result); + } catch (e) { + } +})(); + +(() => { + swan.removeStorage({ + key: 'key', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + swan.removeStorageSync('key'); + } catch (e) { + } + try { + swan.clearStorageSync(); + } catch (e) { + } +})(); + +(() => { + swan.getLocation({ + type: 'gcj02', + success(res) { + console.log('纬度:' + res.latitude); + console.log('经度:' + res.longitude); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.getLocation({ + type: 'gcj02', + success(res) { + swan.openLocation({ + latitude: res.latitude, + longitude: res.longitude, + scale: 18 + }); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + let mapContext: swan.MapContext; + Page({ + data: { + latitude: '40.042500', + longitude: '116.274040', + }, + onReady() { + mapContext = swan.createMapContext('myMap'); + }, + getCenterLocation() { + mapContext.getCenterLocation({ + success(res) { + console.log("经度" + res.longitude); + console.log("纬度" + res.latitude); + } + }); + }, + moveToLocation() { + mapContext.moveToLocation(); + }, + translateMarker() { + mapContext.translateMarker({ + markerId: 0, + rotate: 90, + autoRotate: true, + duration: 1000, + destination: { + latitude: 23.10229, + longitude: 113.3345211, + }, + animationEnd() { + console.log('animation end'); + } + }); + }, + includePoints() { + mapContext.includePoints({ + padding: [10], + points: [{ + latitude: 23, + longitude: 113.33, + }, { + latitude: 23, + longitude: 113.3345211, + }] + }); + }, + getRegion() { + mapContext.getRegion({ + success(res) { + console.log("西南角的经纬度" + res.southwest); + console.log("东北角的经纬度" + res.northeast); + } + }); + } + }); +})(); + +(() => { + Page({ + onReady() { + const ctx = this.createCanvasContext('myCanvas'); + ctx.setFillStyle('#ff0000'); + ctx.arc(100, 100, 50, 0, 2 * Math.PI); + ctx.fill(); + ctx.draw(); + } + }); + Page({ + onReady() { + const ctx = this.createCanvasContext('myCanvas'); + } + }); + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('#ff0000'); + ctx.arc(100, 100, 50, 0, 2 * Math.PI); + ctx.fill(); + + ctx.draw(); + + swan.canvasGetImageData({ + canvasId: 'myCanvas', + x: 0, + y: 0, + width: 100, + height: 100, + success(res) { + console.log(res); + } + }); + const data = new Uint8ClampedArray([255, 0, 0, 1]); + swan.canvasPutImageData({ + canvasId: 'myCanvas', + data, + x: 0, + y: 0, + width: 1, + height: 2, + success(res) { + console.log('success'); + } + }); + swan.canvasToTempFilePath({ + x: 100, + y: 200, + width: 50, + height: 50, + destWidth: 100, + destHeight: 100, + canvasId: 'myCanvas', + success(res) { + console.log(res.tempFilePath); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.setShadow(10, 50, 50, 'red'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create linear gradient + const grd = ctx.createLinearGradient(0, 0, 200, 0); + grd.addColorStop(0, 'blue'); + grd.addColorStop(1, 'red'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create circular gradient + const grd = ctx.createCircularGradient(75, 50, 50); + grd.addColorStop(0, 'red'); + grd.addColorStop(1, 'blue'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create circular gradient + const grd = ctx.createLinearGradient(30, 10, 120, 10); + grd.addColorStop(0, 'red'); + grd.addColorStop(0.16, 'orange'); + grd.addColorStop(0.33, 'yellow'); + grd.addColorStop(0.5, 'green'); + grd.addColorStop(0.66, 'cyan'); + grd.addColorStop(0.83, 'blue'); + grd.addColorStop(1, 'purple'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(30, 10); + ctx.lineTo(200, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(5); + ctx.moveTo(50, 30); + ctx.lineTo(200, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.moveTo(70, 50); + ctx.lineTo(200, 50); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.moveTo(90, 70); + ctx.lineTo(200, 70); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(30, 10); + ctx.lineTo(200, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('butt'); + ctx.setLineWidth(10); + ctx.moveTo(50, 30); + ctx.lineTo(200, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('round'); + ctx.setLineWidth(10); + ctx.moveTo(70, 50); + ctx.lineTo(200, 50); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('square'); + ctx.setLineWidth(10); + ctx.moveTo(90, 70); + ctx.lineTo(200, 70); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('bevel'); + ctx.setLineWidth(10); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('round'); + ctx.setLineWidth(10); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('miter'); + ctx.setLineWidth(10); + ctx.moveTo(130, 10); + ctx.lineTo(220, 50); + ctx.lineTo(130, 90); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setLineDash([10, 20], 5); + ctx.beginPath(); + ctx.moveTo(0, 100); + ctx.lineTo(400, 100); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(1); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(2); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(3); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(4); + ctx.moveTo(130, 10); + ctx.lineTo(220, 50); + ctx.lineTo(130, 90); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.rect(30, 30, 150, 75); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setStrokeStyle('blue'); + ctx.strokeRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('red'); + ctx.fillRect(0, 0, 150, 200); + ctx.setFillStyle('blue'); + ctx.fillRect(150, 0, 150, 200); + ctx.clearRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.rect(10, 10, 100, 30); + ctx.setFillStyle('red'); + ctx.fill(); + ctx.beginPath(); + ctx.rect(10, 40, 100, 30); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 70, 100, 30); + ctx.rect(10, 100, 100, 30); + ctx.setFillStyle('green'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.closePath(); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(10, 10); + ctx.lineTo(100, 10); + ctx.moveTo(10, 100); + ctx.lineTo(100, 100); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(10, 10); + ctx.rect(10, 10, 100, 50); + ctx.lineTo(110, 60); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.arc(100, 75, 50, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(10, 10, 25, 15); + ctx.scale(2, 2); + ctx.strokeRect(10, 10, 25, 15); + ctx.scale(2, 2); + ctx.strokeRect(10, 10, 25, 15); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(100, 10, 150, 100); + ctx.rotate(20 * Math.PI / 180); + ctx.strokeRect(100, 10, 150, 100); + ctx.rotate(20 * Math.PI / 180); + ctx.strokeRect(100, 10, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(10, 10, 150, 100); + ctx.translate(20, 20); + ctx.strokeRect(10, 10, 150, 100); + ctx.translate(20, 20); + ctx.strokeRect(10, 10, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + swan.downloadFile({ + url: 'https://b.bdstatic.com/searchbox/icms/searchbox/img/LOGO300x300.jpg', + success(res) { + ctx.save(); + ctx.beginPath(); + ctx.arc(50, 50, 25, 0, 2 * Math.PI); + ctx.clip(); + ctx.drawImage(res.tempFilePath, 25, 25); + ctx.restore(); + ctx.draw(); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFontSize(20); + ctx.fillText('20', 20, 20); + ctx.setFontSize(30); + ctx.fillText('30', 40, 40); + ctx.setFontSize(40); + ctx.fillText('40', 60, 60); + ctx.setFontSize(50); + ctx.fillText('50', 90, 90); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFontSize(20); + ctx.fillText('Hello', 20, 20); + ctx.fillText('World', 100, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setStrokeStyle('red'); + ctx.moveTo(150, 20); + ctx.lineTo(150, 170); + ctx.stroke(); + + ctx.setFontSize(15); + ctx.setTextAlign('left'); + ctx.fillText('textAlign=left', 150, 60); + + ctx.setTextAlign('center'); + ctx.fillText('textAlign=center', 150, 80); + + ctx.setTextAlign('right'); + ctx.fillText('textAlign=right', 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setStrokeStyle('red'); + ctx.moveTo(5, 75); + ctx.lineTo(295, 75); + ctx.stroke(); + + ctx.setFontSize(20); + + ctx.setTextBaseline('top'); + ctx.fillText('top', 5, 75); + + ctx.setTextBaseline('middle'); + ctx.fillText('middle', 50, 75); + + ctx.setTextBaseline('bottom'); + ctx.fillText('bottom', 120, 75); + + ctx.setTextBaseline('normal'); + ctx.fillText('normal', 200, 75); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + swan.chooseImage({ + success(res) { + ctx.drawImage(res.tempFilePaths[0], 0, 0, 150, 100); + ctx.draw(); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFillStyle('red'); + ctx.fillRect(10, 10, 150, 100); + ctx.setGlobalAlpha(0.2); + ctx.setFillStyle('blue'); + ctx.fillRect(50, 50, 150, 100); + ctx.setFillStyle('yellow'); + ctx.fillRect(100, 100, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.font = 'italic bold 20px cursive'; + const metrics = ctx.measureText('Hello World'); + console.log(metrics.width); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + const pattern = ctx.createPattern('/path/to/image', 'repeat-x'); + ctx.fillStyle = pattern; + ctx.fillRect(0, 0, 300, 150); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // Draw quadratic curve + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.bezierCurveTo(20, 100, 200, 100, 200, 20); + ctx.setStrokeStyle('black'); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // Draw quadratic curve + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.quadraticCurveTo(20, 100, 200, 20); + ctx.setStrokeStyle('blue'); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // save the default fill style + ctx.save(); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + + // restore to the previous saved state + ctx.restore(); + ctx.fillRect(50, 50, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // save the default fill style + ctx.save(); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + + // restore to the previous saved state + ctx.restore(); + ctx.fillRect(50, 50, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + ctx.draw(); + ctx.fillRect(30, 30, 150, 100); + ctx.draw(); +})(); + +(() => { + swan.showToast({ + title: '我是标题', + icon: 'loading', + duration: 1000, + }); + swan.showLoading({ + title: '加载中', + mask: 'true' + }); + + setTimeout(() => { + swan.hideLoading(); + }, 2000); + + swan.showModal({ + title: '提示', + content: '这是一个模态弹窗', + cancelColor: '#999999', + confirmColor: '#0099cc', + success(res) { + if (res.confirm) { + console.log('用户点击了确定'); + } else if (res.cancel) { + console.log('用户点击了取消'); + } + } + }); + swan.showActionSheet({ + itemList: ['同意', '一般', '不同意'], + success(res) { + console.log(`用户点击了第${(res.tapIndex + 1)}个按钮`); + } + }); +})(); + +(() => { + swan.setNavigationBarTitle({ + title: '我是页面标题' + }); + swan.setNavigationBarColor({ + frontColor: '#ffffff', + backgroundColor: '#ff0000', + animation: { + duration: 500, + timingFunc: 'linear' + } + }); +})(); + +(() => { + swan.setTabBarBadge({ + index: 0, + text: '文本' + }); + swan.removeTabBarBadge({ + index: 0 + }); + swan.showTabBarRedDot({ + index: 0 + }); + swan.hideTabBarRedDot({ + index: 0 + }); + swan.setTabBarStyle({ + color: '#FFFFBD', + selectedColor: '#FFFFBD', + backgroundColor: '#FFFFBD', + borderStyle: 'white' + }); + swan.setTabBarItem({ + index: 0, + text: '文本', + // 图片路径 + iconPath: '/images/component_normal.png', + // 选中图片路径 + selectedIconPath: '/images/component_selected.png', + }); + swan.showTabBar({ + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + swan.hideTabBar({ + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.navigateTo({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); + swan.redirectTo({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); + swan.switchTab({ + url: '/list', + }); + // 注意:调用 navigateTo 跳转时,调用页面会被加入堆栈,而 redirectTo 方法则不会。见下方示例代码 + + // 当前是首页 + swan.navigateTo({ + url: 'list?key=value' + }); + + // 当前是列表页 + swan.navigateTo({ + url: 'detail?key=value' + }); + + // 在详情页内 navigateBack,将返回首页 + swan.navigateBack({ + delta: 2 + }); + swan.reLaunch({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); +})(); + +(() => { + const animation = swan.createAnimation({ + transformOrigin: "50% 50%", + duration: 1000, + timingFunction: "ease", + delay: 0 + }); + Page({ + data: { + animationData: {} + }, + starttoanimate() { + const animation = swan.createAnimation(); + animation.rotate(90).translateY(10).step(); + animation.rotate(-90).translateY(-10).step(); + this.setData({ + animationData: animation.export() + }); + } + }); +})(); + +(() => { + swan.pageScrollTo({ + scrollTop: 0, + duration: 300 + }); +})(); + +(() => { + Page({ + onPullDownRefresh() { + // do something + } + }); + swan.startPullDownRefresh(); + swan.stopPullDownRefresh(); +})(); + +(() => { + swan.createIntersectionObserver({} as any, { + selectAll: true + }).relativeTo('.container') + .observe('.ball', res => { + console.log(res.intersectionRect); // 相交区域 + console.log(res.intersectionRect.left); // 相交区域的左边界坐标 + console.log(res.intersectionRect.top); // 相交区域的上边界坐标 + console.log(res.intersectionRect.width); // 相交区域的宽度 + console.log(res.intersectionRect.height); // 相交区域的高度 + }); + Page({ + queryMultipleNodes() { + const query = swan.createSelectorQuery(); + query.select('#the-id').boundingClientRect(); + query.selectViewport().scrollOffset(); + query.exec((res) => { + // res[0].top, // #the-id节点的上边界坐标 + // res[1].scrollTop // 显示区域的竖直滚动位置 + }); + } + }); + Component({ + // queryMultipleNodes() { + // const query = swan.createSelectorQuery().in(this); + // query.select('#the-id').boundingClientRect((res) => { + // // res.top // 这个组件内 #the-id 节点的上边界坐标 + // }).exec(); + // } + }); + Page({ + getRect() { + swan.createSelectorQuery().select('#the-id').boundingClientRect((res) => { + const rect = res as swan.NodesRefRect; + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }).exec(); + }, + getAllRects() { + swan.createSelectorQuery().selectAll('.a-class').boundingClientRect((rects) => { + (rects as swan.NodesRefRect[]).forEach((rect) => { + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }); + }).exec(); + } + }); + Page({ + getScrollOffset() { + swan.createSelectorQuery().selectViewport().scrollOffset((res) => { + res.id; // 节点的ID + res.dataset; // 节点的dataset + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + }).exec(); + } + }); + Page({ + getFields() { + swan.createSelectorQuery().select('#the-id').fields({ + dataset: true, + size: true, + scrollOffset: true, + properties: ['scrollX', 'scrollY'], + computedStyle: ['margin', 'backgroundColor'] + }, (res) => { + res.dataset; // 节点的dataset + res.width; // 节点的宽度 + res.height; // 节点的高度 + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + res.scrollX; // 节点 scroll-x 属性的当前值 + res.scrollY; // 节点 scroll-y 属性的当前值 + // 此处返回指定要返回的样式名 + res.margin; + res.backgroundColor; + }).exec(); + } + }); +})(); + +(() => { + swan.getSystemInfo({ + success(res) { + console.log(res.model); + console.log(res.pixelRatio); + console.log(res.windowWidth); + console.log(res.windowHeight); + console.log(res.language); + console.log(res.version); + console.log(res.platform); + } + }); + try { + const res = swan.getSystemInfoSync(); + console.log(res.model); + console.log(res.pixelRatio); + console.log(res.windowWidth); + console.log(res.windowHeight); + console.log(res.language); + console.log(res.version); + console.log(res.platform); + } catch (e) { + // Do something when catch error + } + try { + const res = swan.getEnvInfoSync(); + console.log(res.appKey); + console.log(res.appName); + console.log(res.lastAppURL); + console.log(res.sdkVersion); + console.log(res.scheme); + } catch (e) { + // Do something when catch error + } + swan.canIUse('view.hover-class'); + swan.canIUse('scroll-view.scroll-x'); + swan.canIUse('cover-view'); + swan.canIUse('button.size.default'); + swan.canIUse('button.size.default'); + swan.canIUse('request.object.success.data'); + swan.canIUse('getSavedFileList'); + swan.canIUse('getSavedFileList.object'); + swan.canIUse('getSavedFileList.object.success'); +})(); + +(() => { + swan.onMemoryWarning((res) => { + console.log('onMemoryWarningReceive'); + }); +})(); + +(() => { + swan.getNetworkType({ + success(res) { + console.log(res.networkType); + } + }); + swan.onNetworkStatusChange((res) => { + console.log(res.isConnected); + console.log(res.networkType); + }); +})(); + +(() => { + swan.onAccelerometerChange((res) => { + console.log(res.x); + console.log(res.y); + console.log(res.z); + }); + swan.startAccelerometer({ + interval: 'ui' + }); + swan.stopAccelerometer(); +})(); + +(() => { + swan.onCompassChange((res) => { + console.log(res.direction); + }); + swan.startCompass(); + swan.stopCompass(); +})(); + +(() => { + swan.scanCode({ + success(res) { + console.log(res.result); + console.log(res.scanType); + } + }); +})(); + +(() => { + swan.onUserCaptureScreen(() => { + console.log('用户截屏了'); + }); +})(); + +(() => { + swan.makePhoneCall({ + phoneNumber: '000000' // 仅为示例,并非真实的电话号码 + }); +})(); + +(() => { + swan.setClipboardData({ + data: 'baidu', + success(res) { + swan.getClipboardData({ + success(res) { + console.log(res.data); // baidu + } + }); + } + }); + swan.getClipboardData({ + success(res) { + console.log(res.data); + } + }); +})(); + +(() => { + swan.getExtConfig({ + success(res) { + console.log(res.extConfig); + } + }); + const data = swan.getExtConfigSync(); + console.log(data.extConfig); +})(); + +(() => { + swan.login({ + success(res) { + swan.request({ + url: 'https://xxx/xxx', // 开发者服务器地址 + data: { + code: res.code + } + }); + }, + fail(err) { + console.log('login fail', err); + } + }); + swan.checkSession({ + success(res) { + console.log('登录态有效'); + swan.getUserInfo({ + success(res) { + console.log('用户名', res.userInfo.nickName); + swan.request({ + url: "https://xxx/decrypt_user_data", // 开发者服务器地址,对 data 进行解密 + data: { + data: res.data, + iv: res.iv + } + }); + } + }); + }, + fail(err) { + console.log('登录态无效'); + swan.login({ + success(res) { + swan.request({ + url: 'https://xxx/xxx', // 开发者服务器地址,用 code 换取 session_key + data: { + code: res.code + } + }); + }, + fail(err) { + console.log('登录失败', err); + } + }); + } + }); + + try { + const result = swan.isLoginSync(); + console.log('isLoginSync', result); + } catch (e) { + console.log('error', e); + } +})(); + +(() => { + swan.authorize({ + scope: 'scope.userLocation', + success(res) { + // 用户已经同意智能小程序使用定位功能 + swan.getLocation(); + } + }); +})(); + +(() => { + swan.getSwanId({ + success(res) { + console.log(res.data.swanid); + } + }); + swan.getUserInfo({ + success(res) { + console.log('用户名', res.userInfo.nickName); + } + }); +})(); + +(() => { + swan.openSetting({ + success(res) { + console.log(res.authSetting['scope.userInfo']); + console.log(res.authSetting['scope.userLocation']); + } + }); + swan.getSetting({ + success(res) { + console.log(res.authSetting['scope.userInfo']); + console.log(res.authSetting['scope.userLocation']); + } + }); +})(); + +(() => { + Page({ + onShareAppMessage() { + return { + title: '智能小程序示例', + content: '世界很复杂,百度更懂你', + path: '/pages/openShare/openShare?key=value' + }; + } + }); + swan.openShare({ + title: '智能小程序示例', + content: '世界很复杂,百度更懂你', + path: '/pages/openShare/openShare?key=value' + }); +})(); + +(() => { + swan.chooseAddress({ + success(res) { + console.log(res.userName); + console.log(res.postalCode); + console.log(res.provinceName); + console.log(res.cityName); + console.log(res.countyName); + console.log(res.detailInfo); + console.log(res.telNumber); + } + }); +})(); + +(() => { + swan.requestPolymerPayment({ + orderInfo: { + dealId: "470193086", + appKey: "MMMabc", + totalAmount: "1", + tpOrderId: "3028903626", + dealTitle: "智能小程序Demo支付测试", + signFieldsRange: 1, + rsaSign: '', + bizInfo: '' + }, + success(res) { + swan.showToast({ + title: '支付成功', + icon: 'success' + }); + }, + fail(err) { + swan.showToast({ + title: JSON.stringify(err) + }); + console.log('pay fail', err); + } + }); +})(); + +(() => { + swan.chooseInvoiceTitle({ + success(res) { + console.log(res.type); + console.log(res.title); + console.log(res.taxNumber); + console.log(res.companyAddress); + console.log(res.telephone); + console.log(res.bankName); + console.log(res.bankAccount); + } + }); +})(); + +(() => { + swan.navigateToSmartProgram({ + appKey: '4fecoAqgCIUtzIyA4FAPgoyrc4oUc25c', // 要打开的小程序 App Key + path: '', // 打开的页面路径,如果为空则打开首页 + extraData: { + foo: 'baidu' + }, + success(res) { + // 打开成功 + } + }); + swan.navigateBackSmartProgram({ + extraData: { + foo: 'baidu' + }, + success(res) { + // 返回成功 + } + }); +})(); + +(() => { + if (swan.setMetaDescription) { + swan.setMetaDescription({ + content: '当前小程序页面描述信息', + success(res) { + console.log('设置成功'); + }, + fail(res) { + console.log('设置失败'); + }, + complete(res) { + console.log('设置失败'); + } + }); + } + if (swan.setMetaKeywords) { + swan.setMetaKeywords({ + content: '小程序, 关键字', + success(res) { + console.log('设置成功'); + }, + fail(res) { + console.log('设置失败'); + }, + complete(res) { + console.log('设置失败'); + } + }); + } + if (swan.setDocumentTitle) { + swan.setDocumentTitle({ + title: '我是页面标题' + }); + } +})(); + +(() => { + swan.loadSubPackage({ + root: 'subpackage', + success(res) { + console.log('下载成功', res); + }, + fail(err) { + console.log('下载失败', err); + } + }); +})(); + +(() => { + const updateManager = swan.getUpdateManager(); + + updateManager.onCheckForUpdate((res) => { + // 请求完新版本信息的回调 + console.log(res.hasUpdate); + }); + + updateManager.onUpdateReady((res) => { + swan.showModal({ + title: '更新提示', + content: '新版本已经准备好,是否重启应用?', + success(res) { + if (res.confirm) { + // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 + updateManager.applyUpdate(); + } + } + }); + }); + + updateManager.onUpdateFailed((res) => { + // 新的版本下载失败 + }); +})(); + +(() => { + // 打开调试 + swan.setEnableDebug({ + enableDebug: true + }); + + // 关闭调试 + swan.setEnableDebug({ + enableDebug: false + }); +})(); + +(() => { + swan.reportAnalytics('purchase', { + price: 120, + color: 'red' + }); +})(); diff --git a/types/baidu-app/index.d.ts b/types/baidu-app/index.d.ts new file mode 100644 index 0000000000..244e9dd473 --- /dev/null +++ b/types/baidu-app/index.d.ts @@ -0,0 +1,4758 @@ +// Type definitions for swan-app 2.2 +// Project: https://smartprogram.baidu.com/docs/develop/tutorial/codedir/ +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.8 + +declare namespace swan { + // #region 基本参数 + interface DataResponse { + /** 回调函数返回的内容 */ + data: string | ArrayBuffer; + statusCode: number; + header: any; + result: string; + } + interface ErrMsgResponse { + /** 成功:ok,错误:详细信息 */ + errMsg: "ok" | string; + } + interface TempFileResponse { + /** 文件的临时路径 */ + tempFilePath: string; + /** 开发者服务器返回的 HTTP 状态码 */ + statusCode: number; + } + interface BaseOptions { + /** 接口调用成功的回调函数 */ + success?(res: R): void; + /** 接口调用失败的回调函数 */ + fail?(res: E): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(res: any): void; + } + interface ErrCodeResponse { + errCode: number; + } + // #endregion + // #region 网络API列表 + // 发起请求 + interface RequestHeader { + [key: string]: string; + } + interface RequestOptions extends BaseOptions { + /** 开发者服务器接口地址 */ + url: string; + /** 请求的参数 */ + data?: string | object; + /** 设置请求的 header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: + | "GET" + | "OPTIONS" + | "GET" + | "HEAD" + | "POST" + | "PUT" + | "DELETE"; + /** 如果设为json,会尝试对返回的数据做一次 JSON.parse 默认值为json */ + dataType?: string; + /** + * 设置响应的数据类型。合法值:text、arraybuffer 默认值为text + * @version 1.7.0 + */ + responseType?: string; + /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ + success?(res: DataResponse): void; + fail?(err: { errCode: number; errMsg: string; }): void; + } + /** + * swan.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。 + */ + function request(options: RequestOptions): RequestTask; + + /** + * 返回一个 requestTask 对象,通过 requestTask,可中断请求任务。 + */ + interface RequestTask { + abort(): void; + } + + interface UploadTask { + /** + * 监听上传进度变化 + * @version 1.4.0 + */ + onProgressUpdate( + callback?: ( + res: { + /** 上传进度百分比 */ + progress: number; + /** 已经上传的数据长度,单位 Bytes */ + totalBytesSent: number; + /** 预期需要上传的数据总长度,单位 Bytes */ + totalBytesExpectedToSend: number; + } + ) => void + ): void; + /** + * 中断下载任务 + * @version 1.4.0 + */ + abort(): void; + } + // 上传下载 + interface UploadFileOptions extends BaseOptions { + /** 开发者服务器 url */ + url: string; + /** 要上传文件资源的路径 */ + filePath: string; + /** 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ + name: string; + /** HTTP 请求 Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** HTTP 请求中其他额外的 form data */ + formData?: any; + } + interface UploadFileResponse { + data: string; // 开发者服务器返回的数据 + statusCode: number; // 开发者服务器返回的 HTTP 状态码 + } + /** + * 将本地资源上传到开发者服务器。 + * 如页面通过 swan.chooseImage 等接口获取到一个本地资源的临时文件路径后, + * 可通过此接口将本地资源上传到指定服务器。 + * 客户端发起一个 HTTPS POST 请求, + * 其中 Content-Type 为 multipart/form-data 。 + */ + function uploadFile(options: UploadFileOptions): UploadTask; + interface DownloadTask { + /** + * 监听下载进度变化 + * @version 1.4.0 + */ + onProgressUpdate( + callback?: ( + res: { + /** 下载进度百分比 */ + progress: number; + /** 已经下载的数据长度,单位 Bytes */ + totalBytesWritten: number; + /** 预期需要下载的数据总长度,单位 Bytes */ + totalBytesExpectedToWrite: number; + } + ) => void + ): void; + /** + * 中断下载任务 + * @version 1.4.0 + */ + abort(): void; + } + interface DownloadFileOptions extends BaseOptions { + /** 下载资源的 url */ + url: string; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 下载文件资源到本地。客户端直接发起一个 HTTP GET 请求, + * 把下载到的资源根据 type 进行处理,并返回文件的本地临时路径。 + */ + function downloadFile(options: DownloadFileOptions): DownloadTask; + // WebSocket + interface ConnectSocketOptions extends BaseOptions { + /** 开发者服务器接口地址,必须是 HTTPS 协议,且域名必须是后台配置的合法域名 */ + url: string; + /** HTTP Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: string; + /** + * 子协议数组 + * @version 1.4.0 + */ + protocols?: string[]; + } + /** + * 创建一个 WebSocket 连接; + * 一个微信小程序同时只能有一个 WebSocket 连接, + * 如果当前已存在一个 WebSocket 连接, + * 会自动关闭该连接,并重新创建一个 WebSocket 连接。 + */ + function connectSocket(options: ConnectSocketOptions): void; + /** 监听WebSocket连接打开事件。 */ + function onSocketOpen(callback: (res: any) => void): void; + /** 监听WebSocket错误。 */ + function onSocketError(callback: (error: any) => void): void; + interface SendSocketMessageOptions extends BaseOptions { + /** 需要发送的内容 */ + data: string | ArrayBuffer; + } + /** + * 通过 WebSocket 连接发送数据,需要先 swan.connectSocket, + * 并在 swan.onSocketOpen 回调之后才能发送。 + */ + function sendSocketMessage(options: SendSocketMessageOptions): void; + /** + * 监听WebSocket接受到服务器的消息事件。 + */ + function onSocketMessage(callback: (res: DataResponse) => void): void; + /** + * 关闭WebSocket连接。 + */ + interface CloseSocketOptions extends BaseOptions { + code?: number; // 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) 1.4.0 + reason?: string; // 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) + } + + /** + * 关闭WebSocket连接。 + */ + function closeSocket(options?: CloseSocketOptions): void; + /** 监听WebSocket关闭。 */ + function onSocketClose(callback: (res: any) => void): void; + /** + * 在接入AI之前需要使用管理员权限操作详细情况官网 + * https://smartprogram.baidu.com/docs/develop/api/ai/ + */ + // #region AI + namespace ai { + /** + * 用户向服务请求识别身份证,身份证识别包括正面和背面。 + */ + interface ocrIdCardOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true; false: 不检测旋转角度,默认不检测。 + id_card_side?: string; // front:身份证含照片的一面;back:身份证带国徽的一面。 + detect_risk?: boolean; // 是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能,默认不开启,即:false。可选值:true-开启;false-不开启。 + success?(res: ocrIdCardResponse): void; + } + /** + * 识别银行卡并返回卡号、发卡行和卡片类型。 + */ + interface ocrBankCardOptions extends BaseOptions { + image: string; // 图片资源地址 + success?(res: ocrBankCardResponse): void; + } + /** + * 对机动车驾驶证所有关键字段进行识别。 + */ + interface ocrDrivingLicenseOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true;false:不检测旋转角度,默认不检测。 + unified_valid_period?: boolean; // true: 归一化格式输出;false 或无此参数按非归一化格式输出。 + success?(res: ocrDrivingLicenseResponse): void; + } + /** + * 对机动车行驶证正本所有关键字段进行识别 + */ + interface ocrVehicleLicenseOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true; false:不检测旋转角度,默认不检测。 + accuracy?: string; // normal 使用快速服务,1200ms左右时延;缺省或其它值使用高精度服务,1600ms左右时延。 + success?(res: ocrVehicleLicenseResponse): void; + } + interface ocrIdCardResponse { + direction: number; // 图像方向,当 detect_direction=true 时存在。-1: 未定义,0: 正向,1: 逆时针90度,2: 逆时针180度,3: 逆时针270度。 + image_status: string; // normal-识别正常;reversed_side-身份证正反面颠倒;non_idcard-上传的图片中不包含身份证;blurred-身份证模糊;other_type_card-其他类型证照;over_exposure-身份证关键字段反光或过曝;unknown-未知状态。 + risk_type: string; // 输入参数 detect_risk = true 时,则返回该字段识别身份证类型: normal-正常身份证;copy-复印件;temporary-临时身份证;screen-翻拍;unknown-其他未知情况。 + edit_tool: string; // 如果参数 detect_risk = true 时,则返回此字段。如果检测身份证被编辑过,该字段指定编辑软件名称,如:Adobe Photoshop CC 2014 (Macintosh),如果没有被编辑过则返回值无此参数。 + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示words_result的元素个数。 + words_result: { // 定位和识别结果 + [key: string]: { + location: { // 位置数组(坐标0点为左上角) + left: number; // 表示定位位置的长方形左上顶点的水平坐标。 + top: number; // 表示定位位置的长方形左上顶点的垂直坐标。 + width: number; // 表示定位位置的长方形的宽度。 + height: number; // 表示定位位置的长方形的高。 + } + words: string; // 识别结果字符串 + } + }; + } + interface ocrBankCardResponse { + log_id: string; // 请求标识码,随机数,唯一。 + result: { // 返回结果 + bank_card_number: string; // 银行卡卡号 + bank_name: string; // 银行名,不能识别时为空 。 + bank_card_type: string; // 银行卡类型,0: 不能识别; 1: 借记卡; 2: 信用卡 。 + }; + } + interface ocrDrivingLicenseResponse { + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示 words_result 的元素个数。 + words_result: { + [key: string]: { words: string }; + }; + } + interface ocrVehicleLicenseResponse { + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示 words_result 的元素个数。 + words_result: { + [key: string]: { words: string }; + }; + } + /** + * 用户向服务请求识别身份证,身份证识别包括正面和背面。 + */ + function ocrIdCard(options: ocrIdCardOptions): void; + /** + * 识别银行卡并返回卡号、发卡行和卡片类型。 + */ + function ocrBankCard(options: ocrBankCardOptions): void; + /** + * 对机动车驾驶证所有关键字段进行识别。 + */ + function ocrDrivingLicense(options: ocrDrivingLicenseOptions): void; + /** + * 对机动车行驶证正本所有关键字段进行识别 + */ + function ocrVehicleLicense(options: ocrVehicleLicenseOptions): void; + /** + * 运用业界领先的深度学习技术,判断一段文本内容是否符合网络发文规范,实现 + * 自动化、智能化的文本审核。 + */ + interface textReviewOptions extends BaseOptions { + content: string; // 待审核文本,UTF-8,不可为空,不超过20000字节。 + success?(res: textReviewResponse): void; + } + interface textReviewResponse { + log_id: string; // 唯一的log id,用于问题定位。 + result: { // 审核结果详情 + spam: number; // 请求中是否包含违禁,0表示非违禁,1表示违禁,2表示建议人工复审 。 + reject: any[]; // 审核未通过的类别列表与详情 + review: any[]; // 待人工复审的类别列表与详情 + pass: Array<{ // 审核通过的类别列表与详情 + label: number; // 请求中的违禁类型 + score: number; // 违禁检测分,范围 0~1,数值从低到高代表风险程度的高低 。 + hit: string[]; // 违禁类型对应命中的违禁词集合,可能为空 。 + }>; + }; + /** + * 违禁labels类型说明: + * 值 说明 + * 1 暴恐违禁 + * 2 文本色情 + * 3 政治敏感 + * 4 恶意推广 + * 5 低俗辱骂 + */ + } + /** + * 运用业界领先的深度学习技术,判断一段文本内容是否符合网络发文规范,实现 + * 自动化、智能化的文本审核。 + */ + function textReview(options: textReviewOptions): void; + /** + * 将文本转换为可以播放的mp3文件。 + */ + interface textToAudioOptions extends BaseOptions { + tex: string; // 合成的文本,使用UTF-8编码,小于512个中文字或者英文数字(文本在百度服务器内转换为GBK后,长度必须小于1024字节)。 + ctp?: string | number; // 客户端类型选择,Web端填写固定值1。 + lan?: string; // 固定值zh。语言选择,目前只有中英文混合模式,填写固定值zh。 + spd?: string; // 语速,取值0-9,默认为5中语速。 + pit?: string; // 音调,取值0-9,默认为5中语调。 + vol?: string; // 音量,取值0-9,默认为5中音量。 + per?: string; // 发音人选择, 0为普通女声,1为普通男生,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声。 + success?(res: textToAudioResponse): void; + } + interface textToAudioResponse { + filePath: string; + } + /** + * 将文本转换为可以播放的mp3文件。 + */ + function textToAudio(options: textToAudioOptions): void; + /** + * 自定义图像审核。 + */ + interface imageAuditOptions extends BaseOptions { + image: string; // 图像资源地址 + imgUrl?: string; // 网图URL地址,以网图形式请求,图片Url需要做UrlEncode,不能与image并存。 + success?(res: imageAuditResponse): void; + } + interface imageAuditResponse { + log_id: string; // 请求唯一id + conclusion: string; // 审核结果描述,成功才返回,失败不返回。 + conclusionType: number; // 审核结果标识,成功才返回,失败不返回。 + data: imageAuditdata[]; + // 审核项详细信息,响应成功并且conclusion为疑似或不合规时才返回,响应失败或conclusion为合规是不返回。 + } + interface imageAuditdata { + type: number; + msg: number; + probability: number; + stars: imageAuditdata[]; + words: number; + } + /** + * 自定义图像审核。 + */ + function imageAudit(options: imageAuditOptions): void; + /** + * 通用物体及场景识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多个物体及场景标签。 + */ + interface GeneralIdentifyOptions extends BaseOptions { + image: string; // 图像资源地址 + success?(res: GeneralIdentifyResponse): void; + } + interface GeneralIdentifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 返回结果数目,及result数组中的元素个数。 + result: Array<{ // 标签结果数组 + keyword: string; // 图片中的物体或场景名称 + score: number; // 置信度,0-1 + root: string; // 识别结果的上层标签,有部分钱币、动漫、烟酒等tag无上层标签。 + }>; + } + /** + * 通用物体及场景识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多个物体及场景标签。 + */ + function advancedGeneralIdentify(options: GeneralIdentifyOptions): void; + /** + * 用户向服务请求检测图像中的主体位置。 + */ + interface DetectIdentifyOptions extends BaseOptions { + image: string; // 图像资源地址 + with_face?: number; // 如果检测主体是人,主体区域是否带上人脸部分,0-不带人脸区域,其他-带人脸区域,裁剪类需求推荐带人脸,检索/识别类需求推荐不带人脸。默认取1,带人脸。 + success?(res: DetectIdentifyResponse): void; + } + interface DetectIdentifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: { // 裁剪结果 + left: number; // 表示定位位置的长方形左上顶点的水平坐标。 + top: number; // 表示定位位置的长方形左上顶点的垂直坐标。 + width: number; // 表示定位位置的长方形的宽度。 + height: number; // 表示定位位置的长方形的高度。 + }; + } + /** + * 用户向服务请求检测图像中的主体位置。 + */ + function objectDetectIdentify(options: DetectIdentifyOptions): void; + /** + * 用于检测一张车辆图片的具体车型,即对于输入的一张图片(可正常解码,且长 + * 宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。 + */ + interface carClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + color_result?: string; // 颜色 + top_num?: number; // 返回结果top n,默认5。 + success?(res: carClassifyResponse): void; + } + interface carClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: Array<{ + name: string; // 车型名称,示例:宝马x6 + score: number; // 置信度,示例:0.5321 + year: string; // 年份 + }>; + location_result: { // 车在图片中的位置信息 + left: number; // 左起像素位置 + top: number; // 上起像素位置 + width: number; // 像素宽 + height: number; // 像素高 + }; + } + /** + * 用于检测一张车辆图片的具体车型,即对于输入的一张图片(可正常解码,且长 + * 宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。 + */ + function carClassify(options: carClassifyOptions): void; + /** + * 用于菜品识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图 + * 片的菜品名称、卡路里信息、置信度。 + */ + interface dishClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + filter_threshold?: number; // 默认0.95,可以通过该参数调节识别效果,降低非菜识别率. + top_num?: number; // 返回结果top n,默认5。 + success?(res: dishClassifyResponse): void; + } + interface dishClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 返回结果数目,及result数组中的元素个数。 + result: Array<{ // 菜品识别结果数组 + name: string; // 菜名,示例:鱼香肉丝。 + calorie: number; // 卡路里,每100g的卡路里含量。 + probability: number; // 识别结果中每一行的置信度值,0-1。 + }>; + } + /** + * 用于菜品识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图 + * 片的菜品名称、卡路里信息、置信度。 + */ + function dishClassify(options: dishClassifyOptions): void; + /** + * 用于检测和识别图片中的品牌 LOGO 信息 + */ + interface logoClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + custom_lib?: boolean; // 是否只检索用户子库,true则只检索用户子库,false(默认)为检索底库+用户子库。 + success?(res: logoClassifyResponse): void; + } + interface logoClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 识别结果数,标识返回结果数目。 + result: Array<{ // 菜品识别结果数组 + type: number; // type=0 为1千种高优商标识别结果;type=1 为2万类logo库的结果;其它type为自定义logo库结果。 + name: number; // 识别的品牌名称 + probability: number; // 分类结果置信度(0–1.0) + location: { + left: number; // 左起像素位置 + top: number; // 上起像素位置 + width: number; // 像素宽 + height: number; // 像素高 + }; // 位置信息(左起像素位置、上起像素位置、像素宽、像素高) + }>; + } + /** + * 用于检测和识别图片中的品牌 LOGO 信息 + */ + function logoClassify(options: logoClassifyOptions): void; + /** + * 用于检测和识别图片中的动物信息 + */ + interface animalClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + top_num?: number; // 返回预测得分top结果数,默认为6 + success?(res: animalClassifyResponse): void; + } + interface animalClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 识别结果数,标识返回结果数目。 + result: Array<{ // 菜品识别结果数组 + name: number; // 动物名称,示例:蒙古马。 + score: number; // 置信度,示例:0.5321。 + }>; + } + /** + * 用于检测和识别图片中的动物信息 + */ + function animalClassify(options: animalClassifyOptions): void; + /** + * 用于检测和识别图片中的植物信息 + */ + interface plantClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + success?(res: plantClassifyResponse): void; + } + interface plantClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: Array<{ // 菜品识别结果数组 + name: number; // 植物名称,示例:吉娃莲。 + score: number; // 置信度,示例:0.5321。 + }>; + } + /** + * 用于检测和识别图片中的植物信息 + */ + function plantClassify(options: plantClassifyOptions): void; + + /** + * 获取全局唯一的语音识别器voiceRecognizer。 + */ + interface VoiceRecognizerStart { + mode?: string; // 听音模式,有效值dnn/touch + longSpeech?: boolean; // 是否开启长语音 + context?: string; // 语音识别所用的场景值,有效值见下表格。 + } + interface VoiceRecognizeResponse { + result: string; // 小程序语音识别过程中的返回内容 + } + interface VoiceErrorResponse { + result: string; // 小程序语音识别过程中的返回内容 + } + interface VoiceRecognizerTask { + start(options: VoiceRecognizerStart): void; // 开始; + stop(): void; // 停止; + cancel(): void; // 取消; + onStart(callback: () => void): void; // 引擎准备就绪,可以开始说话; + onRecognize(callback: (res: VoiceRecognizeResponse) => void): void; // ;有识别结果返回 + onFinish(callback: (res: DataResponse) => void): void; // 识别完成; + onError(callback: (res: VoiceErrorResponse) => void): void; // 识别遇到错;误 + } + /** + * 获取全局唯一的语音识别器voiceRecognizer。 + */ + function getVoiceRecognizer(): VoiceRecognizerTask; + } + // #endregion + + // #endregion + // #region 媒体API列表 + // 媒体-----图片 + type ImageSizeType = "original" | "compressed"; + type ImageSourceType = "album" | "camera"; + type VideoSourceType = "album" | "camera"; + type CameraDevice = "front" | "back"; + interface TempFile { + /** 本地文件路径 */ + path: string; + /** 本地文件大小,单位:B */ + size: number; + } + interface TempFilesData { + /** 文件的临时路径 */ + tempFilePaths: string; + /** + * 图片的本地文件列表,每一项是一个 File 对象 + * @version 1.2.0 + */ + tempFiles: TempFile[]; + } + interface ChooseImageOptions extends BaseOptions { + /** 最多可以选择的图片张数,默认9 */ + count?: number; + /** original 原图,compressed 压缩图,默认二者都有 */ + sizeType?: ImageSizeType[]; + /** album 从相册选图,camera 使用相机,默认二者都有 */ + sourceType?: ImageSourceType[]; + /** 成功则返回图片的本地文件路径列表 tempFilePaths */ + success(res: TempFilesData): void; + } + /** + * 从本地相册选择图片或使用相机拍照。 + */ + function chooseImage(options: ChooseImageOptions): void; + interface PreviewImageOptions extends BaseOptions { + /** 当前显示图片的链接,不填则默认为 urls 的第一张 */ + current?: string; + /** 需要预览的图片链接列表 */ + urls: string[]; + } + /** + * 预览图片。 + */ + function previewImage(options: PreviewImageOptions): void; + interface GetImageInfoOptions extends BaseOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + src: string; + } + /** + * 获取图片信息 + */ + function getImageInfo(options: GetImageInfoOptions): void; + interface SaveImageToPhotosAlbumOptions extends BaseOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + filePath: string; + success(res: { errMsg: string }): void; + } + /** + * 保存图片到系统相册。 + * 需要用户授权 scope.writePhotosAlbum + * @version 1.2.0 + */ + function saveImageToPhotosAlbum(options: SaveImageToPhotosAlbumOptions): void; + // 媒体-----录音 + interface StartRecordAudioOptions extends BaseOptions { + /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 开始录音。当主动调用swan.stopRecord, + * 或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。 + * 注:文件的临时路径,在小程序本次启动期间可以正常使用, + * 如需持久保存,需在主动调用swan.saveFile,在小程序下次启动时才能访问得到。 + * @deprecated 1.6.0 + */ + function startRecord(options: StartRecordAudioOptions): void; + + interface StopRecordAudioOptions extends BaseOptions { + success?(res: TempFileResponse): void; + } + /** + * 主动调用停止录音。 + */ + function stopRecord(options?: StopRecordAudioOptions): void; + type EncodeBitRate = + | 8000 + | 11025 + | 12000 + | 16000 + | 22050 + | 24000 + | 32000 + | 44100 + | 48000; + interface RecorderManagerStartOptions { + /** + * 指定录音的时长,单位 ms + * 如果传入了合法的 duration + * 在到达指定的 duration 后会自动停止录音,最大值 600000(10 分钟),默认值 60000(1 分钟) + */ + duration?: number; + /** + * 采样率,有效值 8000/16000/44100 + */ + sampleRate?: number; + /** + * 否 录音通道数,有效值 1/2 + */ + numberOfChannels?: number; + /** + * 编码码率 + * 采样率和码率有一定要求,具体有效值如下: + * 采样率 编码码率 + * + 8000 16000 ~ 48000 + * + 11025 16000 ~ 48000 + * + 12000 24000 ~ 64000 + * + 16000 24000 ~ 96000 + * + 22050 32000 ~ 128000 + * + 24000 32000 ~ 128000 + * + 32000 48000 ~ 192000 + * + 44100 64000 ~ 320000 + * + 48000 64000 ~ 320000 + */ + encodeBitRate: number; + /** 音频格式,有效值 aac/mp3 */ + format: string; + } + interface OnRecorderManagerStopOptions { + tempFilePath: string; + } + interface OnFrameRecordedOptions { + /** 录音分片结果数据 */ + frameBuffer: ArrayBuffer; + /** 当前帧是否正常录音结束前的最后一帧 */ + isLastFrame: boolean; + } + interface RecorderManager { + /** 开始录音 */ + start(options?: RecorderManagerStartOptions): void; + /** 暂停录音 */ + pause(): void; + /** 继续录音 */ + resume(): void; + /** 停止录音 */ + stop(): void; + /** 录音开始事件 */ + onStart(callback?: () => void): void; + /** 录音暂停事件 */ + onPause(callback?: () => void): void; + /** 录音恢复事件 */ + onResume(callback?: () => void): void; + /** 录音停止事件,会回调文件地址 */ + onStop(callback?: (options: OnRecorderManagerStopOptions) => void): void; + /** 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件 */ + onFrameRecorded(callback?: (options: OnFrameRecordedOptions) => void): void; + /** 录音错误事件, 会回调错误信息 */ + onError(callback?: (err: ErrMsgResponse) => void): void; + } + /** + * 获取全局唯一的录音管理器 recorderManager + * @version 1.6.0 + */ + function getRecorderManager(): RecorderManager; + // 媒体-----音频播放控制 + interface PlayVoiceOptions extends BaseOptions { + /** 需要播放的语音文件的文件路径 */ + filePath: string; + } + /** + * 开始播放语音,同时只允许一个语音文件正在播放, + * 如果前一个语音文件还没播放完,将中断前一个语音播放。 + * @deprecated 1.6.0 + */ + function playVoice(options: PlayVoiceOptions): void; + /** + * 暂停正在播放的语音。 + * 再次调用swan.playVoice播放同一个文件时,会从暂停处开始播放。 + * 如果想从头开始播放,需要先调用 swan.stopVoice。 + * @deprecated 1.6.0 + */ + function pauseVoice(): void; + /** + * 结束播放语音。 + * @deprecated 1.6.0 + */ + function stopVoice(): void; + // 媒体-----音乐播放控制 + interface BackgroundAudioPlayerState { + /** 选定音频的长度(单位:s),只有在当前有音乐播放时返回 */ + duration: number; + /** 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 */ + currentPosition: number; + /** 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) */ + status: number; + /** 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 */ + downloadPercent: number; + /** 歌曲数据链接,只有在当前有音乐播放时返回 */ + dataUrl: string; + } + interface GetBackgroundAudioPlayerStateOptions extends BaseOptions { + /** 接口调用成功的回调函数 */ + success?(state: BackgroundAudioPlayerState): void; + /** 接口调用失败的回调函数 */ + fail?(): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(): void; + } + /** + * 获取音乐播放状态。 + * @deprecated 1.2.0 + */ + function getBackgroundAudioPlayerState( + options: GetBackgroundAudioPlayerStateOptions + ): void; + interface PlayBackgroundAudioOptions extends BaseOptions { + /** 音乐链接 */ + dataUrl: string; + /** 音乐标题 */ + title?: string; + /** 封面URL */ + coverImgUrl?: string; + } + /** + * 播放音乐,同时只能有一首音乐正在播放。 + * @deprecated 1.2.0 + */ + function playBackgroundAudio(options: PlayBackgroundAudioOptions): void; + /** + * 暂停播放音乐。 + * @deprecated 1.2.0 + */ + function pauseBackgroundAudio(options?: PlayBackgroundAudioOptions): void; + interface SeekBackgroundAudioOptions extends BaseOptions { + /** 音乐位置,单位:秒 */ + position: number; + } + /** + * 控制音乐播放进度。 + * @deprecated 1.2.0 + */ + function seekBackgroundAudio(options: SeekBackgroundAudioOptions): void; + /** + * 停止播放音乐。 + * @deprecated 1.2.0 + */ + function stopBackgroundAudio(options?: PlayBackgroundAudioOptions): void; + /** + * 监听音乐播放。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioPlay(callback: () => void): void; + /** + * 监听音乐暂停。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioPause(callback: () => void): void; + /** + * 监听音乐停止。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioStop(callback: () => void): void; + interface BackgroundAudioManager { + /** 当前音频的长度(单位:s),只有在当前有合法的 src 时返回 */ + readonly duration: number; + /** 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回 */ + readonly currentTime: number; + /** 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 */ + readonly paused: boolean; + /** 音频的数据源,默认为空字符串,当设置了新的 src 时,会自动开始播放 ,目前支持的格式有 m4a, aac, mp3, wav */ + src?: string; + /** 音频开始播放的位置(单位:s) */ + startTime?: number; + /** 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲。 是 */ + buffered: number; + /** 音频标题,用于做原生音频播放器音频标题。原生音频播放器中的分享功能,分享出去的卡片标题,也将使用该值。 */ + title?: string; + /** 专辑名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ + epname?: string; + /** 歌手名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ + singer?: string; + /** 封面图url,用于做原生音频播放器背景图。原生音频播放器中的分享功能,分享出去的卡片配图及背景也将使用该图。 */ + coverImgUrl?: string; + /** 播放 */ + play(): void; + /** 暂停 */ + pause(): void; + /** 停止 */ + stop(): void; + /** 跳转到指定位置,单位 s */ + seek(position: number): void; + /** 背景音频进入可以播放状态,但不保证后面可以流畅播放 */ + onCanplay(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放事件 */ + onPlay(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频暂停事件 */ + onPause(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频停止事件 */ + onStop(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频自然播放结束事件 */ + onEnded(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放进度更新事件 */ + onTimeUpdate(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放错误事件 */ + onError(callback: (res: ErrCodeResponse) => void): void; + /** 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 */ + onWaiting(callback: (res: ErrCodeResponse) => void): void; + } + /** + * 获取全局唯一的背景音频管理器 backgroundAudioManager。 + * @version 1.2.0 + */ + function getBackgroundAudioManager(): BackgroundAudioManager; + // 媒体-----音频组件控制 + /** + * audioContext 通过 audioId 跟一个

+
    + ${userMessages.map(message => safeHtml`
  • ${message}
  • `)} +
+
`; -commonTags.commaListsAnd` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -commonTags.commaListsOr` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -let fruits = ['apple', 'orange', 'watermelon']; - -commonTags.html` -
-
    - ${fruits.map(fruit => `
  • ${fruit}
  • `)} - ${'
  • kiwi
  • \n
  • guava
  • '} -
-
-`; - -commonTags.codeBlock` -
-
    - ${fruits.map(fruit => `
  • ${fruit}
  • `)} - ${'
  • kiwi
  • \n
  • guava
  • '} -
-
-`; - -commonTags.source` -
-
    - ${fruits.map(fruit => `
  • ${fruit}
  • `)} - ${'
  • kiwi
  • \n
  • guava
  • '} -
-
-`; - -let userMessages = ['hi', 'what are you up to?', ''] -commonTags.html` -
-
    - ${userMessages.map(message => commonTags.safeHtml`
  • ${message}
  • `)} -
-
-` - -commonTags.oneLine` +oneLine` foo bar baz `; -commonTags.oneLineTrim` +oneLineTrim` https://news.com/article ?utm_source=designernews.co `; -commonTags.oneLineCommaLists` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -commonTags.oneLineCommaListsOr` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -commonTags.oneLineCommaListsAnd` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -commonTags.inlineLists` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -commonTags.oneLineInlineLists` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -let verb = 'notice'; - -commonTags.stripIndent` +const verb = 'notice'; +stripIndent` This is a multi-line string. You'll ${verb} that it is indented. We don't want to output this indentation. But we do want to keep this line indented. `; -commonTags.stripIndents` +stripIndents` This is a multi-line string. You'll ${verb} that it is indented. We don't want to output this indentation. We don't want to keep this line indented either. `; -/* Test Tag Constructor */ +inlineLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; -new commonTags.TemplateTag(); +oneLineInlineLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; -const substitutionReplacer = (oldValue : string, newValue : string) => ({ - onSubstitution(substitution : string, resultSoFar : string) { +commaLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commaListsOr` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commaListsAnd` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +oneLineCommaLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +oneLineCommaListsOr` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +oneLineCommaListsAnd` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +id`hello ${'world'}`; + +oneLine(String.raw)` + foo + bar\nbaz +`; + +stripIndent(' foo\n bar'); + +const doNothing = createTag(); +doNothing`foo bar`; + +const substitutionReplacer = (oldValue: string, newValue: string): TemplateTransformer => ({ + onSubstitution(substitution, resultSoFar) { if (substitution === oldValue) { return newValue; } return substitution; - } + }, }); -new commonTags.TemplateTag(substitutionReplacer('fizz', 'buzz')); +const replaceFizzWithBuzz = createTag(substitutionReplacer('fizz', 'buzz')); +replaceFizzWithBuzz`foo bar ${'fizz'}`; -new commonTags.TemplateTag( - substitutionReplacer('fizz', 'buzz'), - substitutionReplacer('foo', 'bar') +createTag(); +createTag(substitutionReplacer('fizz', 'buzz')); +createTag(substitutionReplacer('fizz', 'buzz'), substitutionReplacer('foo', 'bar')); +createTag([substitutionReplacer('fizz', 'buzz'), substitutionReplacer('foo', 'bar')]); +new TemplateTag(); +new TemplateTag(substitutionReplacer('fizz', 'buzz')); +new TemplateTag(substitutionReplacer('fizz', 'buzz'), substitutionReplacer('foo', 'bar')); +new TemplateTag([substitutionReplacer('fizz', 'buzz'), substitutionReplacer('foo', 'bar')]); + +const tt: TemplateTransformer<{ foo: string }> = { + getInitialContext() { + return { foo: 'bar' }; + }, + onString(str, context) { + // $ExpectType string + str; + // $ExpectType { foo: string; } + context; + return ''; + }, + onSubstitution(substitution, resultSoFar, context) { + // $ExpectType string + substitution; + // $ExpectType string + resultSoFar; + // $ExpectType { foo: string; } + context; + return ''; + }, + onEndResult(endResult, context) { + // $ExpectType string + endResult; + // $ExpectType { foo: string; } + context; + return ''; + }, +}; + +createTag({}); +createTag(tt); +createTag({ + onString: str => `${str}!`, +}); +createTag({ + onSubstitution: substitution => `${substitution}!`, +}); +createTag({ + onEndResult: endResult => `${endResult}!`, +}); +new TemplateTag({}); +new TemplateTag(tt); +new TemplateTag({ + onString: str => `${str}!`, +}); +new TemplateTag({ + onSubstitution: substitution => `${substitution}!`, +}); +new TemplateTag({ + onEndResult: endResult => `${endResult}!`, +}); + +createTag(trimResultTransformer()); +createTag(trimResultTransformer('')); +createTag(trimResultTransformer('start')); +createTag(trimResultTransformer('end')); +createTag(trimResultTransformer('left')); +createTag(trimResultTransformer('right')); + +createTag(stripIndentTransformer()); +createTag(stripIndentTransformer('initial')); +createTag(stripIndentTransformer('all')); + +createTag(replaceResultTransformer('foo', 'bar')); +createTag(replaceResultTransformer(/baz/g, 'bar')); +createTag( + replaceResultTransformer(/baz/g, (substring, ...matches) => { + // $ExpectType string + substring; + // $ExpectType any[] + matches; + return ''; + }) ); -new commonTags.TemplateTag([ - substitutionReplacer('fizz', 'buzz'), - substitutionReplacer('foo', 'bar') -]); +createTag(replaceSubstitutionTransformer('foo', 'bar')); +createTag(replaceSubstitutionTransformer(/baz/g, 'bar')); +createTag( + replaceSubstitutionTransformer(/baz/g, (substring, ...matches) => { + // $ExpectType string + substring; + // $ExpectType any[] + matches; + return ''; + }) +); -new commonTags.TemplateTag({}); +createTag(replaceStringTransformer('foo', 'bar')); +createTag(replaceStringTransformer(/baz/g, 'bar')); +createTag( + replaceStringTransformer(/baz/g, (substring, ...matches) => { + // $ExpectType string + substring; + // $ExpectType any[] + matches; + return ''; + }) +); -new commonTags.TemplateTag({ - onEndResult: endResult => `${endResult}!` -}); +createTag(inlineArrayTransformer()); +createTag(inlineArrayTransformer({})); +createTag(inlineArrayTransformer({ separator: 'foo' })); +createTag(inlineArrayTransformer({ conjunction: 'bar' })); +createTag(inlineArrayTransformer({ serial: true })); -new commonTags.TemplateTag({ - onSubstitution: substitution => `${substitution}!`, - onEndResult: endResult => `${endResult}!` -}); - -/* Tests Built-in Transformers */ - -new commonTags.TemplateTag(commonTags.trimResultTransformer()); -new commonTags.TemplateTag(commonTags.trimResultTransformer('left')); -new commonTags.TemplateTag(commonTags.trimResultTransformer('right')); - -new commonTags.TemplateTag(commonTags.stripIndentTransformer()); -new commonTags.TemplateTag(commonTags.stripIndentTransformer('initial')); -new commonTags.TemplateTag(commonTags.stripIndentTransformer('all')); - -new commonTags.TemplateTag(commonTags.replaceResultTransformer('foo', 'bar')); -new commonTags.TemplateTag(commonTags.replaceSubstitutionTransformer(/baz/g, 'bar')); - -new commonTags.TemplateTag(commonTags.replaceSubstitutionTransformer('foo', 'bar')); -new commonTags.TemplateTag(commonTags.replaceSubstitutionTransformer(/baz/g, 'bar')); - -new commonTags.TemplateTag(commonTags.inlineArrayTransformer()); -new commonTags.TemplateTag(commonTags.inlineArrayTransformer({})); -new commonTags.TemplateTag(commonTags.inlineArrayTransformer({separator: 'foo'})); -new commonTags.TemplateTag(commonTags.inlineArrayTransformer({conjunction: 'bar'})); - -new commonTags.TemplateTag(commonTags.splitStringTransformer('foo')); +createTag(splitStringTransformer('foo')); diff --git a/types/common-tags/index.d.ts b/types/common-tags/index.d.ts index 65f0b61673..3a12c91109 100644 --- a/types/common-tags/index.d.ts +++ b/types/common-tags/index.d.ts @@ -1,67 +1,220 @@ -// Type definitions for common-tags v1.4.0 +// Type definitions for common-tags 1.8 // Project: https://github.com/declandewet/common-tags // Definitions by: Viktor Zozuliak // Paul Wang +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -declare module 'common-tags' { - type TemplateTag = (literals: TemplateStringsArray, ...placeholders: any[]) => string; +export as namespace commonTags; - type TemplateTransformer = { - onSubstitution?: (substitution: string, resultSoFar: string) => string; - onEndResult?: (endResult : string) => string; - } +export type JSTag = (literals: TemplateStringsArray, ...placeholders: any[]) => string; - /* Built-in Tags */ - export var commaLists: TemplateTag; - - export var commaListsAnd: TemplateTag; - - export var commaListsOr: TemplateTag; - - export var html: TemplateTag; - - export var codeBlock: TemplateTag; - - export var source: TemplateTag; - - export var safeHtml: TemplateTag; - - export var oneLine: TemplateTag; - - export var oneLineTrim: TemplateTag; - - export var oneLineCommaLists: TemplateTag; - - export var oneLineCommaListsOr: TemplateTag; - - export var oneLineCommaListsAnd: TemplateTag; - - export var inlineLists: TemplateTag; - - export var oneLineInlineLists: TemplateTag; - - export var stripIndent: TemplateTag; - - export var stripIndents: TemplateTag; - - /* New Tag Constructor */ - export var TemplateTag: { - new(): TemplateTag; - new(...transformers: TemplateTransformer[]): TemplateTag; - new(transformers: TemplateTransformer[]): TemplateTag; - }; - - /* Built-in Transformers */ - export var trimResultTransformer: (side?: 'left'|'right') => TemplateTransformer; - - export var stripIndentTransformer: (type?: 'initial'|'all') => TemplateTransformer; - - export var replaceResultTransformer: (replaceWhat: string|RegExp, replaceWith: string) => TemplateTransformer; - - export var replaceSubstitutionTransformer: (replaceWhat: string|RegExp, replaceWith: string) => TemplateTransformer; - - export var inlineArrayTransformer: (opts?: {separator?: string, conjunction?: string}) => TemplateTransformer; - - export var splitStringTransformer: (splitBy: string) => TemplateTransformer; +export interface TemplateTag { + (str: string): string; + (tag: JSTag): TemplateTag; + (literals: TemplateStringsArray, ...placeholders: any[]): string; } + +/** + * You'll often find that you might want to include an array in a template. + * Typically, doing something like `${array.join(', ')}` would work - but what if you're printing a list of items + * in an HTML template and want to maintain the indentation? You'd have to count the spaces manually and include + * them in the `.join()` call - which is a bit ugly for my taste. + * This tag properly indents arrays, as well as newline characters in string substitutions, + * by converting them to an array split by newline and re-using the same array inclusion logic. + */ +export const html: TemplateTag; + +/** + * alias for `html` + */ +export const codeBlock: TemplateTag; + +/** + * alias for `html` + */ +export const source: TemplateTag; + +/** + * A tag very similar to `html` but it does safe HTML escaping for strings coming from substitutions. + * When combined with regular `html` tag, you can do basic HTML templating that is safe from + * XSS (Cross-Site Scripting) attacks. + */ +export const safeHtml: TemplateTag; + +/** + * Allows you to keep your single-line strings under 80 characters without resorting to crazy string concatenation. + */ +export const oneLine: TemplateTag; + +/** + * Allows you to keep your single-line strings under 80 characters while trimming the new lines. + */ +export const oneLineTrim: TemplateTag; + +/** + * If you want to strip the initial indentation from the beginning of each line in a multiline string. + * Important note: this tag will not indent multiline strings coming from the substitutions. + * If you want that behavior, use the `html` tag (aliases: `source`, `codeBlock`). + */ +export const stripIndent: TemplateTag; + +/** + * If you want to strip *all* of the indentation from the beginning of each line in a multiline string. + */ +export const stripIndents: TemplateTag; + +/** + * Allows you to inline an array substitution as a list. + */ +export const inlineLists: TemplateTag; + +/** + * Allows you to inline an array substitution as a list, rendered out on a single line. + */ +export const oneLineInlineLists: TemplateTag; + +/** + * Allows you to inline an array substitution as a comma-separated list. + */ +export const commaLists: TemplateTag; + +/** + * Allows you to inline an array substitution as a comma-separated list, the last of which is preceded by the word "or". + */ +export const commaListsOr: TemplateTag; + +/** + * Allows you to inline an array substitution as a comma-separated list, the last of which is preceded by the word "and". + */ +export const commaListsAnd: TemplateTag; + +/** + * Allows you to inline an array substitution as a comma-separated list, and is rendered out on to a single line. + */ +export const oneLineCommaLists: TemplateTag; + +/** + * Allows you to inline an array substitution as a comma-separated list, the last of which is preceded by the word "or", and is rendered out on to a single line. + */ +export const oneLineCommaListsOr: TemplateTag; + +/** + * Allows you to inline an array substitution as a comma-separated list, the last of which is preceded by the word "and", and is rendered out on to a single line. + */ +export const oneLineCommaListsAnd: TemplateTag; + +/** + * A no-op tag that might come in useful in some scenarios, e.g. mocking. + */ +export const id: TemplateTag; + +export interface TemplateTransformer { + /** + * Called before everything else. + * The result of this hook will be passed to other hooks as `context`. + * If omitted, `context` will be an empty object. + */ + getInitialContext?: () => TCtx; + /** + * Called when the tag encounters a string. + * (a string is whatever's not inside "${}" in your template literal) + * `str` is the value of the current string + */ + onString?: (str: string, context: TCtx) => string; + /** + * Called when the tag encounters a substitution. + * (a substitution is whatever's inside "${}" in your template literal) + * `substitution` is the value of the current substitution + * `resultSoFar` is the end result up to the point of this substitution + */ + onSubstitution?: (substitution: string, resultSoFar: string, context: TCtx) => string; + /** + * Called when all substitutions have been parsed + * `endResult` is the final value. + */ + onEndResult?: (endResult: string, context: TCtx) => string; +} + +export type PluginFunction = (oldValue: string, newValue: string) => TemplateTransformer; + +/** + * New Tag factory + */ +export function createTag(transformers?: Array>): TemplateTag; +export function createTag(...transformers: Array>): TemplateTag; +export function createTag(...pluginFunctions: PluginFunction[]): TemplateTag; + +export const TemplateTag: { + /** + * New Tag Constructor + * @deprecated + */ + new (transformers?: Array>): TemplateTag; + new (...transformers: Array>): TemplateTag; + new (...pluginFunctions: PluginFunction[]): TemplateTag; +}; + +/** + * TemplateTag transformer that trims whitespace on the end result of a tagged template + * @param [side=''] The side of the string to trim. Can be 'start' or 'end' (alternatively 'left' or 'right') + * @return a TemplateTag transformer + */ +export function trimResultTransformer( + side?: 'start' | 'end' | 'left' | 'right' | '' +): TemplateTransformer; + +/** + * strips indentation from a template literal + * @param [type='initial'] whether to remove all indentation or just leading indentation. can be 'all' or 'initial' + * @return a TemplateTag transformer + */ +export function stripIndentTransformer(type?: 'initial' | 'all'): TemplateTransformer; + +/** + * Replaces a value or pattern in the end result with a new value. + * @param replaceWhat the value or pattern that should be replaced + * @param replaceWith the replacement value + * @return a TemplateTag transformer + */ +export function replaceResultTransformer( + replaceWhat: string | RegExp, + replaceWith: string | ((substring: string, ...args: any[]) => string) +): TemplateTransformer; + +/** + * Replaces the result of all substitutions (results of calling ${ ... }) with a new value. + * Same as for `replaceResultTransformer`, replaceWhat can be a string or regular expression and replaceWith is the new value. + */ +export function replaceSubstitutionTransformer( + replaceWhat: string | RegExp, + replaceWith: string | ((substring: string, ...args: any[]) => string) +): TemplateTransformer; + +/** + * Replaces the result of all strings (what's not in ${ ... }) with a new value. + * Same as for `replaceResultTransformer`, replaceWhat can be a string or regular expression and replaceWith is the new value. + */ +export function replaceStringTransformer( + replaceWhat: string | RegExp, + replaceWith: string | ((substring: string, ...args: any[]) => string) +): TemplateTransformer; + +/** + * Converts an array substitution to a string containing a list + * @param [opts.separator=''] what to separate each item with (always followed by a space) + * @param [opts.conjunction=''] replace the last separator with this value + * @param [opts.serial=false] should the separator be included before the conjunction? As in the case of serial/oxford commas + * @return a TemplateTag transformer + */ +export function inlineArrayTransformer(opts?: { + separator?: string; + conjunction?: string; + serial?: boolean; +}): TemplateTransformer; + +/** + * Splits a string substitution into an array by the provided splitBy substring, only if the string contains the splitBy substring. + */ +export function splitStringTransformer(splitBy: string): TemplateTransformer; diff --git a/types/common-tags/tslint.json b/types/common-tags/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/common-tags/tslint.json +++ b/types/common-tags/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/configstore/configstore-tests.ts b/types/configstore/configstore-tests.ts index ffd04e31a7..9365afdbda 100644 --- a/types/configstore/configstore-tests.ts +++ b/types/configstore/configstore-tests.ts @@ -5,6 +5,7 @@ let value: any; let key: string; let num: number; let object: any; +let path: string; cs.set(key, value); value = cs.get(key); @@ -13,4 +14,12 @@ cs.delete(key); object = cs.all; cs.all = object; num = cs.size; -key = cs.path; +path = cs.path; + +const csWithPathOption = new Configstore('foo', null, { configPath: path }); + +csWithPathOption.set(key, value); +value = csWithPathOption.get(key); +csWithPathOption.delete(key); + +key = csWithPathOption.path; diff --git a/types/configstore/index.d.ts b/types/configstore/index.d.ts index 2617f2bce0..bbc0740c23 100644 --- a/types/configstore/index.d.ts +++ b/types/configstore/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for configstore 2.1 +// Type definitions for configstore 4.0 // Project: https://github.com/yeoman/configstore // Definitions by: ArcticLight // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -67,5 +67,6 @@ declare class Configstore { declare namespace Configstore { interface ConfigstoreOptions { globalConfigPath?: boolean; + configPath?: string; } } diff --git a/types/connect-mongo/index.d.ts b/types/connect-mongo/index.d.ts index ea39a13f42..7173cb50dc 100644 --- a/types/connect-mongo/index.d.ts +++ b/types/connect-mongo/index.d.ts @@ -110,6 +110,7 @@ declare namespace connectMongo { length: (callback: (err: any, length: number) => void) => void; clear: (callback?: (err?: any) => void) => void; touch: (sid: string, session: Express.SessionData, callback?: (err: any) => void) => void; + close: () => void; } } diff --git a/types/connect-redis/index.d.ts b/types/connect-redis/index.d.ts index 5675512795..c5a26de73a 100644 --- a/types/connect-redis/index.d.ts +++ b/types/connect-redis/index.d.ts @@ -1,7 +1,6 @@ // Type definitions for connect-redis // Project: https://npmjs.com/package/connect-redis // Definitions by: Xavier Stouder -// Albert Kurniawan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 diff --git a/types/convict/index.d.ts b/types/convict/index.d.ts index 2c3dbf0547..fd605f5077 100644 --- a/types/convict/index.d.ts +++ b/types/convict/index.d.ts @@ -37,6 +37,24 @@ declare namespace convict { parse: (content: string) => any; } + type PredefinedFormat = + | '*' + | 'int' + | 'port' + | 'windows_named_pipe' + | 'port_or_windows_named_pipe' + | 'url' + | 'email' + | 'ipaddress' + | 'duration' + | 'timestamp' + | 'nat' + | String + | Object + | Number + | RegExp + | Boolean; + interface SchemaObj { default: T; doc?: string; @@ -52,7 +70,7 @@ declare namespace convict { * If omitted, format will be set to the value of Object.prototype.toString.call * for the default value */ - format?: string | any[] | ((val: any) => void); + format?: PredefinedFormat | any[] | ((val: any) => void); env?: string; arg?: string; sensitive?: boolean; diff --git a/types/create-hash/create-hash-tests.ts b/types/create-hash/create-hash-tests.ts new file mode 100644 index 0000000000..d039a5a704 --- /dev/null +++ b/types/create-hash/create-hash-tests.ts @@ -0,0 +1,9 @@ +import createHash = require('create-hash'); + +const hash = createHash('sha224'); + +hash.update('synchronous write'); +hash.digest(); +hash.write('write to it as a stream'); +hash.end(); +hash.read(); diff --git a/types/create-hash/index.d.ts b/types/create-hash/index.d.ts new file mode 100644 index 0000000000..712be2520f --- /dev/null +++ b/types/create-hash/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for create-hash 1.2 +// Project: https://github.com/crypto-browserify/createHash +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { Hash } from 'crypto'; + +export = createHash; + +declare function createHash(algo: createHash.Algorithm): Hash; + +declare namespace createHash { + type Algorithm = + | 'md5' + | 'rmd160' + | 'ripemd160' + | 'sha' + | 'sha1' + | 'sha224' + | 'sha256' + | 'sha384' + | 'sha512'; +} diff --git a/types/create-hash/tsconfig.json b/types/create-hash/tsconfig.json new file mode 100644 index 0000000000..83e50b425c --- /dev/null +++ b/types/create-hash/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "create-hash-tests.ts" + ] +} diff --git a/types/create-hash/tslint.json b/types/create-hash/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/create-hash/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/create-hmac/create-hmac-tests.ts b/types/create-hmac/create-hmac-tests.ts new file mode 100644 index 0000000000..f233a0390a --- /dev/null +++ b/types/create-hmac/create-hmac-tests.ts @@ -0,0 +1,9 @@ +import createHmac = require('create-hmac'); + +const hmac = createHmac('sha224', Buffer.from('secret key')); + +hmac.update('synchronous write'); +hmac.digest(); +hmac.write('write to it as a stream'); +hmac.end(); +hmac.read(); diff --git a/types/create-hmac/index.d.ts b/types/create-hmac/index.d.ts new file mode 100644 index 0000000000..3d6bcfeafa --- /dev/null +++ b/types/create-hmac/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for create-hmac 1.1 +// Project: https://github.com/crypto-browserify/createHmac +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { Hmac } from 'crypto'; + +export = createHmac; + +declare function createHmac(algo: createHmac.Algorithm, key: string | Buffer): Hmac; + +declare namespace createHmac { + type Algorithm = + | 'rmd160' + | 'ripemd160' + | 'md5' + | 'sha' + | 'sha1' + | 'sha224' + | 'sha256' + | 'sha384' + | 'sha512'; +} diff --git a/types/create-hmac/tsconfig.json b/types/create-hmac/tsconfig.json new file mode 100644 index 0000000000..badd99da29 --- /dev/null +++ b/types/create-hmac/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "create-hmac-tests.ts" + ] +} diff --git a/types/create-hmac/tslint.json b/types/create-hmac/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/create-hmac/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cropperjs/index.d.ts b/types/cropperjs/index.d.ts index 30556e11fc..d444c20705 100644 --- a/types/cropperjs/index.d.ts +++ b/types/cropperjs/index.d.ts @@ -426,8 +426,9 @@ declare class cropperjs { /** * Replace the image's src and rebuild the cropper. * @param url A new image url + * @param hasSameSize If the new image has the same size with the old one, then it will not rebuilt the cropper and only update the urls of all related images. (Default: false) */ - replace(url: string): void; + replace(url: string, hasSameSize?: boolean): void; /** * Enable (unfreeze) the cropper. diff --git a/types/crumb/crumb-tests.ts b/types/crumb/crumb-tests.ts new file mode 100644 index 0000000000..90612a3e4a --- /dev/null +++ b/types/crumb/crumb-tests.ts @@ -0,0 +1,47 @@ +import * as hapi from 'hapi'; +import * as crumb from 'crumb'; + +const server = new hapi.Server({ port: 8000 }); + +server.register({ + plugin: crumb, + options: { + key: 'csrf-token', + size: 50, + autoGenerate: true, + addToViewContext: true, + cookieOptions: { + path: '/', + }, + headerName: 'X-CSRF-Token', + restful: true, + skip: () => false, + enforce: true, + logUnauthorized: false, + } +}); + +server.route({ + method: 'get', + path: '/', + handler: async (_, h) => { + return h.continue; + }, +}); + +server.route({ + method: 'get', + path: '/custom', + options: { + plugins: { + crumb: { + key: 'x-csrf-token', + source: 'query', + restful: true, + }, + }, + }, + handler: async (_, h) => { + return h.continue; + }, +}); diff --git a/types/crumb/index.d.ts b/types/crumb/index.d.ts new file mode 100644 index 0000000000..16311c99bf --- /dev/null +++ b/types/crumb/index.d.ts @@ -0,0 +1,114 @@ +// Type definitions for crumb 7.2 +// Project: https://github.com/hapijs/crumb +// Definitions by: Silas Rech +// Simon Schick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Request, Plugin, ResponseToolkit, ServerStateCookieOptions } from 'hapi'; + +declare module 'hapi' { + interface PluginSpecificConfiguration { + crumb?: boolean | { + /** + * The name of the cookie to store the CSRF crumb into. + */ + key?: string; + + /** + * Specifies how the crumb will be sent in requests. + * + * @default 'payload' + */ + source?: 'payload' | 'query'; + + /** + * Override for the server's 'restful' setting + */ + restful?: boolean; + }; + } +} + +declare namespace crumb { + type SkipFunction = (request?: Request, h?: ResponseToolkit) => boolean; + + interface RegisterOptions { + /** + * The name of the cookie to store the CSRF crumb into. + * + * @default 'crumb' + */ + key?: string; + + /** + * The length of the crumb to generate. + * See {@link https://github.com/hapijs/cryptiles cryptiles} for more information. + * + * @default 43 + */ + size?: number; + + /** + * Whether to automatically generate a new crumb for requests. + * + * @default true + */ + autoGenerate?: boolean; + + /** + * Whether to automatically add the crumb to view contexts as the given key. + * + * @default true + */ + addToViewContext?: boolean; + + /** + * Storage options for the cookie containing the crumb + * + * @default { path: '/' } + */ + cookieOptions?: ServerStateCookieOptions; + + /** + * Specify the name of the custom CSRF header. + * + * @default 'X-CSRF-Token' + */ + headerName?: string; + + /** + * RESTful mode that validates crumb tokens from 'X-CSRF-Token' request header for POST, PUT, PATCH and DELETE server routes. + * Disables payload/query crumb validation. + * + * @default false + */ + restful?: boolean; + + /** + * A function which when provided, is called for every request. + * If the provided function returns true, validation and generation of crumb is skipped. + * + * @default false + */ + skip?: boolean | SkipFunction; + + /** + * Using enforce with false will set the CSRF header cookie but won't execute the validation. + * + * @default true + */ + enforce?: boolean; + + /** + * Whether to add to the request log with tag 'crumb' and data 'validation failed'. + * + * @default false + */ + logUnauthorized?: boolean; + } +} + +declare const crumb: Plugin; + +export = crumb; diff --git a/types/crumb/tsconfig.json b/types/crumb/tsconfig.json new file mode 100644 index 0000000000..5beceb6a88 --- /dev/null +++ b/types/crumb/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "crumb-tests.ts" + ] +} diff --git a/types/crumb/tslint.json b/types/crumb/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/crumb/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/crypto-hash/crypto-hash-tests.ts b/types/crypto-hash/crypto-hash-tests.ts new file mode 100644 index 0000000000..73e62ad1c6 --- /dev/null +++ b/types/crypto-hash/crypto-hash-tests.ts @@ -0,0 +1,29 @@ +import { sha1, sha256, sha384, sha512 } from 'crypto-hash'; + +// $ExpectType Promise +sha1('🦄'); +// $ExpectType Promise +sha1('🦄', { outputFormat: 'buffer' }); +// $ExpectType Promise +sha1('🦄', { outputFormat: 'hex' }); + +// $ExpectType Promise +sha256('🦄'); +// $ExpectType Promise +sha256('🦄', { outputFormat: 'buffer' }); +// $ExpectType Promise +sha256('🦄', { outputFormat: 'hex' }); + +// $ExpectType Promise +sha384('🦄'); +// $ExpectType Promise +sha384('🦄', { outputFormat: 'buffer' }); +// $ExpectType Promise +sha384('🦄', { outputFormat: 'hex' }); + +// $ExpectType Promise +sha512('🦄'); +// $ExpectType Promise +sha512('🦄', { outputFormat: 'buffer' }); +// $ExpectType Promise +sha512('🦄', { outputFormat: 'hex' }); diff --git a/types/crypto-hash/index.d.ts b/types/crypto-hash/index.d.ts new file mode 100644 index 0000000000..c22864b2ae --- /dev/null +++ b/types/crypto-hash/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for crypto-hash 1.0 +// Project: https://github.com/sindresorhus/crypto-hash#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function sha1( + buffer: string | ArrayBuffer | ArrayBufferView, + options?: OptionsHexOutput +): Promise; +export function sha1( + buffer: string | ArrayBuffer | ArrayBufferView, + options: OptionBufferOutput +): Promise; + +export function sha256( + buffer: string | ArrayBuffer | ArrayBufferView, + options?: OptionsHexOutput +): Promise; +export function sha256( + buffer: string | ArrayBuffer | ArrayBufferView, + options: OptionBufferOutput +): Promise; + +export function sha384( + buffer: string | ArrayBuffer | ArrayBufferView, + options?: OptionsHexOutput +): Promise; +export function sha384( + buffer: string | ArrayBuffer | ArrayBufferView, + options: OptionBufferOutput +): Promise; + +export function sha512( + buffer: string | ArrayBuffer | ArrayBufferView, + options?: OptionsHexOutput +): Promise; +export function sha512( + buffer: string | ArrayBuffer | ArrayBufferView, + options: OptionBufferOutput +): Promise; + +export interface OptionsHexOutput { + outputFormat?: 'hex'; +} + +export interface OptionBufferOutput { + outputFormat: 'buffer'; +} diff --git a/types/crypto-hash/tsconfig.json b/types/crypto-hash/tsconfig.json new file mode 100644 index 0000000000..410ee34985 --- /dev/null +++ b/types/crypto-hash/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "crypto-hash-tests.ts" + ] +} diff --git a/types/crypto-hash/tslint.json b/types/crypto-hash/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/crypto-hash/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cryptr/cryptr-tests.ts b/types/cryptr/cryptr-tests.ts new file mode 100644 index 0000000000..3c655d7288 --- /dev/null +++ b/types/cryptr/cryptr-tests.ts @@ -0,0 +1,10 @@ +import Cryptr = require('cryptr'); + +// $ExpectType Cryptr +const cryptr = new Cryptr('myTotallySecretKey'); + +// $ExpectType string +const encrypted_string = cryptr.encrypt('bacon'); + +// $ExpectType string +cryptr.decrypt(encrypted_string); diff --git a/types/cryptr/index.d.ts b/types/cryptr/index.d.ts new file mode 100644 index 0000000000..4aec15c419 --- /dev/null +++ b/types/cryptr/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for cryptr 4.0 +// Project: https://github.com/MauriceButler/cryptr +// Definitions by: Roman Rogowski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Cryptr { + /** + * Cryptr provides a mechanism for aes-256-ctr encryption/decryption. + * @param secret key used for encryption/decryption + */ + constructor(secret: string); + + /** Encrypt a string. */ + encrypt(value: string): string; + + /** Decrypt a string. */ + decrypt(value: string): string; +} + +export = Cryptr; diff --git a/types/cryptr/tsconfig.json b/types/cryptr/tsconfig.json new file mode 100644 index 0000000000..2727c48e08 --- /dev/null +++ b/types/cryptr/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "cryptr-tests.ts" + ] +} diff --git a/types/cryptr/tslint.json b/types/cryptr/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cryptr/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cson-parser/cson-parser-tests.ts b/types/cson-parser/cson-parser-tests.ts new file mode 100644 index 0000000000..955aadcffe --- /dev/null +++ b/types/cson-parser/cson-parser-tests.ts @@ -0,0 +1,5 @@ +import * as CSON from 'cson-parser'; + +CSON.parse('[ 1, 2, a: "str" ]'); + +CSON.stringify({ domain: 'typescript.org' }, null, 4); diff --git a/types/cson-parser/index.d.ts b/types/cson-parser/index.d.ts new file mode 100644 index 0000000000..b8e1db7421 --- /dev/null +++ b/types/cson-parser/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for cson-parser 4.0 +// Project: https://github.com/groupon/cson-parser +// Definitions by: Silas Rech +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +export type ReplacerFunction = (key: string, value: any) => any; + +/** + * Converts a CSON string into an object. + * @param text A valid CSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ +export function parse(text: string, reviver?: (key: any, value: any) => any): any; + +/** + * Converts a JavaScript value to a CSON string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results or an array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. + * @param space Adds indentation, white space, and line break characters to the return-value CSON text to make it easier to read. + */ +export function stringify(value: any, replacer?: ReplacerFunction | Array<(number | string)> | null, space?: string | number): string; diff --git a/types/cson-parser/tsconfig.json b/types/cson-parser/tsconfig.json new file mode 100644 index 0000000000..374ff4913f --- /dev/null +++ b/types/cson-parser/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cson-parser-tests.ts" + ] +} diff --git a/types/cson-parser/tslint.json b/types/cson-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cson-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/d3-brush/d3-brush-tests.ts b/types/d3-brush/d3-brush-tests.ts index dc2c9a0dc8..c5a287b562 100644 --- a/types/d3-brush/d3-brush-tests.ts +++ b/types/d3-brush/d3-brush-tests.ts @@ -48,7 +48,7 @@ brush = brush.extent(function(d, i, group) { // chainable brush = brush.filter(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - const e = > event; + const e = event as d3Brush.D3BrushEvent; console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement return e.sourceEvent.type !== 'zoom' || !d.filterZoomEvent; // datum type is BrushDatum (as propagated to SVGGElement with brush event attached) diff --git a/types/d3-drag/d3-drag-tests.ts b/types/d3-drag/d3-drag-tests.ts index cf5428e7e2..5e376c003b 100644 --- a/types/d3-drag/d3-drag-tests.ts +++ b/types/d3-drag/d3-drag-tests.ts @@ -134,7 +134,7 @@ touchableFn = circleDrag.touchable(); circleCustomDrag.subject(function(d, i, g) { // Cast event type for completeness, otherwise event is of type any. - const e = > event; + const e = event as d3Drag.D3DragEvent; const that: SVGCircleElement = this; const datum: CircleDatum = d; const index: number = i; @@ -163,14 +163,14 @@ subjectAccessor = circleCustomDrag.subject(); function dragstarted(this: SVGCircleElement, d: CircleDatum) { // cast d3 event to drag event. Otherwise, d3 event is currently defined as type 'any' - const e = > event; + const e = event as d3Drag.D3DragEvent; e.sourceEvent.stopPropagation(); select(this).classed('dragging', true); } function dragged(this: SVGCircleElement, d: CircleDatum) { // cast d3 event to drag event. Otherwise, d3 event is currently defined as type 'any' - const e = > event; + const e = event as d3Drag.D3DragEvent; select(this).attr('cx', d.x = e.x).attr('cy', d.y = e.y); } diff --git a/types/d3-selection/d3-selection-tests.ts b/types/d3-selection/d3-selection-tests.ts index bafc1aeb11..092e8bfa5a 100644 --- a/types/d3-selection/d3-selection-tests.ts +++ b/types/d3-selection/d3-selection-tests.ts @@ -1060,7 +1060,7 @@ interface SuccessEvent { const successEvent = { type: 'wonEuro2016', team: 'Island' }; function customListener(this: HTMLBodyElement | null, finalOpponent: string): string { - const e = d3Selection.event; + const e = d3Selection.event as SuccessEvent; return `${e.team} defeated ${finalOpponent} in the EURO 2016 Cup. Who would have thought!!!`; } diff --git a/types/d3-selection/tslint.json b/types/d3-selection/tslint.json index c89636b4b7..26ee29cf50 100644 --- a/types/d3-selection/tslint.json +++ b/types/d3-selection/tslint.json @@ -2,7 +2,6 @@ "extends": "dtslint/dt.json", "rules": { // TODO - "no-angle-bracket-type-assertion": false, "no-this-assignment": false, "unified-signatures": false, "no-unnecessary-generics": false diff --git a/types/d3-shape/index.d.ts b/types/d3-shape/index.d.ts index eccf7f1b80..0c0e27cbd7 100644 --- a/types/d3-shape/index.d.ts +++ b/types/d3-shape/index.d.ts @@ -38,7 +38,7 @@ export interface CanvasPath_D3Shape { // ----------------------------------------------------------------------------------- /** - * Interface corresponding to the minimum data type assumed by the accessor functions of the Arc generator + * Interface corresponding to the minimum data type assumed by the accessor functions of the Arc generator */ export interface DefaultArcObject { /** @@ -994,14 +994,17 @@ export function lineRadial(): LineRadial<[number, number]>; */ export function lineRadial(): LineRadial; +/** + * @deprecated Use LineRadial + */ export type RadialLine = LineRadial; /** - * DEPRECATED: Use lineRadial() + * @deprecated Use lineRadial() */ export function radialLine(): RadialLine<[number, number]>; /** - * DEPRECATED: Use lineRadial() + * @deprecated Use lineRadial() */ export function radialLine(): RadialLine; @@ -1620,16 +1623,16 @@ export function areaRadial(): AreaRadial<[number, number]>; export function areaRadial(): AreaRadial; /** - * DEPRECATED: Use AreaRadial interface + * @deprecated Use AreaRadial interface */ export type RadialArea = AreaRadial; /** - * DEPRECATED: Use areaRadial() + * @deprecated Use areaRadial() */ export function radialArea(): RadialArea<[number, number]>; /** - * DEPRECATED: Use areaRadial() + * @deprecated Use areaRadial() */ export function radialArea(): RadialArea; @@ -2239,7 +2242,7 @@ export interface LinkRadial { } /** - * DEPRECATED: Use LinkRadial interface + * @deprecated Use LinkRadial interface */ export type RadialLink = LinkRadial; diff --git a/types/d3-zoom/d3-zoom-tests.ts b/types/d3-zoom/d3-zoom-tests.ts index 19a16930d6..c758e83448 100644 --- a/types/d3-zoom/d3-zoom-tests.ts +++ b/types/d3-zoom/d3-zoom-tests.ts @@ -91,7 +91,7 @@ interface GroupDatum { function zoomedCanvas(this: HTMLCanvasElement, d: CanvasDatum) { // Cast d3 event to D3ZoomEvent to be used in zoom event handler - const e = > event; + const e = event as d3Zoom.D3ZoomEvent; if (context) { context.save(); context.clearRect(0, 0, this.width, this.height); // this element @@ -112,7 +112,7 @@ canvasZoom = d3Zoom.zoom() function zoomedSVGOverlay(this: SVGRectElement) { // Cast d3 event to D3ZoomEvent to be used in zoom event handler - const e = > event; + const e = event as d3Zoom.D3ZoomEvent; g.attr('transform', e.transform.toString()); } @@ -146,7 +146,7 @@ constraintFn = svgZoom.constrain(); // chainable svgZoom = svgZoom.filter(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - const e = > event; + const e = event as d3Zoom.D3ZoomEvent; console.log('Overlay Rectangle width: ', this.width.baseVal.value); // this typing is SVGRectElement return e.sourceEvent.type !== 'brush' || !d.filterBrushEvent; // datum type is SVGDatum (as propagated to SVGRectElement with zoom event attached) @@ -178,7 +178,7 @@ touchableFn = svgZoom.touchable(); // chainable svgZoom = svgZoom.wheelDelta(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - const e = event; + const e = event as WheelEvent; const that: SVGRectElement = this; const datum: SVGDatum = d; const index: number = i; diff --git a/types/d3-zoom/tslint.json b/types/d3-zoom/tslint.json index c89636b4b7..26ee29cf50 100644 --- a/types/d3-zoom/tslint.json +++ b/types/d3-zoom/tslint.json @@ -2,7 +2,6 @@ "extends": "dtslint/dt.json", "rules": { // TODO - "no-angle-bracket-type-assertion": false, "no-this-assignment": false, "unified-signatures": false, "no-unnecessary-generics": false diff --git a/types/d3kit/d3kit-tests.ts b/types/d3kit/d3kit-tests.ts index ec3b2de1ce..705b9fcc59 100644 --- a/types/d3kit/d3kit-tests.ts +++ b/types/d3kit/d3kit-tests.ts @@ -304,7 +304,7 @@ function test_svg_chart() { * Test plate functions */ plate = new d3kit.SvgPlate(); - plate = chart.addPlate('a-plate', plate, true); // with doNotAppend + plate = chart.addPlate('a-plate', plate, true) as d3kit.SvgPlate; // with doNotAppend chart = chart.addPlate('a-plate', plate); // without doNotAppend chart = chart.removePlate('a-plate'); @@ -381,7 +381,7 @@ function test_hybrid_chart() { * Test plate functions */ plate = new d3kit.SvgPlate(); - plate = chart.addPlate('a-plate', plate, true); // with doNotAppend + plate = chart.addPlate('a-plate', plate, true) as d3kit.SvgPlate; // with doNotAppend chart = chart.addPlate('a-plate', plate); // without doNotAppend chart = chart.removePlate('a-plate'); diff --git a/types/d3kit/v1/d3kit-tests.ts b/types/d3kit/v1/d3kit-tests.ts index 18f1f144f9..92c20fa35d 100644 --- a/types/d3kit/v1/d3kit-tests.ts +++ b/types/d3kit/v1/d3kit-tests.ts @@ -380,8 +380,8 @@ describe('Skeleton', function(){ b: 2 }); expect(skeleton).to.include.keys(['a', 'b']); - expect((skeleton).a).to.equal(1); - expect((skeleton).b).to.equal(2); + expect((skeleton as any).a).to.equal(1); + expect((skeleton as any).b).to.equal(2); }); it('should overwrite existing fields', function(){ skeleton.mixin({ @@ -391,7 +391,7 @@ describe('Skeleton', function(){ b: 3 }); expect(skeleton).to.include.keys(['b']); - expect((skeleton).b).to.equal(3); + expect((skeleton as any).b).to.equal(3); }); it('should keep original fields if not overwritten', function(){ skeleton.mixin({ @@ -403,9 +403,9 @@ describe('Skeleton', function(){ b: 3 }); expect(skeleton).to.include.keys(['a', 'b', 'c']); - expect((skeleton).a).to.equal(1); - expect((skeleton).b).to.equal(3); - expect((skeleton).c).to.equal(20); + expect((skeleton as any).a).to.equal(1); + expect((skeleton as any).b).to.equal(3); + expect((skeleton as any).c).to.equal(20); }); }); @@ -720,7 +720,7 @@ describe('Chartlet', function(){ beforeEach(function(done){ ChildChartlet = function() { var chartlet = new d3kit.Chartlet(callback, callback, callback); - (chartlet).runTest = function (testFunction: any) { + (chartlet as any).runTest = function (testFunction: any) { testFunction(chartlet); }; return chartlet; @@ -730,7 +730,7 @@ describe('Chartlet', function(){ var chartlet = new d3kit.Chartlet(callback, callback, callback); var child = ChildChartlet(); configureFunction(chartlet, child); - (chartlet).runTest = (child).runTest; + (chartlet as any).runTest = (child as any).runTest; return chartlet; }; @@ -850,7 +850,7 @@ describe('Chartlet', function(){ }) .property('foo', function(d:number) {return 2 * d;}); - (parent).runTest(function(child: d3kit.Chartlet) { + (parent as any).runTest(function(child: d3kit.Chartlet) { expect(child.getPropertyValue('bar', 4, 0)).to.be.equal(8); }); }); @@ -862,7 +862,7 @@ describe('Chartlet', function(){ }) .property('foo', function(d:number) {return 2 * d;}); - (parent).runTest(function(child: d3kit.Chartlet) { + (parent as any).runTest(function(child: d3kit.Chartlet) { expect(child.getPropertyValue('foo', 4, 0)).to.be.equal(8); }); }); @@ -878,7 +878,7 @@ describe('Chartlet', function(){ .property('bar', function(d:number) {return 3 * d;}) .property('baz', function(d:number) {return 4 * d;}); - (parent).runTest(function(child: d3kit.Chartlet) { + (parent as any).runTest(function(child: d3kit.Chartlet) { expect(child.getPropertyValue('foo-x', 1, 0)).to.be.equal(2); expect(child.getPropertyValue('bar-x', 1, 0)).to.be.equal(3); expect(child.getPropertyValue('baz-x', 1, 0)).to.be.equal(4); @@ -894,7 +894,7 @@ describe('Chartlet', function(){ .property('bar', function(d:number) {return 3 * d;}) .property('baz', function(d:number) {return 4 * d;}); - (parent).runTest(function(child: d3kit.Chartlet) { + (parent as any).runTest(function(child: d3kit.Chartlet) { expect(child.getPropertyValue('foo', 1, 0)).to.be.equal(2); expect(child.getPropertyValue('bar', 1, 0)).to.be.equal(3); expect(child.getPropertyValue('baz', 1, 0)).to.be.equal(4); @@ -914,7 +914,7 @@ describe('Chartlet', function(){ var child = new d3kit.Chartlet(callback, callback, callback, ['foo']) .publishEventsTo(parent.getDispatcher()); - (child.getDispatcher()).foo(99); + (child.getDispatcher() as any).foo(99); }); }); }); diff --git a/types/datatables.net/tslint.json b/types/datatables.net/tslint.json index 3db14f85ea..2b6ccb9109 100644 --- a/types/datatables.net/tslint.json +++ b/types/datatables.net/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} \ No newline at end of file diff --git a/types/dd-trace/dd-trace-tests.ts b/types/dd-trace/dd-trace-tests.ts index 9d6936875a..f98a0853cf 100644 --- a/types/dd-trace/dd-trace-tests.ts +++ b/types/dd-trace/dd-trace-tests.ts @@ -2,6 +2,7 @@ import * as tracer from "dd-trace"; import SpanContext = require("dd-trace/src/opentracing/span_context"); tracer.init({ + enabled: true, service: "MyLovelyService", hostname: "localhost", port: 8126, diff --git a/types/dd-trace/index.d.ts b/types/dd-trace/index.d.ts index 311fa7675e..43bfd7183f 100644 --- a/types/dd-trace/index.d.ts +++ b/types/dd-trace/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for dd-trace-js 0.6 +// Type definitions for dd-trace-js 0.7 // Project: https://github.com/DataDog/dd-trace-js // Definitions by: Colin Bradley // Eloy Durán @@ -54,6 +54,12 @@ declare class TraceProxy extends Tracer { } interface TracerOptions { + /** + * Whether to enable the tracer. + * @default true + */ + enabled?: boolean; + /** * Enable debug logging in the tracer. * @default false @@ -185,6 +191,7 @@ declare class Scope { type Plugin = | "amqp10" | "amqplib" + | "bluebird" | "elasticsearch" | "express" | "graphql" @@ -197,8 +204,10 @@ type Plugin = | "mysql" | "mysql2" | "pg" + | "q" | "redis" - | "restify"; + | "restify" + | "when"; interface BasePluginOptions { /** diff --git a/types/debounce-promise/debounce-promise-tests.ts b/types/debounce-promise/debounce-promise-tests.ts new file mode 100644 index 0000000000..75b53dc764 --- /dev/null +++ b/types/debounce-promise/debounce-promise-tests.ts @@ -0,0 +1,25 @@ +import debounce = require("debounce-promise"); +import { DebounceOptions } from "debounce-promise"; + +const options: DebounceOptions = {}; +const optionsA: DebounceOptions = { leading: true }; +const f = async () => 2; +const f2 = (a: string) => 2; +debounce(f, 100); +debounce(f, 0, options); +debounce(f, 100, optionsA); +debounce(f, 10, { accumulate: true }); +const foo = debounce(async () => f2, 10, { + leading: true, + accumulate: true +}); +foo().then(f => f("2")); +const bar = debounce(async () => [1, 2, 3], 100); +bar().then(ar => ar.concat()); + +// Converts the return value from the producer function to a promise +const two = debounce((a: string, b: number, c: { d: boolean }) => [4], 10, { + leading: true, + accumulate: true +}); +two("1", 2, { d: false }).then(ar => ar.pop(), () => 2); diff --git a/types/debounce-promise/index.d.ts b/types/debounce-promise/index.d.ts new file mode 100644 index 0000000000..905ca7fc50 --- /dev/null +++ b/types/debounce-promise/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for debounce-promise 3.1 +// Project: https://github.com/bjoerge/debounce-promise +// Definitions by: Wu Haotian +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +declare namespace debounce { + interface DebounceOptions { + leading?: boolean; + accumulate?: boolean; + } +} + +declare function debounce any>( + func: T, + wait?: number, + options?: debounce.DebounceOptions +): ( + ...args: Parameters +) => ReturnType extends Promise + ? ReturnType + : Promise>; + +export = debounce; diff --git a/types/debounce-promise/tsconfig.json b/types/debounce-promise/tsconfig.json new file mode 100644 index 0000000000..7e41251117 --- /dev/null +++ b/types/debounce-promise/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "debounce-promise-tests.ts"] +} diff --git a/types/debounce-promise/tslint.json b/types/debounce-promise/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/debounce-promise/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/debounce/debounce-tests.ts b/types/debounce/debounce-tests.ts index 4acff7c446..5f0463a4c1 100644 --- a/types/debounce/debounce-tests.ts +++ b/types/debounce/debounce-tests.ts @@ -14,6 +14,9 @@ const imm1: number = (debounce((x: number) => x * 2, 100, true))(2); const clearable = debounce(doThings); clearable.clear(); +const flushable = debounce(doThings); +flushable.flush(); + // Intentionally asserts that the member variable has all the same benefits as the direct export. // Eventually, if debounce stop supporting the CommonJS-only module calling (`require("debounce")(...)`), // we can remove this and change the top import&require to `import { debounce } from "debounce";`. diff --git a/types/debounce/index.d.ts b/types/debounce/index.d.ts index fa244351d6..e561cb51fe 100644 --- a/types/debounce/index.d.ts +++ b/types/debounce/index.d.ts @@ -1,13 +1,15 @@ -// Type definitions for debounce 3.0 +// Type definitions for debounce 1.2 // Project: https://github.com/component/debounce // Definitions by: Denis Sokolov // Josh Goldberg +// Wayne Carson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace _debounce { const debounce: typeof _debounce; } -declare function _debounce
(f: A, interval?: number, immediate?: boolean): A & { clear(): void; }; +declare function _debounce(f: A, interval?: number, immediate?: boolean): A & { clear(): void; } + & { flush(): void }; export = _debounce; diff --git a/types/deprecate/deprecate-tests.ts b/types/deprecate/deprecate-tests.ts new file mode 100644 index 0000000000..3df2257c40 --- /dev/null +++ b/types/deprecate/deprecate-tests.ts @@ -0,0 +1,9 @@ +import deprecate = require('deprecate'); + +deprecate('someMethod'); +deprecate('someMethod', 'This is deprecated'); +deprecate('someMethod', 'This is deprecated', 'foo', 'bar'); + +deprecate.color = '\x1b[31;1m'; +deprecate.silence = true; +deprecate.stream = process.stderr; diff --git a/types/deprecate/index.d.ts b/types/deprecate/index.d.ts new file mode 100644 index 0000000000..a053721ff5 --- /dev/null +++ b/types/deprecate/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for deprecate 1.1 +// Project: https://github.com/brianc/node-deprecate +// Definitions by: Toilal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +declare namespace deprecate { + /** + * Set to false to not output a color. Defaults to '\x1b[31;1m' which is red. + */ + let color: string; + + /** + * Set to false to do nothing at all when the deprecate method is called. Useful in tests of the library you're deprecating things within. + */ + let silence: boolean; + + /** + * The stream to which output is written. Defaults to process.stderr + */ + let stream: NodeJS.WriteStream; +} + +/** + * Call deprecate within a function you are deprecating. + * + * It will spit out all the messages to the console the first time and only the first time the method is called. + */ +declare function deprecate(methodName: string, ...message: string[]): void; + +export = deprecate; diff --git a/types/deprecate/tsconfig.json b/types/deprecate/tsconfig.json new file mode 100644 index 0000000000..75acd6cda6 --- /dev/null +++ b/types/deprecate/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "deprecate-tests.ts" + ] +} diff --git a/types/deprecate/tslint.json b/types/deprecate/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/deprecate/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/detect-browser/detect-browser-tests.ts b/types/detect-browser/detect-browser-tests.ts index 48abb964f8..7453ed044a 100644 --- a/types/detect-browser/detect-browser-tests.ts +++ b/types/detect-browser/detect-browser-tests.ts @@ -1,7 +1,64 @@ -import { detect } from 'detect-browser'; +import { BrowserName, BrowserInfo, detect } from 'detect-browser'; const browser = detect(); if (browser) { - const name: string = browser.name; - const version: string = browser.version; + const name: string | undefined = browser.name; + const version: string | undefined = browser.version; + const os: string | undefined | null = browser.os; + const bot: true | undefined = browser.bot; } + +const browserInfos: BrowserInfo[] = []; + +// Those that can happen when 'detect' hits on a browser + +browserInfos.push( + { + name: "chrome", + version: "1.2.3", + os: null + } +); + +browserInfos.push( + { + name: "edge", + version: "24.5.3", + os: "Sun OS" + } +); + +browserInfos.push( + { + name: "edge", + version: "13.0", + os: "Windows 10", + bot: true + } +); + +// Those that could be returned when it's a bot + +browserInfos.push( + { + name: "facebook", + version: "1.0.2", + os: "Linux", + bot: true + } +); + +browserInfos.push( + { + name: "crios", + version: "2.9.4", + os: undefined, + bot: true + } +); + +browserInfos.push( + { + bot: true + } +); diff --git a/types/detect-browser/index.d.ts b/types/detect-browser/index.d.ts index 22d6bf9c17..943484b013 100644 --- a/types/detect-browser/index.d.ts +++ b/types/detect-browser/index.d.ts @@ -1,30 +1,42 @@ -// Type definitions for detect-browser 2.0 +// Type definitions for detect-browser 3.0 // Project: https://github.com/DamonOehlman/detect-browser // Definitions by: Rogier Schouten -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Brian Caruso +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export {}; export type BrowserName = + "aol" | "android" | "bb10" | "chrome" | "crios" | "edge" | + "facebook" | "firefox" | "fxios" | "ie" | + "instagram" | "ios" | + "ios-webview" | "kakaotalk" | + "node" | "opera" | "phantomjs" | "safari" | + "samsung" | "vivaldi" | - "yandexbrowser" | - "node"; + "yandexbrowser"; export interface BrowserInfo { - name: BrowserName; - version: string; - os: string; + name?: string; + version?: string; + os?: string | null; + bot?: true; } -export function detect(): null | BrowserInfo; +export function detect(): null | false | BrowserInfo; +export function detectOS(userAgentString: string): null | string; +export function parseUserAgent(userAgentString: string): null | BrowserInfo; +export function getNodeVersion(): false | BrowserInfo; diff --git a/types/detect-character-encoding/detect-character-encoding-tests.ts b/types/detect-character-encoding/detect-character-encoding-tests.ts new file mode 100644 index 0000000000..42f21a688e --- /dev/null +++ b/types/detect-character-encoding/detect-character-encoding-tests.ts @@ -0,0 +1,10 @@ +import detectCharacterEncoding = require("detect-character-encoding"); + +const buf: Buffer = null as any; + +const result: detectCharacterEncoding.Result | null = detectCharacterEncoding(buf); + +if (result) { + const str: string = result.encoding; + const num: number = result.confidence; +} diff --git a/types/detect-character-encoding/index.d.ts b/types/detect-character-encoding/index.d.ts new file mode 100644 index 0000000000..123a7659eb --- /dev/null +++ b/types/detect-character-encoding/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for detect-character-encoding 0.7 +// Project: https://github.com/sonicdoe/detect-character-encoding#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = detectCharacterEncoding; + +declare function detectCharacterEncoding(buf: Buffer): detectCharacterEncoding.Result | null; + +declare namespace detectCharacterEncoding { + interface Result { + encoding: string; + confidence: number; + } +} diff --git a/types/detect-character-encoding/tsconfig.json b/types/detect-character-encoding/tsconfig.json new file mode 100644 index 0000000000..e2adad72dd --- /dev/null +++ b/types/detect-character-encoding/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "detect-character-encoding-tests.ts" + ] +} diff --git a/types/detect-character-encoding/tslint.json b/types/detect-character-encoding/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/detect-character-encoding/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/detox/detox-tests.ts b/types/detox/detox-tests.ts deleted file mode 100644 index 58fe5c1912..0000000000 --- a/types/detox/detox-tests.ts +++ /dev/null @@ -1,31 +0,0 @@ -declare var describe: (test: string, callback: () => void) => void; -declare var beforeAll: (callback: () => void) => void; -declare var afterAll: (callback: () => void) => void; -declare var test: (test: string, callback: () => void) => void; - -describe('Test', () => { - beforeAll(async () => { - await device.reloadReactNative(); - }); - - afterAll(async () => { - await element(by.id('element')).clearText(); - }); - - test('Test', async () => { - await element(by.id('element')).replaceText('text'); - await element(by.id('element')).tap(); - await element(by.id('element')).scroll(50, 'down'); - await element(by.id('scrollView')).scrollTo('bottom'); - await expect(element(by.id('element')).atIndex(0)).toNotExist(); - await element(by.id('scrollView')).swipe('down', 'fast'); - await element(by.type('UIPickerView')).setColumnToValue(1, "6"); - - await expect(element(by.id('element').withAncestor(by.id('parent_element')))).toNotExist(); - await expect(element(by.id('element').withDescendant(by.id('child_element')))).toNotExist(); - - await waitFor(element(by.id('element'))).toBeVisible().withTimeout(2000); - await device.pressBack(); - await waitFor(element(by.text('Text5'))).toBeVisible().whileElement(by.id('ScrollView630')).scroll(50, 'down'); - }); -}); diff --git a/types/detox/index.d.ts b/types/detox/index.d.ts index a7bfa12bca..de74163bf1 100644 --- a/types/detox/index.d.ts +++ b/types/detox/index.d.ts @@ -3,428 +3,435 @@ // Definitions by: Tareq El-Masri , Steve Chun // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare const detox: Detox.Detox; -declare const device: Detox.Device; -declare const element: Detox.Element; -declare const waitFor: Detox.WaitFor; -declare const expect: Detox.Expect>; -declare const by: Detox.Matchers; +declare global { + const detox: Detox.Detox; + const device: Detox.Device; + const element: Detox.Element; + const waitFor: Detox.WaitFor; + const expect: Detox.Expect>; + const by: Detox.Matchers; -declare namespace Detox { - interface Detox { - /** - * The setup phase happens inside detox.init(). This is the phase where detox reads its configuration, starts a server, loads its expection library and starts a simulator - * @param config - * @param options - * @example const config = require('../package.json').detox; - * - * before(async () => { - * await detox.init(config); - * }); - */ - init(config: any, options?: DetoxInitOptions): Promise; - /** - * Artifacts currently include only logs from the app process before each task - * @param args - */ - beforeEach(...args: any[]): Promise; - /** - * Artifacts currently include only logs from the app process after each task - * @param args - */ - afterEach(...args: any[]): Promise; - /** - * The cleanup phase should happen after all the tests have finished. This is the phase where detox-server shuts down. - * @example after(async () => { - * await detox.cleanup(); - * }); - */ - cleanup(): Promise; - } - interface Device { - /** - * Launch the app - * @param config - * @example // Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, - * // if the app isn't running, it will launch a new instance. default is false - * await device.launchApp({newInstance: true}); - * // Grant or deny runtime permissions for your application. - * await device.launchApp({permissions: {calendar: 'YES'}}); - * // Mock opening the app from URL to test your app's deep link handling mechanism. - * await device.launchApp({url: url}); - */ - launchApp(config: DeviceLanchAppConfig): Promise; - /** - * By default, terminateApp() with no params will terminate the app - * To terminate another app, specify its bundle id - * @param bundle - * @example await device.terminateApp('other.bundle.id'); - */ - terminateApp(bundle?: string): Promise; - /** - * Send application to background by bringing com.apple.springboard to the foreground. - * Combining sendToHome() with launchApp({newInstance: false}) will simulate app coming back from background. - * @example await device.sendToHome(); - * await device.launchApp({newInstance: false}); - */ - sendToHome(): Promise; - /** - * If this is a React Native app, reload the React Native JS bundle. This action is much faster than device.launchApp(), and can be used if you just need to reset your React Native logic. - * @example await device.reloadReactNative() - */ - reloadReactNative(): Promise; - /** - * By default, installApp() with no params will install the app file defined in the current configuration. - * To install another app, specify its path - * @param path - * @example await device.installApp('path/to/other/app'); - */ - installApp(path?: any): Promise; - /** - * By default, uninstallApp() with no params will uninstall the app defined in the current configuration. - * To uninstall another app, specify its bundle id - * @param bundle - * @example await device.installApp('other.bundle.id'); - */ - uninstallApp(bundle?: string): Promise; - /** - * Mock opening the app from URL. sourceApp is an optional parameter to specify source application bundle id. - * @param url - */ - openURL(url: {url: string, sourceApp?: string}): Promise; - /** - * Mock handling of received user notification when app is in foreground. - * @param params - */ - sendUserNotification(...params: any[]): Promise; - /** - * Mock handling of received user activity when app is in foreground. - * @param params - */ - sendUserActivity(...params: any[]): Promise; - /** - * Takes "portrait" or "landscape" and rotates the device to the given orientation. Currently only available in the iOS Simulator. - * @param orientation - */ - setOrientation(orientation: Orientation): Promise; - /** - * Note: setLocation is dependent on fbsimctl. if fbsimctl is not installed, the command will fail, it must be installed. Sets the simulator location to the given latitude and longitude. - * @param lat - * @param lon - * @example await device.setLocation(32.0853, 34.7818); - */ - setLocation(lat: number, lon: number): Promise; - /** - * Disable EarlGrey's network synchronization mechanism on preffered endpoints. Usful if you want to on skip over synchronizing on certain URLs. - * @param urls - * @example await device.setURLBlacklist(['.*127.0.0.1.*']); - */ - setURLBlacklist(urls: string[]): Promise; - /** - * Enable EarlGrey's synchronization mechanism (enabled by default). This is being reset on every new instance of the app. - * @example await device.enableSynchronization(); - */ - enableSynchronization(): Promise; - /** - * Disable EarlGrey's synchronization mechanism (enabled by default) This is being reset on every new instance of the app. - * @example await device.disableSynchronization(); - */ - disableSynchronization(): Promise; - /** - * Resets the Simulator to clean state (like the Simulator > Reset Content and Settings... menu item), especially removing previously set permissions. - * @example await device.resetContentAndSettings(); - */ - resetContentAndSettings(): Promise; - /** - * Returns the current device, ios or android. - * @example if (device.getPlatform() === 'ios') { - * await expect(loopSwitch).toHaveValue('1'); - * } - */ - getPlatform(): "ios" | "android"; - /** - * Simulate press back button (Android Only) - */ - pressBack(): Promise; - /** - * Simulate shake (iOS Only) - */ - shake(): Promise; - } + namespace Detox { + interface Detox { + /** + * The setup phase happens inside detox.init(). This is the phase where detox reads its configuration, starts a server, loads its expection library and starts a simulator + * @param config + * @param options + * @example const config = require('../package.json').detox; + * + * before(async () => { + * await detox.init(config); + * }); + */ + init(config: any, options?: DetoxInitOptions): Promise; + /** + * Artifacts currently include only logs from the app process before each task + * @param args + */ + beforeEach(...args: any[]): Promise; + /** + * Artifacts currently include only logs from the app process after each task + * @param args + */ + afterEach(...args: any[]): Promise; + /** + * The cleanup phase should happen after all the tests have finished. This is the phase where detox-server shuts down. + * @example after(async () => { + * await detox.cleanup(); + * }); + */ + cleanup(): Promise; + } + interface Device { + /** + * Launch the app + * @param config + * @example // Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, + * // if the app isn't running, it will launch a new instance. default is false + * await device.launchApp({newInstance: true}); + * // Grant or deny runtime permissions for your application. + * await device.launchApp({permissions: {calendar: 'YES'}}); + * // Mock opening the app from URL to test your app's deep link handling mechanism. + * await device.launchApp({url: url}); + */ + launchApp(config: DeviceLanchAppConfig): Promise; + /** + * By default, terminateApp() with no params will terminate the app + * To terminate another app, specify its bundle id + * @param bundle + * @example await device.terminateApp('other.bundle.id'); + */ + terminateApp(bundle?: string): Promise; + /** + * Send application to background by bringing com.apple.springboard to the foreground. + * Combining sendToHome() with launchApp({newInstance: false}) will simulate app coming back from background. + * @example await device.sendToHome(); + * await device.launchApp({newInstance: false}); + */ + sendToHome(): Promise; + /** + * If this is a React Native app, reload the React Native JS bundle. This action is much faster than device.launchApp(), and can be used if you just need to reset your React Native logic. + * @example await device.reloadReactNative() + */ + reloadReactNative(): Promise; + /** + * By default, installApp() with no params will install the app file defined in the current configuration. + * To install another app, specify its path + * @param path + * @example await device.installApp('path/to/other/app'); + */ + installApp(path?: any): Promise; + /** + * By default, uninstallApp() with no params will uninstall the app defined in the current configuration. + * To uninstall another app, specify its bundle id + * @param bundle + * @example await device.installApp('other.bundle.id'); + */ + uninstallApp(bundle?: string): Promise; + /** + * Mock opening the app from URL. sourceApp is an optional parameter to specify source application bundle id. + * @param url + */ + openURL(url: { url: string; sourceApp?: string }): Promise; + /** + * Mock handling of received user notification when app is in foreground. + * @param params + */ + sendUserNotification(...params: any[]): Promise; + /** + * Mock handling of received user activity when app is in foreground. + * @param params + */ + sendUserActivity(...params: any[]): Promise; + /** + * Takes "portrait" or "landscape" and rotates the device to the given orientation. Currently only available in the iOS Simulator. + * @param orientation + */ + setOrientation(orientation: Orientation): Promise; + /** + * Note: setLocation is dependent on fbsimctl. if fbsimctl is not installed, the command will fail, it must be installed. Sets the simulator location to the given latitude and longitude. + * @param lat + * @param lon + * @example await device.setLocation(32.0853, 34.7818); + */ + setLocation(lat: number, lon: number): Promise; + /** + * Disable EarlGrey's network synchronization mechanism on preffered endpoints. Usful if you want to on skip over synchronizing on certain URLs. + * @param urls + * @example await device.setURLBlacklist(['.*127.0.0.1.*']); + */ + setURLBlacklist(urls: string[]): Promise; + /** + * Enable EarlGrey's synchronization mechanism (enabled by default). This is being reset on every new instance of the app. + * @example await device.enableSynchronization(); + */ + enableSynchronization(): Promise; + /** + * Disable EarlGrey's synchronization mechanism (enabled by default) This is being reset on every new instance of the app. + * @example await device.disableSynchronization(); + */ + disableSynchronization(): Promise; + /** + * Resets the Simulator to clean state (like the Simulator > Reset Content and Settings... menu item), especially removing previously set permissions. + * @example await device.resetContentAndSettings(); + */ + resetContentAndSettings(): Promise; + /** + * Returns the current device, ios or android. + * @example if (device.getPlatform() === 'ios') { + * await expect(loopSwitch).toHaveValue('1'); + * } + */ + getPlatform(): "ios" | "android"; + /** + * Simulate press back button (Android Only) + */ + pressBack(): Promise; + /** + * Simulate shake (iOS Only) + */ + shake(): Promise; + } - type DetoxAny = Element & Actions & WaitFor; + type DetoxAny = Element & Actions & WaitFor; - interface Element { - (by: Matchers): DetoxAny; + interface Element { + (by: Matchers): DetoxAny; - /** - * Choose from multiple elements matching the same matcher using index - * @param index - * @example await element(by.text('Product')).atIndex(2); - */ - atIndex(index: number): DetoxAny; - } - interface Matchers { - (by: Matchers): Matchers; + /** + * Choose from multiple elements matching the same matcher using index + * @param index + * @example await element(by.text('Product')).atIndex(2); + */ + atIndex(index: number): DetoxAny; + } + interface Matchers { + (by: Matchers): Matchers; - /** - * by.id will match an id that is given to the view via testID prop. - * @param id - * @example // In a React Native component add testID like so: - * - * // Then match with by.id: - * await element(by.id('tap_me')); - */ - id(id: string): Matchers; - /** - * Find an element by text, useful for text fields, buttons. - * @param text - * @example await element(by.text('Tap Me')); - */ - text(text: string): Matchers; - /** - * Find an element by accessibilityLabel on iOS, or by contentDescription on Android. - * @param label - * @example await element(by.label('Welcome')); - */ - label(label: string): Matchers; - /** - * Find an element by native view type. - * @param nativeViewType - * @example await element(by.type('RCTImageView')); - */ - type(nativeViewType: string): Matchers; - /** - * Find an element with an accessibility trait. (iOS only) - * @example await element(by.traits(['button'])); - */ - traits(traits: string[]): Matchers; - /** - * Find an element by a matcher with a parent matcher - * @param parentBy - * @example await element(by.id('Grandson883').withAncestor(by.id('Son883'))); - */ - withAncestor(parentBy: Matchers): Matchers; - /** - * Find an element by a matcher with a child matcher - * @param childBy - * @example await element(by.id('Son883').withDescendant(by.id('Grandson883'))); - */ - withDescendant(childBy: Matchers): Matchers; - /** - * Find an element by multiple matchers - * @param by - * @example await element(by.text('Product').and(by.id('product_name')); - */ - and(by: Matchers): Matchers; - } - interface Expect { - (element: Element): Expect; - /** - * Expect the view to be at least 75% visible. - * @example await expect(element(by.id('UniqueId204'))).toBeVisible(); - */ - toBeVisible(): R; - /** - * Expect the view to not be visible. - * @example await expect(element(by.id('UniqueId205'))).toBeNotVisible(); - */ - toBeNotVisible(): R; - /** - * Expect the view to exist in the UI hierarchy. - * @example await expect(element(by.id('UniqueId205'))).toExist(); - */ - toExist(): R; - /** - * Expect the view to not exist in the UI hierarchy. - * @example await expect(element(by.id('RandomJunk959'))).toNotExist(); - */ - toNotExist(): R; - /** - * In React Native apps, expect UI component of type to have text. - * In native iOS apps, expect UI elements of type UIButton, UILabel, UITextField or UITextViewIn to have inputText with text. - * @param text - * @example await expect(element(by.id('UniqueId204'))).toHaveText('I contain some text'); - */ - toHaveText(text: string): R; - /** - * It searches by accessibilityLabel on iOS, or by contentDescription on Android. - * In React Native it can be set for both platforms by defining an accessibilityLabel on the view. - * @param label - * @example await expect(element(by.id('UniqueId204'))).toHaveLabel('Done'); - */ - toHaveLabel(label: string): R; - /** - * In React Native apps, expect UI component to have testID with that id. - * In native iOS apps, expect UI element to have accesibilityIdentifier with that id. - * @param id - * @example await expect(element(by.text('I contain some text'))).toHaveId('UniqueId204'); - */ - toHaveId(id: string): R; - /** - * Expect components like a Switch to have a value ('0' for off, '1' for on). - * @param value - * @example await expect(element(by.id('UniqueId533'))).toHaveValue('0'); - */ - toHaveValue(value: any): R; - } - interface WaitFor { - /** - * This API polls using the given expectation continuously until the expectation is met. Use manual synchronization with waitFor only as a last resort. - * NOTE: Every waitFor call must set a timeout using withTimeout(). Calling waitFor without setting a timeout will do nothing. - * @example await waitFor(element(by.id('UniqueId336'))).toExist().withTimeout(2000); - */ - (element: Element): Expect; - /** - * Waits for the condition to be met until the specified time (millis) have elapsed. - * @param millis number - * @example await waitFor(element(by.id('UniqueId336'))).toExist().withTimeout(2000); - */ - withTimeout(millis: number): Promise; - /** - * Performs the action repeatedly on the element until an expectation is met - * @param by - * @example await waitFor(element(by.text('Text5'))).toBeVisible().whileElement(by.id('ScrollView630')).scroll(50, 'down'); - */ - whileElement(by: Matchers): DetoxAny; - } - interface Actions { - /** - * Simulate tap on an element - * @example await element(by.id('tappable')).tap(); - */ - tap(): Promise>; - /** - * Simulate long press on an element - * @example await element(by.id('tappable')).longPress(); - */ - longPress(): Promise>; - /** - * Simulate multiple taps on an element. - * @param times number - * @example await element(by.id('tappable')).multiTap(3); - */ - multiTap(times: number): Promise>; - /** - * Simulate tap at a specific point on an element. - * Note: The point coordinates are relative to the matched element and the element size could changes on different devices or even when changing the device font size. - * @param point - * @example await element(by.id('tappable')).tapAtPoint({ x:5, y:10 }); - */ - tapAtPoint(point: { x: number, y: number }): Promise>; - /** - * Use the builtin keyboard to type text into a text field. - * @param text - * @example await element(by.id('textField')).typeText('passcode'); - */ - typeText(text: string): Promise>; - /** - * Paste text into a text field. - * @param text - * @example await element(by.id('textField')).replaceText('passcode again'); - */ - replaceText(text: string): Promise>; - /** - * Clear text from a text field. - * @example await element(by.id('textField')).clearText(); - */ - clearText(): Promise>; - /** - * - * @param pixels - * @param direction - * @example - * await element(by.id('scrollView')).scroll(100, 'down'); - * await element(by.id('scrollView')).scroll(100, 'up'); - */ - scroll(pixels: number, direction: Direction): Promise>; - /** - * Scroll to edge. - * @param edge - * @example await element(by.id('scrollView')).scrollTo('bottom'); - * await element(by.id('scrollView')).scrollTo('top'); - */ - scrollTo(edge: Direction): Promise>; - /** - * - * @param direction - * @param speed - * @param percentage - * @example await element(by.id('scrollView')).swipe('down'); - * await element(by.id('scrollView')).swipe('down', 'fast'); - * await element(by.id('scrollView')).swipe('down', 'fast', 0.5); - */ - swipe(direction: Direction, speed?: Speed, percentage?: number): Promise>; - /** - * (iOS Only) column - number of datepicker column (starts from 0) value - string value in setted column (must be correct) - * @param column - * @param value - * @example await expect(element(by.type('UIPickerView'))).toBeVisible(); - * await element(by.type('UIPickerView')).setColumnToValue(1,"6"); - * await element(by.type('UIPickerView')).setColumnToValue(2,"34"); - */ - setColumnToValue(column: number, value: string): Promise>; - } + /** + * by.id will match an id that is given to the view via testID prop. + * @param id + * @example // In a React Native component add testID like so: + * + * // Then match with by.id: + * await element(by.id('tap_me')); + */ + id(id: string): Matchers; + /** + * Find an element by text, useful for text fields, buttons. + * @param text + * @example await element(by.text('Tap Me')); + */ + text(text: string): Matchers; + /** + * Find an element by accessibilityLabel on iOS, or by contentDescription on Android. + * @param label + * @example await element(by.label('Welcome')); + */ + label(label: string): Matchers; + /** + * Find an element by native view type. + * @param nativeViewType + * @example await element(by.type('RCTImageView')); + */ + type(nativeViewType: string): Matchers; + /** + * Find an element with an accessibility trait. (iOS only) + * @example await element(by.traits(['button'])); + */ + traits(traits: string[]): Matchers; + /** + * Find an element by a matcher with a parent matcher + * @param parentBy + * @example await element(by.id('Grandson883').withAncestor(by.id('Son883'))); + */ + withAncestor(parentBy: Matchers): Matchers; + /** + * Find an element by a matcher with a child matcher + * @param childBy + * @example await element(by.id('Son883').withDescendant(by.id('Grandson883'))); + */ + withDescendant(childBy: Matchers): Matchers; + /** + * Find an element by multiple matchers + * @param by + * @example await element(by.text('Product').and(by.id('product_name')); + */ + and(by: Matchers): Matchers; + } + interface Expect { + (element: Element): Expect; + /** + * Expect the view to be at least 75% visible. + * @example await expect(element(by.id('UniqueId204'))).toBeVisible(); + */ + toBeVisible(): R; + /** + * Expect the view to not be visible. + * @example await expect(element(by.id('UniqueId205'))).toBeNotVisible(); + */ + toBeNotVisible(): R; + /** + * Expect the view to exist in the UI hierarchy. + * @example await expect(element(by.id('UniqueId205'))).toExist(); + */ + toExist(): R; + /** + * Expect the view to not exist in the UI hierarchy. + * @example await expect(element(by.id('RandomJunk959'))).toNotExist(); + */ + toNotExist(): R; + /** + * In React Native apps, expect UI component of type to have text. + * In native iOS apps, expect UI elements of type UIButton, UILabel, UITextField or UITextViewIn to have inputText with text. + * @param text + * @example await expect(element(by.id('UniqueId204'))).toHaveText('I contain some text'); + */ + toHaveText(text: string): R; + /** + * It searches by accessibilityLabel on iOS, or by contentDescription on Android. + * In React Native it can be set for both platforms by defining an accessibilityLabel on the view. + * @param label + * @example await expect(element(by.id('UniqueId204'))).toHaveLabel('Done'); + */ + toHaveLabel(label: string): R; + /** + * In React Native apps, expect UI component to have testID with that id. + * In native iOS apps, expect UI element to have accesibilityIdentifier with that id. + * @param id + * @example await expect(element(by.text('I contain some text'))).toHaveId('UniqueId204'); + */ + toHaveId(id: string): R; + /** + * Expect components like a Switch to have a value ('0' for off, '1' for on). + * @param value + * @example await expect(element(by.id('UniqueId533'))).toHaveValue('0'); + */ + toHaveValue(value: any): R; + } + interface WaitFor { + /** + * This API polls using the given expectation continuously until the expectation is met. Use manual synchronization with waitFor only as a last resort. + * NOTE: Every waitFor call must set a timeout using withTimeout(). Calling waitFor without setting a timeout will do nothing. + * @example await waitFor(element(by.id('UniqueId336'))).toExist().withTimeout(2000); + */ + (element: Element): Expect; + /** + * Waits for the condition to be met until the specified time (millis) have elapsed. + * @param millis number + * @example await waitFor(element(by.id('UniqueId336'))).toExist().withTimeout(2000); + */ + withTimeout(millis: number): Promise; + /** + * Performs the action repeatedly on the element until an expectation is met + * @param by + * @example await waitFor(element(by.text('Text5'))).toBeVisible().whileElement(by.id('ScrollView630')).scroll(50, 'down'); + */ + whileElement(by: Matchers): DetoxAny; + } + interface Actions { + /** + * Simulate tap on an element + * @example await element(by.id('tappable')).tap(); + */ + tap(): Promise>; + /** + * Simulate long press on an element + * @example await element(by.id('tappable')).longPress(); + */ + longPress(): Promise>; + /** + * Simulate multiple taps on an element. + * @param times number + * @example await element(by.id('tappable')).multiTap(3); + */ + multiTap(times: number): Promise>; + /** + * Simulate tap at a specific point on an element. + * Note: The point coordinates are relative to the matched element and the element size could changes on different devices or even when changing the device font size. + * @param point + * @example await element(by.id('tappable')).tapAtPoint({ x:5, y:10 }); + */ + tapAtPoint(point: { x: number; y: number }): Promise>; + /** + * Use the builtin keyboard to type text into a text field. + * @param text + * @example await element(by.id('textField')).typeText('passcode'); + */ + typeText(text: string): Promise>; + /** + * Paste text into a text field. + * @param text + * @example await element(by.id('textField')).replaceText('passcode again'); + */ + replaceText(text: string): Promise>; + /** + * Clear text from a text field. + * @example await element(by.id('textField')).clearText(); + */ + clearText(): Promise>; + /** + * + * @param pixels + * @param direction + * @example + * await element(by.id('scrollView')).scroll(100, 'down'); + * await element(by.id('scrollView')).scroll(100, 'up'); + */ + scroll(pixels: number, direction: Direction): Promise>; + /** + * Scroll to edge. + * @param edge + * @example await element(by.id('scrollView')).scrollTo('bottom'); + * await element(by.id('scrollView')).scrollTo('top'); + */ + scrollTo(edge: Direction): Promise>; + /** + * + * @param direction + * @param speed + * @param percentage + * @example await element(by.id('scrollView')).swipe('down'); + * await element(by.id('scrollView')).swipe('down', 'fast'); + * await element(by.id('scrollView')).swipe('down', 'fast', 0.5); + */ + swipe( + direction: Direction, + speed?: Speed, + percentage?: number + ): Promise>; + /** + * (iOS Only) column - number of datepicker column (starts from 0) value - string value in setted column (must be correct) + * @param column + * @param value + * @example await expect(element(by.type('UIPickerView'))).toBeVisible(); + * await element(by.type('UIPickerView')).setColumnToValue(1,"6"); + * await element(by.type('UIPickerView')).setColumnToValue(2,"34"); + */ + setColumnToValue( + column: number, + value: string + ): Promise>; + } - type Direction = "left" | "right" | "top" | "bottom" | "up" | "down"; - type Orientation = "portrait" | "landscape"; - type Speed = "fast" | "slow"; - - interface LanguageAndLocale { - language?: string; - locale?: string; - } - - interface DetoxInitOptions { - /** - * Detox exports device, expect, element, by and waitFor as globals by default, if you want to control their initialization manually, set init detox with initGlobals set to false. - * This is useful when during E2E tests you also need to run regular expectations in node. jest Expect for instance, will not be overriden by Detox when this option is used. - */ - initGlobals?: boolean; - /** - * By default await detox.init(config); will launch the installed app. If you wish to control when your app is launched, add {launchApp: false} param to your init. - */ - launchApp?: boolean; - } - - interface DeviceLanchAppConfig { - /** - * Restart the app - * Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, if the app isn't running, it will launch a new instance. default is false - */ - newInstance?: boolean; - /** - * Set runtime permissions - * Grant or deny runtime permissions for your application. - */ - permissions?: any; - /** - * Launch from URL - * Mock opening the app from URL to test your app's deep link handling mechanism. - */ - url?: any; - /** - * Launch with user notifications - */ - userNotification?: any; - /** - * Launch with user activity - */ - userActivity?: any; - /** - * Launch into a fresh installation - * A flag that enables relaunching into a fresh installation of the app (it will uninstall and install the binary again), default is false. - */ - delete?: boolean; - /** - * Detox can start the app with additional launch arguments - * The added launchArgs will be passed through the launch command to the device and be accessible via [[NSProcessInfo processInfo] arguments] - */ - launchArgs?: any; - - /** - * Launch config for specifying the native language and locale - */ - languageAndLocale?: LanguageAndLocale; + type Direction = "left" | "right" | "top" | "bottom" | "up" | "down"; + type Orientation = "portrait" | "landscape"; + type Speed = "fast" | "slow"; + interface LanguageAndLocale { + language?: string; + locale?: string; + } + interface DetoxInitOptions { + /** + * Detox exports device, expect, element, by and waitFor as globals by default, if you want to control their initialization manually, set init detox with initGlobals set to false. + * This is useful when during E2E tests you also need to run regular expectations in node. jest Expect for instance, will not be overriden by Detox when this option is used. + */ + initGlobals?: boolean; + /** + * By default await detox.init(config); will launch the installed app. If you wish to control when your app is launched, add {launchApp: false} param to your init. + */ + launchApp?: boolean; + } + interface DeviceLanchAppConfig { + /** + * Restart the app + * Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, if the app isn't running, it will launch a new instance. default is false + */ + newInstance?: boolean; + /** + * Set runtime permissions + * Grant or deny runtime permissions for your application. + */ + permissions?: any; + /** + * Launch from URL + * Mock opening the app from URL to test your app's deep link handling mechanism. + */ + url?: any; + /** + * Launch with user notifications + */ + userNotification?: any; + /** + * Launch with user activity + */ + userActivity?: any; + /** + * Launch into a fresh installation + * A flag that enables relaunching into a fresh installation of the app (it will uninstall and install the binary again), default is false. + */ + delete?: boolean; + /** + * Detox can start the app with additional launch arguments + * The added launchArgs will be passed through the launch command to the device and be accessible via [[NSProcessInfo processInfo] arguments] + */ + launchArgs?: any; + /** + * Launch config for specifying the native language and locale + */ + languageAndLocale?: LanguageAndLocale; + } } } + +export { by, detox, device, element, expect, waitFor }; diff --git a/types/detox/runners/jest/adapters/index.d.ts b/types/detox/runners/jest/adapters/index.d.ts new file mode 100644 index 0000000000..ca195ae744 --- /dev/null +++ b/types/detox/runners/jest/adapters/index.d.ts @@ -0,0 +1,9 @@ +interface DetoxJestAdapter { + detox: Detox.Detox; + beforeEach: () => Promise; + afterAll: () => Promise; +} + +declare const adapter: DetoxJestAdapter; + +export default adapter; diff --git a/types/detox/runners/mocha/adapters/index.d.ts b/types/detox/runners/mocha/adapters/index.d.ts new file mode 100644 index 0000000000..8e13b3bc01 --- /dev/null +++ b/types/detox/runners/mocha/adapters/index.d.ts @@ -0,0 +1,9 @@ +interface DetoxMochaAdapter { + detox: Detox.Detox; + beforeEach: (context: any) => Promise; + afterEach: (context: any) => Promise; +} + +declare const adapter: DetoxMochaAdapter; + +export default adapter; diff --git a/types/detox/test/detox-global-tests.ts b/types/detox/test/detox-global-tests.ts new file mode 100644 index 0000000000..42415c548d --- /dev/null +++ b/types/detox/test/detox-global-tests.ts @@ -0,0 +1,40 @@ +declare var describe: (test: string, callback: () => void) => void; +declare var beforeAll: (callback: () => void) => void; +declare var afterAll: (callback: () => void) => void; +declare var test: (test: string, callback: () => void) => void; + +describe("Test", () => { + beforeAll(async () => { + await device.reloadReactNative(); + }); + + afterAll(async () => { + await element(by.id("element")).clearText(); + }); + + test("Test", async () => { + await element(by.id("element")).replaceText("text"); + await element(by.id("element")).tap(); + await element(by.id("element")).scroll(50, "down"); + await element(by.id("scrollView")).scrollTo("bottom"); + await expect(element(by.id("element")).atIndex(0)).toNotExist(); + await element(by.id("scrollView")).swipe("down", "fast"); + await element(by.type("UIPickerView")).setColumnToValue(1, "6"); + + await expect( + element(by.id("element").withAncestor(by.id("parent_element"))) + ).toNotExist(); + await expect( + element(by.id("element").withDescendant(by.id("child_element"))) + ).toNotExist(); + + await waitFor(element(by.id("element"))) + .toBeVisible() + .withTimeout(2000); + await device.pressBack(); + await waitFor(element(by.text("Text5"))) + .toBeVisible() + .whileElement(by.id("ScrollView630")) + .scroll(50, "down"); + }); +}); diff --git a/types/detox/test/detox-jest-setup-tests.ts b/types/detox/test/detox-jest-setup-tests.ts new file mode 100644 index 0000000000..002b5605bb --- /dev/null +++ b/types/detox/test/detox-jest-setup-tests.ts @@ -0,0 +1,28 @@ +declare var beforeAll: (callback: () => void) => void; +declare var beforeEach: (callback: () => void) => void; +declare var afterAll: (callback: () => void) => void; + +import adapter from "detox/runners/jest/adapters"; + +// Normally the Detox configuration from the project's package.json like so: +// const config = require("./package.json").detox; +declare const config: any; + +beforeAll(async () => { + await detox.init(config); + + const initOptions: Detox.DetoxInitOptions = { + initGlobals: false, + launchApp: false, + }; + await detox.init(config, initOptions); +}); + +beforeEach(async () => { + await adapter.beforeEach(); +}); + +afterAll(async () => { + await adapter.afterAll(); + await detox.cleanup(); +}); diff --git a/types/detox/test/detox-mocha-setup-tests.ts b/types/detox/test/detox-mocha-setup-tests.ts new file mode 100644 index 0000000000..3f502d1391 --- /dev/null +++ b/types/detox/test/detox-mocha-setup-tests.ts @@ -0,0 +1,32 @@ +// tslint:disable:only-arrow-functions + +declare var before: (callback: () => void) => void; +declare var beforeEach: (callback: () => void) => void; +declare var after: (callback: () => void) => void; +declare var afterEach: (callback: () => void) => void; + +import adapter from "detox/runners/mocha/adapters"; + +// Normally the Detox configuration from the project's package.json like so: +// const config = require("./package.json").detox; +declare const config: any; + +// Normally, the beforeEach and afterEach function should take `this` as its argument, +// but `this` cannot be used since it doesn't have a type signature (and therefore always implicltly any) +declare const context: any; + +before(async function() { + await detox.init(config); +}); + +beforeEach(async function() { + await adapter.beforeEach(context); +}); + +afterEach(async function() { + await adapter.afterEach(context); +}); + +after(async function() { + await detox.cleanup(); +}); diff --git a/types/detox/test/detox-module-tests.ts b/types/detox/test/detox-module-tests.ts new file mode 100644 index 0000000000..318569c03d --- /dev/null +++ b/types/detox/test/detox-module-tests.ts @@ -0,0 +1,42 @@ +declare var describe: (test: string, callback: () => void) => void; +declare var beforeAll: (callback: () => void) => void; +declare var afterAll: (callback: () => void) => void; +declare var test: (test: string, callback: () => void) => void; + +import { by, device, element, expect, waitFor } from "detox"; + +describe("Test", () => { + beforeAll(async () => { + await device.reloadReactNative(); + }); + + afterAll(async () => { + await element(by.id("element")).clearText(); + }); + + test("Test", async () => { + await element(by.id("element")).replaceText("text"); + await element(by.id("element")).tap(); + await element(by.id("element")).scroll(50, "down"); + await element(by.id("scrollView")).scrollTo("bottom"); + await expect(element(by.id("element")).atIndex(0)).toNotExist(); + await element(by.id("scrollView")).swipe("down", "fast"); + await element(by.type("UIPickerView")).setColumnToValue(1, "6"); + + await expect( + element(by.id("element").withAncestor(by.id("parent_element"))) + ).toNotExist(); + await expect( + element(by.id("element").withDescendant(by.id("child_element"))) + ).toNotExist(); + + await waitFor(element(by.id("element"))) + .toBeVisible() + .withTimeout(2000); + await device.pressBack(); + await waitFor(element(by.text("Text5"))) + .toBeVisible() + .whileElement(by.id("ScrollView630")) + .scroll(50, "down"); + }); +}); diff --git a/types/detox/tsconfig.json b/types/detox/tsconfig.json index 2d1a22fb79..7be4d3bb9e 100644 --- a/types/detox/tsconfig.json +++ b/types/detox/tsconfig.json @@ -1,24 +1,25 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6" - ], + "lib": ["es6"], "target": "ES2015", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", - "detox-tests.ts" + "runners/jest/adapters/index.d.ts", + "runners/mocha/adapters/index.d.ts", + "test/detox-global-tests.ts", + "test/detox-module-tests.ts", + "test/detox-jest-setup-tests.ts", + "test/detox-mocha-setup-tests.ts" ] } diff --git a/types/devexpress-web/v172/tslint.json b/types/devexpress-web/v172/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/devexpress-web/v172/tslint.json +++ b/types/devexpress-web/v172/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/devexpress-web/v181/tslint.json b/types/devexpress-web/v181/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/devexpress-web/v181/tslint.json +++ b/types/devexpress-web/v181/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/dhtmlxgantt/dhtmlxgantt-tests.ts b/types/dhtmlxgantt/dhtmlxgantt-tests.ts index 6ea32b509d..e31665d486 100644 --- a/types/dhtmlxgantt/dhtmlxgantt-tests.ts +++ b/types/dhtmlxgantt/dhtmlxgantt-tests.ts @@ -28,10 +28,12 @@ gantt.locale.labels.new_task = "New task"; gantt.init("scheduler_here", start); gantt.load("/data/events"); +const wbs: string = gantt.getWBSCode(gantt.getTask(1)); + //events gantt.attachEvent("onBeforeLightbox", function (id?: string) { gantt.showTask(id); }); //gantt enterprise var gantt2 = Gantt.getGanttInstance(); -gantt2.config.api_date = "format"; +gantt2.config.xml_date = "format"; diff --git a/types/dhtmlxgantt/index.d.ts b/types/dhtmlxgantt/index.d.ts index 79d02cc181..f2e322b0e3 100644 --- a/types/dhtmlxgantt/index.d.ts +++ b/types/dhtmlxgantt/index.d.ts @@ -1,18 +1,12 @@ -// Type definitions for dhtmlxGantt 4.0.0 -// Project: http://dhtmlx.com/docs/products/dhtmlxGantt +// Type definitions for dhtmlxGantt 6.0.0 +// Project: https://dhtmlx.com/docs/products/dhtmlxGantt // Definitions by: Maksim Kozhukh , Christophe Camicas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - type GanttCallback = (...args: any[]) => any; -type GanttEventName = 'onAfterAutoSchedule'|'onAfterBatchUpdate'|'onAfterLightbox'|'onAfterLinkAdd'|'onAfterLinkDelete'|'onAfterLinkUpdate'|'onAfterRedo'|'onAfterTaskAdd'|'onAfterTaskAutoSchedule'|'onAfterTaskDelete'|'onAfterTaskDrag'|'onAfterTaskMove'|'onAfterTaskUpdate'|'onAfterUndo'|'onAjaxError'|'onBeforeAutoSchedule'|'onBeforeBatchUpdate'|'onBeforeCollapse'|'onBeforeDataRender'|'onBeforeExpand'|'onBeforeGanttReady'|'onBeforeGanttRender'|'onBeforeLightbox'|'onBeforeLinkAdd'|'onBeforeLinkDelete'|'onBeforeLinkDisplay'|'onBeforeLinkUpdate'|'onBeforeParse'|'onBeforeRedo'|'onBeforeRowDragEnd'|'onBeforeTaskAdd'|'onBeforeTaskAutoSchedule'|'onBeforeTaskChanged'|'onBeforeTaskDelete'|'onBeforeTaskDisplay'|'onBeforeTaskDrag'|'onBeforeTaskMove'|'onBeforeTaskSelected'|'onBeforeTaskUpdate'|'onBeforeUndo'|'onCircularLinkError'|'onClear'|'onCollapse'|'onColumnResize'|'onColumnResizeEnd'|'onColumnResizeStart'|'onContextMenu'|'onDataRender'|'onEmptyClick'|'onError'|'onExpand'|'onGanttReady'|'onGanttRender'|'onGanttScroll'|'onGridHeaderClick'|'onGridResize'|'onGridResizeEnd'|'onGridResizeStart'|'onLightbox'|'onLightboxButton'|'onLightboxCancel'|'onLightboxChange'|'onLightboxDelete'|'onLightboxSave'|'onLinkClick'|'onLinkDblClick'|'onLinkIdChange'|'onLinkValidation'|'onLoadEnd'|'onLoadStart'|'onMouseMove'|'onOptionsLoad'|'onParse'|'onRowDragEnd'|'onRowDragStart'|'onScaleAdjusted'|'onScaleClick'|'onTaskClick'|'onTaskClosed'|'onTaskCreated'|'onTaskDblClick'|'onTaskDrag'|'onTaskIdChange'|'onTaskLoading'|'onTaskOpened'|'onTaskRowClick'|'onTaskSelected'|'onTaskUnselected'|'onTemplatesReady'; +type GanttEventName = "onAfterAutoSchedule"|"onAfterBatchUpdate"|"onAfterLightbox"|"onAfterLinkAdd"|"onAfterLinkDelete"|"onAfterLinkUpdate"|"onAfterQuickInfo"|"onAfterRedo"|"onAfterSort"|"onAfterTaskAdd"|"onAfterTaskAutoSchedule"|"onAfterTaskDelete"|"onAfterTaskDrag"|"onAfterTaskMove"|"onAfterTaskUpdate"|"onAfterUndo"|"onAjaxError"|"onAutoScheduleCircularLink"|"onBeforeAutoSchedule"|"onBeforeBatchUpdate"|"onBeforeCollapse"|"onBeforeDataRender"|"onBeforeExpand"|"onBeforeGanttReady"|"onBeforeGanttRender"|"onBeforeLightbox"|"onBeforeLinkAdd"|"onBeforeLinkDelete"|"onBeforeLinkDisplay"|"onBeforeLinkUpdate"|"onBeforeMultiSelect"|"onBeforeParse"|"onBeforeRedo"|"onBeforeRedoStack"|"onBeforeRowDragEnd"|"onBeforeRowDragMove"|"onBeforeTaskAdd"|"onBeforeTaskAutoSchedule"|"onBeforeTaskChanged"|"onBeforeTaskDelete"|"onBeforeTaskDisplay"|"onBeforeTaskDrag"|"onBeforeTaskMove"|"onBeforeTaskMultiSelect"|"onBeforeTaskSelected"|"onBeforeTaskUpdate"|"onBeforeUndo"|"onBeforeUndoStack"|"onCircularLinkError"|"onClear"|"onCollapse"|"onColumnResize"|"onColumnResizeEnd"|"onColumnResizeStart"|"onContextMenu"|"onDataProcessorReady"|"onDataRender"|"onDestroy"|"onEmptyClick"|"onError"|"onExpand"|"onGanttLayoutReady"|"onGanttReady"|"onGanttRender"|"onGanttScroll"|"onGridHeaderClick"|"onGridResize"|"onGridResizeEnd"|"onGridResizeStart"|"onLightbox"|"onLightboxButton"|"onLightboxCancel"|"onLightboxChange"|"onLightboxDelete"|"onLightboxSave"|"onLinkClick"|"onLinkDblClick"|"onLinkIdChange"|"onLinkValidation"|"onLoadEnd"|"onLoadStart"|"onMouseMove"|"onMultiSelect"|"onOptionsLoad"|"onParse"|"onQuickInfo"|"onRowDragEnd"|"onRowDragStart"|"onScaleAdjusted"|"onScaleClick"|"onTaskClick"|"onTaskClosed"|"onTaskCreated"|"onTaskDblClick"|"onTaskDrag"|"onTaskIdChange"|"onTaskLoading"|"onTaskMultiSelect"|"onTaskOpened"|"onTaskRowClick"|"onTaskSelected"|"onTaskUnselected"|"onTemplatesReady"; interface GanttTemplates { - /** - * specifies the format of dates that are set by means of API methods. Used to parse incoming dates - * @param date the date which needs formatting - */ - api_date(date: Date): string; /** * specifies the content of start date or end date columns in grid @@ -37,7 +31,7 @@ interface GanttTemplates { drag_link(from: string|number, from_start: boolean, to: string|number, to_start: boolean): string; /** - * specifies the CSS class that will be applied to the link receiver (pop-up circle near the task bar) + * specifies the CSS class that will be applied to the pop-up that appears when a user drags a link * @param from the id of the source task * @param from_start true, if the link is being dragged from the start of the source task, false - if
from the end of the task * @param to the id of the target task( 'null' or 'undefined', if the target task isn't specified yet) @@ -96,6 +90,42 @@ interface GanttTemplates { */ grid_row_class(start: Date, end: Date, task: any): string; + /** + * defines the height of the filled area in the resourceHistogram + * @param start_date start date of the scale cell + * @param end_date end date of the scale cell + * @param resource the resource object + * @param tasks tasks that are assigned to the specified resource and overlap start/end dates of the cell + */ + histogram_cell_allocated(start_date: Date, end_date: Date, resource: any, tasks: any[]): void; + + /** + * specifies the height of the line that defines the available capacity of the resource + * @param start_date start date of the scale cell + * @param end_date end date of the scale cell + * @param resource the resource object + * @param tasks tasks that are assigned to the specified resource and overlap start/end dates of the cell + */ + histogram_cell_capacity(start_date: Date, end_date: Date, resource: any, tasks: any[]): void; + + /** + * defines the CSS class which is applied to a cell of the resource panel + * @param start_date start date of the scale cell + * @param end_date end date of the scale cell + * @param resource the resource object + * @param tasks tasks that are assigned to the specified resource and overlap start/end dates of the cell + */ + histogram_cell_class(start_date: Date, end_date: Date, resource: any, tasks: any[]): void; + + /** + * defines the label inside a cell + * @param start_date start date of the scale cell + * @param end_date end date of the scale cell + * @param resource the resource object + * @param tasks tasks that are assigned to the specified resource and overlap start/end dates of the cell + */ + histogram_cell_label(start_date: Date, end_date: Date, resource: any, tasks: any[]): void; + /** * specifies the CSS class that will be applied to a link * @param link the link object @@ -148,6 +178,24 @@ interface GanttTemplates { */ quick_info_title(start: Date, end: Date, task: any): string; + /** + * defines the CSS class names of cells in the resource timeline cells + * @param start_date start date of the scale cell + * @param end_date end date of the scale cell + * @param resource the resource object + * @param tasks tasks that are assigned to specified resource and overlap start/end dates of the cell + */ + resource_cell_class(start_date: Date, end_date: Date, resource: any, tasks: any[]): string; + + /** + * defines the HTML content of resource timeline cells + * @param start_date start date of the scale cell + * @param end_date end date of the scale cell + * @param resource the resource object + * @param tasks tasks that are assigned to specified resource and overlap start/end dates of the cell + */ + resource_cell_value(start_date: Date, end_date: Date, resource: any, tasks: any[]): string; + /** * specifies the CSS class that will be applied to cells of the time scale of the timeline area * @param date the date of a cell @@ -165,7 +213,7 @@ interface GanttTemplates { * @param item the task object assigned to the row * @param date the date of a cell */ - task_cell_class(item: Date, date: Date): string; + task_cell_class(item: any, date: Date): string; /** * specifies the CSS class that will be applied to task bars @@ -266,14 +314,9 @@ interface GanttTemplates { * @param task the task's object */ lightbox_header(start_date: Date, end_date: Date, task: any): string; - } interface GanttConfigOptions { - /** - * sets the date format for addTask() method to - */ - api_date: string; /** * enables auto scheduling @@ -281,7 +324,7 @@ interface GanttConfigOptions { auto_scheduling: boolean; /** - * allows or forbids creation of links from parent tasks (projects) to their children + * allows or forbids creating links from parent tasks (projects) to their children */ auto_scheduling_descendant_links: boolean; @@ -290,16 +333,36 @@ interface GanttConfigOptions { */ auto_scheduling_initial: boolean; + /** + * defines whether the whole project will be moved (see the details below) + */ + auto_scheduling_move_projects: boolean; + /** * enables the auto scheduling mode, in which tasks will always be rescheduled to the earliest possible date */ auto_scheduling_strict: boolean; + /** + * automatically converts tasks with subtasks to projects and projects without subtasks back to tasks + */ + auto_types: boolean; + /** * enables automatic adjusting of the grid's columns to the grid's width */ autofit: boolean; + /** + * enables autoscrolling while dragging a task or link out of the current browser screen + */ + autoscroll: boolean; + + /** + * defines the speed of autoscrolling (in ms) while dragging a task or link out of the current browser screen + */ + autoscroll_speed: number; + /** * forces the Gantt chart to automatically change its size to show all tasks without scrolling */ @@ -311,10 +374,15 @@ interface GanttConfigOptions { autosize_min_width: number; /** - * enables the dynamic loading in the Gantt chart + * enables dynamic loading in the Gantt chart */ branch_loading: boolean; + /** + * specifies that the task has children that are not yet loaded from the backend + */ + branch_loading_property: string; + /** * stores a collection of buttons resided in the left bottom corner of the lightbox */ @@ -325,6 +393,16 @@ interface GanttConfigOptions { */ buttons_right: any[]; + /** + * changes the name of the property that affects binding of a calendar to a task/group of tasks + */ + calendar_property: string; + + /** + * enables cascade deleting of nested tasks and links + */ + cascade_delete: boolean; + /** * configures the columns of the table */ @@ -380,6 +458,11 @@ interface GanttConfigOptions { */ drag_progress: boolean; + /** + * enables drag and drop of items of the project type + */ + drag_project: boolean; + /** * enables the possibility to resize tasks by drag-and-drop */ @@ -400,6 +483,11 @@ interface GanttConfigOptions { */ editable_property: string; + /** + * an object that contains definitions of inline editors + */ + editor_types: any; + /** * sets the end value of the time scale */ @@ -426,7 +514,7 @@ interface GanttConfigOptions { grid_resizer_column_attribute: string; /** - * sets the maximum width of the grid + * sets the width of the grid */ grid_width: number; @@ -446,15 +534,30 @@ interface GanttConfigOptions { initial_scroll: boolean; /** - * 'says' to preserve the initial grid's width during resizing the columns within + * 'says' to preserve the initial grid's width while resizing columns within */ keep_grid_width: boolean; + /** + * enables keyboard navigation in gantt + */ + keyboard_navigation: boolean; + + /** + * enables keyboard navigation by cells + */ + keyboard_navigation_cells: boolean; + /** * sets the name of the attribute of the task layer's DOM element */ layer_attribute: string; + /** + * specifies the layout object + */ + layout: any; + /** * specifies the lightbox object */ @@ -496,7 +599,7 @@ interface GanttConfigOptions { min_column_width: number; /** - * sets the minimum step (in milliseconds) for task's time values + * Sets the minimum duration (in milliseconds) that can be set for a task during resizing. */ min_duration: number; @@ -521,15 +624,20 @@ interface GanttConfigOptions { open_tree_initially: boolean; /** - * activates the 'branch' mode that allows dragging tasks only within the parent branch + * activates the 'branch' mode that allows reordering tasks within the same nesting level */ - order_branch: boolean; + order_branch: string|boolean; /** - * activates the 'branch' mode that allows dragging tasks within the whole gantt + * activates the 'branch' mode that allows reordering tasks within the whole gantt */ order_branch_free: boolean; + /** + * adds an empty row into the end of the list of tasks to simplify tasks editing via keyboard + */ + placeholder_task: boolean; + /** * preserves the current position of the vertical and horizontal scrolls while re-drawing the gantt chart */ @@ -565,6 +673,26 @@ interface GanttConfigOptions { */ redo: boolean; + /** + * defines a set of working calendars that can be assigned to a specific resource, e.g. a user + */ + resource_calendars: any; + + /** + * defines the property of a task object that stores a resource id associated with resourceGrid/Timeline/Histogram + */ + resource_property: string; + + /** + * tells the resource timeline to render elements and call templates for non-allocated cells + */ + resource_render_empty_cells: boolean; + + /** + * specifies the name of the dataStore connected to the resourceGrid/resourceTimeline/resourceHistogram views + */ + resource_store: string; + /** * sets the id of the virtual root element */ @@ -580,6 +708,11 @@ interface GanttConfigOptions { */ row_height: number; + /** + * switches gantt to the right-to-left mode + */ + rtl: boolean; + /** * sets the height of the time scale and the header of the grid */ @@ -600,6 +733,11 @@ interface GanttConfigOptions { */ scroll_on_click: boolean; + /** + * set the sizes of the vertical (width) and horizontal (height) scrolls + */ + scroll_size: number; + /** * enables selection of tasks in the Gantt chart */ @@ -665,6 +803,11 @@ interface GanttConfigOptions { */ smart_rendering: boolean; + /** + * specifies that only visible part of the time scale is rendered on the screen + */ + smart_scales: boolean; + /** * enables sorting in the table */ @@ -676,7 +819,7 @@ interface GanttConfigOptions { start_date: Date; /** - * sets the start day of weeks + * sets the starting day of the week */ start_on_monday: boolean; @@ -731,12 +874,12 @@ interface GanttConfigOptions { tooltip_hide_timeout: number; /** - * sets the the right (if positive) offset of the tooltip's position + * sets the right (if positive) offset of the tooltip's position */ tooltip_offset_x: number; /** - * sets the the top (if positive) offset of the tooltip's position + * sets the top (if positive) offset of the tooltip's position */ tooltip_offset_y: number; @@ -756,10 +899,15 @@ interface GanttConfigOptions { touch_drag: number|boolean; /** - * enables/disables vibration while moving tasks on touch devices + * returns vibration feedback before/after drag and drop on touch devices */ touch_feedback: boolean; + /** + * defines the duration of vibration feedback before/after drag and drop on touch devices (in milliseconds) + */ + touch_feedback_duration: number; + /** * redefines functions responsible for displaying different types of tasks */ @@ -790,33 +938,33 @@ interface GanttConfigOptions { */ undo_types: any; + /** + * enables WAI-ARIA support to make the component recognizable for screen readers + */ + wai_aria_attributes: boolean; + /** * enables calculating the duration of tasks in working time instead of calendar time */ work_time: boolean; /** - * sets the date format that is used to parse data from the data set + * defines date formats that are used to parse data from a data set and to send data to a server */ xml_date: string; - } interface GanttDateHelpers { add(origin: Date, count: number, unit: string): Date; copy(origin: Date): Date; - date_part(origin: Date): Date; time_part(origin: Date): Date; - day_start(origin: Date): Date; month_start(origin: Date): Date; week_start(origin: Date): Date; year_start(origin: Date): Date; - getISOWeek(origin: Date): number; getUTCISOWeek(origin: Date): number; - date_to_str(format: string): any; str_to_date(format: string): any; convert_to_utc(origin: Date): Date; @@ -828,8 +976,6 @@ interface GanttHotkeys { edit_cancel: number; } -//Gantt.locale - interface GanttLocaleDate { month_full: string[]; month_short: string[]; @@ -867,22 +1013,102 @@ interface GanttLocale { } interface GanttEnterprise { - /** - * Creates a new instance of Gantt - */ getGanttInstance(): GanttStatic; } interface GanttStatic { - templates: GanttTemplates; - config: GanttConfigOptions; - date: GanttDateHelpers; - keys: GanttHotkeys; - skin: string; - version: string; - locale: GanttLocale; + + /** + * redefines the default click behavior for buttons of the Gantt chart + */ $click: any; + /** + * dhtmlx ajax module + */ + ajax: any; + + /** + * the interface of the working calendar object + */ + calendar: any; + + /** + * defines configuration options for dates, scale, controls + */ + config: GanttConfigOptions; + + /** + * stores various constants to reduce the use of magic numbers in the code + */ + constants: any; + + /** + * a set of date formatting methods + */ + date: GanttDateHelpers; + + /** + * a set of flags which describe current environment + */ + env: any; + + /** + * an object that stores various extensions + */ + ext: any; + + /** + * specifies JSON serialization and parsing + */ + json: any; + + /** + * defines the hot keys for the Gantt chart + */ + keys: GanttHotkeys; + + /** + * a locale object (region-specific labels) of the Gantt chart + */ + locale: GanttLocale; + + /** + * specifies serialization and parsing in the XML format of dhtmlxGantt 1.0 + */ + oldxml: any; + + /** + * returns the current skin of the Gantt chart + */ + skin: string; + + /** + * returns objects of the available skins + */ + skins: any; + + /** + * defines formatting templates for dates, titles, tooltips in the Gantt chart + */ + templates: GanttTemplates; + + /** + * returns the version of dhtmlxGantt + */ + version: string; + + /** + * specifies XML serialization and parsing + */ + xml: any; + + /** + * adds a calendar into Gantt + * @param calendar an object with configuration of the calendar + */ + addCalendar(calendar: any): number; + /** * adds a new dependency link * @param link the link object @@ -890,10 +1116,10 @@ interface GanttStatic { addLink(link: any): string|number; /** - * displayes an additional layer with custom elements for a link in the timeline area - * @param func a render function or a config object + * displays an additional layer with custom elements for a link in the timeline area + * @param func a render function or a config object */ - addLinkLayer(func: GanttCallback|any): string; + addLinkLayer(func: any): string; /** * adds a marker to the timeline area @@ -901,25 +1127,33 @@ interface GanttStatic { */ addMarker(marker: any): string; + /** + * adds a new keyboard shortcut + * @param shortcut the key name or the name of keys combination for a shortcut (
shortcut syntax) + * @param handler the handler of the shortcut call + * @param scope the name of the context element to attach the handler function to (list of scopes) + */ + addShortcut(shortcut: string, handler: GanttCallback, scope: string): void; + /** * adds a new task * @param task the task object * @param parent the parent's id - * @param index optional, the position the task will be added into (0 or greater) + * @param index optional, optional, the position the task will be added into (0 or greater) */ addTask(task: any, parent: string, index?: number): string|number; /** - * displayes an additional layer with custom elements for a task in the timeline area - * @param func a render function or a config object + * displays an additional layer with custom elements for a task in the timeline area + * @param func a render function or a config object */ - addTaskLayer(func: GanttCallback|any): string; + addTaskLayer(func: any): string; /** * calls an alert message box * @param config the alert box's configuration */ - alert(config: any): void; + alert(config: any): HTMLElement; /** * if the specified expression is false, an errorMessage is shown in the red popup at the top right corner of the screen @@ -937,8 +1171,9 @@ interface GanttStatic { /** * recalculates the schedule of the project + * @param taskId optional, optional, the task id */ - autoSchedule(): void; + autoSchedule(taskId?: string|number): void; /** * updates multiple tasks/links at once @@ -960,6 +1195,12 @@ interface GanttStatic { */ calculateDuration(start: Date, end: Date): number; + /** + * calculates the duration of a task + * @param config the configuration object of a time span + */ + calculateDuration(config: any): number; + /** * calculates the end date of a task * @param start the date when a task is scheduled to begin @@ -968,6 +1209,12 @@ interface GanttStatic { */ calculateEndDate(start: Date, duration: number, unit: string): Date; + /** + * calculates the end date of a task + * @param config the configuration object of a time span + */ + calculateEndDate(config: any): Date; + /** * calculates the level of a task * @param task the task's object @@ -982,10 +1229,10 @@ interface GanttStatic { callEvent(name: string, params: any[]): boolean; /** - * changes the name of the lighbox's structure defined for of the task - * @param id the task id + * repaints the lighbox for the task according to its type + * @param type the task type */ - changeLightboxType(id: string|number): void; + changeLightboxType(type: string): void; /** * changes the link's id @@ -1008,10 +1255,20 @@ interface GanttStatic { checkEvent(name: GanttEventName): boolean; /** - * removes all tasks from the Gantt chart + * removes all tasks and additional elements (including markers) from the Gantt chart */ clearAll(): void; + /** + * clears the stack of stored redo commands + */ + clearRedoStack(): void; + + /** + * clears the stack of stored undo commands + */ + clearUndoStack(): void; + /** * closes the branch with the specified id * @param id the branch id @@ -1023,11 +1280,17 @@ interface GanttStatic { */ collapse(): void; + /** + * returns the index of the column by the date + * @param date a date object + */ + columnIndexByDate(date: Date): void; + /** * calls a confirm message box * @param config the confirm box's configuration */ - confirm(config: any): void; + confirm(config: any): HTMLElement; /** * creates a deep copy of provided object @@ -1041,11 +1304,23 @@ interface GanttStatic { */ correctTaskWorkTime(task: any): void; + /** + * creates a working calendar + * @param parentCalendar optional, (optional) an existing calendar that is used for creating a new one on the base of it + */ + createCalendar(parentCalendar?: any): void; + + /** + * creates a datastore according to the provided configuration + * @param config a configuration object of a datastore + */ + createDatastore(config: any): void; + /** * adds a new task and opens the lightbox to confirm * @param task the task object * @param parent the parent's id - * @param index optional, the position the task will be added into (0 or greater) + * @param index optional, optional, the position the task will be added into (0 or greater) */ createTask(task: any, parent: string, index?: number): string|number; @@ -1056,7 +1331,7 @@ interface GanttStatic { dataProcessor(url: string): void; /** - * returns the date of the specified horizontal position in the chart area + * gets the date of the specified horizontal position in the chart area * @param pos the relative horizontal position you want to know the date of */ dateFromPos(pos: number): Date; @@ -1067,6 +1342,12 @@ interface GanttStatic { */ defined(task: any): boolean; + /** + * deletes a task calendar by its id + * @param id the id of the calendar + */ + deleteCalendar(id: string|number): void; + /** * deletes the specified dependency link * @param id the dependency link's id @@ -1083,7 +1364,12 @@ interface GanttStatic { * deletes the specified task * @param id the task's id */ - deleteTask(id: string): void; + deleteTask(id: string|number): void; + + /** + * destroys the gantt instance + */ + destructor(): void; /** * detaches all events from dhtmlxGantt (both custom and inner) @@ -1096,6 +1382,14 @@ interface GanttStatic { */ detachEvent(id: string): void; + /** + * iterates over all parent tasks of the specified task in the Gantt chart + * @param code a function that will iterate over tasks. Takes a task object as a parameter + * @param startTask the id of the item the parent tasks of which should be iterated over + * @param master optional, the object, that 'this' will refer to + */ + eachParent(code: GanttCallback, startTask: string|number, master?: any): void; + /** * iterates over all selected tasks in the Gantt chart * @param code a function that will iterate over tasks. Takes a task id as a parameter @@ -1103,10 +1397,10 @@ interface GanttStatic { eachSelectedTask(code: GanttCallback): void; /** - * iterates over specified tasks in the Gantt chart + * iterates over all child tasks in the Gantt chart * @param code a function that will iterate over tasks. Takes a task object as a parameter - * @param parent the parent id. If specified, the function will iterate over childs of the
specified parent - * @param master the object, that 'this' will refer to + * @param parent optional, the parent id. If specified, the function will iterate over childs of the
specified parent + * @param master optional, the object, that 'this' will refer to */ eachTask(code: GanttCallback, parent?: string|number, master?: any): void; @@ -1115,21 +1409,81 @@ interface GanttStatic { * @param node the HTML node or its id * @param event the name of an HTML event (without the 'on' prefix) * @param handler the event handler - * @param master an object that the this keyword refers to + * @param options optional, optional, the value of either the useCapture or options parameter. Read details */ - event(node: HTMLElement|string, event: string, handler: GanttCallback, master?: any): string; + event(node: HTMLElement|string, event: string, handler: GanttCallback, options?: any): void; /** * removes an event handler from an HTML element - * @param id the id of an event handler + * @param node the HTML node or its id + * @param event the name of an HTML event (without the 'on' prefix) + * @param handler the event handler + * @param options optional, optional, the value of either the useCapture or options parameter. Read details */ - eventRemove(id: string): void; + eventRemove(node: HTMLElement|string, event: string, handler: GanttCallback, options?: any): void; /** * expands gantt to the full screen mode */ expand(): void; + /** + * exports data from the Gantt chart to an Excel document + * @param _export_ an object with export settings (see the details) + */ + exportToExcel(_export_: any): void; + + /** + * exports data from the Gantt chart to an iCal string + * @param _export_ an object with export settings (see the details) + */ + exportToICal(_export_: any): void; + + /** + * exports the structure and data of a Gantt chart into a JSON object + * @param config an object with Gantt configuration + */ + exportToJSON(config: any): void; + + /** + * exports data from the Gantt chart to MS Project + * @param _export_ an object with export settings (see the details) + */ + exportToMSProject(_export_: any): void; + + /** + * exports a Gantt chart into the PDF format + * @param _export_ an object with export settings (see the details) + */ + exportToPDF(_export_: any): void; + + /** + * exports a Gantt chart into the PNG format + * @param _export_ an object with export settings (see the details) + */ + exportToPNG(_export_: any): void; + + /** + * returns all dependency loops in the chart + */ + findCycles(): any[]; + + /** + * sets focus on the gantt + */ + focus(): void; + + /** + * gets worktime calendar by id + * @param calendarId the id of the global calendar or "global" + */ + getCalendar(calendarId: string|number): any; + + /** + * gets all the calendars added into Gantt + */ + getCalendars(): any[]; + /** * returns the 1st-level child tasks of the specified parent branch * @param id the parent branch's id @@ -1143,10 +1497,34 @@ interface GanttStatic { getClosestWorkTime(config: any): Date; /** - * get the index of a task in the tree + * returns the index of the column by its name + * @param name the name of the column + */ + getColumnIndex(name: string): number; + + /** + * returns all tasks and links that a task is connected with + * @param id optional, optional, the id of a task + */ + getConnectedGroup(id?: string|number): any; + + /** + * returns the configuration object of a datastore + * @param name the name of the datastore + */ + getDatastore(name: string): any; + + /** + * returns the free slack of a task + * @param task the object of a task + */ + getFreeSlack(task: any): number; + + /** + * gets the index of a task in the tree * @param id the task id */ - getGlobalTaskIndex(id: string|number): void; + getGlobalTaskIndex(id: string|number): number; /** * gets the configuration object of a column @@ -1251,10 +1629,21 @@ interface GanttStatic { getPrevSibling(id: string|number): string|number; /** - * returns the stack of stored redo commands + * returns the stack of stored redo user actions */ getRedoStack(): any[]; + /** + * returns all tasks assigned to the resource + * @param resourceId the id of the resource + */ + getResourceAssignments(resourceId: string|number): any[]; + + /** + * returns the configuration of the time scale + */ + getScale(): any; + /** * returns the scroll position */ @@ -1263,13 +1652,20 @@ interface GanttStatic { /** * returns the id of the selected task */ - getSelectedId(): string|number; + getSelectedId(): string; /** * returns an array of the currently selected tasks */ getSelectedTasks(): any[]; + /** + * gets a key navigation shortcut handler + * @param shortcut the key name or the name of keys combination for a shortcut (shortcut syntax) + * @param scope the name of the context element to attach the handler function to (list of scopes) + */ + getShortcutHandler(shortcut: string, scope: string): GanttCallback; + /** * returns siblings of the specified task (including itself) * @param id the task id @@ -1290,30 +1686,66 @@ interface GanttStatic { /** * calculates the combined start/end dates of tasks nested in a project or another task - * @param task_id the task's id, api/gantt_root_id_config.md will be used if not specified + * @param task_id optional, the task's id, api/gantt_root_id_config.md will be used if not specified */ getSubtaskDates(task_id?: string|number): any; + /** + * calculates the combined duration of tasks nested in a project or another task. + * @param task_id optional, the task's id, api/gantt_root_id_config.md will be used if not specified + */ + getSubtaskDuration(task_id?: string|number): number; + /** * returns the task object * @param id the task id */ getTask(id: string|number): any; + /** + * finds a task by the specified criteria + * @param propertyName the name of the property to match, or a filter function + * @param propertyValue the property value + */ + getTaskBy(propertyName: string|GanttCallback, propertyValue: any): any[]; + + /** + * returns a task by its index + * @param index the task index in the tree (zero-based numbering) + */ + getTaskByIndex(index: number): any; + /** * returns a collection of tasks which occur during the specified period - * @param from the start date of the period - * @param to the end date of the period + * @param from optional, the start date of the period + * @param to optional, the end date of the period */ getTaskByTime(from?: Date, to?: Date): any[]; + /** + * returns a task by its WBS code + * @param code the WBS code of the task + */ + getTaskByWBSCode(code: string): any; + + /** + * gets a calendar assigned to the specified task (a task level calendar) + * @param task the object of a task + */ + getTaskCalendar(task: any): any; + /** * gets the number of tasks that are currently loaded in the gantt */ getTaskCount(): number; /** - * get the index of a task in the branch + * returns the visible height of a task + */ + getTaskHeight(): number; + + /** + * gets the index of a task in the branch * @param id the task id */ getTaskIndex(id: string|number): number; @@ -1345,7 +1777,19 @@ interface GanttStatic { getTaskTop(id: number|string): number; /** - * returns the stack of stored undo commands + * returns the type of a task + * @param task the task object + */ + getTaskType(task: any): string; + + /** + * returns the total slack of a task + * @param task the object of a task + */ + getTotalSlack(task: any): number; + + /** + * returns the stack of stored undo user actions */ getUndoStack(): any[]; @@ -1354,6 +1798,12 @@ interface GanttStatic { */ getVisibleTaskCount(): number; + /** + * returns the WBS code (the outline number) of a task + * @param task the object of a task + */ + getWBSCode(task: any): string; + /** * returns the working hours of the specified date * @param date a date to check @@ -1374,7 +1824,7 @@ interface GanttStatic { /** * hides the lightbox modal overlay that blocks interactions with the remaining screen - * @param box an element to hide + * @param box optional, an element to hide */ hideCover(box?: HTMLElement): void; @@ -1388,11 +1838,23 @@ interface GanttStatic { */ hideQuickInfo(): void; + /** + * converts an Excel file to JSON + * @param config an object with configuration properties of an imported file + */ + importFromExcel(config: any): void; + + /** + * converts an XML or MPP MS Project file to JSON + * @param config an object with configuration properties of an imported file + */ + importFromMSProject(config: any): void; + /** * constructor. Initializes a dhtmlxGantt object * @param container an HTML container ( or its id) where a dhtmlxGantt object will be initialized - * @param from the start value of the time scale (X–Axis) - * @param to the end value of the time scale (X–Axis) + * @param from optional, the start value of the time scale (X–Axis) + * @param to optional, the end value of the time scale (X–Axis) */ init(container: string|HTMLElement, from?: Date, to?: Date): void; @@ -1403,6 +1865,12 @@ interface GanttStatic { */ isChildOf(childId: string|number, parentId: string|number): boolean; + /** + * checks whether the link is circular + * @param link the link object + */ + isCircularLink(link: any): boolean; + /** * checks whether the specified link is critical * @param link the link's object @@ -1427,12 +1895,30 @@ interface GanttStatic { */ isLinkExists(id: string|number): boolean; + /** + * checks whether the specified task or link is read-only + * @param id the task/link id + */ + isReadonly(id: string|number): boolean; + /** * checks whether the specified task is currently selected * @param task the task's id */ isSelectedTask(task: string|number): boolean; + /** + * checks whether the specified task is split + * @param task the object of a task + */ + isSplitTask(task: any): boolean; + + /** + * checks whether the specified task is summary + * @param task the object of a task + */ + isSummaryTask(task: any): boolean; + /** * checks whether the specified task exists * @param id the task id @@ -1458,11 +1944,17 @@ interface GanttStatic { */ isWorkTime(date: Date, timeunit: string): boolean; + /** + * checks whether the specified date is working or not + * @param config the configuration object of a time span + */ + isWorkTime(config: any): boolean; + /** * loads data to the gantt from an external data source * @param url the server-side url (may be a static file or a server side script that outputs data) - * @param type ('json', 'xml', 'oldxml') the data type. The default value - 'json' - * @param callback the callback function + * @param type optional, ('json', 'xml', 'oldxml') the data type. The default value - 'json' + * @param callback optional, the callback function */ load(url: string, type?: string, callback?: GanttCallback): void; @@ -1476,7 +1968,7 @@ interface GanttStatic { * calls a message box of the specified type * @param config the message box's configuration */ - message(config: any): void; + message(config: any): HTMLElement; /** * adds properties of the 'source' object into the 'target' object @@ -1488,15 +1980,15 @@ interface GanttStatic { /** * calls a modalbox - * @param config the modal box' configuration + * @param config the modal box's configuration */ - modalbox(config: any): void; + modalbox(config: any): HTMLElement; /** * moves a task to a new position * @param sid the id of the task to move * @param tindex the index of the position that the task will be moved to
(the index within a branch) - * @param parent the parent id. If specified, the tindex will refer to the index in the
'parent' branch + * @param parent optional, the parent id. If specified, the tindex will refer to the index in the
'parent' branch */ moveTask(sid: string|number, tindex: number, parent?: string|number): void; @@ -1509,9 +2001,9 @@ interface GanttStatic { /** * loads data from a client-side resource * @param url a string or object which represents data - * @param type ( 'json', 'xml' ) the data type. The default value - 'json' + * @param type optional, optional, ('json', 'xml') the data type. The default value - 'json' */ - parse(url: string|any, type?: string): void; + parse(url: any, type?: string): void; /** * gets the relative horizontal position of the specified date in the chart area @@ -1538,8 +2030,9 @@ interface GanttStatic { /** * refreshes the task and its related links * @param id the task id + * @param refresh_links optional, optional, defines whether links related to the task should be refreshed, true by default */ - refreshTask(id: string|number): void; + refreshTask(id: string|number, refresh_links?: boolean): void; /** * removes the specified layer related to a link @@ -1547,6 +2040,13 @@ interface GanttStatic { */ removeLinkLayer(layerId: string): void; + /** + * removes a keyboard shortcut + * @param shortcut the key name or the name of keys combination for a shortcut (shortcut syntax) + * @param scope the element to which the shortcut is attached (list of scopes) + */ + removeShortcut(shortcut: string, scope: any): void; + /** * removes the specified layer related to a task * @param layerId a DOM element that will be displayed in the layer @@ -1569,7 +2069,7 @@ interface GanttStatic { resetLightbox(): void; /** - * re-calculates the duration of a project task depending on dates its childs + * re-calculates the duration of a project task depending on the dates of its children * @param task the task's object */ resetProjectDates(task: any): void; @@ -1598,8 +2098,8 @@ interface GanttStatic { /** * scrolls the Gantt container to the specified position - * @param x the value of the horizontal scroll or 'null' (to not display the horizontal scroll) - * @param y the value of the vertical scroll or 'null' (to not display the vertical scroll) + * @param x value of horizontal scroll or 'null' (if the scroll position shouldn't be changed) + * @param y value of vertical scroll or 'null' (if the scroll position shouldn't be changed) */ scrollTo(x: number, y: number): void; @@ -1611,16 +2111,16 @@ interface GanttStatic { /** * serializes the data into JSON or XML format - * @param type the format that the data will be serialized into.
Possible values: 'json' (default ), 'xml'. + * @param type optional, the format that the data will be serialized into.
Possible values: 'json' (default ), 'xml'. */ serialize(type?: string): void; /** * returns a list of options * @param list_name the name of a list - * @param options an array of options + * @param options optional, an array of options */ - serverList(list_name: string, options?: any[]): void; + serverList(list_name: string, options?: any[]): any[]; /** * set the parent for a task @@ -1642,7 +2142,7 @@ interface GanttStatic { /** * shows the lightbox modal overlay that blocks interactions with the remaining screen - * @param box an element to hide + * @param box optional, an element to hide */ showCover(box?: HTMLElement): void; @@ -1671,11 +2171,11 @@ interface GanttStatic { showTask(id: string|number): void; /** - * sorts the tasks in the grid - * @param field the name of the column that the grid will be sorted by or a custom
sorting function - * @param desc specifies the sorting direction: true - descending sort and false - ascending
sort. By default, false - * @param parent the id of the parent task. Specify the parameter if you want to sort tasks only in
the branch of the specified parent. - * @param silent specifies whether rendering shall be invoked after reordering items + * sorts tasks in the grid + * @param field the name of the column that the grid will be sorted by or a custom sorting function + * @param desc optional, specifies the sorting direction: true - descending sort and false - ascending
sort. By default, false + * @param parent optional, the id of the parent task. Specify the parameter if you want to sort tasks only in the branch of the specified parent. + * @param silent optional, specifies whether rendering should be invoked after reordering items */ sort(field: string|GanttCallback, desc?: boolean, parent?: string|number, silent?: boolean): void; @@ -1697,8 +2197,15 @@ interface GanttStatic { /** * removes selection from the selected task + * @param id optional, optional, the id of the task to remove selection from, see details */ - unselectTask(): void; + unselectTask(id?: string|number): void; + + /** + * unsets a working time in the Gantt Chart + * @param config the configuration object of a time span + */ + unsetWorkTime(config: any): void; /** * updates the specified collection with new options @@ -1724,11 +2231,8 @@ interface GanttStatic { * @param id the task id */ updateTask(id: string): void; - } - - declare var gantt: GanttStatic; declare var Gantt: GanttEnterprise; @@ -1737,5 +2241,5 @@ declare module "gantt" { } declare module "Gantt" { - export = GanttEnterprise; -} + export = Gantt; +} \ No newline at end of file diff --git a/types/dialogflow/index.d.ts b/types/dialogflow/index.d.ts index c421c47f68..8329021bb8 100644 --- a/types/dialogflow/index.d.ts +++ b/types/dialogflow/index.d.ts @@ -23,12 +23,7 @@ export namespace v2 { searchAgents( request: SearchAgentRequest, options?: gax.CallOptions, - cb?: ( - err: Error, - agents: Agent[], - arg3: any, - response: any - ) => void + cb?: (err: Error, agents: Agent[], arg3: any, response: any) => void ): Promise; searchAgentsStream( request: SearchAgentRequest, @@ -213,7 +208,28 @@ export namespace v2 { getProjectId(): Promise; getProjectId(callback?: (error: Error, id: string) => string): void; - // TODO: add Session Entity Types service methods + // TODO: add streaming calls + + listSessionEntityTypes( + request: ListSessionEntityTypesRequest, + options?: gax.CallOptions + ): Promise<[SessionEntityType[]]>; + getSessionEntityType( + request: GetSessionEntityTypeRequest, + options?: gax.CallOptions + ): Promise<[SessionEntityType]>; + createSessionEntityType( + request: CreateSessionEntityTypeRequest, + options?: gax.CallOptions + ): Promise<[SessionEntityType]>; + updateSessionEntityType( + request: UpdateSessionEntityTypeRequest, + options?: gax.CallOptions + ): Promise<[SessionEntityType]>; + deleteSessionEntityType( + request: DeleteSessionEntityTypeRequest, + options?: gax.CallOptions + ): Promise; } class SessionsClient { @@ -504,6 +520,30 @@ export interface DeleteEntityTypeRequest { name: string; } +export interface ListSessionEntityTypesRequest { + parent: string; + pageSize?: number; +} + +export interface GetSessionEntityTypeRequest { + name: string; +} + +export interface CreateSessionEntityTypeRequest { + parent: string; + sessionEntityType: SessionEntityType; +} + +export interface UpdateSessionEntityTypeRequest { + sessionEntityType: SessionEntityType; + /** @link https://github.com/google/protobuf/blob/master/src/google/protobuf/field_mask.proto */ + updateMask: any; +} + +export interface DeleteSessionEntityTypeRequest { + name: string; +} + export interface ListIntentsRequest { parent: string; languageCode?: string; diff --git a/types/dicer/dicer-tests.ts b/types/dicer/dicer-tests.ts new file mode 100644 index 0000000000..cd7f7a4251 --- /dev/null +++ b/types/dicer/dicer-tests.ts @@ -0,0 +1,81 @@ +import Dicer = require("dicer"); +import * as fs from "fs"; +import * as stream from "stream"; + +function testDicerSyntax() { + const opts: Dicer.Config = { + boundary: "testing", + }; + const dicer = new Dicer(opts); + const opts2: Dicer.Config = { + headerFirst: true, + maxHeaderPairs: 1, + }; + const opts3: Dicer.Config = { + boundary: "more-testing", + headerFirst: false, + maxHeaderPairs: 8, + }; + dicer.setBoundary("new-testing-boundary"); + dicer.on("part", handleDicerPartStream); + dicer.on("finish", () => { + console.log("dicer parsing finished"); + }); + dicer.on("preamble", part => { + console.log("dicer preamble to new part"); + }); + dicer.on("trailer", data => { + console.log(`dicer trailing data found: ${data.length} bytes`); + }); + dicer.on("close", () => { + console.log("dicer close"); + }); + dicer.on("drain", () => { + console.log("dicer drain"); + }); + dicer.on("error", err => { + console.error(`dicer error: ${err.message || JSON.stringify(err)}`); + }); + dicer.on("finish", () => { + console.log("dicer finish"); + }); + dicer.on("pipe", (src: stream.Readable) => { + console.log("dicer pipe"); + }); + dicer.on("unpipe", (src: stream.Readable) => { + console.log("dicer unpipe"); + }); + const inputFileStream = fs.createReadStream("in-test-file.txt"); + inputFileStream.pipe(dicer); +} +/** + * Handle a part found by a Dicer parser + * + * @param part Part found + */ +function handleDicerPartStream(part: Dicer.PartStream) { + console.log("dicer part found"); + const outputFileStream = fs.createWriteStream("out-test-file.txt"); + part.on("readable", () => { + console.log("part readable"); + }); + part.on("header", header => { + console.log(`part header found:\n${JSON.stringify(header)}`); + }); + part.on("data", () => { + console.log("part data"); + }); + part.on("finish", () => { + console.log("part finished"); + }); + part.on("error", err => { + console.error(`part error: ${err.message || JSON.stringify(err)}`); + }); + part.on("end", () => { + console.log("part ended"); + }); + part.on("close", () => { + console.log("part closed"); + }); + part.pipe(outputFileStream); +} diff --git a/types/dicer/index.d.ts b/types/dicer/index.d.ts new file mode 100644 index 0000000000..55d2c76411 --- /dev/null +++ b/types/dicer/index.d.ts @@ -0,0 +1,167 @@ +// Type definitions for dicer 0.2 +// Project: https://github.com/mscdex/dicer +// Definitions by: Robin Goupil +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +/// + +export = Dicer; + +import stream = require("stream"); + +// tslint:disable:unified-signatures + +/** + * A very fast streaming multipart parser for node.js. + * Dicer is a WritableStream + * + * Dicer (special) events: + * - on('finish', ()) - Emitted when all parts have been parsed and the Dicer instance has been ended. + * - on('part', (stream: PartStream)) - Emitted when a new part has been found. + * - on('preamble', (stream: PartStream)) - Emitted for preamble if you should happen to need it (can usually be ignored). + * - on('trailer', (data: Buffer)) - Emitted when trailing data was found after the terminating boundary (as with the preamble, this can usually be ignored too). + */ +declare class Dicer extends stream.Writable { + /** + * Creates and returns a new Dicer instance with the following valid config settings: + * + * @param config The configuration to use + */ + constructor(config: Dicer.Config); + /** + * Sets the boundary to use for parsing and performs some initialization needed for parsing. + * You should only need to use this if you set headerFirst to true in the constructor and are parsing the boundary from the preamble header. + * + * @param boundary The boundary to use + */ + setBoundary(boundary: string): void; + addListener(event: "finish", listener: () => void): this; + addListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + addListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + addListener(event: "trailer", listener: (data: Buffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "part", listener: (stream: Dicer.PartStream) => void): this; + on(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + on(event: "trailer", listener: (data: Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "part", listener: (stream: Dicer.PartStream) => void): this; + once(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + once(event: "trailer", listener: (data: Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + prependListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + prependListener(event: "trailer", listener: (data: Buffer) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + prependOnceListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + prependOnceListener(event: "trailer", listener: (data: Buffer) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + removeListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + removeListener(event: "trailer", listener: (data: Buffer) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pipe", listener: (src: stream.Readable) => void): this; + removeListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; +} + +declare namespace Dicer { + interface Config { + /** + * This is the boundary used to detect the beginning of a new part. + */ + boundary?: string; + /** + * If true, preamble header parsing will be performed first. + */ + headerFirst?: boolean; + /** + * The maximum number of header key=>value pairs to parse Default: 2000 (same as node's http). + */ + maxHeaderPairs?: number; + } + + /** + * PartStream is a _ReadableStream_ + * + * PartStream (special) events: + * - on('header', (header: object)) - An object containing the header for this particular part. Each property value is an array of one or more string values. + */ + interface PartStream extends stream.Readable { + addListener(event: "header", listener: (header: object) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: "header", listener: (header: object) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "header", listener: (header: object) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "header", listener: (header: object) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "header", listener: (header: object) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: "header", listener: (header: object) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + } +} diff --git a/types/dicer/tsconfig.json b/types/dicer/tsconfig.json new file mode 100644 index 0000000000..09c2832cb1 --- /dev/null +++ b/types/dicer/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dicer-tests.ts" + ] +} diff --git a/types/dicer/tslint.json b/types/dicer/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dicer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/diffie-hellman/diffie-hellman-tests.ts b/types/diffie-hellman/diffie-hellman-tests.ts new file mode 100644 index 0000000000..645ebc23bd --- /dev/null +++ b/types/diffie-hellman/diffie-hellman-tests.ts @@ -0,0 +1,48 @@ +import * as dh from 'diffie-hellman'; + +const dh1 = dh.getDiffieHellman('modp1'); +// $ExpectType DiffieHellman +dh1; +// $ExpectType Buffer +dh1.generateKeys(); +// $ExpectType string +dh1.generateKeys('hex'); +// $ExpectType Buffer +dh1.getPrime(); +// $ExpectType string +dh1.getPrime('hex'); +// $ExpectType Buffer +dh1.getGenerator(); +// $ExpectType string +dh1.getGenerator('hex'); +const pk = dh1.getPublicKey(); +// $ExpectType Buffer +pk; +// $ExpectType string +dh1.getPublicKey('hex'); +// $ExpectType Buffer +dh1.getPrivateKey(); +// $ExpectType string +dh1.getPrivateKey('hex'); +// $ExpectType Buffer +dh1.computeSecret(pk); +// $ExpectType Buffer +dh1.computeSecret(pk.toString('hex'), 'hex'); +// $ExpectType string +dh1.computeSecret(pk.toString('hex'), 'hex', 'hex'); + +const dh2 = dh.createDiffieHellman(new Buffer([5])); +// $ExpectType DiffieHellman +dh2; +dh.createDiffieHellman('prime', 'hex'); +dh.createDiffieHellman('prime', 'hex', new Buffer([5])); +dh.createDiffieHellman('prime', 'hex', 5); +dh.createDiffieHellman('prime', 'hex', 'generator', 'hex'); +dh.createDiffieHellman(1); +dh.createDiffieHellman(1, 1); +dh.createDiffieHellman(1, new Buffer([5])); + +dh2.setPublicKey(pk); +dh2.setPublicKey(pk.toString('hex'), 'hex'); +dh2.setPrivateKey(pk); +dh2.setPrivateKey(pk.toString('hex'), 'hex'); diff --git a/types/diffie-hellman/index.d.ts b/types/diffie-hellman/index.d.ts new file mode 100644 index 0000000000..7b59cf9182 --- /dev/null +++ b/types/diffie-hellman/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for diffie-hellman 5.0 +// Project: https://github.com/crypto-browserify/diffie-hellman +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export { createDiffieHellman, getDiffieHellman, DiffieHellman } from 'crypto'; diff --git a/types/diffie-hellman/tsconfig.json b/types/diffie-hellman/tsconfig.json new file mode 100644 index 0000000000..743c9eea4c --- /dev/null +++ b/types/diffie-hellman/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "diffie-hellman-tests.ts" + ] +} diff --git a/types/diffie-hellman/tslint.json b/types/diffie-hellman/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/diffie-hellman/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dinero.js/dinero.js-tests.ts b/types/dinero.js/dinero.js-tests.ts new file mode 100644 index 0000000000..803184c3db --- /dev/null +++ b/types/dinero.js/dinero.js-tests.ts @@ -0,0 +1,71 @@ +import Dinero = require("dinero.js"); + +Dinero.globalExchangeRatesApi = { + endpoint: "https://yourexchangerates.api/latest?base={{from}}", + propertyPath: "data.rates.{{to}}", + headers: { + "user-key": "xxxxxxxxx", + }, +}; +Dinero.globalExchangeRatesApi = { + endpoint: "https://yourexchangerates.api/latest?base={{from}}", + propertyPath: "data.rates.{{to}}", + roundingMode: "HALF_UP", +}; + +Dinero(); +Dinero({ amount: 1 }); +Dinero({ currency: "USD" }); +Dinero({ precision: 2 }); + +let number: number; +let string: string; +let boolean: boolean; + +let dinero: Dinero.Dinero = Dinero(); +let dineroArr: Dinero.Dinero[]; +let dineroObject: Dinero.DineroObject; + +number = dinero.getAmount(); +string = dinero.getCurrency(); +string = dinero.setLocale("fr-FR").getLocale(); +number = dinero.convertPrecision(4).getPrecision(); +dinero = dinero.add(Dinero({ amount: 104545, precision: 4 })); +dinero = dinero.subtract(Dinero({ amount: 104545, precision: 4 })); +dinero = dinero.multiply(2.00125); +dinero = dinero.multiply(2.00125, "HALF_UP"); +dinero = dinero.divide(2); +dinero = dinero.divide(2, "HALF_UP"); +dinero = dinero.percentage(50); +dineroArr = dinero.allocate([50, 50]); +dinero.convert("EUR").then(d => (dinero = d)); +dinero.convert("XBT", { + endpoint: "https://yourexchangerates.api/latest?base={{from}}", + propertyPath: "data.rates.{{to}}", + headers: { + "user-key": "xxxxxxxxx", + }, + roundingMode: "HALF_UP", +}); +boolean = dinero.equalsTo(Dinero({ amount: 500, currency: "EUR" })); +boolean = dinero.lessThan(Dinero({ amount: 800 })); +boolean = dinero.lessThanOrEqual(Dinero({ amount: 800 })); +boolean = dinero.greaterThan(Dinero({ amount: 800 })); +boolean = dinero.greaterThanOrEqual(Dinero({ amount: 800 })); +boolean = dinero.isZero(); +boolean = dinero.isPositive(); +boolean = dinero.isNegative(); +boolean = dinero.hasSubUnits(); +boolean = dinero.hasCents(); +boolean = dinero.hasSameCurrency(Dinero({ amount: 1000, currency: "EUR" })); +boolean = dinero.hasSameAmount(Dinero({ amount: 1000, currency: "EUR" })); +string = dinero.toFormat("0,0 dollar"); +string = dinero.toFormat("0,0 dollar", "HALF_EVEN"); +number = dinero.toUnit(); +number = dinero.toRoundedUnit(1); +number = dinero.toRoundedUnit(1, "HALF_EVEN"); +dineroObject = dinero.toObject(); +dineroArr = Dinero.normalizePrecision([ + Dinero({ amount: 100, precision: 2 }), + Dinero({ amount: 1000, precision: 3 }), +]); diff --git a/types/dinero.js/index.d.ts b/types/dinero.js/index.d.ts new file mode 100644 index 0000000000..82a5026380 --- /dev/null +++ b/types/dinero.js/index.d.ts @@ -0,0 +1,78 @@ +// Type definitions for dinero.js 1.4 +// Project: https://sarahdayan.github.io/dinero.js +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export as namespace Dinero; + +export = DineroFactory; + +declare function DineroFactory(options?: Dinero.Options): DineroFactory.Dinero; + +declare namespace DineroFactory { + let globalExchangeRatesApi: ExchangeRatesApiOptions; + function normalizePrecision(objects: Dinero[]): Dinero[]; + + interface Options { + amount?: number; + currency?: string; + precision?: number; + } + + interface Dinero { + getAmount(): number; + getCurrency(): string; + getLocale(): string; + setLocale(newLocale: string): Dinero; + getPrecision(): number; + convertPrecision(newPrecision: number): Dinero; + add(addend: Dinero): Dinero; + subtract(subtrahend: Dinero): Dinero; + multiply(multiplier: number, roundingMode?: RoundingMode): Dinero; + divide(divisor: number, roundingMode?: RoundingMode): Dinero; + percentage(percentage: number): Dinero; + allocate(ratios: number[]): Dinero[]; + convert(currency: string, options?: ExchangeRatesApiOptions): Promise; + equalsTo(comparator: Dinero): boolean; + lessThan(comparator: Dinero): boolean; + lessThanOrEqual(comparator: Dinero): boolean; + greaterThan(comparator: Dinero): boolean; + greaterThanOrEqual(comparator: Dinero): boolean; + isZero(): boolean; + isPositive(): boolean; + isNegative(): boolean; + hasSubUnits(): boolean; + /** + * @deprecated since version 2.0 + */ + hasCents(): boolean; + hasSameCurrency(comparator: Dinero): boolean; + hasSameAmount(comparator: Dinero): boolean; + toFormat(format?: string, roundingMode?: RoundingMode): string; + toUnit(): number; + toRoundedUnit(digits: number, roundingMode?: RoundingMode): number; + toObject(): DineroObject; + } + + type RoundingMode = + | "HALF_ODD" + | "HALF_EVEN" + | "HALF_UP" + | "HALF_DOWN" + | "HALF_TOWARDS_ZERO" + | "HALF_AWAY_FROM_ZERO"; + + interface ExchangeRatesApiOptions { + endpoint: string; + propertyPath: string; + headers?: { [header: string]: string }; + roundingMode?: RoundingMode; + } + + interface DineroObject { + amount: number; + currency: string; + precision: number; + } +} diff --git a/types/dinero.js/tsconfig.json b/types/dinero.js/tsconfig.json new file mode 100644 index 0000000000..2b306e0676 --- /dev/null +++ b/types/dinero.js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dinero.js-tests.ts" + ] +} diff --git a/types/dinero.js/tslint.json b/types/dinero.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dinero.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index bab3ee6f2b..cd06bc7ebb 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -7,6 +7,7 @@ // Marius Meisenzahl // Rob Moran // Cameron Diver +// Pascal Sthamer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -15,8 +16,16 @@ import * as stream from 'stream'; import * as events from 'events'; +// The modem parameter is an instance of docker-modem, which is missing type declarations. +// https://github.com/apocas/docker-modem + declare namespace Dockerode { - interface Container { + class Container { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(options: {}, callback: Callback): void; inspect(callback: Callback): void; inspect(options?: {}): Promise; @@ -100,18 +109,20 @@ declare namespace Dockerode { logs(callback: Callback): void; logs(options?: ContainerLogsOptions): Promise; - stats(options: {}, callback: Callback): void; - stats(callback: Callback): void; - stats(options?: {}): Promise; + stats(options: {}, callback: Callback): void; + stats(callback: Callback): void; + stats(options?: {}): Promise; - attach(options: {}, callback: Callback): void; - attach(options: {}): Promise; - - modem: any; - id?: string; + attach(options: {}, callback: Callback): void; + attach(options: {}): Promise; } - interface Image { + class Image { + constructor(modem: any, name: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; @@ -132,24 +143,28 @@ declare namespace Dockerode { remove(options: {}, callback: Callback): void; remove(callback: Callback): void; remove(options?: {}): Promise; - - modem: any; - id?: string; } - interface Volume { + class Volume { + constructor(modem: any, name: string); + + modem: any; + name: string; + inspect(callback: Callback): void; inspect(): Promise; remove(options: {}, callback: Callback): void; remove(callback: Callback): void; remove(options?: {}): Promise; - - modem: any; - name?: string; } - interface Service { + class Service { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; @@ -159,20 +174,24 @@ declare namespace Dockerode { update(options: {}, callback: Callback): void; update(options: {}): Promise; - - modem: any; - id?: string; } - interface Task { + class Task { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; - - modem: any; - id?: string; } - interface Node { + class Node { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; @@ -183,12 +202,11 @@ declare namespace Dockerode { remove(options: {}, callback: Callback): void; remove(callback: Callback): void; remove(options?: {}): Promise; - - modem: any; - id?: string; } - interface Plugin { + class Plugin { + constructor(modem: any, name: string, remote?: any); + modem: any; name: string; remote: any; @@ -227,7 +245,12 @@ declare namespace Dockerode { upgrade(auth: any, options?: {}): Promise; } - interface Secret { + class Secret { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; @@ -238,12 +261,14 @@ declare namespace Dockerode { remove(options: {}, callback: Callback): void; remove(callback: Callback): void; remove(options?: {}): Promise; - - modem: any; - id?: string; } - interface Network { + class Network { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; @@ -258,12 +283,14 @@ declare namespace Dockerode { disconnect(options: {}, callback: Callback): void; disconnect(callback: Callback): void; disconnect(options?: {}): Promise; - - modem: any; - id?: string; } - interface Exec { + class Exec { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; @@ -272,9 +299,6 @@ declare namespace Dockerode { resize(options: {}, callback: Callback): void; resize(options: {}): Promise; - - modem: any; - id?: string; } interface ImageInfo { @@ -446,20 +470,99 @@ declare namespace Dockerode { GlobalIPv6Address: string; GlobalIPv6PrefixLen: number; MacAddress: string; - } + }; }; Node?: { - ID: string; - IP: string; - Addr: string; - Name: string; - Cpus: number; - Memory: number; - Labels: any; - } + ID: string; + IP: string; + Addr: string; + Name: string; + Cpus: number; + Memory: number; + Labels: any; + }; }; } + interface NetworkStats { + [name: string]: { + rx_bytes: number; + rx_dropped: number; + rx_errors: number; + rx_packets: number; + tx_bytes: number; + tx_dropped: number; + tx_errors: number; + tx_packets: number; + }; + } + + interface CPUStats { + cpu_usage: { + percpu_usage: number[]; + usage_in_usermode: number; + total_usage: number; + usage_in_kernelmode: number; + }; + system_cpu_usage: number; + online_cpus: number; + throttling_data: { + periods: number; + throttled_periods: number; + throttled_time: number; + }; + } + + interface MemoryStats { + stats: { + total_pgmajfault: number; + cache: number; + mapped_file: number; + total_inactive_file: number; + pgpgout: number; + rss: number; + total_mapped_file: number; + writeback: number; + unevictable: number; + pgpgin: number; + total_unevictable: number; + pgmajfault: number; + total_rss: number; + total_rss_huge: number; + total_writeback: number; + total_inactive_anon: number; + rss_huge: number; + hierarchical_memory_limit: number; + total_pgfault: number; + total_active_file: number; + active_anon: number; + total_active_anon: number; + total_pgpgout: number; + total_cache: number; + inactive_anon: number; + active_file: number; + pgfault: number; + inactive_file: number; + total_pgpgin: number; + }; + max_usage: number; + usage: number; + failcnt: number; + limit: number; + } + + interface ContainerStats { + read: string; + pid_stats: { + current: number; + }; + networks: NetworkStats; + memory_stats: MemoryStats; + blkio_stats: {}; + cpu_stats: CPUStats; + precpu_stats: CPUStats; + } + interface HostConfig { AutoRemove: boolean; Binds: string[]; @@ -652,13 +755,45 @@ declare namespace Dockerode { GlobalIPv6Address?: string; GlobalIPV6PrefixLen?: number; MacAddress?: string; - DriverOpts?: {[key: string]: string}; + DriverOpts?: { [key: string]: string }; } interface EndpointsConfig { [key: string]: EndpointSettings; } + type MountType = + | "bind" + | "volume" + | "tmpfs"; + + type MountConsistency = + | "default" + | "consistent" + | "cached" + | "delegated"; + + type MountPropagation = + | "private" + | "rprivate" + | "shared" + | "rshared" + | "slave" + | "rslave"; + + interface MountSettings { + Target: string; + Source: string; + Type: MountType; + ReadOnly ?: boolean; + Consistency ?: MountConsistency; + BindOptions ?: { + Propagation: MountPropagation; + }; + } + + type MountConfig = MountSettings[]; + interface ContainerCreateOptions { name?: string; Hostname?: string; @@ -715,6 +850,7 @@ declare namespace Dockerode { DnsSearch?: string[]; ExtraHosts?: any; VolumesFrom?: string[]; + Mounts?: MountConfig; CapAdd?: string[]; CapDrop?: string[]; GroupAdd?: string[]; @@ -894,8 +1030,8 @@ declare namespace Dockerode { } interface ImageBuildContext { - context: string; - src: string[]; + context: string; + src: string[]; } interface DockerVersion { @@ -906,7 +1042,7 @@ declare namespace Dockerode { Details: { ApiVersion: string; Arch: string; - BuilTime: Date; + BuildTime: Date; Experimental: string; GitCommit: string; GoVersion: string; diff --git a/types/dot-prop/dot-prop-tests.ts b/types/dot-prop/dot-prop-tests.ts index 420fe2d320..7b21eb76c9 100644 --- a/types/dot-prop/dot-prop-tests.ts +++ b/types/dot-prop/dot-prop-tests.ts @@ -18,6 +18,6 @@ dotProp.has({foo: {bar: 'unicorn'}}, 'foo.bar'); dotProp.delete(obj, 'foo.bar'); console.log(obj); -( obj).foo.bar = {x: 'y', y: 'x'}; +(obj as any).foo.bar = {x: 'y', y: 'x'}; dotProp.delete(obj, 'foo.bar.x'); console.log(obj); diff --git a/types/dropbox-chooser/dropbox-chooser-tests.ts b/types/dropbox-chooser/dropbox-chooser-tests.ts index f0930733f8..e998bad7bf 100644 --- a/types/dropbox-chooser/dropbox-chooser-tests.ts +++ b/types/dropbox-chooser/dropbox-chooser-tests.ts @@ -1,7 +1,7 @@ // Tests for Dropbox Chooser DefinitelyTyped TS definitions -const options: DropboxChooserOptions = { - success: (files: ReadonlyArray) => { +const options: Dropbox.ChooserOptions = { + success: (files: ReadonlyArray) => { console.log('Success, selected files were:', files); }, }; @@ -9,7 +9,7 @@ const options: DropboxChooserOptions = { const Dropbox = window.Dropbox!; Dropbox.choose(options); -const sampleFile: DropboxChooserFile = { +const sampleFile: Dropbox.ChooserFile = { id: 'SAMPLE_ID', name: 'HelloBox.jpg', link: 'http://localhost/1.png', diff --git a/types/dropbox-chooser/index.d.ts b/types/dropbox-chooser/index.d.ts index 8c9db6f72d..c5fd8a6cd6 100644 --- a/types/dropbox-chooser/index.d.ts +++ b/types/dropbox-chooser/index.d.ts @@ -4,13 +4,13 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace Dropbox { - interface DropboxChooser { + interface Chooser { choose(options: ChooserOptions): void; } interface ChooserOptions { - // alled when a user selects an item in the Chooser - success(files: ReadonlyArray): void; + // called when a user selects an item in the Chooser + success(files: ReadonlyArray): void; // called when the user closes the dialog without selecting a file cancel?(): void; @@ -31,7 +31,7 @@ declare namespace Dropbox { sizeLimit?: number; } - interface File { + interface ChooserFile { // Unique ID for the file, compatible with Dropbox API v2. id: string; @@ -55,12 +55,12 @@ declare namespace Dropbox { // whether or not the file is actually a directory isDir: boolean; } -} -type DropboxChooser = Dropbox.DropboxChooser; -type DropboxChooserOptions = Dropbox.ChooserOptions; -type DropboxChooserFile = Dropbox.File; + // Refer to "Handling the response" section of: https://www.dropbox.com/developers/chooser + type ChooserFileBoundingBox = 75 | 256 | 800 | 1280 | 2048; + type ChooserFileMode = 'fit' | 'crop' | 'fit_one_and_overflow'; +} interface Window { - Dropbox?: DropboxChooser; + Dropbox?: Dropbox.Chooser; } diff --git a/types/duplexer3/duplexer3-tests.ts b/types/duplexer3/duplexer3-tests.ts index c540828d5d..03c5107e94 100644 --- a/types/duplexer3/duplexer3-tests.ts +++ b/types/duplexer3/duplexer3-tests.ts @@ -8,7 +8,7 @@ writable._write = (input, encoding, done) => { if (readable.push(input)) { done(); } else { - readable.once('drain', <(...args: any[]) => void> done); + readable.once('drain', done as (...args: any[]) => void); } }; diff --git a/types/dynatrace/dynatrace-tests.ts b/types/dynatrace/dynatrace-tests.ts new file mode 100644 index 0000000000..027b924cf9 --- /dev/null +++ b/types/dynatrace/dynatrace-tests.ts @@ -0,0 +1,88 @@ +function customActions() { + const actionId = dynaTrace.enterAction("my custom action", "click"); + dynaTrace.leaveAction(actionId); +} + +function customVisit() { + dynaTrace.tagVisit("My Custom Visit"); + /** after some code execution we can end the visit early */ + dynaTrace.endVisit(); +} + +function signal() { + dynaTrace.signalLoadStart(); + dynaTrace.signalLoadEnd(); + dynaTrace.signalOnLoadStart(); + dynaTrace.signalOnLoadEnd(); + + dynaTrace.sendSignal(false, false, true); +} + +function load() { + dynaTrace.setLoadEndManually(); + dynaTrace.incrementOnLoadEndMarkers(); +} + +function automaticDetection() { + dynaTrace.setAutomaticActionDetection(false); +} + +function reporting() { + dynaTrace.reportError(" Custom error"); + const actionId = dynaTrace.enterAction("second action", "keypress"); + dynaTrace.reportError("Second custom error", actionId); + + dynaTrace.reportEvent("My Event"); + dynaTrace.reportString("My Key", "Custom value"); + dynaTrace.reportValue("Value Key", 2); + dynaTrace.reportWarning("Warning"); +} + +function thirdParty() { + const url = "http://somescript.com"; + dynaTrace.startThirdParty("s", url); + dynaTrace.stopThirdParty(url, true, Date.now() - 1000, Date.now()); +} + +function listener() { + const clickListener = (key: string) => ({}); + dynaTrace.addPageLeavingListener(clickListener); +} + +function streaming() { + dynaTrace.addStreamingNode( + "http://youtube.com", + 120, + true, + false, + 120, + 30, + 10, + 5, + "_info_" + ); +} + +function userInput() { + const userInput = dynaTrace.beginUserInput("", "click", "RETURN", 23); + dynaTrace.endUserInput(userInput); +} + +function Xhr() { + const enterActionId = dynaTrace.enterXhrAction( + "Angular Http request", + 0, + false + ); + dynaTrace.enterXhrCallback(enterActionId); + dynaTrace.leaveXhrCallback(enterActionId); + dynaTrace.leaveXhrAction(enterActionId); +} + +function appVersion() { + dynaTrace.setAppVersion("1.1.1"); +} + +function metadata() { + dynaTrace.setMetaData("some metadata", "value"); +} diff --git a/types/dynatrace/index.d.ts b/types/dynatrace/index.d.ts new file mode 100644 index 0000000000..5627e6b1db --- /dev/null +++ b/types/dynatrace/index.d.ts @@ -0,0 +1,234 @@ +// Type definitions for dynatrace 1.0 +// Project: https://www.dynatrace.com/ +// Definitions by: Alvaro Cruz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface dynaTrace { + /** + * @description disable automatic detection + * Use in conjuction with enterAction + * @example + * dynaTrace.setAutomaticActionDetection(false); + * dynaTrace.enterAction('action message', 'select', null, null); + */ + setAutomaticActionDetection(on: boolean): void; + /** + * @description capture load event manually. + * followed by a signalLoadEnd to complete the capture. + */ + setLoadEndManually(): void; + /** + * @description Signal load start. If load start can be determined more accurately + * than the automatic detection, this function can be used. + */ + signalLoadStart(): void; + /** + * @description Signals that the page has finished loading + */ + signalLoadEnd(): void; + /** + * @description Force signal sending to make certain that actions aren't lost. + * @param forceSync - Force synchronous sending of signal (if false, it'll be sent asynchronously) + * @param sendPreview - Force sending of preview signals which haven't been closed yet. + * @param killUnfinished - Kills unfinished actions and sends them immediately. Handle with care, actions might be inaccurate. + */ + sendSignal( + forceSync: boolean, + sendPreview: boolean, + killUnfinished: boolean + ): void; + /** + * @description parentAction: optional id of parent action. + * - if parameter is not passed => appended to currently running action + * - if a number is passed => action is added as subaction to action with given id + * - if false => new root action is started. + * The function returns an internal tracking object that represents the action that was started. + * This tracking object must be passed to dynaTrace.leaveAction(). + * @param name - name of the action + * @param type + * @param startTime - time in milliseconds. if null, current time is used. + * @param parentAction optional id of parent action. if parameter is not passed=> appended to + * currently running action, if false => root action, if a number is passed, action is added + * as subaction to action with given id. + * @returns id of created action + */ + enterAction( + name: string, + type: string, + time?: number, + parentAction?: number | boolean + ): number; + /** + * @description stops the action that is represented by the given tracking object. + * @param actionId - id of action to leave. must be the value returned by enterAction + * @param time - end time in milliseconds + * @param startTime - optional start time in milliseconds (necessary if start time should be modified) + */ + leaveAction(actionId: number, time?: number, startTime?: number): void; + /** + * @description Reports an error message + * @param parentAction - parent action id. if not passed or null, error is added to current action + */ + reportError(error: string | Error, parentAction?: number): void; + /** + * @description Reports a warning message + * @param parentAction - parent action id. if not passed or null, error is added to current action + */ + reportWarning(warning: string, parentAction?: number): void; + /** + * @description Reports an event + * @param parentAction - parent action id. if not passed or null, error is added to current action + */ + reportEvent(msg: string, parentAction?: number): void; + /** + * @description Reports a key value pair to the server. The data can e.g. be used to create charts. + */ + reportValue(key: string, value: number): void; + /** + * @description Reports a key value pair to the server. The data can e.g. be used to create charts. + * The difference to the reportValue function is that here the value is a string. + */ + reportString(key: string, value: string): void; + /** + * @description The JavaScript ADK enables you to tag your visits with any value you want. + * Use tagVisit(visitName) to tag the current visit with the specified value + */ + tagVisit(visitName: string): void; + /** + * @description Indicates start of a third party resource + * @param type - i = image, s = script, c = custom + */ + startThirdParty(type: "i" | "s" | "c", url: string): void; + /** + * @description Indicates stop of a third party resource + * @param url - Complete URL of resource (must match URL provided in startThirdParty). + * @param success - True if the resource was loaded successfully, false if not. + * @param start - Absolute start time in milliseconds. When parameter is not passed or <= 0, + * time of startThirdParty call is used. + * @param stop - Absolute stop time in milliseconds. When parameter is not passed or <= 0, + * time of stopThirdParty call is used. + */ + stopThirdParty( + url: string, + success: boolean, + start?: number, + stop?: number + ): void; + /** + * @description Adds a listener that is called when the user is leaving the page, + * but before the monitor signal is sent + * @param listener A function that will be called in case the user leaves the page. + */ + addPageLeavingListener(listener: (key: string) => {}): void; + /** + * @description Sends a Streaming Node to the Server + * @param source - URL of the streaming resource + * @param duration - duration of the streaming resource in seconds + * @param userTriggered - did the user trigger the playback or did it start automatically? + * @param watchedCompletely - did the streaming resource play to the end? + * @param maxPlayTime - maximum progress this streaming resource had in seconds + * @param playTime - the time this streaming resource was playing in seconds + * @param bufferingCount - amount of bufferings that occured during the playback + * @param bufferingTime - total time spent with buffering in seconds + * @param type - action type of the streaming node. Is used for classifying events + * on the serverside, e.g. _info_, _warn_, _error_ + */ + addStreamingNode( + source: string, + duration: number, + userTriggered: boolean, + watchedCompletely: boolean, + maxPlayTime: number, + playTime: number, + bufferingCount: number, + bufferingTime: number, + type: "_info_" | "_warn_" | "_error_" + ): void; + /** + * @description Indicates the start of a user input. User inputs must always + * be stopped by calling endUserInput. If an xhr call or a page load happens + * it is checked if a user input is active. If yes, the user input is set to + * have triggered the page action. + * @param domNode - Which triggered the action (button, etc) is used for determining its caption + * @param type - Type of the user input: 'click', 'keypress', 'scroll',... + * @param addInfo - Additional info for user input such as key, mouse button, etc ('F5', 'RETURN',...) + * @param validTime - How long should the user input be able to open actions? default is 30ms + */ + beginUserInput( + domNode: any, + type: string, + addInfo: string, + validTime: number + ): any; + /** + * @description the user input object returned by beginUserInput + */ + endUserInput(userInputObject: any): void; + /** + * @description Initiate ajax action. Must be closed by leaveXhrAction afterwards. + * @param type Additional info about type of xhr (eg. framework name,etc) + * @param mode - The action mode: 0 .. just extend running ajax actions 1 .. extend any running action 2 .. + * extend any running action - visible subaction 3 .. start action if user input is present + * @param webSocket - Indicates if this action is a webSocket action or not + * @returns id of action + */ + enterXhrAction(type: string, mode: number, webSocket: boolean): number; + /** + * @description Indicates the end of an xhr action. Must be started by leaveXhrAction beforehand. + * @param id - id of action (must be the value returned by enterXhrAction) + */ + leaveXhrAction(id: number): void; + /** + * @description Indicates that an xhr callback is active (eg. XMLHttpRequest onreadystatechange). + * This is necessary to automatically add actions started during a callback as subactions. + * Xhr callback must be stopped by leaveXhrCallback. + * @param actionId - id of action where callback belongs to + */ + enterXhrCallback(actionId: number): void; + /** + * @description Indicates the end of an xhr callback. Must be called after enterXhrCallback. + * @param actionId - id of action where callback belongs to + */ + leaveXhrCallback(actionId: number): void; + /** + * @description Indicates the start of a load action. Frameworks often have their own load callback functions. + * This can be used when framework starts load before "DOMContentLoaded". + */ + signalOnLoadStart(): void; + /** + * @description Tells the JavaScript agent to wait for an additional call of signalOnLoadEnd. + * When the last call of signalOnLoadEnd is performed the "onload" action is closed. + * Note: if this function is called, signalOnLoadEnd MUST be called afterwards to indicated the end of one load. + * Otherwise there will be unexpected action behaviour. + */ + incrementOnLoadEndMarkers(): void; + /** + * @description Indicates the end of a load action. needs incrementOnLoadEndMarkers to be called before. + * As soon as the last signalOnLoadEnd is called, the "onload" action is closed. + */ + signalOnLoadEnd(): void; + /** + * @description By default a visit ends after a configurable inactivity time (default is 30 min.). + * Using the ADK, a visit can be ended forcibly, for example when a user logs out from an application. + * Simply call dynaTrace.endVisit() and the visit ends without waiting for the inactivity time. + * For correlation purposes the visit shows as active in the client for about three minutes, + * but actions sent after dynaTrace.endVisit() are added to a new visit. + * End the current UEM visit. This is useful for "logout" buttons, so that, + * when the user logs out, the user's visit can also be closed by calling this method. + */ + endVisit(): void; + /** + * @description Set the application version for this visit. + * This will be read on the server side and included as part of each visit for easy splitting. + * @param appVersion - The version string to be set. + */ + setAppVersion(appVersion: string): void; + /** + * @description Set meta-data for the page via a key/value pair. + * @param key - The readable key for the value + * @param value - The value to associate with the identifier + */ + setMetaData(key: string, value: string): void; +} + +declare let dynaTrace: dynaTrace; diff --git a/types/dynatrace/tsconfig.json b/types/dynatrace/tsconfig.json new file mode 100644 index 0000000000..6c137be982 --- /dev/null +++ b/types/dynatrace/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dynatrace-tests.ts" + ] +} diff --git a/types/dynatrace/tslint.json b/types/dynatrace/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dynatrace/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/easy-api-request/easy-api-request-tests.ts b/types/easy-api-request/easy-api-request-tests.ts index 02b2bc92bf..e1999170fe 100644 --- a/types/easy-api-request/easy-api-request-tests.ts +++ b/types/easy-api-request/easy-api-request-tests.ts @@ -17,7 +17,7 @@ APIRequest.create({ var app = express(); app.get('/', function (req:any, res:express.Response) { - var rMaker = req.testAPI; + var rMaker = req.testAPI as APIRequest.RequestMaker; var r = rMaker(); r.get('/', function (err, resp) { if(err) { @@ -28,7 +28,7 @@ app.get('/', function (req:any, res:express.Response) { }); app.get('/', function (req:any, res:express.Response) { - var rMaker = req.testAPI; + var rMaker = req.testAPI as APIRequest.RequestMaker; var r = rMaker(); r.get('/') .then(function (resp) { diff --git a/types/echarts/index.d.ts b/types/echarts/index.d.ts index 207b8366ef..adc4a2a24e 100644 --- a/types/echarts/index.d.ts +++ b/types/echarts/index.d.ts @@ -9,6 +9,7 @@ // TypeScript Version: 2.3 /// +/// declare namespace echarts { /** diff --git a/types/echarts/options/index.d.ts b/types/echarts/options/index.d.ts new file mode 100644 index 0000000000..fded0ed4c7 --- /dev/null +++ b/types/echarts/options/index.d.ts @@ -0,0 +1,28 @@ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/ej.web.all/tslint.json b/types/ej.web.all/tslint.json index 35e3f27cc8..0615bdcb0e 100644 --- a/types/ej.web.all/tslint.json +++ b/types/ej.web.all/tslint.json @@ -37,6 +37,7 @@ "radix": false, "prefer-for-of": false, "one-line": false, - "no-unnecessary-type-assertion": false + "no-unnecessary-type-assertion": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ejs/ejs-tests.ts b/types/ejs/ejs-tests.ts index 8a0b2404d7..881a3fe103 100644 --- a/types/ejs/ejs-tests.ts +++ b/types/ejs/ejs-tests.ts @@ -29,6 +29,9 @@ result = ejs.render(template, data, options); result = ejs.renderFile(fileName, SimpleCallback); result = ejs.renderFile(fileName, data, SimpleCallback); result = ejs.renderFile(fileName, data, options, SimpleCallback); +asyncResult = ejs.renderFile(fileName); +asyncResult = ejs.renderFile(fileName, data); +asyncResult = ejs.renderFile(fileName, data, options); ejsFunction = ejs.compile(''); ejsFunction = ejs.compile(read(fileName, "utf8")); diff --git a/types/ejs/index.d.ts b/types/ejs/index.d.ts index 73eb716e23..fc578cffff 100644 --- a/types/ejs/index.d.ts +++ b/types/ejs/index.d.ts @@ -54,6 +54,8 @@ export type RenderFileCallback = (err: Error, str?: string) => T; export function renderFile(path: string, cb: RenderFileCallback): T; export function renderFile(path: string, data: Data, cb: RenderFileCallback): T; export function renderFile(path: string, data: Data, opts: Options, cb: RenderFileCallback): T; +// tslint:disable-next-line no-unnecessary-generics +export function renderFile(path: string, data?: Data, opts?: Options): Promise; /** * Clear intermediate JavaScript cache. Calls {@link Cache#reset}. diff --git a/types/elasticsearch/elasticsearch-tests.ts b/types/elasticsearch/elasticsearch-tests.ts index ee57f847fa..0d12a931ed 100644 --- a/types/elasticsearch/elasticsearch-tests.ts +++ b/types/elasticsearch/elasticsearch-tests.ts @@ -209,7 +209,7 @@ client.get({ id: '1', routing: '1' }, (error, response) => { - const routing = response._routing; + const routing = response._routing; }); client.mget({ @@ -338,22 +338,43 @@ client.indices.updateAliases({ // ... }); -client.reindex({ - body: { - source: { - index: "twitter" - }, - dest: { - index: "new_twitter" +client.indices.updateAliases({ + body: { + actions: [ + { + add: { + index: 'logstash-2018.11', alias: 'logstash-filtered', filter: { + query: { + exists: { field: 'id' } + } + }, + routing: 'id' } } + ] + } +}).then((response) => { + // ... +}, (error) => { + // ... +}); + +client.reindex({ + body: { + source: { + index: "twitter" + }, + dest: { + index: "new_twitter" + } + } }) -.then(response => { + .then(response => { const { took, timed_out } = response; // ... -}); + }); // Errors function testErrors() { - throw new elasticsearch.errors.AuthenticationException(); + throw new elasticsearch.errors.AuthenticationException(); } diff --git a/types/elasticsearch/index.d.ts b/types/elasticsearch/index.d.ts index 0d16cc6a4b..54956d89a2 100644 --- a/types/elasticsearch/index.d.ts +++ b/types/elasticsearch/index.d.ts @@ -23,76 +23,76 @@ export class Client { nodes: Nodes; snapshot: Snapshot; tasks: Tasks; - bulk(params: BulkIndexDocumentsParams): Promise; bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; + bulk(params: BulkIndexDocumentsParams): Promise; clearScroll(params: ClearScrollParams, callback: (error: any, response: any) => void): void; clearScroll(params: ClearScrollParams): Promise; count(params: CountParams, callback: (error: any, response: CountResponse) => void): void; count(params: CountParams): Promise; - create(params: CreateDocumentParams): Promise; create(params: CreateDocumentParams, callback: (err: any, response: CreateDocumentResponse, status: any) => void): void; - delete(params: DeleteDocumentParams): Promise; + create(params: CreateDocumentParams): Promise; delete(params: DeleteDocumentParams, callback: (error: any, response: DeleteDocumentResponse) => void): void; - deleteByQuery(params: DeleteDocumentByQueryParams): Promise; + delete(params: DeleteDocumentParams): Promise; deleteByQuery(params: DeleteDocumentByQueryParams, callback: (error: any, response: DeleteDocumentByQueryResponse) => void): void; - deleteScript(params: DeleteScriptParams): Promise; + deleteByQuery(params: DeleteDocumentByQueryParams): Promise; deleteScript(params: DeleteScriptParams, callback: (error: any, response: any) => void): void; - deleteTemplate(params: DeleteTemplateParams): Promise; + deleteScript(params: DeleteScriptParams): Promise; deleteTemplate(params: DeleteTemplateParams, callback: (error: any, response: any) => void): void; - exists(params: ExistsParams): Promise; + deleteTemplate(params: DeleteTemplateParams): Promise; exists(params: ExistsParams, callback: (error: any, response: boolean, status?: any) => void): void; - explain(params: ExplainParams): Promise; + exists(params: ExistsParams): Promise; explain(params: ExplainParams, callback: (error: any, response: ExplainResponse) => void): void; - fieldStats(params: FieldStatsParams): Promise; + explain(params: ExplainParams): Promise; fieldStats(params: FieldStatsParams, callback: (error: any, response: FieldStatsResponse) => void): void; + fieldStats(params: FieldStatsParams): Promise; get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; get(params: GetParams): Promise>; - getScript(params: GetScriptParams): Promise; getScript(params: GetScriptParams, callback: (error: any, response: any) => void): void; - getSource(params: GetSourceParams): Promise; + getScript(params: GetScriptParams): Promise; getSource(params: GetSourceParams, callback: (error: any, response: any) => void): void; - getTemplate(params: GetTemplateParams): Promise; + getSource(params: GetSourceParams): Promise; getTemplate(params: GetTemplateParams, callback: (error: any, response: any) => void): void; - index(params: IndexDocumentParams): Promise; + getTemplate(params: GetTemplateParams): Promise; index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; - info(params: InfoParams): Promise; + index(params: IndexDocumentParams): Promise; info(params: InfoParams, callback: (error: any, response: any) => void): void; + info(params: InfoParams): Promise; mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; mget(params: MGetParams): Promise>; msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; msearch(params: MSearchParams): Promise>; msearchTemplate(params: MSearchTemplateParams, callback: (error: any, response: MSearchResponse) => void): void; msearchTemplate(params: MSearchTemplateParams): Promise>; - mtermvectors(params: MTermVectorsParams): Promise; mtermvectors(params: MTermVectorsParams, callback: (error: any, response: any) => void): void; - ping(params: PingParams): Promise; + mtermvectors(params: MTermVectorsParams): Promise; ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; - putScript(params: PutScriptParams): Promise; + ping(params: PingParams): Promise; putScript(params: PutScriptParams, callback: (err: any, response: any, status: any) => void): void; - putTemplate(params: PutTemplateParams): Promise; + putScript(params: PutScriptParams): Promise; putTemplate(params: PutTemplateParams, callback: (err: any, response: any, status: any) => void): void; - reindex(params: ReindexParams): Promise; + putTemplate(params: PutTemplateParams): Promise; reindex(params: ReindexParams, callback: (error: any, response: ReindexResponse) => void): void; - reindexRethrottle(params: ReindexRethrottleParams): Promise; + reindex(params: ReindexParams): Promise; reindexRethrottle(params: ReindexRethrottleParams, callback: (error: any, response: any) => void): void; - renderSearchTemplate(params: RenderSearchTemplateParams): Promise; + reindexRethrottle(params: ReindexRethrottleParams): Promise; renderSearchTemplate(params: RenderSearchTemplateParams, callback: (error: any, response: any) => void): void; - scroll(params: ScrollParams): Promise>; + renderSearchTemplate(params: RenderSearchTemplateParams): Promise; scroll(params: ScrollParams, callback: (error: any, response: SearchResponse) => void): void; - search(params: SearchParams): Promise>; + scroll(params: ScrollParams): Promise>; search(params: SearchParams, callback: (error: any, response: SearchResponse) => void): void; - searchShards(params: SearchShardsParams): Promise; + search(params: SearchParams): Promise>; searchShards(params: SearchShardsParams, callback: (error: any, response: SearchShardsResponse) => void): void; - searchTemplate(params: SearchTemplateParams): Promise; + searchShards(params: SearchShardsParams): Promise; searchTemplate(params: SearchTemplateParams, callback: (error: any, response: any) => void): void; - suggest(params: SuggestParams): Promise; + searchTemplate(params: SearchTemplateParams): Promise; suggest(params: SuggestParams, callback: (error: any, response: any) => void): void; - termvectors(params: TermvectorsParams): Promise; + suggest(params: SuggestParams): Promise; termvectors(params: TermvectorsParams, callback: (error: any, response: any) => void): void; - update(params: UpdateDocumentParams): Promise; + termvectors(params: TermvectorsParams): Promise; update(params: UpdateDocumentParams, callback: (error: any, response: any) => void): void; - updateByQuery(params: UpdateDocumentByQueryParams): Promise; + update(params: UpdateDocumentParams): Promise; updateByQuery(params: UpdateDocumentByQueryParams, callback: (error: any, response: UpdateDocumentByQueryResponse) => void): void; + updateByQuery(params: UpdateDocumentByQueryParams): Promise; close(): void; } @@ -1400,6 +1400,8 @@ export interface IndicesUpdateAliasesParamsAction { index?: string; indices?: string[]; alias: string; + routing?: string; + filter?: object; }; remove?: { index?: string; diff --git a/types/electron-packager/electron-packager-tests.ts b/types/electron-packager/electron-packager-tests.ts index 06cadf97f0..6b10ea4bf3 100644 --- a/types/electron-packager/electron-packager-tests.ts +++ b/types/electron-packager/electron-packager-tests.ts @@ -13,25 +13,6 @@ function ignoreFunction(path: string) { return true; } -// this is the obsolete API and will be removed in a future version - -packager({ - dir: ".", - name: "myapplication", - platform: "win32", - arch: "all", - electronVersion: "0.34.0", - win32metadata: { - CompanyName: "Acme CO", - FileDescription: "My application", - OriginalFilename: "myapp.exe", - ProductName: "Application", - InternalName: "roadrunner", - "requested-execution-level": "highestAvailable", - "application-manifest": "manifest.xml" - } -}, callback); - function onCompleted(appPaths: string | string[]) { } @@ -102,7 +83,7 @@ packager({ afterExtract: [ completeFunction ], - afterPrune: [ + afterPrune: [ completeFunction ], appCopyright: "Copyright", @@ -122,7 +103,6 @@ packager({ ignore: /ab+c/, out: "out", overwrite: true, - packageManager: false, prune: true, quiet: true, tmpdir: "/tmp", @@ -157,7 +137,6 @@ packager({ new RegExp('abc') ], overwrite: false, - packageManager: "npm", platform: "darwin", prune: false, quiet: false, @@ -184,7 +163,14 @@ packager({ strictSSL: false }, ignore: ignoreFunction, - packageManager: "cnpm", + platform: "linux" +}).then(onCompleted).catch(onError); + +packager({ + dir: ".", + arch: "mips64el", + electronVersion: "1.8.8", + prebuiltAsar: "prebuilt.asar", platform: "linux" }).then(onCompleted).catch(onError); @@ -200,11 +186,14 @@ packager({ quiet: true, strictSSL: false }, - packageManager: "yarn", platform: "mas", extendInfo: { foo: "bar" }, + osxNotarize: { + appleId: "My ID", + appleIdPassword: "Bad Password" + }, osxSign: { identity: "myidentity", entitlements: "path/to/my.entitlements", diff --git a/types/electron-packager/index.d.ts b/types/electron-packager/index.d.ts index 0e438ebc6e..04e62a28b5 100644 --- a/types/electron-packager/index.d.ts +++ b/types/electron-packager/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for electron-packager 12.0 +// Type definitions for electron-packager 13.0 // Project: https://github.com/electron-userland/electron-packager // Definitions by: Maxime LUCE // Juan Jimenez-Anca // John Kleinschmidt // Brendan Forster +// Mark Lee // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -23,20 +24,6 @@ export = electronPackager; */ declare function electronPackager(opts: electronPackager.Options): Promise; -/** - * This will: - * - Find or download the correct release of Electron - * - Use that version of electron to create a app in /-- - * - * You should be able to launch the app on the platform you built for. If not, check your settings and try again. - * - * @param opts - Options to configure packaging. - * @param callback - Callback which is called when packaging is done or an error occured. - * - * @deprecated since version 12.0 - */ -declare function electronPackager(opts: electronPackager.Options, callback: electronPackager.finalCallback): void; - declare namespace electronPackager { /** * Callback which is called when electron-packager is done. @@ -48,8 +35,7 @@ declare namespace electronPackager { type ignoreFunction = (path: string) => boolean; type onCompleteFn = (buildPath: string, electronVersion: string, platform: string, arch: string, callbackFn: () => void) => void; - type arch = "ia32" | "x64" | "armv7l" | "arm64" |"all"; - type packageManager = "npm" | "cnpm" | "yarn" | false; + type arch = "ia32" | "x64" | "armv7l" | "arm64" | "mips64el" | "all"; type platform = "linux" | "win32" | "darwin" | "mas" | "all"; interface AsarOptions { @@ -65,6 +51,11 @@ declare namespace electronPackager { strictSSL?: boolean; } + interface ElectronNotarizeOptions { + appleId: string; + appleIdPassword: string; + } + interface ElectronOsXSignOptions { identity?: string; entitlements?: string; @@ -116,6 +107,10 @@ declare namespace electronPackager { * Whether to package the application's source code into an archive, using Electron's archive format */ asar?: boolean | AsarOptions; + /** + * The path to a prebuilt ASAR file. + */ + prebuiltAsar?: string; /** * The build version of the application. Defaults to the value of appVersion. * Maps to the FileVersion metadata property on Windows, and CFBundleVersion on OS X. @@ -160,10 +155,6 @@ declare namespace electronPackager { * Whether to replace an already existing output directory for a given platform (true) or skip recreating it (false). */ overwrite?: boolean; - /** - * The package manager used to prune devDependencies modules from the outputted Electron app - */ - packageManager?: packageManager; /** * The target platform(s) to build for. Not required if the all option is set. */ @@ -202,6 +193,14 @@ declare namespace electronPackager { * The bundle identifier to use in the application helper's plist. */ helperBundleId?: string; + /** + * Forces support for Mojave (macOS 10.14) dark mode in the packaged app. + */ + darwinDarkModeSupport?: boolean; + /** + * If present, notarizes OS X target apps when the host platform is OS X and XCode is installed. + */ + osxNotarize?: ElectronNotarizeOptions; /** * If present, signs OS X target apps when the host platform is OS X and XCode is installed. */ diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index fdb89d3823..4e2b45cd55 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -478,6 +478,7 @@ export namespace Ember { const addObserver: typeof EmberObjectObserversNs.addObserver; const removeObserver: typeof EmberObjectObserversNs.removeObserver; const get: typeof EmberObjectNs.get; + const notifyPropertyChange: typeof EmberObjectNs.notifyPropertyChange; const getWithDefault: typeof EmberObjectNs.getWithDefault; const getProperties: typeof EmberObjectNs.getProperties; const setProperties: typeof EmberObjectNs.setProperties; diff --git a/types/ember/test/object.ts b/types/ember/test/object.ts index 060bf8ca81..853ed46d46 100755 --- a/types/ember/test/object.ts +++ b/types/ember/test/object.ts @@ -65,4 +65,11 @@ export class Foo2 extends Ember.Object { name }); } + + bar() { + Ember.notifyPropertyChange(this, 'name'); + Ember.notifyPropertyChange(this); // $ExpectError + Ember.notifyPropertyChange('name'); // $ExpectError + Ember.notifyPropertyChange(this, 'name', 'bar'); // $ExpectError + } } diff --git a/types/ember__object/index.d.ts b/types/ember__object/index.d.ts index f915bdc82a..06e417999d 100644 --- a/types/ember__object/index.d.ts +++ b/types/ember__object/index.d.ts @@ -385,6 +385,8 @@ export function defineProperty( meta?: any ): void; +export function notifyPropertyChange(obj: object, keyName: string): void; + declare module '@ember/utils/-private/types' { interface TypeLookup { class: typeof EmberObject; diff --git a/types/ember__object/test/object.ts b/types/ember__object/test/object.ts index b47aa22ffb..391ac183a9 100644 --- a/types/ember__object/test/object.ts +++ b/types/ember__object/test/object.ts @@ -1,4 +1,4 @@ -import EmberObject, { computed } from "@ember/object"; +import EmberObject, { computed, notifyPropertyChange } from "@ember/object"; const LifetimeHooks = EmberObject.extend({ resource: null as {} | null, @@ -47,6 +47,12 @@ class Foo extends EmberObject { b: 11 }); } + bar() { + notifyPropertyChange(this, 'name'); + notifyPropertyChange(this); // $ExpectError + notifyPropertyChange('name'); // $ExpectError + notifyPropertyChange(this, 'name', 'bar'); // $ExpectError + } } // TODO: enable after TS 3.0 https://github.com/typed-ember/ember-cli-typescript/issues/291 diff --git a/types/emoji-mart/index.d.ts b/types/emoji-mart/index.d.ts index 38acd9e021..a92bcb77ff 100644 --- a/types/emoji-mart/index.d.ts +++ b/types/emoji-mart/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for emoji-mart 2.8 // Project: https://github.com/missive/emoji-mart -// Definitions by: Diogo Franco +// Definitions by: Jessica Franco // Nick Winans // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/empty-dir/empty-dir-tests.ts b/types/empty-dir/empty-dir-tests.ts new file mode 100644 index 0000000000..63700ae87b --- /dev/null +++ b/types/empty-dir/empty-dir-tests.ts @@ -0,0 +1,25 @@ +import emptyDir = require('empty-dir'); + +emptyDir('./', (err, isEmpty) => { + // $ExpectType ErrnoException + err; + // $ExpectType boolean + isEmpty; +}); + +// $ExpectType boolean +emptyDir.sync('./test/empty'); + +function filter(filepath: string) { + return !/(Thumbs\.db|\.DS_Store)$/i.test(filepath); +} + +emptyDir('./', filter, (err, isEmpty) => { + // $ExpectType ErrnoException + err; + // $ExpectType boolean + isEmpty; +}); + +// $ExpectType boolean +emptyDir.sync('./test/empty', filter); diff --git a/types/empty-dir/index.d.ts b/types/empty-dir/index.d.ts new file mode 100644 index 0000000000..0f623a991d --- /dev/null +++ b/types/empty-dir/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for empty-dir 1.0 +// Project: https://github.com/js-cli/js-empty-dir +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = emptyDir; + +declare function emptyDir( + dir: string, + cb: (err: NodeJS.ErrnoException, isEmpty: boolean) => void +): void; +declare function emptyDir( + dir: string, + filter: (path: string) => boolean, + cb: (err: NodeJS.ErrnoException, isEmpty: boolean) => void +): void; + +declare namespace emptyDir { + function sync(dir: string, filter?: (path: string) => boolean): boolean; +} diff --git a/types/empty-dir/tsconfig.json b/types/empty-dir/tsconfig.json new file mode 100644 index 0000000000..cb73470ad8 --- /dev/null +++ b/types/empty-dir/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "empty-dir-tests.ts" + ] +} diff --git a/types/empty-dir/tslint.json b/types/empty-dir/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/empty-dir/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/escape-goat/escape-goat-tests.ts b/types/escape-goat/escape-goat-tests.ts new file mode 100644 index 0000000000..cfc1808495 --- /dev/null +++ b/types/escape-goat/escape-goat-tests.ts @@ -0,0 +1,14 @@ +import * as escapeGoat from 'escape-goat'; + +// $ExpectType string +escapeGoat.escape('🦄 & 🐐'); + +// $ExpectType string +escapeGoat.unescape('🦄 & 🐐'); + +// $ExpectType string +escapeGoat.escape('Hello World'); + +const url = 'https://sindresorhus.com?x="🦄"'; +// $ExpectType string +escapeGoat.escapeTag`Unicorn`; diff --git a/types/escape-goat/index.d.ts b/types/escape-goat/index.d.ts new file mode 100644 index 0000000000..f76f384fb0 --- /dev/null +++ b/types/escape-goat/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for escape-goat 1.3 +// Project: https://github.com/sindresorhus/escape-goat#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function escape(input: string): string; +export function unescape(input: string): string; +export function escapeTag(template: TemplateStringsArray, ...substitutions: any[]): string; +export function unescapeTag(template: TemplateStringsArray, ...substitutions: any[]): string; diff --git a/types/escape-goat/tsconfig.json b/types/escape-goat/tsconfig.json new file mode 100644 index 0000000000..9715cb59e1 --- /dev/null +++ b/types/escape-goat/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "escape-goat-tests.ts" + ] +} diff --git a/types/escape-goat/tslint.json b/types/escape-goat/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/escape-goat/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/eslint/eslint-tests.ts b/types/eslint/eslint-tests.ts index c6b8b786fa..ed211d220e 100644 --- a/types/eslint/eslint-tests.ts +++ b/types/eslint/eslint-tests.ts @@ -480,7 +480,10 @@ cli.addPlugin('my-fancy-plugin', {}); cli.isPathIgnored('./dist/index.js'); -const formatter = cli.getFormatter('codeframe'); +let formatter: CLIEngine.Formatter; + +formatter = cli.getFormatter('codeframe'); +formatter = cli.getFormatter(); formatter(cliReport.results); diff --git a/types/eslint/index.d.ts b/types/eslint/index.d.ts index 451477af40..01f39ee83e 100644 --- a/types/eslint/index.d.ts +++ b/types/eslint/index.d.ts @@ -471,7 +471,7 @@ export class CLIEngine { isPathIgnored(filePath: string): boolean; - getFormatter(format: string): CLIEngine.Formatter; + getFormatter(format?: string): CLIEngine.Formatter; getRules(): Map; diff --git a/types/eureka-js-client/eureka-js-client-tests.ts b/types/eureka-js-client/eureka-js-client-tests.ts index 109dab0278..b4b5c5f54e 100644 --- a/types/eureka-js-client/eureka-js-client-tests.ts +++ b/types/eureka-js-client/eureka-js-client-tests.ts @@ -19,3 +19,27 @@ const client = new Eureka({ port: 32768, } }); + +// example configuration against newer Eureka (https://www.npmjs.com/package/eureka-js-client#400-bad-request-errors-from-eureka-server) +const newerClient = new Eureka({ + // application instance information + instance: { + app: 'jqservice', + hostName: 'localhost', + ipAddr: '127.0.0.1', + port: { + $: 443, + '@enabled': true + }, + vipAddress: 'jq.test.something.com', + dataCenterInfo: { + '@class': 'com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo', + name: 'MyOwn', + }, + }, + eureka: { + // eureka server host / port + host: '192.168.99.100', + port: 32768, + } +}); diff --git a/types/eureka-js-client/index.d.ts b/types/eureka-js-client/index.d.ts index bfd9f10666..693e1b8ec8 100644 --- a/types/eureka-js-client/index.d.ts +++ b/types/eureka-js-client/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for eureka-js-client 4.3 +// Type definitions for eureka-js-client 4.4 // Project: https://github.com/jquatier/eureka-js-client -// Definitions by: Ilko Hoffmann +// Definitions by: Ilko Hoffmann , Karl O. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export class Eureka { @@ -26,7 +26,7 @@ export namespace EurekaClient { ipAddr: string; vipAddress: string; dataCenterInfo: DataCenterInfo; - port?: number; + port?: number | LegacyPortWrapper; instanceId?: string; appGroupName?: string; sid?: string; @@ -61,6 +61,10 @@ export namespace EurekaClient { useLocalMetadata?: boolean; preferIpAddress?: boolean; } + interface LegacyPortWrapper { + '$': number; + '@enabled': boolean; + } interface PortWrapper { enabled: boolean; port: number; @@ -71,5 +75,6 @@ export namespace EurekaClient { } interface DataCenterInfo { name: DataCenterName; + '@class'?: string; } } diff --git a/types/expand-tilde/expand-tilde-tests.ts b/types/expand-tilde/expand-tilde-tests.ts new file mode 100644 index 0000000000..8b655f1450 --- /dev/null +++ b/types/expand-tilde/expand-tilde-tests.ts @@ -0,0 +1,3 @@ +import expandTilde = require("expand-tilde"); + +expandTilde("~"); // $ExpectType string diff --git a/types/expand-tilde/index.d.ts b/types/expand-tilde/index.d.ts new file mode 100644 index 0000000000..7eec7b60ad --- /dev/null +++ b/types/expand-tilde/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for expand-tilde 2.0 +// Project: https://github.com/jonschlinkert/expand-tilde +// Definitions by: Chris Arnesen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Bash-like tilde expansion for node.js. + * Expands a leading tilde (~) in a file path to the user home directory, or ~+ to the cwd. + * + * @param {string} filePath - a file path to expand + * @returns {string} the expanded file path + */ +declare function expandTilde(filePath: string): string; + +export = expandTilde; diff --git a/types/expand-tilde/tsconfig.json b/types/expand-tilde/tsconfig.json new file mode 100644 index 0000000000..5ead90e013 --- /dev/null +++ b/types/expand-tilde/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expand-tilde-tests.ts" + ] +} diff --git a/types/expand-tilde/tslint.json b/types/expand-tilde/tslint.json new file mode 100644 index 0000000000..76efdfe46d --- /dev/null +++ b/types/expand-tilde/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-redundant-jsdoc-2": false + } +} diff --git a/types/expirymanager/expirymanager-tests.ts b/types/expirymanager/expirymanager-tests.ts new file mode 100644 index 0000000000..2206b2673e --- /dev/null +++ b/types/expirymanager/expirymanager-tests.ts @@ -0,0 +1,19 @@ +import { ExpiryManager } from "expirymanager"; + +const expiryManager = new ExpiryManager(); + +const keys = ['1', '2']; + +expiryManager.expire(keys, 1); + +expiryManager.unexpire(keys); + +const expiry: number = expiryManager.getExpiry(keys[0]); + +let expiredKeys = expiryManager.getExpiredKeys(); +expiredKeys = expiryManager.getExpiredKeys(expiryManager.now()); + +expiredKeys = expiryManager.extractExpiredKeys(); +expiredKeys = expiryManager.extractExpiredKeys(expiryManager.now()); + +expiryManager.clear(); diff --git a/types/expirymanager/index.d.ts b/types/expirymanager/index.d.ts new file mode 100644 index 0000000000..c192da7af7 --- /dev/null +++ b/types/expirymanager/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for expirymanager 0.9 +// Project: https://github.com/SocketCluster/expirymanager +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Key = any; +export type Keys = Key[]; + +export class ExpiryManager { + constructor(); + + now(): number; + + expire(keys: Keys, seconds: number): void; + unexpire(keys: Keys): void; + + getExpiry(key: Key): number; + + getKeysByExpiry(expiry: number): Keys; + + getExpiredKeys(time?: number): Keys; + extractExpiredKeys(time?: number): Keys; + + clear(): void; +} diff --git a/types/expirymanager/tsconfig.json b/types/expirymanager/tsconfig.json new file mode 100644 index 0000000000..094c4e8c8d --- /dev/null +++ b/types/expirymanager/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expirymanager-tests.ts" + ] +} diff --git a/types/expirymanager/tslint.json b/types/expirymanager/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/expirymanager/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 61467bd5d1..75dee784de 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -145,7 +145,8 @@ Audio.setAudioModeAsync({ playsInSilentModeIOS: true, interruptionModeIOS: 2, interruptionModeAndroid: 1, - allowsRecordingIOS: true + allowsRecordingIOS: true, + playThroughEarpieceAndroid: false }); Audio.setIsEnabledAsync(true); @@ -413,6 +414,21 @@ async () => { result.width; }; +async () => { + const result = await ImageManipulator.manipulateAsync('url', [ + { rotate: 360 }, + { resize: { width: 300 } }, + { resize: { height: 300 } }, + { resize: { height: 300, width: 300 } }, + ], { + compress: 0.75 + }); + + result.height; + result.uri; + result.width; +}; + FaceDetector.Constants.Mode.fast; FaceDetector.Constants.Mode.accurate; FaceDetector.Constants.Landmarks.all; diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index d5891bad2d..9e48e391d8 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for expo 30.0 +// Type definitions for expo 31.0 // Project: https://github.com/expo/expo-sdk // Definitions by: Konstantin Kai // Martynas Kadiša @@ -11,6 +11,8 @@ // Tina Roh // Nathan Phillip Brink // Martin Olsson +// Levan Basharuli +// Pavel Ihm // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -404,6 +406,9 @@ export namespace Audio { /** an enum selecting how your experience’s audio should interact with the audio from other apps on Android: */ interruptionModeAndroid: InterruptionModeAndroid; + + /** Boolean selecting if audio should go to earpiece (only on Android). */ + playThroughEarpieceAndroid: boolean; } function setIsEnabledAsync(value: boolean): Promise; @@ -565,7 +570,7 @@ export interface PlaybackStatusToSet { volume?: number; } -export type PlaybackSource = RequireSource | { uri: string } | Asset; +export type PlaybackSource = RequireSource | { uri: string, headers?: { [header: string]: string }, overrideFileExtensionAndroid?: string } | Asset; export class PlaybackObject { /** @@ -1559,6 +1564,8 @@ export namespace ImageManipulator { } function manipulate(uri: string, actions: Action[], saveOptions?: SaveOptions): Promise; + + function manipulateAsync(uri: string, actions: Action[], saveOptions?: SaveOptions): Promise; } /** @@ -2352,7 +2359,7 @@ export namespace Calendar { /** Name for the account that owns this calendar */ ownerAccount?: string; // Android - /** Time zone for the calendar */ + /** Time zone for the calendar */ timeZone?: string; // Android /** Alarm methods that this calendar supports */ @@ -2395,7 +2402,7 @@ export namespace Calendar { /** Visible name of the event */ title?: string; - /** Location field of the event */ + /** Location field of the event */ location?: string; /** Date when the event record was created */ diff --git a/types/expo/v30/expo-tests.tsx b/types/expo/v30/expo-tests.tsx new file mode 100644 index 0000000000..61467bd5d1 --- /dev/null +++ b/types/expo/v30/expo-tests.tsx @@ -0,0 +1,953 @@ +import * as React from 'react'; +import { Text } from 'react-native'; + +import { + Accelerometer, + AdMobAppEvent, + AdMobBanner, + AdMobInterstitial, + AdMobRewarded, + Amplitude, + Asset, + AuthSession, + Audio, + AppLoading, + BarCodeScanner, + BlurViewProps, + BlurView, + Brightness, + Camera, + CameraObject, + DocumentPicker, + Facebook, + FacebookAds, + FileSystem, + ImagePicker, + ImageManipulator, + FaceDetector, + Linking, + Svg, + IntentLauncherAndroid, + KeepAwake, + LinearGradient, + Permissions, + PublisherBanner, + registerRootComponent, + ScreenOrientation, + SQLite, + Calendar, + MailComposer, + Location, + Updates, + MediaLibrary, + Haptic, + Constants +} from 'expo'; + +const reverseGeocode: Promise = Location.reverseGeocodeAsync({ + latitude: 0, + longitude: 0 +}); + +Accelerometer.addListener((obj) => { + obj.x; + obj.y; + obj.z; +}); +Accelerometer.removeAllListeners(); +Accelerometer.setUpdateInterval(1000); + +() => ( + console.log(error)} + style={{ flex: 1 }} + /> +); + +() => ( + console.log(error)} + onAdMobDispatchAppEvent={(event: AdMobAppEvent) => console.log(event)} + style={{ flex: 1 }} + /> +); + +AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/1033173712'); // Test ID, Replace with your-admob-unit-id +AdMobInterstitial.setTestDeviceID('EMULATOR'); +async () => { + await AdMobInterstitial.requestAdAsync(); + await AdMobInterstitial.showAdAsync(); +}; + +AdMobRewarded.setAdUnitID('ca-app-pub-3940256099942544/1033173712'); // Test ID, Replace with your-admob-unit-id +AdMobRewarded.setTestDeviceID('EMULATOR'); +async () => { + await AdMobRewarded.requestAdAsync(); + await AdMobRewarded.showAdAsync(); +}; + +Amplitude.initialize('key'); +Amplitude.setUserId('userId'); +Amplitude.setUserProperties({key: 1}); +Amplitude.clearUserProperties(); +Amplitude.logEvent('name'); +Amplitude.logEventWithProperties('event', {key: 'value'}); +Amplitude.setGroup('type', ['value']); + +const asset = Asset.fromModule(1); +asset.downloadAsync(); +Asset.loadAsync(1); +Asset.loadAsync([1, 2, 3]); +const asset1 = new Asset({ + uri: 'uri', + type: 'type', + name: 'name', + hash: 'hash', + width: 122, + height: 122 +}); + +const url = AuthSession.getRedirectUrl(); +AuthSession.dismiss(); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: 'url2' +}).then(result => { + switch (result.type) { + case 'success': + result.event; + result.params; + break; + case 'error': + result.errorCode; + result.params; + result.event; + break; + case 'dismissed': + case 'cancel': + result.type; + break; + } +}); +AuthSession.startAsync({ + authUrl: 'url1', + returnUrl: undefined +}); + +Audio.setAudioModeAsync({ + shouldDuckAndroid: false, + playsInSilentModeIOS: true, + interruptionModeIOS: 2, + interruptionModeAndroid: 1, + allowsRecordingIOS: true +}); +Audio.setIsEnabledAsync(true); + +Audio.INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS === 0; +Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX === 1; +Audio.INTERRUPTION_MODE_IOS_DUCK_OTHERS === 2; + +Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX === 1; +Audio.INTERRUPTION_MODE_ANDROID_DUCK_OTHERS === 2; + +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT === 0; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_THREE_GPP === 1; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4 === 2; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_NB === 3; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_WB === 4; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADIF === 5; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADTS === 6; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_RTP_AVP === 7; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG2TS === 8; +Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_WEBM === 9; + +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT === 0; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB === 1; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_WB === 2; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC === 3; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_HE_AAC === 4; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC_ELD === 5; +Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_VORBIS === 6; + +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_LINEARPCM === 'lpcm'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AC3 === 'ac-3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_60958AC3 === 'cac3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLEIMA4 === 'ima4'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC === 'aac '; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4CELP === 'celp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4HVXC === 'hvxc'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4TWINVQ === 'twvq'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE3 === 'MAC3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE6 === 'MAC6'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ULAW === 'ulaw'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ALAW === 'alaw'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN === 'QDMC'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN2 === 'QDM2'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_QUALCOMM === 'Qclp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER1 === '.mp1'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER2 === '.mp2'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER3 === '.mp3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLELOSSLESS === 'alac'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE === 'aach'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_LD === 'aacl'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD === 'aace'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_SBR === 'aacf'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_V2 === 'aacg'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE_V2 === 'aacp'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_SPATIAL === 'aacs'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR === 'samr'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR_WB === 'sawb'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AUDIBLE === 'AUDB'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ILBC === 'ilbc'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_DVIINTELIMA === 0x6d730011; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_MICROSOFTGSM === 0x6d730031; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_AES3 === 'aes3'; +Audio.RECORDING_OPTION_IOS_OUTPUT_FORMAT_ENHANCEDAC3 === 'ec-3'; + +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN === 0; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_LOW === 0x20; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MEDIUM === 0x40; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH === 0x60; +Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_MAX === 0x7f; + +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_CONSTANT === 0; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_LONG_TERM_AVERAGE === 1; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE_CONSTRAINED === 2; +Audio.RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE === 3; + +Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY; +Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY; +async () => { + const result = await Audio.Sound.create({uri: 'uri'}, { + volume: 0.55, + rate: 16.5 + }, null, true); + + const sound = result.sound; + const status = result.status; + + if (!status.isLoaded) { + status.error; + } else { + status.didJustFinish; + // etc. + } + + const _status = await sound.getStatusAsync(); + await sound.loadAsync({uri: 'uri'}); +}; + +() => ( + Promise.resolve()} + onFinish={() => {}} + onError={(error) => console.log(error)} /> +); +() => ( + +); + +const barcodeReadCallback = () => {}; +() => ( + +); + +() => ( + +); + +async () => { + await Brightness.setBrightnessAsync(0.65); + await Brightness.setSystemBrightnessAsync(0.75); + const br1 = await Brightness.getBrightnessAsync(); + const br2 = await Brightness.getSystemBrightnessAsync(); +}; + +Camera.Constants.AutoFocus; +Camera.Constants.Type; +Camera.Constants.FlashMode; +Camera.Constants.WhiteBalance; +Camera.Constants.VideoQuality; +Camera.Constants.BarCodeType; +() => { + return( { + if (component) { + component.recordAsync(); + } + }} />); +}; +async (camera: CameraObject) => { + const picture = await camera.takePictureAsync({ + quality: 0.5, + base64: true, + exif: true + }); + + picture.uri; + picture.width; + picture.height; + picture.exif; + picture.base64; + + camera.takePictureAsync({ + quality: 1, + onPictureSaved: pic => { + pic.uri; + pic.width; + pic.height; + pic.exif; + pic.base64; + } + }); +}; + +async () => { + const result = await DocumentPicker.getDocumentAsync(); + + if (result.type === 'success') { + result.name; + result.uri; + result.size; + } +}; + +async () => { + const { type, expires, token } = await Facebook.logInWithReadPermissionsAsync("appId"); +}; + +() => ( + {}} + onError={() => {}} /> +); + +async () => { + const info = await FileSystem.getInfoAsync('file'); + + info.exists; + info.isDirectory; + + if (info.exists) { + info.md5; + info.uri; + info.size; + info.modificationTime; + } + + const string: string = await FileSystem.readAsStringAsync('file'); + await FileSystem.writeAsStringAsync('file', 'content'); + await FileSystem.deleteAsync('file'); + await FileSystem.moveAsync({ from: 'from', to: 'to'}); + await FileSystem.copyAsync({ from: 'from', to: 'to' }); + await FileSystem.makeDirectoryAsync('dir'); + const dirs: string[] = await FileSystem.readDirectoryAsync('dir'); + const result = await FileSystem.downloadAsync('from', 'to'); + + result.headers; + result.status; + result.uri; + result.md5; +}; + +async () => { + // Video test + const result = await ImagePicker.launchImageLibraryAsync({ + mediaTypes: ImagePicker.MediaTypeOptions.Videos, + }); + + if (!result.cancelled) { + result.uri; + result.width; + result.height; + result.duration; + result.type; + } +}; + +async () => { + // Image test + const result = await ImagePicker.launchImageLibraryAsync({ + mediaTypes: ImagePicker.MediaTypeOptions.Images, + base64: true, + aspect: [4, 3], + quality: 1, + exif: true, + }); + + if (!result.cancelled) { + result.uri; + result.width; + result.height; + result.exif; + result.base64; + result.type; + } +}; + +async () => { + const result = await ImageManipulator.manipulate('url', [ + { rotate: 90 }, + { resize: { width: 300 } }, + { resize: { height: 300 } }, + { resize: { height: 300, width: 300 } }, + ], { + compress: 0.75 + }); + + result.height; + result.uri; + result.width; +}; + +FaceDetector.Constants.Mode.fast; +FaceDetector.Constants.Mode.accurate; +FaceDetector.Constants.Landmarks.all; +FaceDetector.Constants.Landmarks.none; +FaceDetector.Constants.Classifications.all; +FaceDetector.Constants.Classifications.none; +async () => { + const result = await FaceDetector.detectFaces('url', { + mode: FaceDetector.Constants.Mode.fast, + detectLandmarks: FaceDetector.Constants.Landmarks.all, + runClassifications: FaceDetector.Constants.Classifications.none + }); + + result.faces[0]; +}; + +async () => { + function isBoolean(x: boolean) { + } + function isString(x: string) { + } + // Two examples of members inherited from react-native Linking + // to prove that inheritence is working. + Linking.addEventListener('url', (e) => { + e.url === ''; + }); + isBoolean(await Linking.canOpenURL('expo://')); + + // Extensions added by expo. + + isString(Linking.makeUrl('path')); + isString(Linking.makeUrl('path', { q: 2, u: 'ery', })); + + const { + path, + queryParams, + } = Linking.parse(''); + isString(path); + isString(queryParams['x'] || ''); + + const { + path: path2, + queryParams: queryParams2, + } = await Linking.parseInitialURLAsync(); + isString(path2); + isString(queryParams2['y'] || ''); +}; + +() => ( + + + + + + + + + STROKED TEXT + + + + + + + + We go up and down, + then up again + + + + + + + + + + + + + + + + + + + + + + +); + +() => ( + +); + +IntentLauncherAndroid.ACTION_ACCESSIBILITY_SETTINGS === 'android.settings.ACCESSIBILITY_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_NOTIFICATION_REDACTION === 'android.settings.ACTION_APP_NOTIFICATION_REDACTION'; +IntentLauncherAndroid.ACTION_CONDITION_PROVIDER_SETTINGS === 'android.settings.ACTION_CONDITION_PROVIDER_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_LISTENER_SETTINGS === 'android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS'; +IntentLauncherAndroid.ACTION_PRINT_SETTINGS === 'android.settings.ACTION_PRINT_SETTINGS'; +IntentLauncherAndroid.ACTION_ADD_ACCOUNT_SETTINGS === 'android.settings.ADD_ACCOUNT_SETTINGS'; +IntentLauncherAndroid.ACTION_AIRPLANE_MODE_SETTINGS === 'android.settings.AIRPLANE_MODE_SETTINGS'; +IntentLauncherAndroid.ACTION_APN_SETTINGS === 'android.settings.APN_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_DETAILS_SETTINGS === 'android.settings.APPLICATION_DETAILS_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_DEVELOPMENT_SETTINGS === 'android.settings.APPLICATION_DEVELOPMENT_SETTINGS'; +IntentLauncherAndroid.ACTION_APPLICATION_SETTINGS === 'android.settings.APPLICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_NOTIFICATION_SETTINGS === 'android.settings.APP_NOTIFICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_APP_OPS_SETTINGS === 'android.settings.APP_OPS_SETTINGS'; +IntentLauncherAndroid.ACTION_BATTERY_SAVER_SETTINGS === 'android.settings.BATTERY_SAVER_SETTINGS'; +IntentLauncherAndroid.ACTION_BLUETOOTH_SETTINGS === 'android.settings.BLUETOOTH_SETTINGS'; +IntentLauncherAndroid.ACTION_CAPTIONING_SETTINGS === 'android.settings.CAPTIONING_SETTINGS'; +IntentLauncherAndroid.ACTION_CAST_SETTINGS === 'android.settings.CAST_SETTINGS'; +IntentLauncherAndroid.ACTION_DATA_ROAMING_SETTINGS === 'android.settings.DATA_ROAMING_SETTINGS'; +IntentLauncherAndroid.ACTION_DATE_SETTINGS === 'android.settings.DATE_SETTINGS'; +IntentLauncherAndroid.ACTION_DEVICE_INFO_SETTINGS === 'android.settings.DEVICE_INFO_SETTINGS'; +IntentLauncherAndroid.ACTION_DEVICE_NAME === 'android.settings.DEVICE_NAME'; +IntentLauncherAndroid.ACTION_DISPLAY_SETTINGS === 'android.settings.DISPLAY_SETTINGS'; +IntentLauncherAndroid.ACTION_DREAM_SETTINGS === 'android.settings.DREAM_SETTINGS'; +IntentLauncherAndroid.ACTION_HARD_KEYBOARD_SETTINGS === 'android.settings.HARD_KEYBOARD_SETTINGS'; +IntentLauncherAndroid.ACTION_HOME_SETTINGS === 'android.settings.HOME_SETTINGS'; +IntentLauncherAndroid.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS === 'android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS === 'android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS'; +IntentLauncherAndroid.ACTION_INPUT_METHOD_SETTINGS === 'android.settings.INPUT_METHOD_SETTINGS'; +IntentLauncherAndroid.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS === 'android.settings.INPUT_METHOD_SUBTYPE_SETTINGS'; +IntentLauncherAndroid.ACTION_INTERNAL_STORAGE_SETTINGS === 'android.settings.INTERNAL_STORAGE_SETTINGS'; +IntentLauncherAndroid.ACTION_LOCALE_SETTINGS === 'android.settings.LOCALE_SETTINGS'; +IntentLauncherAndroid.ACTION_LOCATION_SOURCE_SETTINGS === 'android.settings.LOCATION_SOURCE_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS === 'android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_APPLICATIONS_SETTINGS === 'android.settings.MANAGE_APPLICATIONS_SETTINGS'; +IntentLauncherAndroid.ACTION_MANAGE_DEFAULT_APPS_SETTINGS === 'android.settings.MANAGE_DEFAULT_APPS_SETTINGS'; +IntentLauncherAndroid.ACTION_MEMORY_CARD_SETTINGS === 'android.settings.MEMORY_CARD_SETTINGS'; +IntentLauncherAndroid.ACTION_MONITORING_CERT_INFO === 'android.settings.MONITORING_CERT_INFO'; +IntentLauncherAndroid.ACTION_NETWORK_OPERATOR_SETTINGS === 'android.settings.NETWORK_OPERATOR_SETTINGS'; +IntentLauncherAndroid.ACTION_NFCSHARING_SETTINGS === 'android.settings.NFCSHARING_SETTINGS'; +IntentLauncherAndroid.ACTION_NFC_PAYMENT_SETTINGS === 'android.settings.NFC_PAYMENT_SETTINGS'; +IntentLauncherAndroid.ACTION_NFC_SETTINGS === 'android.settings.NFC_SETTINGS'; +IntentLauncherAndroid.ACTION_NIGHT_DISPLAY_SETTINGS === 'android.settings.NIGHT_DISPLAY_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS === 'android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS'; +IntentLauncherAndroid.ACTION_NOTIFICATION_SETTINGS === 'android.settings.NOTIFICATION_SETTINGS'; +IntentLauncherAndroid.ACTION_PAIRING_SETTINGS === 'android.settings.PAIRING_SETTINGS'; +IntentLauncherAndroid.ACTION_PRIVACY_SETTINGS === 'android.settings.PRIVACY_SETTINGS'; +IntentLauncherAndroid.ACTION_QUICK_LAUNCH_SETTINGS === 'android.settings.QUICK_LAUNCH_SETTINGS'; +IntentLauncherAndroid.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS === 'android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS'; +IntentLauncherAndroid.ACTION_SECURITY_SETTINGS === 'android.settings.SECURITY_SETTINGS'; +IntentLauncherAndroid.ACTION_SETTINGS === 'android.settings.SETTINGS'; +IntentLauncherAndroid.ACTION_SHOW_ADMIN_SUPPORT_DETAILS === 'android.settings.SHOW_ADMIN_SUPPORT_DETAILS'; +IntentLauncherAndroid.ACTION_SHOW_INPUT_METHOD_PICKER === 'android.settings.SHOW_INPUT_METHOD_PICKER'; +IntentLauncherAndroid.ACTION_SHOW_REGULATORY_INFO === 'android.settings.SHOW_REGULATORY_INFO'; +IntentLauncherAndroid.ACTION_SHOW_REMOTE_BUGREPORT_DIALOG === 'android.settings.SHOW_REMOTE_BUGREPORT_DIALOG'; +IntentLauncherAndroid.ACTION_SOUND_SETTINGS === 'android.settings.SOUND_SETTINGS'; +IntentLauncherAndroid.ACTION_STORAGE_MANAGER_SETTINGS === 'android.settings.STORAGE_MANAGER_SETTINGS'; +IntentLauncherAndroid.ACTION_SYNC_SETTINGS === 'android.settings.SYNC_SETTINGS'; +IntentLauncherAndroid.ACTION_SYSTEM_UPDATE_SETTINGS === 'android.settings.SYSTEM_UPDATE_SETTINGS'; +IntentLauncherAndroid.ACTION_TETHER_PROVISIONING_UI === 'android.settings.TETHER_PROVISIONING_UI'; +IntentLauncherAndroid.ACTION_TRUSTED_CREDENTIALS_USER === 'android.settings.TRUSTED_CREDENTIALS_USER'; +IntentLauncherAndroid.ACTION_USAGE_ACCESS_SETTINGS === 'android.settings.USAGE_ACCESS_SETTINGS'; +IntentLauncherAndroid.ACTION_USER_DICTIONARY_INSERT === 'android.settings.USER_DICTIONARY_INSERT'; +IntentLauncherAndroid.ACTION_USER_DICTIONARY_SETTINGS === 'android.settings.USER_DICTIONARY_SETTINGS'; +IntentLauncherAndroid.ACTION_USER_SETTINGS === 'android.settings.USER_SETTINGS'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_AIRPLANE_MODE === 'android.settings.VOICE_CONTROL_AIRPLANE_MODE'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE === 'android.settings.VOICE_CONTROL_BATTERY_SAVER_MODE'; +IntentLauncherAndroid.ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE === 'android.settings.VOICE_CONTROL_DO_NOT_DISTURB_MODE'; +IntentLauncherAndroid.ACTION_VOICE_INPUT_SETTINGS === 'android.settings.VOICE_INPUT_SETTINGS'; +IntentLauncherAndroid.ACTION_VPN_SETTINGS === 'android.settings.VPN_SETTINGS'; +IntentLauncherAndroid.ACTION_VR_LISTENER_SETTINGS === 'android.settings.VR_LISTENER_SETTINGS'; +IntentLauncherAndroid.ACTION_WEBVIEW_SETTINGS === 'android.settings.WEBVIEW_SETTINGS'; +IntentLauncherAndroid.ACTION_WIFI_IP_SETTINGS === 'android.settings.WIFI_IP_SETTINGS'; +IntentLauncherAndroid.ACTION_WIFI_SETTINGS === 'android.settings.WIFI_SETTINGS'; +IntentLauncherAndroid.ACTION_WIRELESS_SETTINGS === 'android.settings.WIRELESS_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_AUTOMATION_SETTINGS === 'android.settings.ZEN_MODE_AUTOMATION_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_EVENT_RULE_SETTINGS === 'android.settings.ZEN_MODE_EVENT_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS === 'android.settings.ZEN_MODE_EXTERNAL_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_PRIORITY_SETTINGS === 'android.settings.ZEN_MODE_PRIORITY_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS === 'android.settings.ZEN_MODE_SCHEDULE_RULE_SETTINGS'; +IntentLauncherAndroid.ACTION_ZEN_MODE_SETTINGS === 'android.settings.ZEN_MODE_SETTINGS'; + +KeepAwake.activate(); +KeepAwake.deactivate(); + +() => ( + +); + +() => ( + +); + +Permissions.CAMERA === 'camera'; +Permissions.CAMERA_ROLL === 'cameraRoll'; +Permissions.AUDIO_RECORDING === 'audioRecording'; +Permissions.CONTACTS === 'contacts'; +Permissions.NOTIFICATIONS === 'remoteNotifications'; +Permissions.REMOTE_NOTIFICATIONS === 'remoteNotifications'; +Permissions.SYSTEM_BRIGHTNESS === 'systemBrightness'; +Permissions.USER_FACING_NOTIFICATIONS === 'userFacingNotifications'; +Permissions.REMINDERS === 'reminders'; +async () => { + const result = await Permissions.askAsync(Permissions.CAMERA); + + result.status === 'granted'; + result.status === 'denied'; + result.status === 'undetermined'; + + result.expires === 'never'; +}; + +ScreenOrientation.Orientation.ALL; +ScreenOrientation.allow(ScreenOrientation.Orientation.ALL); + +class __TestEntry__ extends React.Component { + render() { + return( + test + ); + } +} +registerRootComponent(__TestEntry__); + +Calendar.EntityTypes.EVENT === 'event'; +Calendar.EntityTypes.REMINDER === 'reminder'; + +Calendar.CalendarType.LOCAL === 'local'; +Calendar.CalendarType.CALDAV === 'caldav'; +Calendar.CalendarType.EXCHANGE === 'exchange'; +Calendar.CalendarType.SUBSCRIBED === 'subscribed'; +Calendar.CalendarType.BIRTHDAYS === 'birthdays'; + +async () => { + const result = await Calendar.getCalendarsAsync(Calendar.EntityTypes.EVENT); + result.length; + + const calendar = result[0]; + calendar.id === ''; + calendar.title === ''; + calendar.sourceId === ''; + calendar.type === Calendar.CalendarType.BIRTHDAYS; + calendar.color === ''; + calendar.entityType === Calendar.EntityTypes.EVENT; + calendar.allowsModifications === true; + calendar.allowedAvailabilities === ['']; + calendar.isPrimary === true; + calendar.name === ''; + calendar.ownerAccount === ''; + calendar.timeZone === ''; + calendar.allowedReminders === ['']; + calendar.allowedAttendeeTypes === ['']; + calendar.isVisible === false; + calendar.isSynced === false; + calendar.accessLevel === Calendar.CalendarAccessLevel.CONTRIBUTOR; + + if (calendar.source) { + calendar.source.id === ''; + calendar.source.type === ''; + calendar.source.name === ''; + calendar.source.isLocalAccount === false; + } + + const id1 = await Calendar.createCalendarAsync({ + accessLevel: Calendar.CalendarAccessLevel.EDITOR + }); + + id1 === ''; + + const id2 = await Calendar.updateCalendarAsync('1234', { + isVisible: false + }); + + id2 === ''; + + const id3 = await Calendar.updateCalendarAsync('1234', null); + + await Calendar.deleteCalendarAsync('1234'); + + const events = await Calendar.getEventsAsync( + ['123', '124'], + new Date(), + new Date() + ); + + const event1 = events[0]; + + event1.accessLevel === Calendar.EventAccessLevel.CONFIDENTIAL; + event1.alarms === []; + event1.allDay === true; + event1.availability === Calendar.Availability.FREE; + event1.calendarId === ''; + event1.creationDate === ''; + event1.endDate === ''; + event1.endTimeZone === ''; + event1.guestsCanInviteOthers === true; + event1.guestsCanModify === true; + event1.guestsCanSeeGuests === false; + event1.id === ''; + event1.instanceId === ''; + event1.isDetached === false; + + const event2 = await Calendar.getEventAsync('123', { + futureEvents: true + }); + + const eventId1 = await Calendar.createEventAsync('123'); + + const eventId2 = await Calendar.updateEventAsync('1234'); + + await Calendar.deleteEventAsync('1234'); + + const attendees = await Calendar.getAttendeesForEventAsync('123'); + + const aId1 = await Calendar.createAttendeeAsync('123'); + + const aId2 = await Calendar.updateAttendeeAsync('123'); + + await Calendar.deleteAttendeeAsync('123'); + + const reminders = await Calendar.getRemindersAsync(['123']); + + const reminder = await Calendar.getReminderAsync('123'); + + const remId1 = await Calendar.createReminderAsync('123'); + + const remId2 = await Calendar.updateReminderAsync('123'); + + await Calendar.deleteReminderAsync('123'); + + const sources = await Calendar.getSourcesAsync(); + + const source = await Calendar.getSourceAsync('123'); + + Calendar.openEventInCalendar('123'); +}; + +async () => { + const result = await MailComposer.composeAsync({ + subject: 'sss' + }); + + result.status === 'saved'; +}; + +async () => { + const updateEventListener: Updates.UpdateEventListener = ({ type, manifest, message }) => { + switch (type) { + case Updates.EventType.DOWNLOAD_STARTED: + case Updates.EventType.DOWNLOAD_PROGRESS: + case Updates.EventType.DOWNLOAD_FINISHED: + case Updates.EventType.NO_UPDATE_AVAILABLE: + case Updates.EventType.ERROR: + return true; + } + }; + + Updates.reload(); + + Updates.reloadFromCache(); + + Updates.addListener(updateEventListener); + + const updateCheckResult = await Updates.checkForUpdateAsync(); + + if (updateCheckResult.isAvailable) { + console.log(updateCheckResult.manifest); + } + + Updates.fetchUpdateAsync({ eventListener: updateEventListener }); + + const bundleFetchResult = await Updates.fetchUpdateAsync(); + + if (bundleFetchResult.isNew) { + console.log(bundleFetchResult.manifest); + } +}; + +async () => { + const asset: MediaLibrary.Asset = await MediaLibrary.createAssetAsync('some-url'); + const getAssetsOptions: MediaLibrary.GetAssetsOptions = { + first: 0, + after: 'lastAssetId', + album: 'albumId', + sortBy: MediaLibrary.SortBy.creationTime, + mediaType: MediaLibrary.MediaType.photo + }; + const assetsList: MediaLibrary.GetAssetsResult = await MediaLibrary.getAssetsAsync(getAssetsOptions); + const endCursor: string = assetsList.endCursor; + const hasNextPage: boolean = assetsList.hasNextPage; + const totalCount: number = assetsList.totalCount; + const asset1: MediaLibrary.Asset = await MediaLibrary.getAssetInfoAsync(asset); + if (await MediaLibrary.deleteAssetsAsync(assetsList.assets)) { + console.log('assets deleted'); + } + const albums: MediaLibrary.Album[] = await MediaLibrary.getAlbumsAsync(); + const album: MediaLibrary.Album | null = await MediaLibrary.getAlbumAsync('albumName'); + const album1: MediaLibrary.Album = await MediaLibrary.createAlbumAsync('albumName', asset1); + if (await MediaLibrary.addAssetsToAlbumAsync([asset, asset1], album1, true)) { + console.log('assets added'); + } + + const moments: MediaLibrary.Album[] = await MediaLibrary.getMomentsAsync(); + + switch (getAssetsOptions.mediaType) { + case MediaLibrary.MediaType.audio: + case MediaLibrary.MediaType.photo: + case MediaLibrary.MediaType.video: + case MediaLibrary.MediaType.unknow: + return true; + } + + switch (getAssetsOptions.sortBy) { + case MediaLibrary.SortBy.default: + case MediaLibrary.SortBy.id: + case MediaLibrary.SortBy.creationTime: + case MediaLibrary.SortBy.modificationTime: + case MediaLibrary.SortBy.mediaType: + case MediaLibrary.SortBy.width: + case MediaLibrary.SortBy.height: + case MediaLibrary.SortBy.duration: + return true; + } +}; +// #region MediaLibrary +async () => { + const mlAsset: MediaLibrary.Asset = await MediaLibrary.createAssetAsync('localUri'); + const mlAssetResult: MediaLibrary.GetAssetsResult = await MediaLibrary.getAssetsAsync({ + first: 0, + after: '', + album: 'Album', + sortBy: MediaLibrary.SortBy.creationTime, + mediaType: MediaLibrary.MediaType.photo + }); + const mlAsset1: MediaLibrary.Asset = await MediaLibrary.getAssetInfoAsync(mlAsset); + const areDeleted: boolean = await MediaLibrary.deleteAssetsAsync([mlAsset]); + const albums: MediaLibrary.Album[] = await MediaLibrary.getAlbumsAsync(); + const album: MediaLibrary.Album = await MediaLibrary.getAlbumAsync('album'); + const album1: MediaLibrary.Album = await MediaLibrary.createAlbumAsync('album', mlAsset); + const areAddedToAlbum: boolean = await MediaLibrary.addAssetsToAlbumAsync([mlAsset, mlAsset1], 'album'); + const areDeletedFromAlbum: boolean = await MediaLibrary.removeAssetsFromAlbumAsync([mlAsset, mlAsset1], 'album'); + const momuents: MediaLibrary.Album[] = await MediaLibrary.getMomentsAsync(); +}; +//#endregion + +// #region Haptic +Haptic.impact(Haptic.ImpactStyles.Heavy); +Haptic.impact(Haptic.ImpactStyles.Light); +Haptic.impact(Haptic.ImpactStyles.Medium); + +Haptic.notification(Haptic.NotificationType.Error); +Haptic.notification(Haptic.NotificationType.Success); +Haptic.notification(Haptic.NotificationType.Error); + +Haptic.selection(); +// #endregion + +// #region Constants +async () => { + const appOwnerShip = Constants.appOwnership; + const expoVersion = Constants.expoVersion; + const installationId = Constants.installationId; + const deviceId = Constants.deviceId; + const deviceName = Constants.deviceName; + const deviceYearClass = Constants.deviceYearClass; + const isDevice = Constants.isDevice; + const platform = Constants.platform; + const sessionId = Constants.sessionId; + const statusBarHeight = Constants.statusBarHeight; + const systemFonts = Constants.systemFonts; + const manifest = Constants.manifest; + const linkingUri = Constants.linkingUri; + const userAgent: string = await Constants.getWebViewUserAgentAsync(); +}; +// #endregion diff --git a/types/expo/v30/index.d.ts b/types/expo/v30/index.d.ts new file mode 100644 index 0000000000..d5891bad2d --- /dev/null +++ b/types/expo/v30/index.d.ts @@ -0,0 +1,3147 @@ +// Type definitions for expo 30.0 +// Project: https://github.com/expo/expo-sdk +// Definitions by: Konstantin Kai +// Martynas Kadiša +// Jan Aagaard +// Sergio Sánchez +// Fernando Helwanger +// Umidbek Karimov +// Moshe Feuchtwanger +// Michael Prokopchuk +// Tina Roh +// Nathan Phillip Brink +// Martin Olsson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { EventSubscription } from 'fbemitter'; +import { Component, ComponentClass, Ref, ComponentType } from 'react'; +import { + ColorPropType, + ImageRequireSource, + ImageURISource, + LinkingStatic as ReactNativeLinkingStatic, + NativeEventEmitter, + ViewProps, + ViewStyle, + Permission, + StyleProp +} from 'react-native'; + +export type Axis = number; +export type BarCodeReadCallback = (params: { type: string; data: string; }) => void; +export type Md5 = string; +export type Orientation = 'portrait' | 'landscape'; +export type RequireSource = ImageRequireSource; +export type ResizeModeContain = 'contain'; +export type ResizeModeCover = 'cover'; +export type ResizeModeStretch = 'stretch'; +export type URISource = ImageURISource; + +export interface HashMap { [key: string]: any; } +export interface StringHashMap { [key: string]: string; } + +/** Access the device accelerometer sensor(s) to respond to changes in acceleration in 3d space. */ +export namespace Accelerometer { + interface AccelerometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + /** + * Subscribe for updates to the accelerometer. + * @param listener A callback that is invoked when an accelerometer update is available. When invoked, the listener is provided a single argumument that is an object containing keys x, y, z. + * @returns An EventSubscription object that you can call remove() on when you would like to unsubscribe the listener. + */ + function addListener(listener: (obj: AccelerometerObject) => any): EventSubscription; + + /** Remove all listeners. */ + function removeAllListeners(): void; + + /** + * Subscribe for updates to the accelerometer. + * @param intervalMs Desired interval in milliseconds between accelerometer updates. + */ + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Admob + */ +export type AdMobBannerSize = + | 'banner' + | 'largeBanner' + | 'mediumRectangle' + | 'fullBanner' + | 'leaderboard' + | 'smartBannerPortrait' + | 'smartBannerLandscape'; +export interface AdMobBannerProperties extends ViewProps { + bannerSize?: AdMobBannerSize; + adUnitID?: string; + testDeviceID?: string; + didFailToReceiveAdWithError?(errorDescription: string): void; + adViewDidReceiveAd?(): void; + adViewWillPresentScreen?(): void; + adViewWillDismissScreen?(): void; + adViewDidDismissScreen?(): void; + adViewWillLeaveApplication?(): void; +} + +export class AdMobBanner extends Component { } +export interface AdMobAppEvent { + name: string; + info: string; +} +export interface PublisherBannerProperties extends AdMobBannerProperties { + onAdMobDispatchAppEvent?(event: AdMobAppEvent): void; +} +export class PublisherBanner extends Component { } + +export type AdMobInterstitialEmptyEvent = + | 'interstitialDidLoad' + | 'interstitialDidOpen' + | 'interstitialDidClose' + | 'interstitialWillLeaveApplication'; +export type AdMobInterstitialEvent = AdMobInterstitialEmptyEvent | 'interstitialDidFailToLoad'; +export namespace AdMobInterstitial { + function setAdUnitID(id: string): void; + function setTestDeviceID(id: string): void; + function requestAdAsync(): Promise; + function showAdAsync(): Promise; + function dismissAdAsync(): Promise; + function getIsReadyAsync(): Promise; + function addEventListener(event: 'interstitialDidFailToLoad', handler: (error: string) => void): void; + function addEventListener(event: AdMobInterstitialEmptyEvent, handler: () => void): void; + function removeEventListener(event: 'interstitialDidFailToLoad', handler: (error: string) => void): void; + function removeEventListener(event: AdMobInterstitialEmptyEvent, handler: () => void): void; + function removeAllListeners(): void; +} + +export type AdMobRewardedEmptyEvent = + | 'rewardedVideoDidLoad' + | 'rewardedVideoDidOpen' + | 'rewardedVideoDidStart' + | 'rewardedVideoDidClose' + | 'rewardedVideoWillLeaveApplication'; +export type AdMobRewardedEvent = AdMobRewardedEmptyEvent | 'rewardedVideoDidRewardUser' | 'rewardedVideoDidFailToLoad'; +export namespace AdMobRewarded { + function setAdUnitID(id: string): void; + function setTestDeviceID(id: string): void; + function requestAdAsync(): Promise; + function showAdAsync(): Promise; + function dismissAdAsync(): Promise; + function getIsReadyAsync(): Promise; + function addEventListener(event: 'rewardedVideoDidRewardUser', handler: (type: string, amount: number) => void): void; + function addEventListener(event: 'rewardedVideoDidFailToLoad', handler: (error: string) => void): void; + function addEventListener(event: AdMobRewardedEmptyEvent, handler: () => void): void; + function removeEventListener(event: 'rewardedVideoDidRewardUser', handler: (type: string, amount: number) => void): void; + function removeEventListener(event: 'rewardedVideoDidFailToLoad', handler: (error: string) => void): void; + function removeEventListener(event: AdMobRewardedEmptyEvent, handler: () => void): void; + function removeAllListeners(): void; +} + +/** + * Provides access to Amplitude mobile analytics which basically lets you log various events to the Cloud. This module wraps Amplitude’s iOS and Android SDKs. + * + * Note: Session tracking may not work correctly when running Experiences in the main Expo app. It will work correctly if you create a standalone app. + */ +export namespace Amplitude { + /** Initializes Amplitude with your Amplitude API key. */ + function initialize(apiKey: string): void; + + /** Assign a user ID to the current user. If you don’t have a system for user IDs you don’t need to call this. */ + function setUserId(userId: string): void; + + /** Set properties for the current user. */ + function setUserProperties(userProperties: HashMap): void; + + /** Clear properties set by `setUserProperties()`. */ + function clearUserProperties(): void; + + /** Log an event to Amplitude. */ + function logEvent(eventName: string): void; + + /** Log an event to Amplitude with custom properties. */ + function logEventWithProperties( + eventName: string, + + /** A map of custom properties. */ + properties: HashMap + ): void; + + /** Add the current user to a group. */ + function setGroup( + /** The group name, e.g. `'sports'`. */ + groupType: string, + + /** An array of group names, e.g. `['tennis', 'soccer']`. */ + groupNames: string[] + ): void; +} + +// #region AppLoading +/** The following props are recommended, but optional for the sake of backwards compatibility (they were introduced in SDK21). If you do not provide any props, you are responsible for coordinating loading assets, handling errors, and updating state to unmount the `AppLoading` component. */ +export interface AppLoadingProps { + /** A `function` that returns a `Promise`. The `Promise` should resolve when the app is done loading data and assets. */ + startAsync?: () => Promise; + + /** Required if you provide `startAsync`. Called when `startAsync` resolves or rejects. This should be used to set state and unmount the `AppLoading` component. */ + onFinish?: () => void; + + /** If `startAsync` throws an error, it is caught and passed into the function provided to `onError`. */ + onError?: (error: Error) => void; +} + +/** + * A React component that tells Expo to keep the app loading screen open if it is the first and only component rendered in your app. When it is removed, the loading screen will disappear and your app will be visible. + * + * This is incredibly useful to let you download and cache fonts, logo and icon images and other assets that you want to be sure the user has on their device for an optimal experience before rendering they start using the app. + */ +export class AppLoading extends Component { } +// #endregion AppLoading + +/** This module provides an interface to Expo’s asset system. An asset is any file that lives alongside the source code of your app that the app needs at runtime. Examples include images, fonts and sounds. Expo’s asset system integrates with React Native’s, so that you can refer to files with require('path/to/file'). This is how you refer to static image files in React Native for use in an Image component, for example. */ +export class Asset { + constructor({ name, type, hash, uri, width, height }: { + name: string; + type: string; + hash: string; + uri: string; + width?: number; + height?: number; + }); + + /** The MD5 hash of the asset’s data. */ + hash: Md5; + + /** The name of the asset file without the extension. Also without the part from @ onward in the filename (used to specify scale factor for images). */ + name: string; + + /** The extension of the asset filename. */ + type: string; + + /** A URI that points to the asset’s data on the remote server. When running the published version of your app, this refers to the the location on Expo’s asset server where Expo has stored your asset. When running the app from XDE during development, this URI points to XDE’s server running on your computer and the asset is served directly from your computer. */ + uri: string; + + /** If the asset has been downloaded (by calling `downloadAsync()`), the `file://` URI pointing to the local file on the device that contains the asset data. */ + localUri: string; + + /** If the asset is an image, the width of the image data divided by the scale factor. The scale factor is the number after `@` in the filename, or `1` if not present. */ + width?: number; + + /** If the asset is an image, the height of the image data divided by the scale factor. The scale factor is the number after `@` in the filename, or `1` if not present. */ + height?: number; + + downloading: boolean; + downloaded: boolean; + downloadCallbacks: Array<{ resolve: () => any, reject: (e?: any) => any }>; + + /** Downloads the asset data to a local file in the device’s cache directory. Once the returned promise is fulfilled without error, the localUri field of this asset points to a local file containing the asset data. The asset is only downloaded if an up-to-date local file for the asset isn’t already present due to an earlier download. */ + downloadAsync(): Promise; + + /** Returns the `Expo.Asset` instance representing an asset given its module. */ + static fromModule(module: RequireSource): Asset; + + /** + * A helper that wraps `Expo.Asset.fromModule(module).downloadAsync` for convenience. + * @param moduleIds An array of `require('path/to/file')`. Can also be just one module without an Array. + */ + static loadAsync(module: RequireSource[] | RequireSource): Promise; +} + +/** + * Provides basic sample playback and recording. + * + * Note that Expo does not yet support backgrounding, so audio is not available to play in the background of your experience. Audio also automatically stops if headphones / bluetooth audio devices are disconnected. + */ +export namespace Audio { + enum InterruptionModeIos { + /** This is the default option. If this option is set, your experience’s audio is mixed with audio playing in background apps. */ + INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS = 0, + + /** If this option is set, your experience’s audio interrupts audio from other apps. */ + INTERRUPTION_MODE_IOS_DO_NOT_MIX = 1, + + /** If this option is set, your experience’s audio lowers the volume ("ducks") of audio from other apps while your audio plays. */ + INTERRUPTION_MODE_IOS_DUCK_OTHERS = 2 + } + + const INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS: 0; + const INTERRUPTION_MODE_IOS_DO_NOT_MIX: 1; + const INTERRUPTION_MODE_IOS_DUCK_OTHERS: 2; + + enum InterruptionModeAndroid { + /** If this option is set, your experience’s audio interrupts audio from other apps. */ + INTERRUPTION_MODE_ANDROID_DO_NOT_MIX = 1, + + /** This is the default option. If this option is set, your experience’s audio lowers the volume ("ducks") of audio from other apps while your audio plays. */ + INTERRUPTION_MODE_ANDROID_DUCK_OTHERS = 2 + } + + const INTERRUPTION_MODE_ANDROID_DO_NOT_MIX: 1; + const INTERRUPTION_MODE_ANDROID_DUCK_OTHERS: 2; + + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_DEFAULT: 0; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_THREE_GPP: 1; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4: 2; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_NB: 3; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AMR_WB: 4; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADIF: 5; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_AAC_ADTS: 6; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_RTP_AVP: 7; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG2TS: 8; + const RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_WEBM: 9; + + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_DEFAULT: 0; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_NB: 1; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AMR_WB: 2; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC: 3; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_HE_AAC: 4; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC_ELD: 5; + const RECORDING_OPTION_ANDROID_AUDIO_ENCODER_VORBIS: 6; + + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_LINEARPCM: 'lpcm'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AC3: 'ac-3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_60958AC3: 'cac3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLEIMA4: 'ima4'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC: 'aac '; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4CELP: 'celp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4HVXC: 'hvxc'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4TWINVQ: 'twvq'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE3: 'MAC3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MACE6: 'MAC6'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ULAW: 'ulaw'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ALAW: 'alaw'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN: 'QDMC'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QDESIGN2: 'QDM2'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_QUALCOMM: 'Qclp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER1: '.mp1'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER2: '.mp2'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEGLAYER3: '.mp3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_APPLELOSSLESS: 'alac'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE: 'aach'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_LD: 'aacl'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD: 'aace'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_SBR: 'aacf'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_ELD_V2: 'aacg'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_HE_V2: 'aacp'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MPEG4AAC_SPATIAL: 'aacs'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR: 'samr'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AMR_WB: 'sawb'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AUDIBLE: 'AUDB'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ILBC: 'ilbc'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_DVIINTELIMA: 0x6d730011; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_MICROSOFTGSM: 0x6d730031; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_AES3: 'aes3'; + const RECORDING_OPTION_IOS_OUTPUT_FORMAT_ENHANCEDAC3: 'ec-3'; + + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MIN: 0; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_LOW: 0x20; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MEDIUM: 0x40; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH: 0x60; + const RECORDING_OPTION_IOS_AUDIO_QUALITY_MAX: 0x7f; + + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_CONSTANT: 0; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_LONG_TERM_AVERAGE: 1; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE_CONSTRAINED: 2; + const RECORDING_OPTION_IOS_BIT_RATE_STRATEGY_VARIABLE: 3; + + type RecordingStatus = { + canRecord: false, + isDoneRecording: false + } | { + canRecord: true, + isRecording: boolean, + durationMillis: number + } | { + canRecord: false, + isDoneRecording: true, + durationMillis: number + }; + + const RECORDING_OPTIONS_PRESET_HIGH_QUALITY: RecordingOptions; + const RECORDING_OPTIONS_PRESET_LOW_QUALITY: RecordingOptions; + + interface RecordingOptions { + android: { + extension: string; + outputFormat: number; + audioEncoder: number; + sampleRate?: number; + numberOfChannels?: number; + bitRate?: number; + maxFileSize?: number; + }; + ios: { + extension: string; + outputFormat?: string | number; + audioQuality: number; + sampleRate: number; + numberOfChannels: number; + bitRate: number; + bitRateStrategy?: number; + bitDepthHint?: number; + linearPCMBitDepth?: number; + linearPCMIsBigEndian?: boolean; + linearPCMIsFloat?: boolean; + }; + } + + interface AudioMode { + /** Boolean selecting if your experience’s audio should play in silent mode on iOS. This value defaults to `false`. */ + playsInSilentModeIOS: boolean; + + /** Boolean selecting if recording is enabled on iOS. This value defaults to `false`. NOTE: when this flag is set to true, playback may be routed to the phone receiver instead of to the speaker. */ + allowsRecordingIOS: boolean; + + /** Enum selecting how your experience’s audio should interact with the audio from other apps on iOS. */ + interruptionModeIOS: InterruptionModeIos; + + /** Boolean selecting if your experience’s audio should automatically be lowered in volume ("duck") if audio from another app interrupts your experience. This value defaults to true. If false, audio from other apps will pause your audio. */ + shouldDuckAndroid: boolean; + + /** an enum selecting how your experience’s audio should interact with the audio from other apps on Android: */ + interruptionModeAndroid: InterruptionModeAndroid; + } + + function setIsEnabledAsync(value: boolean): Promise; + function setAudioModeAsync(mode: AudioMode): Promise; + + /** This class represents a sound corresponding to an Asset or URL. */ + class Sound extends PlaybackObject { + constructor(); + + /** + * Creates and loads a sound from source, with optional `initialStatus`, `onPlaybackStatusUpdate`, and `downloadFirst`. + * + * @returns A `Promise` that is rejected if creation failed, or fulfilled with the following dictionary if creation succeeded: + * - `sound`: The newly created and loaded Sound object. + * - `status`: The PlaybackStatus of the Sound object. See the AV documentation for further information. + */ + static create( + /** + * The source of the sound. The following forms are supported: + * + * - A dictionary of the form `{ uri: 'http://path/to/file' }` with a network URL pointing to an audio file on the web. + * - `require('path/to/file')` for an audio file asset in the source code directory. + * - An `Expo.Asset` object for an audio file asset. + */ + source: PlaybackSource, + + /** The initial intended PlaybackStatusToSet of the sound, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. */ + initialStatus?: PlaybackStatusToSet, + + /** A function taking a single parameter PlaybackStatus. This value defaults to `null` if no parameter is passed. */ + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null, + + /** If set to true, the system will attempt to download the resource to the device before loading. This value defaults to `true`. Note that at the moment, this will only work for `source`s of the form `require('path/to/file')` or `Asset` objects. */ + downloadFirst?: boolean + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } + + class Recording { + constructor(); + + /** Gets the `status` of the `Recording`. */ + getStatusAsync(): Promise; + + /** Sets a function to be called regularly with the `status` of the `Recording`. */ + setOnRecordingStatusUpdate(onRecordingStatusUpdate?: (status: RecordingStatus) => void): void; + + /** Sets the interval with which onRecordingStatusUpdate is called while the recording can record. This value defaults to 500 milliseconds. */ + setProgressUpdateInterval(progressUpdateIntervalMillis: number): void; + + /** Loads the recorder into memory and prepares it for recording. This must be called before calling `startAsync()`. This method can only be called if the `Recording` instance has never yet been prepared. */ + prepareToRecordAsync( + /** Options for the recording, including sample rate, bitrate, channels, format, encoder, and extension. If no options are passed to `prepareToRecordAsync()`, the recorder will be created with options `Expo.Audio.RECORDING_OPTIONS_PRESET_LOW_QUALITY`. */ + options?: RecordingOptions + ): Promise; + + /** Begins recording. This method can only be called if the `Recording` has been prepared. */ + startAsync(): Promise; + + /** + * Pauses recording. This method can only be called if the Recording has been prepared. + * + * NOTE: This is only available on Android API version 24 and later. + */ + pauseAsync(): Promise; + + /** Stops the recording and deallocates the recorder from memory. This reverts the Recording instance to an unprepared state, and another Recording instance must be created in order to record again. This method can only be called if the `Recording` has been prepared. */ + stopAndUnloadAsync(): Promise; + + /** + * Gets the local URI of the Recording. Note that this will only succeed once the Recording is prepared to record. + * + * @returns A string with the local URI of the `Recording`, or `null` if the `Recording` is not prepared to record. + */ + getURI(): string | null | undefined; + + /** + * Creates and loads a new `Sound` object to play back the `Recording`. Note that this will only succeed once the `Recording` is done recording (once `stopAndUnloadAsync()` has been called). + * + * @returns A Promise that is rejected if creation failed, or fulfilled with the following dictionary if creation succeeded: + * - `sound`: the newly created and loaded Sound object. + * - `status`: the PlaybackStatus of the Sound object. + */ + createNewLoadedSound( + /** The initial intended `PlaybackStatusToSet` of the sound, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. */ + initialStatus?: PlaybackStatusToSet, + + /** A function taking a single parameter `PlaybackStatus`. This value defaults to `null` if no parameter is passed. */ + onPlaybackStatusUpdate?: ((status: PlaybackStatus) => void) | null + ): Promise<{ sound: Sound, status: PlaybackStatus }>; + } +} + +/** + * AuthSession + */ +export namespace AuthSession { + type StartAsyncResponse = { + type: 'cancel'; + } | { + type: 'dismissed'; + } | { + type: 'success'; + params: HashMap; + event: HashMap; + } | { + type: 'error'; + params: HashMap; + errorCode: string; + event: HashMap; + }; + + function startAsync(options: { authUrl: string; returnUrl?: string; }): Promise; + function dismiss(): void; + function getRedirectUrl(): string; +} + +// #region AV +/** + * AV + */ +export type PlaybackStatus = { + isLoaded: false; + androidImplementation?: string; + + /** Populated exactly once when an error forces the object to unload. */ + error?: string; +} | { + isLoaded: true; + androidImplementation?: string; + uri: string; + progressUpdateIntervalMillis: number; + durationMillis?: number; + positionMillis: number; + playableDurationMillis?: number; + shouldPlay: boolean; + isPlaying: boolean; + isBuffering: boolean; + rate: number; + shouldCorrectPitch: boolean; + volume: number; + isMuted: boolean; + isLooping: boolean; + + /** True exactly once when the track plays to finish. */ + didJustFinish: boolean; +}; + +export interface PlaybackStatusToSet { + androidImplementation?: string; + isLooping?: boolean; + isMuted?: boolean; + positionMillis?: number; + progressUpdateIntervalMillis?: number; + /** The desired playback rate of the media. This value must be between `0.0` and `32.0`. Only available on Android API version 23 and later and iOS. */ + rate?: number; + shouldCorrectPitch?: boolean; + shouldPlay?: boolean; + /** A number between `0.0` (silence) and `1.0` (maximum volume). */ + volume?: number; +} + +export type PlaybackSource = RequireSource | { uri: string } | Asset; + +export class PlaybackObject { + /** + * Gets the `PlaybackStatus` of the `playbackObject`. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject`. + */ + getStatusAsync(): Promise; + + /** + * Loads the media from source into memory and prepares it for playing. This must be called before calling setStatusAsync() or any of the convenience set status methods. This method can only be called if the playbackObject is in an unloaded state. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once it is loaded, or rejects if loading failed. The `Promise` will also reject if the `playbackObject` was already loaded. See below for details on `PlaybackStatus`. + */ + loadAsync( + /** + * The source of the media. The following forms are supported: + * - A dictionary of the form `{ uri: 'http://path/to/file' }` with a network URL pointing to a media file on the web. + * - `require('path/to/file')` for a media file asset in the source code directory. + * - An `Expo.Asset object` for a media file asset. + */ + source: PlaybackSource, + + /** The initial intended `PlaybackStatusToSet` of the `playbackObject`, whose values will override the default initial playback status. This value defaults to `{}` if no parameter is passed. See below for details on `PlaybackStatusToSet` and the default initial playback status. */ + initialStatus?: PlaybackStatusToSet, + + /** If set to `true`, the system will attempt to download the resource to the device before loading. This value defaults to true. Note that at the moment, this will only work for sources of the form `require('path/to/file')` or `Expo.Asset` objects. */ + downloadFirst?: boolean + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: false })`. */ + pauseAsync(): Promise; + + /** + * This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: true })`. + * + * Playback may not start immediately after calling this function for reasons such as buffering. Make sure to update your UI based on the `isPlaying` and `isBuffering` properties of the `PlaybackStatus`. + */ + playAsync(): Promise; + + /** + * This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: true, positionMillis: millis })`. + * + * Playback may not start immediately after calling this function for reasons such as buffering. Make sure to update your UI based on the isPlaying and `isBuffering` properties of the `PlaybackStatus`. + */ + playFromPositionAsync( + /** The desired position of playback in milliseconds. */ + positionMillis: number, + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis, seekMillisToleranceBefore: toleranceMillisBefore, seekMillisToleranceAfter: toleranceMillisAfter })`. The tolerances are used only on iOS. */ + tolerances?: { + toleranceMillisBefore: number, + toleranceMillisAfter: number + } + ): Promise; + + /** + * Replays the item. When using `playFromPositionAsync(0)` the item is seeked to the position at `0` ms. On iOS this method uses internal implementation of the player and is able to play the item from the beginning immediately. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once the new status has been set successfully, or rejects if setting the new status failed. + */ + replayAsync( + /** The new `PlaybackStatusToSet` of the `playbackObject`, whose values will override the current playback status. */ + status: PlaybackStatusToSet + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ isLooping: value })`. */ + setIsLoopingAsync( + /** A boolean describing if the media should play once (`false`) or loop indefinitely (`true`). */ + isLooping: boolean + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ isMuted: value })`. */ + setIsMutedAsync( + /** A boolean describing if the audio of this media should be muted. */ + isMuted: boolean + ): Promise; + + /** + * Sets a function to be called regularly with the `PlaybackStatus` of the `playbackObject`. See below for details on `PlaybackStatus` and an example use case of this function. + * + * `onPlaybackStatusUpdate` will be called whenever a call to the API for this `playbackObject` completes (such as `setStatusAsync()`, `getStatusAsync()`, or `unloadAsync()`), and will also be called at regular intervals while the media is in the loaded state. Set `progressUpdateIntervalMillis` via `setStatusAsync()` or `setProgressUpdateIntervalAsync()` to modify the interval with which `onPlaybackStatusUpdate` is called while loaded. + */ + setOnPlaybackStatusUpdate( + /** A function taking a single parameter `PlaybackStatus`. */ + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void + ): void; + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis })`. */ + setPositionAsync( + positionMillis: number, + + /** This is equivalent to `playbackObject.setStatusAsync({ positionMillis: millis, seekMillisToleranceBefore: toleranceMillisBefore, seekMillisToleranceAfter: toleranceMillisAfter })`. The tolerances are used only on iOS. */ + tolerances?: { + toleranceMillisBefore: number, + toleranceMillisAfter: number + } + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ progressUpdateIntervalMillis: millis })`. */ + setProgressUpdateIntervalAsync( + /** The new minimum interval in milliseconds between calls of `onPlaybackStatusUpdate`. */ + progressUpdateIntervalMillis: number + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ rate: value, shouldCorrectPitch: shouldCorrectPitch })`. */ + setRateAsync( + /** The desired playback rate of the media. This value must be between `0.0` and `32.0`. Only available on Android API version 23 and later and iOS. */ + rate: number, + /** A boolean describing if we should correct the pitch for a changed rate. If set to `true`, the pitch of the audio will be corrected (so a rate different than `1.0` will timestretch the audio). */ + shouldCorrectPitch: boolean + ): Promise; + + /** Sets a new `PlaybackStatusToSet` on the `playbackObject`. This method can only be called if the media has been loaded. Return a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once the new status has been set successfully, or rejects if setting the new status failed. */ + setStatusAsync( + /** The new `PlaybackStatusToSet` of the `playbackObject`, whose values will override the current playback status. */ + status: PlaybackStatusToSet + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ volume: value })`. */ + setVolumeAsync( + /** A number between `0.0` (silence) and `1.0` (maximum volume). */ + volume: number + ): Promise; + + /** This is equivalent to `playbackObject.setStatusAsync({ shouldPlay: false, positionMillis: 0 })`. */ + stopAsync(): Promise; + + /** + * Unloads the media from memory. `loadAsync()` must be called again in order to be able to play the media. + * + * Returns a `Promise` that is fulfilled with the `PlaybackStatus` of the `playbackObject` once it is unloaded, or rejects if unloading failed. See below for details on `PlaybackStatus`. + */ + unloadAsync(): Promise; +} +// #endregion + +// #region BarCodeScanner +/** + * BarCodeScanner + */ +export interface BarCodeScannerProps extends ViewProps { + type?: 'front' | 'back'; + torchMode?: 'on' | 'off'; + barCodeTypes?: string[]; + onBarCodeRead?: BarCodeReadCallback; +} + +export class BarCodeScanner extends Component { + static Constants: { + TorchMode: { + on: string; + off: string + } + } & CameraConstants; +} +// #endregion + +// #region BlurView +/** + * BlurView + */ +export interface BlurViewProps extends ViewProps { + tint: 'light' | 'default' | 'dark'; + intensity: number; +} +export class BlurView extends Component { } +// #endregion + +/** + * An API to get and set screen brightness. + */ +export namespace Brightness { + /** Sets screen brightness. */ + function setBrightnessAsync( + /** A number between `0` and `1`, representing the desired screen brightness. */ + brightnessValue: number + ): Promise; + + /** + * Gets screen brightness. + * @returns A Promise that is resolved with a number between `0` and `1`, representing the current screen brightness. + */ + function getBrightnessAsync(): Promise; + + /** + * Gets global system screen brightness. + * @returns A Promise that is resolved with a number between `0` and `1`, representing the current system screen brightness. + */ + function getSystemBrightnessAsync(): Promise; + + /** Sets global system screen brightness, requires `WRITE_SETTINGS` permissions on Android. */ + function setSystemBrightnessAsync( + /** A number between `0` and `1`, representing the desired screen brightness. */ + brightnessValue: number + ): Promise; +} + +// #region Camera +/** + * Camera + */ +export interface PictureOptions { + quality?: number; + base64?: boolean; + exif?: boolean; + onPictureSaved?: (data: PictureResponse) => void; +} + +export interface PictureResponse { + uri: string; + width: number; + height: number; + exif: string; + base64: string; +} + +export interface RecordingOptions { + quality?: string | number; + maxDuration?: number; + maxFileSize?: number; +} + +export class CameraObject { + takePictureAsync(options?: PictureOptions): Promise; + recordAsync(options: RecordingOptions): Promise<{ uri: string; }>; + stopRecording(): void; + getSupportedRatiosAsync(): Promise; // Android only +} + +export interface CameraProps extends ViewProps { + autoFocus?: string | number | boolean; + barCodeTypes?: Array; + faceDetectionClassifications?: number; + faceDetectionLandmarks?: number; + faceDetectionMode?: number; + flashMode?: string | number; + /** Distance to plane of sharpest focus. A value between `0` and `1`. `0`: infinity focus, `1`: focus as close as possible. Default: `0`. For Android this is available only for some devices and when `useCamera2Api` is set to `true`. */ + focusDepth?: number; + onBarCodeRead?: BarCodeReadCallback; + onCameraReady?: () => void; + onFacesDetected?: (options: { faces: TrackedFaceFeature[] }) => void; + onMountError?: () => void; + ratio?: string; + ref?: Ref; + type?: string | number; + whiteBalance?: string | number; + /** A value between `0` and `1` being a percentage of device's max zoom. `0`: not zoomed, `1`: maximum zoom. Default: `0`. */ + zoom?: number; +} + +export interface CameraConstants { + readonly Type: { + back: string; + front: string; + }; + readonly FlashMode: { + on: string; + off: string; + auto: string; + torch: string; + }; + readonly AutoFocus: { + on: string; + off: string; + }; + readonly WhiteBalance: { + auto: string; + sunny: string; + cloudy: string; + shadow: string; + fluorescent: string; + incandescent: string; + }; + readonly VideoQuality: { + [videoQuality: string]: number; + }; + readonly BarCodeType: { + aztec: string; + codabar: string; + code39: string; + code93: string; + code128: string; + code138: string; + code39mod43: string; + datamatrix: string; + ean13: string; + ean8: string; + interleaved2of5: string; + itf14: string; + maxicode: string; + pdf417: string; + rss14: string; + rssexpanded: string; + upc_a: string; + upc_e: string; + upc_ean: string; + qr: string; + }; +} + +export class Camera extends Component { + static readonly Constants: CameraConstants; +} +// #endregion + +/** + * Constants + */ +export namespace Constants { + const appOwnership: 'expo' | 'standalone' | 'guest'; + const expoVersion: string; + const installationId: string; + const deviceId: string; + const deviceName: string; + const deviceYearClass: number; + const isDevice: boolean; + + interface Platform { + ios?: { + platform: string; + model: string; + userInterfaceIdiom: string; + buildNumber: string; + }; + android?: { + versionCode: string; + }; + } + const platform: Platform; + const sessionId: string; + const statusBarHeight: number; + const systemFonts: string[]; + + interface Manifest { + name: string; + description?: string; + slug?: string; + sdkVersion?: string; + version?: string; + orientation?: Orientation; + primaryColor?: string; + privacy?: 'public' | 'unlisted'; + scheme?: string; + icon?: string; + platforms?: string[]; + githubUrl?: string; + notification?: { + icon?: string, + color?: string, + androidMode?: 'default' | 'collapse', + androidCollapsedTitle?: string + }; + loading?: { + icon?: string, + exponentIconColor?: 'white' | 'blue', + exponentIconGrayscale?: 1 | 0, + backgroundImage?: string, + backgroundColor?: string, + hideExponentText?: boolean + }; + appKey?: string; + androidStatusBar?: { + barStyle?: 'light-content' | 'dark-content', + backgroundColor?: string + }; + androidShowExponentNotificationInShellApp?: boolean; + extra?: { + [propName: string]: any + }; + rnCliPath?: any; + entryPoint?: string; + packagerOpts?: { + hostType?: string, + dev?: boolean, + strict?: boolean, + minify?: boolean, + urlType?: string, + urlRandomness?: string, + lanType?: string, + [propName: string]: any + }; + ignoreNodeModulesValidation?: any; + nodeModulesPath?: string; + ios?: { + bundleIdentifier?: string, + buildNumber?: string, + config?: { + usesNonExemptEncryption?: boolean, + googleSignIn?: { + reservedClientId: string + } + }, + supportsTablet?: boolean, + infoPlist?: any + }; + android?: { + package?: string, + versionCode?: string, + config?: { + fabric?: { + apiKey: string, + buildSecret: string + }, + googleMaps?: { + apiKey: string + }, + googleSignIn?: { + apiKey: string, + certificateHash: string + } + } + }; + facebookScheme?: any; + facebookAppId?: string; + facebookDisplayName?: string; + splash?: { + backgroundColor?: string; + resizeMode?: ResizeModeContain | ResizeModeCover; + image?: string; + }; + assetBundlePatterns?: string[]; + releaseChannel: string; + [propName: string]: any; + } + const manifest: Manifest; + const linkingUri: string; + + function getWebViewUserAgentAsync(): Promise; +} + +/** + * Contacts + */ +export namespace Contacts { + type PhoneNumbers = 'phoneNumbers'; + type Emails = 'emails'; + type Addresses = 'addresses'; + type Image = 'image'; + type Thumbnail = 'thumbnail'; + type Note = 'note'; + type Birthday = 'birthday'; + type NonGregorianBirthday = 'nonGregorianBirthday'; + type NamePrefix = 'namePrefix'; + type NameSuffix = 'nameSuffix'; + type PhoneticFirstName = 'phoneticFirstName'; + type PhoneticMiddleName = 'phoneticMiddleName'; + type PhoneticLastName = 'phoneticLastName'; + type SocialProfiles = 'socialProfiles'; + type InstantMessageAddresses = 'instantMessageAddresses'; + type UrlAddresses = 'urlAddresses'; + type Dates = 'dates'; + type Relationships = 'relationships'; + + const PHONE_NUMBERS: PhoneNumbers; + const EMAILS: Emails; + const ADDRESSES: Addresses; + const IMAGE: Image; + const THUMBNAIL: Thumbnail; + const NOTE: Note; + const BIRTHDAY: Birthday; + const NON_GREGORIAN_BIRTHDAY: NonGregorianBirthday; + const NAME_PREFIX: NamePrefix; + const NAME_SUFFIX: NameSuffix; + const PHONETIC_FIRST_NAME: PhoneticFirstName; + const PHONETIC_MIDDLE_NAME: PhoneticMiddleName; + const PHONETIC_LAST_NAME: PhoneticLastName; + const SOCIAL_PROFILES: SocialProfiles; + const IM_ADDRESSES: InstantMessageAddresses; + const URLS: UrlAddresses; + const DATES: Dates; + const RELATIONSHIPS: Relationships; + + type FieldType = PhoneNumbers | Emails | Addresses | Image | Thumbnail | + Note | Birthday | NonGregorianBirthday | NamePrefix | NameSuffix | + PhoneticFirstName | PhoneticMiddleName | PhoneticLastName | SocialProfiles | + InstantMessageAddresses | UrlAddresses | Dates | Relationships; + + interface Options { + pageSize?: number; + pageOffset?: number; + fields?: FieldType[]; + } + + interface Contact { + id: string; + contactType: string; + name: string; + firstName?: string; + middleName?: string; + lastName?: string; + previousLastName?: string; + namePrefix?: string; + nameSuffix?: string; + nickname?: string; + phoneticFirstName?: string; + phoneticMiddleName?: string; + phoneticLastName?: string; + emails?: Array<{ + email?: string; + primary?: boolean; + label: string; + id: string; + }>; + phoneNumbers?: Array<{ + number?: string; + primary?: boolean; + digits?: string; + countryCode?: string; + label: string; + id: string; + }>; + addresses?: Array<{ + street?: string; + city?: string; + country?: string; + region?: string; + neighborhood?: string; + postalCode?: string; + poBox?: string; + isoCountryCode?: string; + label: string; + id: string; + }>; + socialProfiles?: Array<{ + service?: string; + localizedProfile?: string; + url?: string; + username?: string; + userId?: string; + label: string; + id: string; + }>; + instantMessageAddresses?: Array<{ + service?: string; + username?: string; + localizedService?: string; + label: string; + id: string; + }>; + urls?: { + label: string; + url?: string; + id: string; + }; + company?: string; + jobTitle?: string; + department?: string; + imageAvailable?: boolean; + image?: { + uri?: string; + }; + thumbnail?: { + uri?: string; + }; + note?: string; + dates?: Array<{ + day?: number; + month?: number; + year?: number; + id: string; + label: string; + }>; + relationships?: Array<{ + label: string; + name?: string; + id: string; + }>; + } + + interface Response { + data: Contact[]; + total: number; + hasNextPage: boolean; + hasPreviousPage: boolean; + } + + function getContactsAsync(options: Options): Promise; + function getContactByIdAsync(options: { id?: string; fields?: FieldType[] }): Promise; +} + +/** + * DocumentPicker + */ +export namespace DocumentPicker { + interface Options { + type?: string; + } + + type Response = { + type: 'success'; + uri: string; + name: string; + size: number; + } | { + type: 'cancel'; + }; + + function getDocumentAsync(options?: Options): Promise; +} + +/** + * ErrorRecovery + */ +export namespace ErrorRecovery { + function setRecoveryProps(props: HashMap): void; +} + +/** + * Facebook + */ +export namespace Facebook { + interface Options { + permissions?: string[]; + behavior?: 'web' | 'native' | 'browser' | 'system'; + } + interface Response { + type: 'cancel' | 'success'; + token?: string; + expires?: number; + } + function logInWithReadPermissionsAsync(appId: string, options?: Options): Promise; +} + +/** + * Facebook Ads + */ +export namespace FacebookAds { + /** + * Interstitial Ads + */ + namespace InterstitialAdManager { + function showAd(placementId: string): Promise; + } + + /** + * Native Ads + */ + type MediaCachePolicy = 'none' | 'icon' | 'image' | 'all'; + class NativeAdsManager { + constructor(placementId: string, numberOfAdsToRequest?: number); + disableAutoRefresh(): void; + setMediaCachePolicy(cachePolicy: MediaCachePolicy): void; + } + + function withNativeAd(component: Component<{ + icon?: string; + coverImage?: string; + title?: string; + subtitle?: string; + description?: string; + callToActionText?: string; + socialContext?: string; + }>): Component<{ adsManager: NativeAdsManager }, { ad: any, canRequestAds: boolean }>; + + /** + * Banner View + */ + type AdType = 'large' | 'rectangle' | 'standard'; + + interface BannerViewProps { + type: AdType; + placementId: string; + onPress: () => void; + onError: () => void; + } + + class BannerView extends Component { } + + /** + * Ad Settings + */ + namespace AdSettings { + const currentDeviceHash: string; + function addTestDevice(device: string): void; + function clearTestDevices(): void; + type SDKLogLevel = 'none' | 'debug' | 'verbose' | 'warning' | 'error' | 'notification'; + function setLogLevel(logLevel: SDKLogLevel): void; + function setIsChildDirected(isDirected: boolean): void; + function setMediationService(mediationService: string): void; + function setUrlPrefix(urlPrefix: string): void; + } +} + +/** + * FaceDetector + */ +export interface Point { + x: Axis; + y: Axis; +} + +export interface FaceFeature { + bounds: { + size: { + width: number; + height: number; + }, + origin: Point; + }; + smilingProbability?: number; + leftEarPosition?: Point; + rightEarPosition?: Point; + leftEyePosition?: Point; + leftEyeOpenProbability?: number; + rightEyePosition?: Point; + rightEyeOpenProbability?: number; + leftCheekPosition?: Point; + rightCheekPosition?: Point; + leftMouthPosition?: Point; + mouthPosition?: Point; + rightMouthPosition?: Point; + bottomMouthPosition?: Point; + noseBasePosition?: Point; + yawAngle?: number; + rollAngle?: number; +} + +export interface TrackedFaceFeature extends FaceFeature { + faceID?: number; +} + +export namespace FaceDetector { + interface DetectFaceResult { + faces: FaceFeature[]; + image: { + uri: string; + width: number; + height: number; + orientation: number; + }; + } + interface Mode { + fast: 'fast'; + accurate: 'accurate'; + } + interface _Shared { + all: 'all'; + none: 'none'; + } + type Landmarks = _Shared; + type Classifications = _Shared; + interface _Constants { + Mode: Mode; + Landmarks: Landmarks; + Classifications: Classifications; + } + + const Constants: _Constants; + + interface DetectionOptions { + mode?: keyof Mode; + detectLandmarks?: keyof Landmarks; + runClassifications?: keyof Classifications; + } + + function detectFaces(uri: string, options?: DetectionOptions): Promise; +} +/** + * FileSystem + */ +export namespace FileSystem { + type FileInfo = { + exists: true; + isDirectory: boolean; + uri: string; + size: number; + modificationTime: number; + md5?: Md5; + } | { + exists: false; + isDirectory: false; + }; + + interface DownloadResult { + uri: string; + status: number; + headers: { [name: string]: string }; + md5?: Md5; + } + + const documentDirectory: string; + const cacheDirectory: string; + + function getInfoAsync(fileUri: string, options?: { md5?: string, size?: boolean; }): Promise; + function readAsStringAsync(fileUri: string): Promise; + function writeAsStringAsync(fileUri: string, contents: string): Promise; + function deleteAsync(fileUri: string, options?: { idempotent: boolean; }): Promise; + function moveAsync(options: { from: string, to: string; }): Promise; + function copyAsync(options: { from: string, to: string; }): Promise; + function makeDirectoryAsync(dirUri: string, options?: { intermediates: boolean }): Promise; + function readDirectoryAsync(dirUri: string): Promise; + function downloadAsync(uri: string, fileUri: string, options?: { md5?: boolean; }): Promise; + function createDownloadResumable( + uri: string, + fileUri: string, + options?: DownloadOptions, + callback?: (totalBytesWritten: number, totalBytesExpectedToWrite: number) => void, + resumeData?: string | null + ): DownloadResumable; + + interface PauseResult { + url: string; + fileUri: string; + options: { md5: boolean; }; + resumeData: string; + } + + interface DownloadOptions { + md5?: boolean; + headers?: { [name: string]: string }; + } + + interface DownloadProgressData { + totalBytesWritten: number; + totalBytesExpectedToWrite: number; + } + + type DownloadProgressCallback = (data: DownloadProgressData) => void; + + class DownloadResumable { + constructor( + url: string, + fileUri: string, + options: DownloadOptions, + callback?: DownloadProgressCallback, + resumeData?: string + ); + + downloadAsync(): Promise; + pauseAsync(): Promise; + resumeAsync(): Promise; + savable(): PauseResult; + } +} + +/** Use TouchID/FaceID (iOS) or the Fingerprint API (Android) to authenticate the user with a fingerprint scan. */ +export namespace LocalAuthentication { + type LocalAuthenticationResult = { + success: true + } | { + success: false, + + /** Error code in the case where authentication fails. */ + error: string + }; + + /** Determine whether a face or fingerprint scanner is available on the device. */ + function hasHardwareAsync(): Promise; + + /** Determine whether the device has saved fingerprints or facial data to use for authentication. */ + function isEnrolledAsync(): Promise; + + /** + * Attempts to authenticate via Fingerprint. Android: When using the fingerprint module on Android, you need to provide a UI component to prompt the user to scan their fingerprint, as the OS has no default alert for it. + * + * @param promptMessage A message that is shown alongside the TouchID/FaceID prompt. (iOS only) + */ + function authenticateAsync(promptMessageIOS?: string): Promise; + + /** Cancels the fingerprint authentication flow. (Android only) */ + function cancelAuthenticate(): void; +} + +/** + * Font + */ +export namespace Font { + interface FontMap { + [name: string]: RequireSource; + } + + function loadAsync(name: string, url: string): Promise; + function loadAsync(map: FontMap): Promise; +} + +// #region GLView +export interface ExpoWebGLRenderingContext extends WebGLRenderingContext { + endFrameEXP(): void; +} + +/** + * A View that acts as an OpenGL ES render target. On mounting, an OpenGL ES + * context is created. Its drawing buffer is presented as the contents of + * the View every frame. + */ +export interface GLViewProps extends ViewProps { + /** + * A function that will be called when the OpenGL ES context is created. + * Passes an object with a WebGLRenderingContext interface as an argument. + */ + onContextCreate(gl: ExpoWebGLRenderingContext): void; + + /** Number of MSAA samples to use on iOS. Defaults to 4. Ignored on Android. */ + msaaSamples?: number; +} + +export class GLView extends Component { } +// #endregion + +/** + * Google + */ +export namespace Google { + interface LogInConfig { + androidClientId?: string; + androidStandaloneAppClientId?: string; + iosClientId?: string; + iosStandaloneAppClientId?: string; + webClientId?: string; + behavior?: 'system' | 'web'; + scopes?: string[]; + } + + type LogInResult = { + type: 'cancel'; + } | { + type: 'success'; + accessToken: string; + idToken?: string; + refreshToken?: string; + serverAuthCode?: string; + user: { + id: string; + name: string; + givenName: string; + familyName: string; + photoUrl?: string; + email?: string; + } + }; + + function logInAsync(config: LogInConfig): Promise; +} + +/** Access the device gyroscope sensor to respond to changes in rotation in 3d space. */ +export namespace Gyroscope { + interface GyroscopeObject { + x: Axis; + y: Axis; + z: Axis; + } + + /** A callback that is invoked when an gyroscope update is available. */ + function addListener(listener: (obj: GyroscopeObject) => any): EventSubscription; + + /** Remove all listeners. */ + function removeAllListeners(): void; + + /** Subscribe for updates to the gyroscope. */ + function setUpdateInterval(intervalMs: number): void; +} + +/** + * ImageManipulator + */ +export namespace ImageManipulator { + type Action = Resize | Rotate | Flip | Crop; + + interface Resize { + resize: { width?: number, height?: number }; + } + + interface Rotate { + rotate: number; + } + + interface Flip { + flip?: { vertical?: boolean; horizontal?: boolean }; + } + + interface Crop { + originX: number; + originY: number; + width: number; + height: number; + } + + interface ImageResult { + uri: string; + width: number; + height: number; + base64?: string; + } + + interface SaveOptions { + base64?: boolean; + /** A value in range `0` - `1` specifying compression level of the result image. `1` means no compression and `0` the highest compression. */ + compress?: number; + format?: 'jpeg' | 'png'; + } + + function manipulate(uri: string, actions: Action[], saveOptions?: SaveOptions): Promise; +} + +/** + * Image Picker + */ +export namespace ImagePicker { + interface ImageInfo { + uri: string; + width: number; + height: number; + type: 'video' | 'image'; + base64?: string; + exif?: object; + duration?: number; + } + + type ImageResult = { cancelled: true } | ({ cancelled: false } & ImageInfo); + + interface _MediaTypeOptions { + All: 'All'; + Videos: 'Videos'; + Images: 'Images'; + } + + const MediaTypeOptions: _MediaTypeOptions; + + interface ImageLibraryOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + base64?: boolean; + exif?: boolean; + mediaTypes?: keyof _MediaTypeOptions; + } + + /** + * require Permissions.CAMERA_ROLL + */ + function launchImageLibraryAsync(options?: ImageLibraryOptions): Promise; + + interface CameraOptions { + allowsEditing?: boolean; + aspect?: [number, number]; + quality?: number; + base64?: boolean; + exif?: boolean; + } + + /** + * require Permissions.CAMERA_ROLL + */ + function launchCameraAsync(options?: CameraOptions): Promise; +} + +/** + * IntentLauncherAndroid + */ +export namespace IntentLauncherAndroid { + const ACTION_ACCESSIBILITY_SETTINGS: 'android.settings.ACCESSIBILITY_SETTINGS'; + const ACTION_APP_NOTIFICATION_REDACTION: 'android.settings.ACTION_APP_NOTIFICATION_REDACTION'; + const ACTION_CONDITION_PROVIDER_SETTINGS: 'android.settings.ACTION_CONDITION_PROVIDER_SETTINGS'; + const ACTION_NOTIFICATION_LISTENER_SETTINGS: 'android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS'; + const ACTION_PRINT_SETTINGS: 'android.settings.ACTION_PRINT_SETTINGS'; + const ACTION_ADD_ACCOUNT_SETTINGS: 'android.settings.ADD_ACCOUNT_SETTINGS'; + const ACTION_AIRPLANE_MODE_SETTINGS: 'android.settings.AIRPLANE_MODE_SETTINGS'; + const ACTION_APN_SETTINGS: 'android.settings.APN_SETTINGS'; + const ACTION_APPLICATION_DETAILS_SETTINGS: 'android.settings.APPLICATION_DETAILS_SETTINGS'; + const ACTION_APPLICATION_DEVELOPMENT_SETTINGS: 'android.settings.APPLICATION_DEVELOPMENT_SETTINGS'; + const ACTION_APPLICATION_SETTINGS: 'android.settings.APPLICATION_SETTINGS'; + const ACTION_APP_NOTIFICATION_SETTINGS: 'android.settings.APP_NOTIFICATION_SETTINGS'; + const ACTION_APP_OPS_SETTINGS: 'android.settings.APP_OPS_SETTINGS'; + const ACTION_BATTERY_SAVER_SETTINGS: 'android.settings.BATTERY_SAVER_SETTINGS'; + const ACTION_BLUETOOTH_SETTINGS: 'android.settings.BLUETOOTH_SETTINGS'; + const ACTION_CAPTIONING_SETTINGS: 'android.settings.CAPTIONING_SETTINGS'; + const ACTION_CAST_SETTINGS: 'android.settings.CAST_SETTINGS'; + const ACTION_DATA_ROAMING_SETTINGS: 'android.settings.DATA_ROAMING_SETTINGS'; + const ACTION_DATE_SETTINGS: 'android.settings.DATE_SETTINGS'; + const ACTION_DEVICE_INFO_SETTINGS: 'android.settings.DEVICE_INFO_SETTINGS'; + const ACTION_DEVICE_NAME: 'android.settings.DEVICE_NAME'; + const ACTION_DISPLAY_SETTINGS: 'android.settings.DISPLAY_SETTINGS'; + const ACTION_DREAM_SETTINGS: 'android.settings.DREAM_SETTINGS'; + const ACTION_HARD_KEYBOARD_SETTINGS: 'android.settings.HARD_KEYBOARD_SETTINGS'; + const ACTION_HOME_SETTINGS: 'android.settings.HOME_SETTINGS'; + const ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS: 'android.settings.IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS'; + const ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS: 'android.settings.IGNORE_BATTERY_OPTIMIZATION_SETTINGS'; + const ACTION_INPUT_METHOD_SETTINGS: 'android.settings.INPUT_METHOD_SETTINGS'; + const ACTION_INPUT_METHOD_SUBTYPE_SETTINGS: 'android.settings.INPUT_METHOD_SUBTYPE_SETTINGS'; + const ACTION_INTERNAL_STORAGE_SETTINGS: 'android.settings.INTERNAL_STORAGE_SETTINGS'; + const ACTION_LOCALE_SETTINGS: 'android.settings.LOCALE_SETTINGS'; + const ACTION_LOCATION_SOURCE_SETTINGS: 'android.settings.LOCATION_SOURCE_SETTINGS'; + const ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS: 'android.settings.MANAGE_ALL_APPLICATIONS_SETTINGS'; + const ACTION_MANAGE_APPLICATIONS_SETTINGS: 'android.settings.MANAGE_APPLICATIONS_SETTINGS'; + const ACTION_MANAGE_DEFAULT_APPS_SETTINGS: 'android.settings.MANAGE_DEFAULT_APPS_SETTINGS'; + const ACTION_MEMORY_CARD_SETTINGS: 'android.settings.MEMORY_CARD_SETTINGS'; + const ACTION_MONITORING_CERT_INFO: 'android.settings.MONITORING_CERT_INFO'; + const ACTION_NETWORK_OPERATOR_SETTINGS: 'android.settings.NETWORK_OPERATOR_SETTINGS'; + const ACTION_NFCSHARING_SETTINGS: 'android.settings.NFCSHARING_SETTINGS'; + const ACTION_NFC_PAYMENT_SETTINGS: 'android.settings.NFC_PAYMENT_SETTINGS'; + const ACTION_NFC_SETTINGS: 'android.settings.NFC_SETTINGS'; + const ACTION_NIGHT_DISPLAY_SETTINGS: 'android.settings.NIGHT_DISPLAY_SETTINGS'; + const ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS: 'android.settings.NOTIFICATION_POLICY_ACCESS_SETTINGS'; + const ACTION_NOTIFICATION_SETTINGS: 'android.settings.NOTIFICATION_SETTINGS'; + const ACTION_PAIRING_SETTINGS: 'android.settings.PAIRING_SETTINGS'; + const ACTION_PRIVACY_SETTINGS: 'android.settings.PRIVACY_SETTINGS'; + const ACTION_QUICK_LAUNCH_SETTINGS: 'android.settings.QUICK_LAUNCH_SETTINGS'; + const ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS: 'android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS'; + const ACTION_SECURITY_SETTINGS: 'android.settings.SECURITY_SETTINGS'; + const ACTION_SETTINGS: 'android.settings.SETTINGS'; + const ACTION_SHOW_ADMIN_SUPPORT_DETAILS: 'android.settings.SHOW_ADMIN_SUPPORT_DETAILS'; + const ACTION_SHOW_INPUT_METHOD_PICKER: 'android.settings.SHOW_INPUT_METHOD_PICKER'; + const ACTION_SHOW_REGULATORY_INFO: 'android.settings.SHOW_REGULATORY_INFO'; + const ACTION_SHOW_REMOTE_BUGREPORT_DIALOG: 'android.settings.SHOW_REMOTE_BUGREPORT_DIALOG'; + const ACTION_SOUND_SETTINGS: 'android.settings.SOUND_SETTINGS'; + const ACTION_STORAGE_MANAGER_SETTINGS: 'android.settings.STORAGE_MANAGER_SETTINGS'; + const ACTION_SYNC_SETTINGS: 'android.settings.SYNC_SETTINGS'; + const ACTION_SYSTEM_UPDATE_SETTINGS: 'android.settings.SYSTEM_UPDATE_SETTINGS'; + const ACTION_TETHER_PROVISIONING_UI: 'android.settings.TETHER_PROVISIONING_UI'; + const ACTION_TRUSTED_CREDENTIALS_USER: 'android.settings.TRUSTED_CREDENTIALS_USER'; + const ACTION_USAGE_ACCESS_SETTINGS: 'android.settings.USAGE_ACCESS_SETTINGS'; + const ACTION_USER_DICTIONARY_INSERT: 'android.settings.USER_DICTIONARY_INSERT'; + const ACTION_USER_DICTIONARY_SETTINGS: 'android.settings.USER_DICTIONARY_SETTINGS'; + const ACTION_USER_SETTINGS: 'android.settings.USER_SETTINGS'; + const ACTION_VOICE_CONTROL_AIRPLANE_MODE: 'android.settings.VOICE_CONTROL_AIRPLANE_MODE'; + const ACTION_VOICE_CONTROL_BATTERY_SAVER_MODE: 'android.settings.VOICE_CONTROL_BATTERY_SAVER_MODE'; + const ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE: 'android.settings.VOICE_CONTROL_DO_NOT_DISTURB_MODE'; + const ACTION_VOICE_INPUT_SETTINGS: 'android.settings.VOICE_INPUT_SETTINGS'; + const ACTION_VPN_SETTINGS: 'android.settings.VPN_SETTINGS'; + const ACTION_VR_LISTENER_SETTINGS: 'android.settings.VR_LISTENER_SETTINGS'; + const ACTION_WEBVIEW_SETTINGS: 'android.settings.WEBVIEW_SETTINGS'; + const ACTION_WIFI_IP_SETTINGS: 'android.settings.WIFI_IP_SETTINGS'; + const ACTION_WIFI_SETTINGS: 'android.settings.WIFI_SETTINGS'; + const ACTION_WIRELESS_SETTINGS: 'android.settings.WIRELESS_SETTINGS'; + const ACTION_ZEN_MODE_AUTOMATION_SETTINGS: 'android.settings.ZEN_MODE_AUTOMATION_SETTINGS'; + const ACTION_ZEN_MODE_EVENT_RULE_SETTINGS: 'android.settings.ZEN_MODE_EVENT_RULE_SETTINGS'; + const ACTION_ZEN_MODE_EXTERNAL_RULE_SETTINGS: 'android.settings.ZEN_MODE_EXTERNAL_RULE_SETTINGS'; + const ACTION_ZEN_MODE_PRIORITY_SETTINGS: 'android.settings.ZEN_MODE_PRIORITY_SETTINGS'; + const ACTION_ZEN_MODE_SCHEDULE_RULE_SETTINGS: 'android.settings.ZEN_MODE_SCHEDULE_RULE_SETTINGS'; + const ACTION_ZEN_MODE_SETTINGS: 'android.settings.ZEN_MODE_SETTINGS'; + + function startActivityAsync(activity: string, data?: HashMap): Promise; +} + +/** + * KeepAwake + */ +export class KeepAwake extends Component { + static activate(): void; + static deactivate(): void; +} + +// #region LinearGradient +/** + * LinearGradient + */ +export interface LinearGradientProps { + colors: string[]; + start?: [number, number]; + end?: [number, number]; + locations?: number[]; + style?: StyleProp; +} + +export class LinearGradient extends Component { } +// #endregion + +/** + * Linking + */ +export interface LinkInfo { + path: string; + queryParams: Partial; +} + +export interface LinkingStatic extends ReactNativeLinkingStatic { + makeUrl(path: string, queryParams?: HashMap): string; + parse(url: string): LinkInfo; + parseInitialURLAsync(): Promise; +} +export const Linking: LinkingStatic; + +/** + * Location + */ +export namespace Location { + interface LocationOptions { + enableHighAccuracy?: boolean; + timeInterval?: number; + distanceInterval?: number; + } + + interface LocationProps { + latitude: number; + longitude: number; + } + + interface Coords extends LocationProps { + altitude: number; + accuracy: number; + } + + interface LocationData { + coords: { + heading: number; + speed: number + } & Coords; + timestamp: number; + } + + interface ProviderStatus { + locationServicesEnabled: boolean; + gpsAvailable?: boolean; + networkAvailable?: boolean; + passiveAvailable?: boolean; + } + + interface HeadingStatus { + magHeading: number; + trueHeading: number; + accuracy: number; + } + + interface GeocodeData { + city: string; + street: string; + region: string; + postalCode: string; + country: string; + name: string; + } + + type LocationCallback = (data: LocationData) => void; + + function getCurrentPositionAsync(options: LocationOptions): Promise; + function watchPositionAsync(options: LocationOptions, callback: LocationCallback): EventSubscription; + function getProviderStatusAsync(): Promise; + function getHeadingAsync(): Promise; + function watchHeadingAsync(callback: (status: HeadingStatus) => void): EventSubscription; + function geocodeAsync(address: string): Promise; + function reverseGeocodeAsync(location: LocationProps): Promise; + function setApiKey(key: string): void; +} + +/** + * Magnetometer + */ +export namespace Magnetometer { + interface MagnetometerObject { + x: Axis; + y: Axis; + z: Axis; + } + + function addListener(listener: (obj: MagnetometerObject) => any): EventSubscription; + function removeAllListeners(): void; + function setUpdateInterval(intervalMs: number): void; +} + +/** + * Notifications + */ +export namespace Notifications { + interface Notification { + origin: 'selected' | 'received'; + data: any; + remote: boolean; + isMultiple: boolean; + } + + interface LocalNotification { + title: string; + body?: string; + data?: any; + ios?: { + sound?: boolean + }; + android?: { + sound?: boolean; + icon?: string; + color?: string; + priority?: 'min' | 'low' | 'high' | 'max'; + sticky?: boolean; + vibrate?: boolean | number[]; + link?: string; + }; + } + + type LocalNotificationId = string | number; + + function addListener(listener: (notification: Notification) => any): EventSubscription; + function getExpoPushTokenAsync(): Promise; + function presentLocalNotificationAsync(localNotification: LocalNotification): Promise; + function scheduleLocalNotificationAsync( + localNotification: LocalNotification, + schedulingOptions: { time: Date | number, repeat?: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year' } + ): Promise; + function dismissNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function dismissAllNotificationsAsync(): Promise; + function cancelScheduledNotificationAsync(localNotificationId: LocalNotificationId): Promise; + function cancelAllScheduledNotificationsAsync(): Promise; + function getBadgeNumberAsync(): Promise; + function setBadgeNumberAsync(number: number): Promise; +} + +/** + * Pedometer + */ +export namespace Pedometer { + function isAvailableAsync(): Promise; + function getStepCountAsync(start: Date, end: Date): Promise<{ steps: number; }>; + function watchStepCount(callback: (params: { steps: number; }) => void): EventSubscription; +} + +/** + * Permissions + */ +export namespace Permissions { + type PermissionType = 'audioRecording' | 'calendar' | + 'cameraRoll' | 'camera' | 'contacts' | 'location' | 'reminders' | + 'remoteNotifications' | 'systemBrightness' | 'userFacingNotifications'; + type PermissionStatus = 'undetermined' | 'granted' | 'denied'; + type PermissionExpires = 'never'; + + interface PermissionDetailsLocationIOS { + scope: 'whenInUse' | 'always'; + } + + interface PermissionDetailsLocationAndroid { + scope: 'fine' | 'coarse' | 'none'; + } + + interface PermissionResponse { + status: PermissionStatus; + expires: PermissionExpires; + ios?: PermissionDetailsLocationIOS; + android?: PermissionDetailsLocationAndroid; + } + + function getAsync(type: PermissionType): Promise; + function askAsync(type: PermissionType): Promise; + + type RemoteNotificationPermission = 'remoteNotifications'; + + const AUDIO_RECORDING: 'audioRecording'; + const CALENDAR: 'calendar'; + const CAMERA_ROLL: 'cameraRoll'; + const CAMERA: 'camera'; + const CONTACTS: 'contacts'; + const LOCATION: 'location'; + const NOTIFICATIONS: RemoteNotificationPermission; + const REMINDERS = 'reminders'; + const REMOTE_NOTIFICATIONS: RemoteNotificationPermission; + const SYSTEM_BRIGHTNESS: 'systemBrightness'; + const USER_FACING_NOTIFICATIONS = 'userFacingNotifications'; +} + +/** + * Register Root Component + */ +export function registerRootComponent(component: ComponentType): void; + +/** + * ScreenOrientation + */ +export namespace ScreenOrientation { + interface Orientations { + ALL: 'ALL'; + ALL_BUT_UPSIDE_DOWN: 'ALL_BUT_UPSIDE_DOWN'; + PORTRAIT: 'PORTRAIT'; + PORTRAIT_UP: 'PORTRAIT_UP'; + PORTRAIT_DOWN: 'PORTRAIT_DOWN'; + LANDSCAPE: 'LANDSCAPE'; + LANDSCAPE_LEFT: 'LANDSCAPE_LEFT'; + LANDSCAPE_RIGHT: 'LANDSCAPE_RIGHT'; + } + + const Orientation: Orientations; + + function allow(orientation: keyof Orientations): void; +} + +/** + * SecureStore + */ +export namespace SecureStore { + interface SecureStoreOptions { + keychainService?: string; + keychainAccessible?: number; + } + + function setItemAsync(key: string, value: string, options?: SecureStoreOptions): Promise; + function getItemAsync(key: string, options?: SecureStoreOptions): Promise; + function deleteItemAsync(key: string, options?: SecureStoreOptions): Promise; +} + +/** + * Segment + */ +export namespace Segment { + function initialize(keys: { + androidWriteKey: string; + iosWriteKey: string; + }): void; + function identify(userId: string): void; + function identifyWithTraits(userId: string, traits: object): void; + function track(event: string): void; + function reset(): void; + function trackWithProperties(event: string, properties: object): void; + function screen(screenName: string): void; + function screenWithProperties(screenName: string, properties: object): void; + function flush(): void; +} + +/** + * Speech + */ +export namespace Speech { + interface SpeechOptions { + language?: string; + pitch?: number; + rate?: number; + onStart?: () => void; + onStopped?: () => void; + onDone?: () => void; + onError?: (error: string) => void; + } + + function speak(text: string, options?: SpeechOptions): void; + function stop(): void; + function isSpeakingAsync(): Promise; + + /** Available on iOS only */ + function pause(): void; + + /** Available on iOS only */ + function resume(): void; +} + +/** + * SQLite + */ +export namespace SQLite { + type Error = any; + + interface Database { + transaction( + callback: (transaction: Transaction) => any, + error?: (error: Error) => any, // TODO def of error + success?: () => any + ): void; + } + + interface Transaction { + executeSql( + sqlStatement: string, + arguments?: string[] | number[], + success?: (transaction: Transaction, resultSet: ResultSet) => any, + error?: (transaction: Transaction, error: Error) => any + ): void; + } + + interface ResultSet { + insertId: number; + rowAffected: number; + rows: { + length: number; + item: (index: number) => any; + _array: HashMap[]; + }; + } + + function openDatabase( + name: string | { + name: string, + version?: string, + description?: string, + size?: number, + callback?: () => any + }, + version?: string, + description?: string, + size?: number, + callback?: () => any + ): any; +} + +// #region Svg +/** + * Svg + */ +export interface SvgCommonProps { + fill?: string; + fillOpacity?: number | string; + fillRule?: 'nonzero' | 'evenodd'; + opacity?: number | string; + stroke?: string; + strokeWidth?: number | string; + strokeOpacity?: number | string; + strokeLinecap?: string; + strokeLineJoin?: string; + strokeDasharray?: any[]; + strokeDashoffset?: any; + transform?: string | object; + x?: number | string; + y?: number | string; + rotate?: number | string; + rotation?: number | string; + scale?: number | string; + origin?: number | string; + originX?: number | string; + originY?: number | string; + id?: string; + disabled?: boolean; + onPress?: () => any; + onPressIn?: () => any; + onPressOut?: () => any; + onLongPress?: () => any; + delayPressIn?: number; + delayPressOut?: number; + delayLongPress?: number; +} + +export interface SvgRectProps extends SvgCommonProps { + width: number | string; + height: number | string; +} + +export interface SvgCircleProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + r: number | string; +} + +export interface SvgEllipseProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + rx: number | string; + ry: number | string; +} + +export interface SvgLineProps extends SvgCommonProps { + x1: number | string; + y1: number | string; + x2: number | string; + y2: number | string; +} + +export interface SvgPolyProps extends SvgCommonProps { + points: string; +} + +export interface SvgPathProps extends SvgCommonProps { + d: string; +} + +export interface SvgTextProps extends SvgCommonProps { + textAnchor?: string; + fontSize?: number | string; + fontWeight?: string; +} + +export interface SvgTSpanProps extends SvgTextProps { + dx?: string; + dy?: string; +} + +export interface SvgTextPathProps extends SvgCommonProps { + href?: string; + startOffset?: string; +} + +export interface SvgUseProps extends SvgCommonProps { + href: string; + x: number | string; + y: number | string; + width?: number | string; + height?: number | string; +} + +export interface SvgSymbolProps extends SvgCommonProps { + viewBox: string; + preserveAspectRatio?: string; + width: number | string; + height: number | string; +} + +export interface SvgLinearGradientProps extends SvgCommonProps { + x1: number | string; + x2: number | string; + y1: number | string; + y2: number | string; +} + +export interface SvgRadialGradientProps extends SvgCommonProps { + cx: number | string; + cy: number | string; + rx: number | string; + ry: number | string; + fx: number | string; + fy: number | string; + gradientUnits?: string; +} + +export interface SvgStopProps extends SvgCommonProps { + offset?: string; + stopColor?: string; + stopOpacity?: string; +} + +export class Svg extends Component<{ width: number, height: number, viewBox?: string, preserveAspectRatio?: string }> { + static Circle: ComponentClass; + static ClipPath: ComponentClass; + static Defs: ComponentClass; + static Ellipse: ComponentClass; + static G: ComponentClass; + static Line: ComponentClass; + static LinearGradient: ComponentClass; + static Path: ComponentClass; + static Polygon: ComponentClass; + static Polyline: ComponentClass; + static RadialGradient: ComponentClass; + static Rect: ComponentClass; + static Stop: ComponentClass; + static Symbol: ComponentClass; + static Text: ComponentClass; + static TextPath: ComponentClass; + static TSpan: ComponentClass; + static Use: ComponentClass; +} +// #endregion + +/** + * Take Snapshot + */ +export function takeSnapshotAsync( + view?: (number | React.ReactElement), + options?: { + width?: number, + height?: number, + format?: 'png' | 'jpg' | 'jpeg' | 'webm', + quality?: number, + result?: 'file' | 'base64' | 'data-uri', + } +): Promise; + +/** Helpful utility functions that don’t fit anywhere else, including some localization and internationalization methods. */ +export namespace Util { + /** Returns the current device country code. */ + function getCurrentDeviceCountryAsync(): Promise; + + /** Returns the current device locale as a string. */ + function getCurrentLocaleAsync(): Promise; + + /** Returns the current device time zone name. */ + function getCurrentTimeZoneAsync(): Promise; + + /** Reloads the current experience. This will fetch and load the newest available JavaScript supported by the device’s Expo environment. This is useful for triggering an update of your experience if you have published a new version. */ + function reload(): void; + + /** _Android only_. Invokes a callback when a new version of your app is successfully downloaded in the background. */ + function addNewVersionListenerExperimental(listener: (event: { + manifest: object; + }) => void): { remove(): void; }; +} + +// #region Video +/** + * Expo Video + */ +export interface NaturalSize { + width: number; + height: number; + orientation: Orientation; +} + +export interface ReadyForDisplayEvent { + naturalSize: NaturalSize; + status: PlaybackStatus; +} + +export enum FullscreenUpdateVariants { + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT = 0, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT = 1, + IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS = 2, + IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS = 3 +} + +export interface FullscreenUpdateEvent { + fullscreenUpdate: FullscreenUpdateVariants; + status: PlaybackStatus; +} + +export interface VideoProps { + source?: PlaybackSource | null; + posterSource?: URISource | RequireSource; + + resizeMode?: ResizeModeContain | ResizeModeCover | ResizeModeStretch; + useNativeControls?: boolean; + usePoster?: boolean; + + onPlaybackStatusUpdate?: (status: PlaybackStatus) => void; + onReadyForDisplay?: (event: ReadyForDisplayEvent) => void; + onIOSFullscreenUpdate?: (event: FullscreenUpdateEvent) => void; + + onLoadStart?: () => void; + onLoad?: (status: PlaybackStatus) => void; + onError?: (error: string) => void; + + status?: PlaybackStatusToSet; + progressUpdateIntervalMillis?: number; + positionMillis?: number; + shouldPlay?: boolean; + rate?: number; + shouldCorrectPitch?: boolean; + volume?: number; + isMuted?: boolean; + isLooping?: boolean; + + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; + rotation?: number; + ref?: Ref; + style?: StyleProp; +} + +export interface VideoState { + showPoster: boolean; +} + +export class Video extends Component { + static RESIZE_MODE_CONTAIN: ResizeModeContain; + static RESIZE_MODE_COVER: ResizeModeCover; + static RESIZE_MODE_STRETCH: ResizeModeStretch; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_PRESENT; + static IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_WILL_DISMISS; + static IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS: FullscreenUpdateVariants.IOS_FULLSCREEN_UPDATE_PLAYER_DID_DISMISS; +} +// #endregion + +/** + * Web Browser + */ +export namespace WebBrowser { + function openBrowserAsync(url: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function openAuthSessionAsync(url: string, redirectUrl?: string): Promise<{ type: 'cancelled' | 'dismissed' }>; + function dismissBrowser(): Promise<{ type: 'dismissed' }>; +} + +// #region Calendar +/** + * Calendar + * + * Provides an API for interacting with the device’s system calendars, events, reminders, and associated records. + */ +export namespace Calendar { + interface Calendar { + /** Internal ID that represents this calendar on the device */ + id?: string; + + /** Visible name of the calendar */ + title?: string; + + sourceId?: string; // iOS + + /** Object representing the source to be used for the calendar */ + source?: Source; + + /** Type of calendar this object represents */ + type?: CalendarType; // iOS + + /** Color used to display this calendar’s events */ + color?: string; + + /** Whether the calendar is used in the Calendar or Reminders OS app */ + entityType?: EntityTypes; // iOS + + /** Boolean value that determines whether this calendar can be modified */ + allowsModifications?: boolean; + + /** Availability types that this calendar supports */ + allowedAvailabilities?: Availability[]; + + /** Boolean value indicating whether this is the device’s primary calendar */ + isPrimary?: boolean; // Android + + /** Internal system name of the calendar */ + name?: string; // Android + + /** Name for the account that owns this calendar */ + ownerAccount?: string; // Android + + /** Time zone for the calendar */ + timeZone?: string; // Android + + /** Alarm methods that this calendar supports */ + allowedReminders?: AlarmMethod[]; // Android + + /** Attendee types that this calendar supports */ + allowedAttendeeTypes?: AttendeeType[]; // Android + + /** Indicates whether the OS displays events on this calendar */ + isVisible?: boolean; // Android + + /** Indicates whether this calendar is synced and its events stored on the device */ + isSynced?: boolean; // Android + + /** Level of access that the user has for the calendar */ + accessLevel?: CalendarAccessLevel; // Android + } + + interface Source { + /** Internal ID that represents this source on the device */ + id?: string; // iOS only ?? + + /** Type of account that owns this calendar */ + type?: string; + + /** Name for the account that owns this calendar */ + name?: string; + + /** Whether this source is the local phone account */ + isLocalAccount?: boolean; // Android + } + + interface Event { + /** Internal ID that represents this event on the device */ + id?: string; + + /** ID of the calendar that contains this event */ + calendarId?: string; + + /** Visible name of the event */ + title?: string; + + /** Location field of the event */ + location?: string; + + /** Date when the event record was created */ + creationDate?: string; // iOS + + /** Date when the event record was last modified */ + lastModifiedDate?: string; // iOS + + /** Time zone the event is scheduled in */ + timeZone?: string; + + /** Time zone for the event end time */ + endTimeZone?: string; // Android + + /** URL for the event */ + url?: string; // iOS + + /** Description or notes saved with the event */ + notes?: string; + + /** Array of Alarm objects which control automated reminders to the user */ + alarms?: Alarm[]; + + /** Object representing rules for recurring or repeating events. Null for one-time events. */ + recurrenceRule?: RecurrenceRule; + + /** Date object or string representing the time when the event starts */ + startDate?: string | Date; + + /** Date object or string representing the time when the event ends */ + endDate?: string | Date; + + /** For recurring events, the start date for the first (original) instance of the event */ + originalStartDate?: string; // iOS + + /** Boolean value indicating whether or not the event is a detached (modified) instance of a recurring event */ + isDetached?: boolean; // iOS + + /** Whether the event is displayed as an all-day event on the calendar */ + allDay?: boolean; + + /** The availability setting for the event */ + availability?: Availability; // Availability + + /** Status of the event */ + status?: EventStatus; // Status + + /** Organizer of the event, as an Attendee object */ + organizer?: string; // Organizer - iOS + + /** Email address of the organizer of the event */ + organizerEmail?: string; // Android + + /** User’s access level for the event */ + accessLevel?: EventAccessLevel; // Android, + + /** Whether invited guests can modify the details of the event */ + guestsCanModify?: boolean; // Android, + + /** Whether invited guests can invite other guests */ + guestsCanInviteOthers?: boolean; // Android + + /** Whether invited guests can see other guests */ + guestsCanSeeGuests?: boolean; // Android + + /** For detached (modified) instances of recurring events, the ID of the original recurring event */ + originalId?: string; // Android + + /** For instances of recurring events, volatile ID representing this instance; not guaranteed to always refer to the same instance */ + instanceId?: string; // Android + } + + interface Attendee { + /** Internal ID that represents this attendee on the device */ + id?: string; // Android + + /** Indicates whether or not this attendee is the current OS user */ + isCurrentUser?: boolean; // iOS + + /** Displayed name of the attendee */ + name?: string; + + /** Role of the attendee at the event */ + role?: AttendeeRole; + + /** Status of the attendee in relation to the event */ + status?: AttendeeStatus; + + /** Type of the attendee */ + type?: AttendeeType; + + /** URL for the attendee */ + url?: string; // iOS + + /** Email address of the attendee */ + email?: string; // Android + } + + interface Reminder { + /** Internal ID that represents this reminder on the device */ + id?: string; + + /** ID of the calendar that contains this reminder */ + calendarId?: string; + + /** Visible name of the reminder */ + title?: string; + + /** Location field of the reminder */ + location?: string; + + /** Date when the reminder record was created */ + creationDate?: string; + + /** Date when the reminder record was last modified */ + lastModifiedDate?: string; + + /** Time zone the reminder is scheduled in */ + timeZone?: string; + + /** URL for the reminder */ + url?: string; + + /** Description or notes saved with the reminder */ + notes?: string; + + /** Array of Alarm objects which control automated alarms to the user about the task */ + alarms?: Alarm[]; + + /** Object representing rules for recurring or repeated reminders. Null for one-time tasks. */ + recurrenceRule?: RecurrenceRule; + + /** Date object or string representing the start date of the reminder task */ + startDate?: string; + + /** Date object or string representing the time when the reminder task is due */ + dueDate?: string; + + /** Indicates whether or not the task has been completed */ + completed?: boolean; + + /** Date object or string representing the date of completion, if completed is true */ + completionDate?: string; + } + + interface Alarm { + /** Date object or string representing an absolute time the alarm should occur; overrides relativeOffset and structuredLocation if specified alongside either */ + absoluteDate?: string; // iOS + + /** Number of minutes from the startDate of the calendar item that the alarm should occur; use negative values to have the alarm occur before the startDate */ + relativeOffset?: string; + structuredLocation?: { + // iOS + title?: string; + proximity?: string; // Proximity + radius?: number; + coords?: { + latitude?: number; + longitude?: number; + }; + }; + + /** Method of alerting the user that this alarm should use; on iOS this is always a notification */ + method?: AlarmMethod; // Method, Android + } + + interface RecurrenceRule { + /** How often the calendar item should recur */ + frequency: Frequency; // Frequency + + /** Interval at which the calendar item should recur. For example, an interval: 2 with frequency: DAILY would yield an event that recurs every other day. Defaults to 1 . */ + interval?: number; + + /** Date on which the calendar item should stop recurring; overrides occurrence if both are specified */ + endDate?: string; + + /** Number of times the calendar item should recur before stopping */ + occurrence?: number; + } + + enum EntityTypes { + EVENT = 'event', + REMINDER = 'reminder', + } + + enum CalendarType { + LOCAL = 'local', + CALDAV = 'caldav', + EXCHANGE = 'exchange', + SUBSCRIBED = 'subscribed', + BIRTHDAYS = 'birthdays' + } + + enum Availability { + NOT_SUPPORTED = 'notSupported', // iOS + BUSY = 'busy', + FREE = 'free', + TENTATIVE = 'tentative', + UNAVAILABLE = 'unavailable' // iOS + } + + enum AlarmMethod { + ALARM = 'alarm', + ALERT = 'alert', + EMAIL = 'email', + SMS = 'sms', + DEFAULT = 'default', + } + + enum AttendeeType { + UNKNOWN = 'unknown', // iOS + PERSON = 'person', // iOS + ROOM = 'room', // iOS + GROUP = 'group', // iOS + RESOURCE = 'resource', + OPTIONAL = 'optional', // Android + REQUIRED = 'required', // Android + NONE = 'none' // Android + } + + enum CalendarAccessLevel { + CONTRIBUTOR = 'contributor', + EDITOR = 'editor', + FREEBUSY = 'freebusy', + OVERRIDE = 'override', + OWNER = 'owner', + READ = 'read', + RESPOND = 'respond', + ROOT = 'root', + NONE = 'none' + } + + enum EventAccessLevel { + CONFIDENTIAL = 'confidential', + PRIVATE = 'private', + PUBLIC = 'public', + DEFAULT = 'default' + } + + enum EventStatus { + NONE = 'none', + CONFIRMED = 'confirmed', + TENTATIVE = 'tentative', + CANCELED = 'canceled' + } + + enum AttendeeRole { + UNKNOWN = 'unknown', // iOS + REQUIRED = 'required', // iOS + OPTIONAL = 'optional', // iOS + CHAIR = 'chair', // iOS + NON_PARTICIPANT = 'nonParticipant', // iOS + ATTENDEE = 'attendee', // Android + ORGANIZER = 'organizer', // Android + PERFORMER = 'performer', // Android + SPEAKER = 'speaker', // Android + NONE = 'none' // Android + } + + enum AttendeeStatus { + UNKNOWN = 'unknown', // iOS + PENDING = 'pending', // iOS + ACCEPTED = 'accepted', + DECLINED = 'declined', + TENTATIVE = 'tentative', + DELEGATED = 'delegated', // iOS + COMPLETED = 'completed', // iOS + IN_PROCESS = 'inProcess', // iOS + INVITED = 'invited', // Android + NONE = 'none' // Android + } + + enum Frequency { + DAILY = 'daily', + WEEKLY = 'weekly', + MONTHLY = 'monthly', + YEARLY = 'yearly' + } + + enum ReminderStatus { + COMPLETED = 'completed', + INCOMPLETE = 'incomplete' + } + + interface RecurringEventOptions { + futureEvents?: boolean; + instanceStartDate?: string; + } + + /** Gets an array of calendar objects with details about the different calendars stored on the device. */ + function getCalendarsAsync( + /** (iOS only) Not required, but if defined, filters the returned calendars to a specific entity type. */ + entityType?: EntityTypes + ): Promise; + + /** Creates a new calendar on the device, allowing events to be added later and displayed. */ + function createCalendarAsync(details: Calendar): Promise; + + /** Updates the provided details of an existing calendar stored on the device. To remove a property, explicitly set it to null in details */ + function updateCalendarAsync(id: string, details?: Calendar | null): Promise; + + /** Deletes an existing calendar and all associated events/reminders/attendees from the device. Use with caution. */ + function deleteCalendarAsync(id: string): Promise; + + /** Returns all events in a given set of calendars over a specified time period. */ + function getEventsAsync( + /** Array of IDs of calendars to search for events in. Required. */ + calendarIds: string[], + + /** Beginning of time period to search for events in. Required. */ + startDate: Date, + + /** End of time period to search for events in. Required. */ + endDate: Date + ): Promise; + + /** Returns a specific event selected by ID. If a specific instance of a recurring event is desired, the start date of this instance must also be provided, as instances of recurring events do not have their own unique and stable IDs on either iOS or Android. */ + function getEventAsync( + /** ID of the event to return. Required. */ + id: string, + + /** A map of options for recurring events */ + recurringEventOptions?: RecurringEventOptions + ): Promise; + + /** Creates a new event on the specified calendar. */ + function createEventAsync( + /** ID of the calendar to create this event in. Required. */ + calendarId: string, + details?: Event + ): Promise; + + /** Updates the provided details of an existing calendar stored on the device. To remove a property, explicitly set it to null in details */ + function updateEventAsync( + /** ID of the event to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Event | null, + + /** A map of options for recurring events */ + recurrentEventOptions?: RecurringEventOptions + ): Promise; + + /** Deletes an existing event from the device. Use with caution. */ + function deleteEventAsync( + /** ID of the event to be deleted. Required. */ + id: string, + + /** A map of options for recurring events */ + recurringEventOptions?: RecurringEventOptions + ): Promise; + + /** Gets all attendees for a given event (or instance of a recurring event). */ + function getAttendeesForEventAsync( + /** ID of the event to return attendees for. Required. */ + eventId: string, + + /** A map of options for recurring events */ + recurrentEventOptions?: RecurringEventOptions + ): Promise; + + /** Available on Android only. Creates a new attendee record and adds it to the specified event. Note that if eventId specifies a recurring event, this will add the attendee to every instance of the event. */ + function createAttendeeAsync( + /** ID of the event to add this attendee to. Required. */ + eventId: string, + + /** A map of details for the attendee to be created */ + details?: Attendee + ): Promise; + + /** Available on Android only. Updates an existing attendee record. To remove a property, explicitly set it to null in details. */ + function updateAttendeeAsync( + /** ID of the attendee record to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Attendee | null + ): Promise; + + /** Available on Android only. Deletes an existing attendee record from the device. Use with caution. */ + function deleteAttendeeAsync(id: string): Promise; + + /** Available on iOS only. Returns a list of reminders matching the provided criteria. */ + function getRemindersAsync( + /** Array of IDs of calendars to search for reminders in. Required. */ + calendarIds: string[], + + status?: ReminderStatus, + + /** Beginning of time period to search for reminders in. Required if status is defined. */ + startDate?: Date, + + /** End of time period to search for reminders in. Required if status is defined. */ + endDate?: Date + ): Promise; + + /** Available on iOS only. Returns a specific reminder selected by ID. */ + function getReminderAsync(id: string): Promise; + + /** Available on iOS only. Creates a new reminder on the specified calendar. */ + function createReminderAsync( + /** ID of the calendar to create this reminder in. Required. */ + calendarId: string, + + /** A map of details for the reminder to be created */ + details?: Reminder + ): Promise; + + /** Available on iOS only. Updates the provided details of an existing reminder stored on the device. To remove a property, explicitly set it to null in details. */ + function updateReminderAsync( + /** ID of the reminder to be updated. Required. */ + id: string, + + /** A map of properties to be updated */ + details?: Reminder | null + ): Promise; + + /** Available on iOS only. Deletes an existing reminder from the device. Use with caution. */ + function deleteReminderAsync(id: string): Promise; + + /** Available on iOS only. */ + function getSourcesAsync(): Promise; + + /** Available on iOS only. Returns a specific source selected by ID. */ + function getSourceAsync(id: string): Promise; + + /** Available on Android only. Sends an intent to open the specified event in the OS Calendar app. */ + function openEventInCalendar( + /** ID of the event to open. Required. */ + id: string + ): void; +} +// #endregion + +// #region MailComposer +/** + * An API to compose mails using OS specific UI. + */ +export namespace MailComposer { + interface ComposeOptions { + /** An array of e-mail addressess of the recipients. */ + recipients?: string[]; + + /** An array of e-mail addressess of the CC recipients. */ + ccRecipients?: string[]; + + /** An array of e-mail addressess of the BCC recipients. */ + bccRecipients?: string[]; + + /** Subject of the mail. */ + subject?: string; + + /** Body of the mail. */ + body?: string; + + /** Whether the body contains HTML tags so it could be formatted properly. Not working perfectly on Android. */ + isHtml?: boolean; + + /** An array of app’s internal file uris to attach. */ + attachments?: string[]; + } + + /** Resolves to a promise with object containing status field that could be either sent, saved or cancelled. Android does not provide such info so it always resolves to sent. */ + function composeAsync( + /** A map defining the data to fill the mail */ + options: ComposeOptions + ): Promise<{ status: 'sent' | 'saved' | 'cancelled' }>; +} +// #endregion + +export namespace Updates { + namespace EventType { + /** A new update is available and has started downloading. */ + type DownloadStart = 'downloadStart'; + /** A new update is currently being downloaded and will be stored in the device's cache. */ + type DownloadProgress = 'downloadProgress'; + /** A new update has finished downloading and is now stored in the device's cache. */ + type DownloadFinished = 'downloadFinished'; + /** No updates are available, and the most up-to-date bundle of this experience is already running. */ + type NoUpdateAvailable = 'noUpdateAvailable'; + /** An error occurred trying to fetch the latest update. */ + type Error = 'error'; + + /** A new update is available and has started downloading. */ + const DOWNLOAD_STARTED: DownloadStart; + /** A new update is currently being downloaded and will be stored in the device's cache. */ + const DOWNLOAD_PROGRESS: DownloadProgress; + /** A new update has finished downloading and is now stored in the device's cache. */ + const DOWNLOAD_FINISHED: DownloadFinished; + /** No updates are available, and the most up-to-date bundle of this experience is already running. */ + const NO_UPDATE_AVAILABLE: NoUpdateAvailable; + /** An error occurred trying to fetch the latest update. */ + const ERROR: Error; + } + + interface UpdateCheck { + /** True if an update is available, false if you're already running the most up-to-date JS bundle. */ + isAvailable: boolean; + /** If `isAvailable` is true, the manifest of the available update. Undefined otherwise. */ + manifest?: Constants.Manifest; + } + + interface UpdateBundle { + /** True if the fetched bundle is new (i.e. a different version that the what's currently running). */ + isNew: boolean; + /** Manifest of the fetched update. */ + manifest: Constants.Manifest; + } + + /** An object that is passed into each event listener when a new version is available. */ + interface UpdateEvent { + /** Type of the event */ + type: EventType.DownloadStart + | EventType.DownloadProgress + | EventType.DownloadFinished + | EventType.NoUpdateAvailable + | EventType.Error; + /** If `type === Expo.Updates.EventType.DOWNLOAD_FINISHED`, the manifest of the newly downloaded update. Undefined otherwise. */ + manifest?: Constants.Manifest; + /** If `type === Expo.Updates.EventType.ERROR`, the error message. Undefined otherwise. */ + message?: string; + } + + /** An optional params object passed to fetchUpdateAsync. */ + interface FetchUpdateAsyncParams { + eventListener: UpdateEventListener; + } + + type UpdateEventListener = (event: UpdateEvent) => any; + + /** + * Invokes a callback when updates-related events occur, + * either on the initial app load or as a result of a call to `Expo.Updates.fetchUpdateAsync`. + */ + function addListener(listener: UpdateEventListener): EventSubscription; + + /** + * Check if a new published version of your project is available. + * Does not actually download the update. + * Rejects if `updates.enabled` is `false` in app.json. + */ + function checkForUpdateAsync(): Promise; + + /** + * Downloads the most recent published version of your experience to the device's local cache. + * Rejects if `updates.enabled` is `false` in app.json. + */ + function fetchUpdateAsync(params?: FetchUpdateAsyncParams): Promise; + + /** + * Immediately reloads the current experience. + * This will use your app.json updates configuration to fetch and load the newest available JS supported by the device's Expo environment. + * This is useful for triggering an update of your experience if you have published a new version. + */ + function reload(): void; + + /** + * Immediately reloads the current experience using the most recent cached version. + * This is useful for triggering an update of your experience if you have published and already downloaded a new version. + */ + function reloadFromCache(): void; +} + +// #region MediaLibrary +/** + * https://docs.expo.io/versions/latest/sdk/media-library + * Provides access to user's media library + * Requires Permissions.CAMERA_ROLL permissions. + */ + +export namespace MediaLibrary { + /** + * Creates an asset from existing file. The most common use case is to save a picture taken by Camera. + */ + function createAssetAsync(localUri: string): Promise; + + /** + * Fetches a page of assets matching the provided criteria. + */ + function getAssetsAsync(options: GetAssetsOptions): Promise; + + /** + * Provides more informations about an asset, including GPS location, local URI and EXIF metadata. + */ + function getAssetInfoAsync(asset: string | Asset): Promise; + + /** + * Deletes assets from the library. On iOS it deletes assets from all albums they belong to, while on Android it keeps all copies of them + * (album is strictly connected to the asset). Also, there is additional dialog on iOS that requires user to confirm this action. + */ + function deleteAssetsAsync(asset: string[] | Asset[]): Promise; + + /** + * Queries for user-created albums in media gallery. + */ + function getAlbumsAsync(): Promise; + + /** + * Queries for an album with a specific name. + */ + function getAlbumAsync(albumName: string): Promise; + + /** + * Creates an album with given name and initial asset. + * The asset parameter is required on Android, since it's not possible to create empty album on this platform. + */ + function createAlbumAsync(albumName: string, asset: string | Asset): Promise; + + /** + * Adds array of assets to the album. + * On Android, by default it copies assets from the current album to provided one, however it's also possible to move them by passing false as copyAssets argument. + * In case they're copied you should keep in mind that getAssetsAsync will return duplicated assets. + */ + function addAssetsToAlbumAsync(assets: Asset[], album: string | Album, copyAssets?: boolean /* default true */): Promise; + + /** + * Removes given assets from album. + * On Android, album will be automatically deleted if there are no more assets inside. + */ + function removeAssetsFromAlbumAsync(assets: Asset[], album: string | Album): Promise; + + /** + * Available on iOS only. Fetches a list of moments, which is a group of assets taken around the same place and time. + */ + function getMomentsAsync(): Promise; + + enum MediaType { + audio = 'audio', + photo = 'photo', + video = 'video', + unknow = 'unknow' + } + + enum SortBy { + default = 'default', + id = 'id', + creationTime = 'creationTime', + modificationTime = 'modificationTime', + mediaType = 'mediaType', + width = 'width', + height = 'height', + duration = 'duration' + } + + // region Asset + interface AssetAndroid { + albumId?: string; + } + + interface AssetIos { + mediaSubtypes?: MediaType[]; + // * + orientation: number; + // * + isFavorite: boolean; + } + + interface Asset extends AssetAndroid, AssetIos { + id: string; + filename: string; + uri: string; + mediaType: string; + width: number; + height: number; + creationTime: number; + modificationTime: number; + duration: number; + // * + localUri?: string; + // * + location?: Location.LocationProps; + // * + exif?: object; + } + + /** + * These fields can be obtained only by calling getAssetInfoAsync method + */ + //#endregion + + // #region Album + interface AlbumIos { + type?: string; + // * + startTime: number; + // * + endTime: number; + // * + approximateLocation?: Location.LocationProps; + // * + locationNames?: string[]; + } + + /** + * These fields apply only to albums whose type is moment + */ + + interface Album extends AlbumIos { + id: string; + title: string; + assetCount: number; + } + // #endregion + + interface GetAssetsOptions { + first?: number; + after?: string; + album?: string | Album; + sortBy?: SortBy; + mediaType?: MediaType; + } + + interface GetAssetsResult { + assets: Asset[]; + endCursor: string; + hasNextPage: boolean; + totalCount: number; + } +} +// #endregion + +// #region Haptic +/** + * https://docs.expo.io/versions/latest/sdk/haptic + * Provides haptic feedback for iOS 10+ devices using the Taptic Engine. + * If this is used in Android the device will use ReactNative.Vibrate instead, it's best to just avoid this. + */ +export namespace Haptic { + /** + * Used to let a user know when a selection change has been registered + */ + function selection(): void; + function notification(notificationType?: NotificationType): void; + function impact(impactStyles?: ImpactStyles): void; + + enum ImpactStyles { + Light = 'light', + Medium = 'medium', + Heavy = 'heavy' + } + + enum NotificationType { + Success = 'success', + Warning = 'warning', + Error = 'error' + } +} +// #endregion diff --git a/types/expo/v30/tsconfig.json b/types/expo/v30/tsconfig.json new file mode 100644 index 0000000000..ec6b729436 --- /dev/null +++ b/types/expo/v30/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "expo": [ + "expo/v30" + ], + "expo/*": [ + "expo/v30/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expo-tests.tsx" + ] +} diff --git a/types/expo/v30/tslint.json b/types/expo/v30/tslint.json new file mode 100644 index 0000000000..8270136207 --- /dev/null +++ b/types/expo/v30/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "void-return": false, + "max-line-length": false + } +} diff --git a/types/express-fileupload/express-fileupload-tests.ts b/types/express-fileupload/express-fileupload-tests.ts index 2a268fb64e..f423e5035a 100644 --- a/types/express-fileupload/express-fileupload-tests.ts +++ b/types/express-fileupload/express-fileupload-tests.ts @@ -9,7 +9,7 @@ const app: express.Express = express(); app.use(fileUpload({debug: true})); function isUploadedFile(file: UploadedFile | UploadedFile[]): file is UploadedFile { - return typeof file === 'object' && ( file).name !== undefined; + return typeof file === 'object' && (file as UploadedFile).name !== undefined; } const uploadHandler: RequestHandler = (req: Request, res: Response, next: NextFunction) => { diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 6b04bf8f11..60ec11648f 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -140,6 +140,7 @@ interface IDataURLOptions { interface IEvent { e: Event; target?: Object; + transform?: { corner: string }; } interface IFillOptions { @@ -3466,7 +3467,7 @@ export class IText extends Object { * @param [endIndex] End index to get styles at * @return styles Style object at a specified (or current) index */ - getSelectionStyles(startIndex: number, endIndex: number): any; + getSelectionStyles(startIndex: number, endIndex: number, complete?: boolean): any; /** * Sets style of a current selection * @param [styles] Styles object @@ -4528,7 +4529,7 @@ interface IUtilMisc { * @param [context] Context to invoke callback in * @param [crossOrigin] crossOrigin value to set image element to */ - loadImage(url: string, callback: (image: HTMLImageElement) => void, context?: any, crossOrigin?: boolean): void; + loadImage(url: string, callback: (image: HTMLImageElement) => void, context?: any, crossOrigin?: string): void; /** * Creates corresponding fabric instances from their object representations diff --git a/types/fastify-jwt/fastify-jwt-tests.ts b/types/fastify-jwt/fastify-jwt-tests.ts index 6b92026b04..fc68ac8bcc 100644 --- a/types/fastify-jwt/fastify-jwt-tests.ts +++ b/types/fastify-jwt/fastify-jwt-tests.ts @@ -1,17 +1,16 @@ -import { IncomingMessage, Server, ServerResponse } from "http"; -import fastifyJwt = require("fastify-jwt"); import fastify = require("fastify"); +import fastifyJwt = require("fastify-jwt"); const app = fastify(); app.register(fastifyJwt, { - secret: "super-secret" + secret: "super-secret", }); app.register(fastifyJwt, { secret: (request, reply, callback) => { return ""; - } + }, }); app.get("/path", (request, reply) => { diff --git a/types/fastify-jwt/package.json b/types/fastify-jwt/package.json index e8c68ab969..5eb77c39fa 100644 --- a/types/fastify-jwt/package.json +++ b/types/fastify-jwt/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "fastify": "^1.11.2" + "fastify": ">=1.13.1 || 2.0.0-rc.1" } } diff --git a/types/favicons/favicons-tests.ts b/types/favicons/favicons-tests.ts index 485ea1d505..ce64c84e67 100644 --- a/types/favicons/favicons-tests.ts +++ b/types/favicons/favicons-tests.ts @@ -1,6 +1,6 @@ -import favicons, { Configuration } from "favicons"; +import * as favicons from "favicons"; -let config: Partial = { +let config: Partial = { path: "/foo/bar" }; @@ -19,7 +19,15 @@ favicons("path/to/file.png", config, (err, res) => { } }); -favicons("file.png", (err, res) => { +favicons("file.png", (err: any, res: any) => { + html = res.html.join(""); + + for (const { name, contents } of [...res.files, ...res.images]) { + html = name + contents.toString(); + } +}); + +favicons("file.png").then((res) => { html = res.html.join(""); for (const { name, contents } of [...res.files, ...res.images]) { diff --git a/types/favicons/index.d.ts b/types/favicons/index.d.ts index 47a9a9d24a..6bd3a4892e 100644 --- a/types/favicons/index.d.ts +++ b/types/favicons/index.d.ts @@ -1,79 +1,84 @@ -// Type definitions for favicons 5.1 +// Type definitions for favicons 5.3 // Project: https://github.com/evilebottnawi/favicons/blob/master/package.json -// Definitions by: Mohsen Azimi +// Definitions by: Mohsen Azimi , Nikk Radetskiy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 /// -export interface Configuration { - /** Path for overriding default icons path @default "/" */ - path: string; - /** Your application's name @default null */ - appName: string | null; - /** Your application's description @default null */ - appDescription: string | null; - /** Your (or your developer's) name @default null */ - developerName: string | null; - /** Your (or your developer's) URL @default null */ - developerURL: string | null; - /** Primary text direction for name, short_name, and description @default "auto" */ - dir: string; - /** Primary language for name and short_name @default "en-US */ - lang: string; - /** Background colour for flattened icons @default "#fff" */ - background: string; - /** Theme color user for example in Android's task switcher @default "#fff" */ - theme_color: string; - /** Preferred display mode: "fullscreen", "standalone", "minimal-ui" or "browser" @default "standalone" */ - display: "fullscreen" | "standalone" | "minimal-ui" | "browser"; - /** Default orientation: "any", "natural", "portrait" or "landscape" @default "any" */ - orientation: "any" | "natural" | "portrait" | "landscape"; - /** Start URL when launching the application from a device @default "/?homescreen=1" */ - start_url: string; - /** Your application's version string @default "1.0" */ - version: string; - /** Print logs to console? @default false */ - logging: boolean; - /** - * Platform Options: - * - offset - offset in percentage - * - background: - * * false - use default - * * true - force use default, e.g. set background for Android icons - * * color - set background for the specified icons - */ - icons: Partial<{ - /* Create Android homescreen icon. */ - android: boolean | { offset: string; background: string }; - /* Create Apple touch icons. */ - appleIcon: boolean | { offset: string; background: string }; - /* Create Apple startup images. */ - appleStartup: boolean | { offset: string; background: string }; - /* Create Opera Coast icon. */ - coast: boolean | { offset: string; background: string }; - /* Create regular favicons. */ - favicons: boolean; - /* Create Firefox OS icons. */ - firefox: boolean | { offset: string; background: string }; - /* Create Windows 8 tile icons. */ - windows: boolean | { background: string }; - /* Create Yandex browser icon. */ - yandex: boolean | { background: string }; - }>; +import { Duplex } from "stream"; + +declare namespace favicons { + interface Configuration { + /** Path for overriding default icons path @default "/" */ + path: string; + /** Your application's name @default null */ + appName: string | null; + /** Your application's description @default null */ + appDescription: string | null; + /** Your (or your developer's) name @default null */ + developerName: string | null; + /** Your (or your developer's) URL @default null */ + developerURL: string | null; + /** Primary text direction for name, short_name, and description @default "auto" */ + dir: string; + /** Primary language for name and short_name @default "en-US */ + lang: string; + /** Background colour for flattened icons @default "#fff" */ + background: string; + /** Theme color user for example in Android's task switcher @default "#fff" */ + theme_color: string; + /** Preferred display mode: "fullscreen", "standalone", "minimal-ui" or "browser" @default "standalone" */ + display: "fullscreen" | "standalone" | "minimal-ui" | "browser"; + /** Default orientation: "any", "natural", "portrait" or "landscape" @default "any" */ + orientation: "any" | "natural" | "portrait" | "landscape"; + /** Start URL when launching the application from a device @default "/?homescreen=1" */ + start_url: string; + /** Your application's version string @default "1.0" */ + version: string; + /** Print logs to console? @default false */ + logging: boolean; + /** + * Platform Options: + * - offset - offset in percentage + * - background: + * * false - use default + * * true - force use default, e.g. set background for Android icons + * * color - set background for the specified icons + */ + icons: Partial<{ + /* Create Android homescreen icon. */ + android: boolean | { offset: string; background: string }; + /* Create Apple touch icons. */ + appleIcon: boolean | { offset: string; background: string }; + /* Create Apple startup images. */ + appleStartup: boolean | { offset: string; background: string }; + /* Create Opera Coast icon. */ + coast: boolean | { offset: string; background: string }; + /* Create regular favicons. */ + favicons: boolean; + /* Create Firefox OS icons. */ + firefox: boolean | { offset: string; background: string }; + /* Create Windows 8 tile icons. */ + windows: boolean | { background: string }; + /* Create Yandex browser icon. */ + yandex: boolean | { background: string }; + }>; + } + + interface FavIconResponse { + images: Array<{ name: string; contents: Buffer }>; + files: Array<{ name: string; contents: Buffer }>; + html: string[]; + } + + type Callback = (error: Error | null, response: FavIconResponse) => void; + + /** You can programmatically access Favicons configuration (icon filenames, HTML, manifest files, etc) with this export */ + const config: Configuration; + + function stream(configuration?: Configuration): Duplex; } - -export interface FavIconResponse { - images: Array<{ name: string; contents: Buffer }>; - files: Array<{ name: string; contents: Buffer }>; - html: string[]; -} - -export type Callback = (error: Error | null, response: FavIconResponse) => void; - -/** You can programmatically access Favicons configuration (icon filenames, HTML, manifest files, etc) with this export */ -export const config: Configuration; - /** * Generate favicons * @param source Source image(s) @@ -82,12 +87,16 @@ export const config: Configuration; */ declare function favicons( source: string | Buffer | string[], - callback?: Callback + configuration?: Partial, +): Promise; +declare function favicons( + source: string | Buffer | string[], + callback?: favicons.Callback ): void; declare function favicons( source: string | Buffer | string[], - configuration?: Partial, - callback?: Callback + configuration?: Partial, + callback?: favicons.Callback ): void; -export default favicons; +export = favicons; diff --git a/types/feathersjs__feathers/feathersjs__feathers-tests.ts b/types/feathersjs__feathers/feathersjs__feathers-tests.ts index 7d0e961700..bf1cdf8aa7 100644 --- a/types/feathersjs__feathers/feathersjs__feathers-tests.ts +++ b/types/feathersjs__feathers/feathersjs__feathers-tests.ts @@ -9,7 +9,7 @@ interface Services { users: User; } -const app = feathers() as Application; +const app = feathers(); app.service('users').get(0).then(u => { const user: User = u; diff --git a/types/feathersjs__feathers/index.d.ts b/types/feathersjs__feathers/index.d.ts index 53cdf182a1..4746b29ff7 100644 --- a/types/feathersjs__feathers/index.d.ts +++ b/types/feathersjs__feathers/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @feathersjs/feathers 3.0 +// Type definitions for @feathersjs/feathers 3.1 // Project: http://feathersjs.com/ // Definitions by: Jan Lohage // Abraao Alves @@ -12,7 +12,8 @@ import { EventEmitter } from 'events'; import * as self from '@feathersjs/feathers'; -declare const feathers: (() => Application) & typeof self; +// tslint:disable-next-line no-unnecessary-generics +declare const feathers: (() => Application) & typeof self; export default feathers; export const version: string; @@ -138,7 +139,7 @@ export interface HooksObject { // todo: figure out what to do: These methods don't actually need to be implemented, so they can be undefined at runtime. Yet making them optional gets cumbersome in strict mode. export interface ServiceMethods { - find(params?: Params): Promise>; + find(params?: Params): Promise>; get(id: Id, params?: Params): Promise; diff --git a/types/file-type/file-type-tests.ts b/types/file-type/file-type-tests.ts index ecfd658a1a..640d2c8fb0 100644 --- a/types/file-type/file-type-tests.ts +++ b/types/file-type/file-type-tests.ts @@ -2,3 +2,5 @@ import fileType = require("file-type"); fileType(new Buffer([0xFF, 0xD8, 0xFF])); fileType(new Uint8Array([0xFF, 0xD8, 0xFF])); + +const minimumBytes: number = fileType.minimumBytes; diff --git a/types/file-type/index.d.ts b/types/file-type/index.d.ts index c7f95c256e..2a0deee26a 100644 --- a/types/file-type/index.d.ts +++ b/types/file-type/index.d.ts @@ -15,4 +15,6 @@ declare namespace FileType { ext: string; mime: string; } + + const minimumBytes: number; } diff --git a/types/find-versions/find-versions-tests.ts b/types/find-versions/find-versions-tests.ts index 81ea6ca974..e92e6d9848 100644 --- a/types/find-versions/find-versions-tests.ts +++ b/types/find-versions/find-versions-tests.ts @@ -1,3 +1,4 @@ import findVersions = require('find-versions'); -findVersions('node v1.0.0'); +findVersions('node v1.0.0'); // $ExpectType string[] +findVersions('1.0', { loose: true }); // $ExpectType string[] diff --git a/types/find-versions/index.d.ts b/types/find-versions/index.d.ts index 449c5a45c3..9531c1628f 100644 --- a/types/find-versions/index.d.ts +++ b/types/find-versions/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for find-versions 2.0 +// Type definitions for find-versions 3.0 // Project: https://github.com/sindresorhus/find-versions // Definitions by: Leonid Logvinov +// Chris Arnesen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function findVersions(version: string): string[]; +declare function findVersions(version: string, options?: { loose: boolean }): string[]; export = findVersions; diff --git a/types/fined/fined-tests.ts b/types/fined/fined-tests.ts new file mode 100644 index 0000000000..5ee4e79bc6 --- /dev/null +++ b/types/fined/fined-tests.ts @@ -0,0 +1,18 @@ +import fined = require('fined'); + +// $ExpectType Result | null +fined({ path: 'path/to/file', extensions: ['.js', '.json'] }); + +const opts = { + name: '.app', + cwd: '.', + extensions: { + rc: 'default-rc-loader', + '.yml': 'default-yml-loader', + }, +}; + +fined({ path: '.' }, opts); +fined({ path: '~', extensions: { rc: 'some-special-rc-loader' } }, opts); +fined({ path: '~' }, {}); +fined({ path: '~' }, { extensions: '.ext' }); diff --git a/types/fined/index.d.ts b/types/fined/index.d.ts new file mode 100644 index 0000000000..107a40760c --- /dev/null +++ b/types/fined/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for fined 1.1 +// Project: https://github.com/js-cli/fined#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = fined; + +declare function fined(path: string | fined.PathSpec, opts?: fined.PathSpec): fined.Result | null; + +declare namespace fined { + interface PathSpec { + path?: string; + name?: string; + extensions?: string | string[] | { [extension: string]: string | null }; + cwd?: string; + findUp?: boolean; + } + + interface Result { + path: string; + extension: string | { [extension: string]: string }; + } +} diff --git a/types/fined/tsconfig.json b/types/fined/tsconfig.json new file mode 100644 index 0000000000..ce11eba9be --- /dev/null +++ b/types/fined/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fined-tests.ts" + ] +} diff --git a/types/fined/tslint.json b/types/fined/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fined/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/flagged-respawn/flagged-respawn-tests.ts b/types/flagged-respawn/flagged-respawn-tests.ts new file mode 100644 index 0000000000..12f949f9fb --- /dev/null +++ b/types/flagged-respawn/flagged-respawn-tests.ts @@ -0,0 +1,14 @@ +import flaggedRespawn = require('flagged-respawn'); + +const flags = ['--flag']; + +flaggedRespawn(flags, process.argv, (ready, child, argv) => { + // $ExpectType boolean + ready; + // $ExpectType Process + child; + // $ExpectType string[] + argv; +}); +flaggedRespawn(flags, process.argv, '--flag', () => {}); +flaggedRespawn(flags, process.argv, ['--flag'], () => {}); diff --git a/types/flagged-respawn/index.d.ts b/types/flagged-respawn/index.d.ts new file mode 100644 index 0000000000..eea62b2e8c --- /dev/null +++ b/types/flagged-respawn/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for flagged-respawn 1.0 +// Project: https://github.com/js-cli/js-flagged-respawn +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = flaggedRespawn; + +declare function flaggedRespawn( + flags: string[], + argv: string[], + callback: flaggedRespawn.Callback +): void; +declare function flaggedRespawn( + flags: string[], + argv: string[], + forcedFlags: string | string[], + callback: flaggedRespawn.Callback +): void; + +declare namespace flaggedRespawn { + type Callback = (ready: boolean, proc: NodeJS.Process, argv: string[]) => void; +} diff --git a/types/flagged-respawn/tsconfig.json b/types/flagged-respawn/tsconfig.json new file mode 100644 index 0000000000..91fce74324 --- /dev/null +++ b/types/flagged-respawn/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "flagged-respawn-tests.ts" + ] +} diff --git a/types/flagged-respawn/tslint.json b/types/flagged-respawn/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/flagged-respawn/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fleximap/fleximap-tests.ts b/types/fleximap/fleximap-tests.ts new file mode 100644 index 0000000000..4ca0181662 --- /dev/null +++ b/types/fleximap/fleximap-tests.ts @@ -0,0 +1,27 @@ +import { FlexiMap } from "fleximap"; + +let flexiMap = new FlexiMap(); +flexiMap = new FlexiMap({ arr: [] }); +flexiMap = new FlexiMap([{ arr: [] }, { obj: {} }]); + +flexiMap.set('keyA', {arr: [], obj: {}}); +let result = flexiMap.get(['keyA', 'arr']); + +flexiMap.add(['keyB1', 'keyB2', 'keyB3'], 123); +result = flexiMap.get(['keyB1', 'keyB2']); + +const arr = []; +arr[5] = 'Hello world'; + +flexiMap.set(['keyC1', 'keyC2'], arr); +result = flexiMap.get(['keyC1', 'keyC2']); + +flexiMap.set(['itemsA', 0], 'hello'); +flexiMap.set(['itemsA', 2], 'world'); +flexiMap.remove(['itemsA', 0]); + +flexiMap.set(['itemsB', 0], 'a'); +flexiMap.set(['itemsB', 1], 'b'); +flexiMap.set(['itemsB', 2], 'c'); +let splicedItems = flexiMap.splice(['itemsB'], 1, 1); +splicedItems = flexiMap.splice(['itemsB'], 1, 0, 'b2'); diff --git a/types/fleximap/index.d.ts b/types/fleximap/index.d.ts new file mode 100644 index 0000000000..8481134ffe --- /dev/null +++ b/types/fleximap/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for fleximap 0.9 +// Project: https://github.com/SocketCluster/fleximap +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export type KeyChain = any; + +export class FlexiMap { + constructor(object?: any[] | object); + + get(keyChain: KeyChain): any; + getRange(keyChain: KeyChain, fromIndex: number, toIndex: number): any; + getRaw(keyChain: KeyChain): any; + getAll(): any[] | object; + + count(keyChain: KeyChain): number; + + hasImmediateKey(key: string): boolean; + hasKey(keyChain: KeyChain): boolean; + hasType(keyChain: KeyChain, type: any): boolean; + hasValue(keyChain: KeyChain, value: any): boolean; + hasObject(keyChain: KeyChain, object: object): boolean; + + set(keyChain: KeyChain, value: any): any; + + add(keyChain: KeyChain, value: any): number; + + concat(keyChain: KeyChain, value: any): any; + + remove(keyChain: KeyChain): any; + removeRange(keyChain: KeyChain, fromIndex: number, toIndex: number): any[]; + removeAll(): void; + + splice(keyChain: KeyChain, index: number, count: number, ...items: any[]): any[]; + + pop(keyChain: KeyChain): any[]; +} diff --git a/types/fleximap/tsconfig.json b/types/fleximap/tsconfig.json new file mode 100644 index 0000000000..710fa81c96 --- /dev/null +++ b/types/fleximap/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fleximap-tests.ts" + ] +} diff --git a/types/fleximap/tslint.json b/types/fleximap/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/fleximap/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/fuzzy-search/fuzzy-search-tests.ts b/types/fuzzy-search/fuzzy-search-tests.ts new file mode 100644 index 0000000000..667cda446f --- /dev/null +++ b/types/fuzzy-search/fuzzy-search-tests.ts @@ -0,0 +1,27 @@ +import FuzzySearch = require('fuzzy-search'); + +const f = new FuzzySearch(['1', '2', '3']); + +new FuzzySearch([{ a: 1 }, { a: 2 }, { a: 3 }], ['a']); + +new FuzzySearch([{ a: 1 }, { a: 2 }, { a: 3 }], ['a'], {}); + +new FuzzySearch([{ a: 1 }, { a: 2 }, { a: 3 }], ['a'], { caseSensitive: true }); + +new FuzzySearch([{ a: 1 }, { a: 2 }, { a: 3 }], ['a'], { sort: true }); + +new FuzzySearch([{ a: 1 }, { a: 2 }, { a: 3 }], ['a'], { caseSensitive: true, sort: true }); + +let strArr: string[]; + +strArr = f.haystack; +// $ExpectType string[] +f.keys; +// $ExpectType Required +f.options; + +strArr = new FuzzySearch(['1', '2', '3']).search(); +strArr = new FuzzySearch(['1', '2', '3']).search('2'); + +// $ExpectType number +FuzzySearch.isMatch('1', '1', false); diff --git a/types/fuzzy-search/index.d.ts b/types/fuzzy-search/index.d.ts new file mode 100644 index 0000000000..8c3d5103ff --- /dev/null +++ b/types/fuzzy-search/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for fuzzy-search 2.1 +// Project: https://github.com/wouter2203/fuzzy-search#readme +// Definitions by: Alex Deas +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +declare class FuzzySearch { + haystack: T[]; + keys: string[]; + options: Required; + + static isMatch(item: string, query: string, caseSensitive: boolean): number; + + constructor(haystack: T[], keys?: string[], options?: FuzzySearch.Options); + search(needle?: string): T[]; +} + +declare namespace FuzzySearch { + interface Options { + caseSensitive?: boolean; + sort?: boolean; + } +} + +export = FuzzySearch; diff --git a/types/fuzzy-search/tsconfig.json b/types/fuzzy-search/tsconfig.json new file mode 100644 index 0000000000..c72f9609d0 --- /dev/null +++ b/types/fuzzy-search/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fuzzy-search-tests.ts" + ] +} diff --git a/types/fuzzy-search/tslint.json b/types/fuzzy-search/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fuzzy-search/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gapi.auth2/gapi.auth2-tests.ts b/types/gapi.auth2/gapi.auth2-tests.ts index 1fc03f7f4f..229a18f5fc 100644 --- a/types/gapi.auth2/gapi.auth2-tests.ts +++ b/types/gapi.auth2/gapi.auth2-tests.ts @@ -144,7 +144,8 @@ function handleSignoutClick(event: MouseEvent) { // Load the API and make an API call. Display the results on the screen. function makeApiCall() { gapi.client.people.people.get({ - resourceName: 'people/me' + resourceName: 'people/me', + personFields: 'names' }).then((resp) => { const p = document.createElement('p'); const name = resp.result.names[0].givenName; diff --git a/types/gapi.people/gapi.people-tests.ts b/types/gapi.people/gapi.people-tests.ts index 65b6339765..349f956b39 100644 --- a/types/gapi.people/gapi.people-tests.ts +++ b/types/gapi.people/gapi.people-tests.ts @@ -64,6 +64,7 @@ var request = gapi.client.people.people.connections.list({ 'resourceName': 'people/me', 'pageSize': 10, + 'personFields': 'names' }); request.execute(function(resp) { diff --git a/types/gapi.people/index.d.ts b/types/gapi.people/index.d.ts index 851eab2c0b..d39dc0b875 100644 --- a/types/gapi.people/index.d.ts +++ b/types/gapi.people/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for Google People API 1.0 // Project: https://developers.google.com/people/ // Definitions by: Tanguy Krotoff +// Joshua O'Brien // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -13,7 +14,7 @@ declare namespace gapi.client.people { resourceName: string; // Query parameters - requestMask?: RequestMask; + personFields: string; } function get(parameters: GetParameters): HttpRequest; @@ -21,7 +22,7 @@ declare namespace gapi.client.people { interface GetBatchGetParameters { // Query parameters resourcesName?: string; - requestMask?: RequestMask; + personFields: string; } function getBatchGet(parameters: GetBatchGetParameters): HttpRequest; @@ -49,7 +50,7 @@ declare namespace gapi.client.people { pageSize?: number; sortOrder?: SortOrder; syncToken?: string; - requestMask?: RequestMask; + personFields: string; } interface Response { @@ -60,10 +61,6 @@ declare namespace gapi.client.people { } } - interface RequestMask { - includeField: string; - } - type SourceType = 'SOURCE_TYPE_UNSPECIFIED' | 'ACCOUNT' | 'PROFILE' | 'DOMAIN_PROFILE' | 'CONTACT'; interface Source { diff --git a/types/gapi/gapi-tests.ts b/types/gapi/gapi-tests.ts index 7c5308aaf9..0de37fdccb 100644 --- a/types/gapi/gapi-tests.ts +++ b/types/gapi/gapi-tests.ts @@ -20,7 +20,8 @@ https://developers.google.com/api-client-library/javascript/reference/referenced }).then(function() { // 3. Initialize and make the API request. return gapi.client.people.people.get({ - resourceName: 'people/me' + resourceName: 'people/me', + personFields: 'name' }); }).then(function(response) { console.log(response.result); diff --git a/types/gdal/gdal-tests.ts b/types/gdal/gdal-tests.ts new file mode 100644 index 0000000000..d30c83d571 --- /dev/null +++ b/types/gdal/gdal-tests.ts @@ -0,0 +1,78 @@ +import * as gdal from 'gdal'; + +// gdal.checksumImage(srcRasterBand, 0, 0, 512, 512); + +gdal.config.get('GDAL_DATA'); +gdal.config.set('GDAL_DATA', 'C:\\warmerda\\bld\\data'); + +/*gdal.contourGenerate({ + src: srcRasterBand, + dst: dstRasterBand +});*/ + +gdal.decToDMS(60, 'lat'); +gdal.decToDMS(60, 'lat', 2); + +/*gdal.fillNodata({ + +});*/ + +let creationOptionsArray: string[]; +creationOptionsArray = ['VRT_CREATION_OPTION=...']; +let creationOptionsObject: object; +creationOptionsObject = { + VRT_CREATION_OPTION: '...' +}; +gdal.open('C:\\datasets\\ogr.shp'); +gdal.open('C:\\datasets\\ogr.shp', 'r'); +gdal.open('C:\\datasets\\ogr.shp', 'r', 'ESRI Shapefile'); +gdal.open('C:\\datasets\\ogr.shp', 'r', ['ESRI Shapefile']); +gdal.open('C:\\datasets\\ogr.shp', 'r+'); +gdal.open('C:\\datasets\\ogr.shp', 'r+', 'ESRI Shapefile'); +gdal.open('C:\\datasets\\ogr.shp', 'r+', ['ESRI Shapefile']); +gdal.open('C:\\datasets\\raster.vrt', 'w', 'VRT'); +gdal.open('C:\\datasets\\raster.vrt', 'w', 'VRT', 512, 512, 3, 1, creationOptionsArray); +gdal.open('C:\\datasets\\raster.vrt', 'w', 'VRT', 512, 512, 3, 1, creationOptionsObject); +gdal.open('C:\\datasets\\raster.vrt', 'w', ['VRT']); +gdal.open('C:\\datasets\\raster.vrt', 'w', ['VRT'], 512, 512, 3, 1, creationOptionsArray); +gdal.open('C:\\datasets\\raster.vrt', 'w', ['VRT'], 512, 512, 3, 1, creationOptionsObject); + +/*let polygonizeOptions: gdal.PolygonizeOptions; +polygonizeOptions = { + src: srcRasterBand, + dst: dstRasterBand, + connectedness: 1, + mask: maskRasterBand, + pixValField: 1, + useFloats: true +}; +gdal.polygonize(polygonizeOptions); +gdal.polygonize({ + src: srcRasterBand, + dst: dstRasterBand, + pixValField: 1 +});*/ + +gdal.quiet(); + +/*let reprojectImageOptions: gdal.ReprojectImageOptions; +reprojectImageOptions = { + src: srcRasterBand, + dst: dstRasterBand, + s_srs: sourceSRS, + t_srs: targetSRS +}; +gdal.reprojectImage(reprojectImageOptions); +gdal.reprojectImage({ + +}); + +gdal.sieveFilter({ + +}); + +gdal.suggestedWarpOutput({ + +});*/ + +gdal.verbose(); diff --git a/types/gdal/index.d.ts b/types/gdal/index.d.ts new file mode 100644 index 0000000000..d6c76ba226 --- /dev/null +++ b/types/gdal/index.d.ts @@ -0,0 +1,707 @@ +// Type definitions for gdal 0.9 +// Project: https://github.com/naturalatlas/node-gdal#readme +// Definitions by: Andrei Digori +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +export as namespace gdal; + +/* Internal interfaces */ + +export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; +export type Resampling = 'NEAREST' | 'GAUSS' | 'CUBIC' | 'AVERAGE' | 'MODE' | 'AVERAGE_MAGPHASE' | 'NONE'; + +export interface XY { + x: number; + y: number; +} + +export interface XYZ extends XY { + z: number; +} + +export interface EnvelopeBounds { + minX: number; + maxX: number; + minY: number; + maxY: number; +} + +export interface Envelope3DBounds extends EnvelopeBounds { + minZ: number; + maxZ: number; +} + +export interface RasterBandStatistics { + min: number; + max: number; + mean: number; + std_dev: number; +} + +export interface RasterBandPixelsWriteOptions { + buffer_width?: number; + buffer_height?: number; + pixel_space?: number; + line_space?: number; +} + +export interface RasterBandPixelsReadOptions { + buffer_width?: number; + buffer_height?: number; + pixel_space?: number; + line_space?: number; + data_type?: string; +} + +export interface ContourGenerateOptions { + src: RasterBand; + dst: Layer; + offset?: number; + interval?: number; + fixedLevels?: number[]; + nodata?: number; + idField?: number; + elevField?: number; +} + +export interface FillNoDataOptions { + src: RasterBand; + mask?: RasterBand; + searchDist: number; + smoothingIterations?: number; +} + +export interface PolygonizeOptions { + src: RasterBand; + dst: Layer; + mask?: RasterBand; + pixValField: number; + connectedness?: number; + useFloats?: boolean; +} + +export interface ReprojectImageOptions { + src: Dataset; + dst: Dataset; + s_srs: SpatialReference; + t_srs: SpatialReference; + resampling?: string; + cutline?: Geometry; + srcBands?: number[]; + dstBands?: number[]; + srcAlphaBand?: number; + dstAlphaBand?: number; + srcNodata?: number; + dstNodata?: number; + memoryLimit?: number; + maxError?: number; + multi?: boolean; + options?: string[] | object; +} + +export interface SieveFilterOptions { + src: RasterBand; + dst: RasterBand; + mask?: RasterBand; + threshold: number; + connectedness?: number; +} + +export interface SuggestedWarpOutputOptions { + src: Dataset; + s_srs: SpatialReference; + t_srs: SpatialReference; + maxError?: number; +} + +/* From API: https://naturalatlas.github.io/node-gdal/ */ + +/* Constants */ + +// CPL Error Codes +export const CPLE_AppDefined: number; +export const CPLE_AssertionFailed: number; +export const CPLE_FileIO: number; +export const CPLE_IllegalArg: number; +export const CPLE_None: number; +export const CPLE_NotSupported: number; +export const CPLE_NoWriteAccess: number; +export const CPLE_ObjectNull: number; +export const CPLE_OpenFailed: number; +export const CPLE_OutOfMemory: number; +export const CPLE_UserInterrupt: number; + +// CPL Error Levels +export const CE_Debug: number; +export const CE_Failure: number; +export const CE_Fatal: number; +export const CE_None: number; +export const CE_Warning: number; + +// DCAP +export const DCAP_CREATE: string; +export const DCAP_CREATECOPY: string; +export const DCAP_VIRTUALIO: string; + +// DMD +export const DMD_CREATIONDATATYPES: string; +export const DMD_CREATIONOPTIONLIST: string; +export const DMD_EXTENSION: string; +export const DMD_HELPTOPIC: string; +export const DMD_LONGNAME: string; +export const DMD_MIMETYPE: string; + +// GCI +export const GCI_AlphaBand: string; +export const GCI_BlackBand: string; +export const GCI_BlueBand: string; +export const GCI_CyanBand: string; +export const GCI_GrayIndex: string; +export const GCI_GreenBand: string; +export const GCI_HueBand: string; +export const GCI_LightnessBand: string; +export const GCI_MagentaBand: string; +export const GCI_PaletteIndex: string; +export const GCI_RedBand: string; +export const GCI_SaturationBand: string; +export const GCI_Undefined: string; +export const GCI_YCbCr_CbBand: string; +export const GCI_YCbCr_CrBand: string; +export const GCI_YCbCr_YBand: string; +export const GCI_YellowBand: string; + +// GDT +export const GDT_Byte: string; +export const GDT_CFloat32: string; +export const GDT_CFloat64: string; +export const GDT_CInt16: string; +export const GDT_CInt32: string; +export const GDT_Float32: string; +export const GDT_Float64: string; +export const GDT_Int16: string; +export const GDT_Int32: string; +export const GDT_UInt16: string; +export const GDT_UInt32: string; +export const GDT_Unknown: string; + +// GRA +export const GRA_Average: string; +export const GRA_Bilinear: string; +export const GRA_Cubic: string; +export const GRA_CubicSpline: string; +export const GRA_Lanczos: string; +export const GRA_Mode: string; +export const GRA_NearestNeighbor: string; + +// ODsC +export const ODrCCreateDataSource: string; +export const ODrCDeleteDataSource: string; +export const ODsCCreateGeomFieldAfterCreateLayer: string; +export const ODsCCreateLayer: string; +export const ODsCDeleteLayer: string; + +// OFT +export const OFTBinary: string; +export const OFTDate: string; +export const OFTDateTime: string; +export const OFTInteger: string; +export const OFTIntegerList: string; +export const OFTReal: string; +export const OFTRealList: string; +export const OFTString: string; +export const OFTStringList: string; +export const OFTTime: string; +export const OFTWideString: string; +export const OFTWideStringList: string; + +// OJ +export const OJLeft: string; +export const OJRight: string; +export const OJUndefined: string; + +// OLC +export const OLCAlterFieldDefn: string; +export const OLCCreateField: string; +export const OLCCreateGeomField: string; +export const OLCDeleteFeature: string; +export const OLCDeleteField: string; +export const OLCFastFeatureCount: string; +export const OLCFastGetExtent: string; +export const OLCFastSetNextByIndex: string; +export const OLCFastSpatialFilter: string; +export const OLCIgnoreFields: string; +export const OLCRandomRead: string; +export const OLCRandomWrite: string; +export const OLCReorderFields: string; +export const OLCSequentialWrite: string; +export const OLCStringsAsUTF8: string; +export const OLCTransactions: string; + +// wkbByteOrder +export const wkbNDR: string; +export const wkbXDR: string; + +// wkbGeometryType +export const wkb25DBit: number; +export const wkbGeometryCollection: number; +export const wkbGeometryCollection25D: number; +export const wkbLinearRing: string; +export const wkbLinearRing25D: number; +export const wkbLineString: number; +export const wkbLineString25D: number; +export const wkbMultiLineString: number; +export const wkbMultiLineString25D: number; +export const wkbMultiPoint: number; +export const wkbMultiPoint25D: number; +export const wkbMultiPolygon: number; +export const wkbMultiPolygon25D: number; +export const wkbNone: number; +export const wkbPoint: number; +export const wkbPoint25D: number; +export const wkbPolygon: number; +export const wkbPolygon25D: number; +export const wkbUnknown: number; + +// wkbVariant +export const wkbVariantIso: string; +export const wkbVariantOgc: string; +export const wkbVariantOldOgc: string; + +/* Classes and interfaces */ + +export class CoordinateTransformation { + constructor(source: SpatialReference, target: SpatialReference | Dataset); + transformPoint(x: number, y: number, z?: number): XYZ; +} + +export interface Dataset { + buildOverviews(resampling: Resampling, overviews: number[], bands?: number[]): void; + close(): void; + executeSQL(statement: string, spatial_filter?: Geometry, dialect?: string): Layer; + flush(): void; + getFileList(): string[]; + getGCPProjection(): string; + getGCPs(): object[]; + getMetadata(domain?: string): object; + setGCPs(gcps: object[], projection: string): void; + testCapability(capability: string): boolean; + + readonly bands: DatasetBands; + readonly description: string; + readonly driver: Driver; + geoTransform: number[]; + readonly layers: DatasetLayers; + readonly rasterSize: XY; + srs: SpatialReference; +} + +export interface DatasetBands { + count(): number; + create(dataType: number): RasterBand; + forEach(callback: (band: RasterBand, i: number) => void): void; + get(id: number): RasterBand; + map(callback: (band: RasterBand, i: number) => T): T[]; + + readonly ds: Dataset; +} + +export interface DatasetLayers { + copy(src_lyr_name: string, dst_lyr_name: string, options?: object | string[]): Layer; + count(): number; + create(name: string, srs: SpatialReference, geomType: number | Geometry, creation_options: string[] | object): Layer; + forEach(callback: (layer: Layer, i: number) => void): void; + get(key: string | number): Layer; + map(callback: (layer: Layer, i: number) => T): T[]; + remove(index: number): void; + + readonly ds: Dataset; +} + +export interface Driver { + copyFiles(name_old: string, name_new: string): void; + create(filename: string, x_size?: number, y_size?: number, band_count?: number, data_type?: number, creation_options?: string[] | object): Dataset; + createCopy(filename: string, src: Dataset, strict?: boolean, options?: string[] | object): Dataset; + deleteDataset(filename: string): void; + getMetadata(domain?: string): object; + open(path: string, mode?: 'r' | 'r+'): Dataset; + rename(new_name: string, old_name: string): void; + + readonly description: string; +} + +export class Envelope { + constructor(bounds: EnvelopeBounds); + contains(envelope: Envelope): boolean; + intersect(envelope: Envelope): void; + intersects(envelope: Envelope): boolean; + isEmpty(): boolean; + merge(envelope: Envelope): void; + toPolygon(): Polygon; +} + +export class Envelope3D extends Envelope { + constructor(bounds: Envelope3DBounds); +} + +export class Feature { + constructor(definition: Layer | FeatureDefn); + clone(): Feature; + destroy(): void; + equals(feature: Feature): boolean; + getFieldDefn(index: number): FieldDefn; + getGeometry(): Geometry; + setFrom(feature: Feature, index_map?: number[], forgiving?: boolean): void; + setGeometry(geometry: Geometry): void; + + readonly defn: FeatureDefn; + fid: number; + readonly fields: FeatureFields; +} + +export class FeatureDefn { + constructor(); + clone(): FeatureDefn; + + readonly fields: FeatureDefnFields; + geomIgnored: boolean; + geomType: number; + readonly name: string; + styleIgnored: boolean; +} + +export interface FeatureDefnFields { + add(field: FieldDefn | FieldDefn[]): void; + count(): number; + forEach(callback: (field: FieldDefn, i: number) => void): void; + get(key: string | number): FieldDefn; + getNames(): string[]; + indexOf(name: string): number; + map(callback: (field: FieldDefn, i: number) => T): T[]; + remove(key: string | number): void; + reorder(map: number[]): void; + + readonly featureDefn: FeatureDefn; +} + +export interface FeatureFields { + count(): number; + forEach(callback: (value: any, key: string) => void): void; + get(key: string | number): any; + getNames(): string[]; + indexOf(name: string): number; + map(callback: (value: any, key: string) => T): T[]; + reset(values: object, value: any): void; + set(key: string | number, value: any): void; + toArray(): any[]; + toJSON(): string; + toObject(): object; + + readonly feature: Feature; +} + +export class FieldDefn { + constructor(name: string, type: string); + + ignored: boolean; + justification: string; + name: string; + precision: number; + type: string; + width: number; +} + +export interface GDALDrivers { + count(): number; + forEach(callback: (driver: Driver, i: number) => void): void; + get(index: number | string): Driver; + getNames(): string[]; + map(callback: (driver: Driver, i: number) => T): T[]; +} + +export abstract class Geometry { + static create(type: number): Geometry; + static fromWKB(wkb: number, srs?: SpatialReference): Geometry; + static fromWKT(wkt: string, srs?: SpatialReference): Geometry; + static getConstructor(type: number): Geometry; + static getName(type: number): string; + + boundary(): Geometry; + buffer(distance: number, segments: number): Geometry; + centroid(): Point; + clone(): Geometry; + closeRings(): void; + contains(geometry: Geometry): boolean; + convexHull(): Geometry; + crosses(geometry: Geometry): boolean; + difference(geometry: Geometry): Geometry; + disjoint(geometry: Geometry): boolean; + distance(geometry: Geometry): number; + empty(): void; + equals(geometry: Geometry): boolean; + getEnvelope(): Envelope; + getEnvelope3D(): Envelope3D; + intersection(geometry: Geometry): Geometry; + intersects(geometry: Geometry): boolean; + isEmpty(): boolean; + isRing(): boolean; + isSimple(): boolean; + isValid(): boolean; + overlaps(geometry: Geometry): boolean; + segmentize(segment_length: number): number; + simplify(tolerance: number): Geometry; + simplifyPreserveTopology(tolerance: number): Geometry; + swapXY(): void; + symDifference(geometry: Geometry): Geometry; + toGML(): Geometry; + toJSON(): Geometry; + toKML(): Geometry; + toObject(): object; + touches(geometry: Geometry): boolean; + toWKB(byte_order?: string, variant?: string): Geometry; + toWKT(): Geometry; + transform(transformation: CoordinateTransformation): void; + transformTo(srs: SpatialReference): void; + union(geometry: Geometry): Geometry; + within(geometry: Geometry): boolean; + + readonly coordinateDimension: number; + readonly dimension: number; + readonly name: string; + srs: SpatialReference; + readonly wkbSize: number; + readonly wkbType: number; +} + +export class GeometryCollection extends Geometry { + getArea(): number; + getLength(): number; + + children: GeometryCollectionChildren; +} + +export interface GeometryCollectionChildren { + add(geometry: Geometry | Geometry[]): void; + count(): number; + forEach(callback: (geometry: Geometry, i: number) => void): void; + get(index: number): Geometry; + map(callback: (geometry: Geometry, i: number) => T): T[]; + remove(index: number): void; + toArray(): Geometry[]; + readonly layer: Layer; +} + +export interface Layer { + flush(): void; + getExtent(force?: boolean): Envelope; + getSpatialFilter(): Geometry; + setAttributeFilter(filter: string): void; + setSpatialFilter(filter: Geometry): void; + setSpatialFilter(minX: number, maxX: number, minY: number, maxY: number): void; + testCapability(capability: string): boolean; + readonly ds: Dataset; + readonly features: LayerFeatures; + readonly fidColumn: string; + readonly fields: LayerFields; + readonly geomColumn: string; + readonly geomType: number; + readonly name: string; + readonly srs: SpatialReference; +} + +export interface LayerFeatures { + add(feature: Feature): void; + count(force?: boolean): number; + first(): Feature; + forEach(callback: (feature: Feature, i: number) => void): void; + get(id: number): Feature; + map(callback: (feature: Feature, i: number) => T): T[]; + next(): Feature; + remove(id: number): void; + set(id: number, feature: Feature): void; + readonly layer: Layer; +} + +export interface LayerFields { + add(def: FieldDefn | FieldDefn[], approx?: boolean): void; + count(): number; + forEach(callback: (field: FieldDefn, i: number) => void): void; + fromJSON(object: object, approx_ok?: boolean): LayerFields; + get(field: string | number): FieldDefn; + getNames(): string[]; + indexOf(field: string): number; + map(callback: (field: FieldDefn, i: number) => T): T[]; + remove(field: string | number): void; + reorder(map: number[]): void; + readonly layer: Layer; +} + +export class LinearRing extends LineString { + getArea(): number; +} + +export class LineString extends Geometry { + addSubLineString(line: LineString, start?: number, end?: number): void; + getLength(): number; + value(distance: number): Point; + readonly points: LineStringPoints; +} + +export interface LineStringPoints { + add(point: Point | Point[]): void; + count(): number; + forEach(callback: (point: Point, i: number) => void): void; + get(index: number): Point; + map(callback: (point: Point, i: number) => T): T[]; + remove(index: number): void; + resize(count: number): void; + reverse(): void; + set(index: number, point: Point): void; + toArray(): Point[]; +} + +export class MultiLineString extends GeometryCollection { + polygonize(): Polygon; +} + +export class MultiPoint extends GeometryCollection {} + +export class MultiPolygon extends GeometryCollection { + getArea(): number; + unionCascaded(): Geometry; +} + +export class Point extends Geometry { + constructor(x: number, y: number, z?: number); + x: number; + y: number; + z: number; +} + +export class Polygon extends Geometry { + getArea(): number; + rings: PolygonRings; +} + +export interface PolygonRings { + add(ring: LinearRing | LinearRing[]): void; + count(): number; + forEach(callback: (ring: LinearRing, i: number) => void): void; + get(index: number): LinearRing; + map(callback: (ring: LinearRing, i: number) => T): T[]; + remove(index: number): void; + toArray(): LinearRing[]; + readonly layer: Layer; +} + +export interface RasterBand { + computeStatistics(allow_approximation: boolean): RasterBandStatistics; + createMaskBand(flags: number): void; + fill(real_value: number, imaginary_value?: number): void; + flush(): void; + getMaskBand(): RasterBand; + getMaskFlags(): number; + getMetadata(domain?: string): object; + getStatistics(allow_approximation: boolean, force: boolean): RasterBandStatistics; + setStatistics(min: number, max: number, mean: number, std_dev: number): void; + readonly blockSize: XY; + categoryNames: string[]; + colorInterpretation: string; + readonly dataType: string; + readonly description: string; + readonly ds: Dataset; + readonly hasArbitraryOverviews: boolean; + readonly id: number; + readonly maximum: number; + readonly minimum: number; + noDataValue: number; + offset: number; + readonly overviews: RasterBandOverviews; + readonly pixels: RasterBandPixels; + readonly readOnly: boolean; + scale: number; + readonly size: XY; + unitType: string; +} + +export interface RasterBandOverviews { + count(): number; + forEach(callback: (overviewBand: RasterBand, i: number) => void): void; + get(index: number): RasterBand; + getBySampleCount(samples: number): RasterBand; + map(callback: (overviewBand: RasterBand, i: number) => T): T[]; +} + +export interface RasterBandPixels { + get(x: number, y: number): number; + read(x: number, y: number, width: number, height: number, data?: TypedArray, options?: RasterBandPixelsReadOptions): TypedArray; + readBlock(x: number, y: number, data?: TypedArray): TypedArray; + set(x: number, y: number, value: number): void; + write(x: number, y: number, width: number, height: number, data: TypedArray, options?: RasterBandPixelsWriteOptions): void; + writeBlock(x: number, y: number, data: TypedArray): void; +} + +export class SpatialReference { + constructor(wkt?: string); + autoIdentifyEPSG(): void; + clone(): SpatialReference; + cloneGeogCS(): SpatialReference; + EPSGTreatsAsLatLong(): boolean; + EPSGTreatsAsNorthingEasting(): boolean; + getAngularUnits(): { value: any, unit: any }; + getAttrValue(node_name: string, attr_index?: number): string; + getAuthorityCode(target_key: string): string; + getAuthorityName(target_key: string): string; + getLinearUnits(): { value: any, unit: any }; + isCompound(): boolean; + isGeocentric(): boolean; + isGeographic(): boolean; + isLocal(): boolean; + isProjected(): boolean; + isSame(srs: SpatialReference): boolean; + isSameGeogCS(srs: SpatialReference): boolean; + isSameVertCS(srs: SpatialReference): boolean; + isVertical(): boolean; + morphFromESRI(): void; + morphToESRI(): void; + setWellKnownGeogCS(name: string): void; + toPrettyWKT(simplify?: boolean): string; + toProj4(): string; + toWKT(): string; + toXML(): string; + validate(): string; + static fromCRSURL(input: string): SpatialReference; + static fromEPSG(input: string): SpatialReference; + static fromEPSGA(input: number): SpatialReference; + static fromESRI(input: string[]): SpatialReference; + static fromMICoordSys(input: string): SpatialReference; + static fromProj4(input: string): SpatialReference; + static fromURL(url: string): SpatialReference; + static fromURN(input: string): SpatialReference; + static fromUserInput(input: string): SpatialReference; + static fromWKT(wkt: string): SpatialReference; + static fromWMSAUTO(input: string): SpatialReference; + static fromXML(input: string): SpatialReference; +} + +export namespace config { + function get(key: string): string; + function set(key: string, value: string): void; +} + +export const drivers: GDALDrivers; +export const lastError: { number: any, message: any, type: any }; +export const version: string; + +export function checksumImage(src: RasterBand, x?: number, y?: number, w?: number, h?: number): number; +export function contourGenerate(options: ContourGenerateOptions): void; +export function decToDMS(angle: number, axis: 'lat' | 'long', precision?: number): string; +export function fillNodata(options: FillNoDataOptions): void; +export function open(path: string, mode?: 'r' | 'r+' | 'w', drivers?: string | string[]): Dataset; +export function open(path: string, mode?: 'w', drivers?: string | string[], x_size?: number, y_size?: number, band_count?: number, data_type?: number, creation_options?: string[] | object): Dataset; +export function polygonize(options: PolygonizeOptions): void; +export function quiet(): void; +export function reprojectImage(options: ReprojectImageOptions): void; +export function sieveFilter(options: SieveFilterOptions): void; +export function suggestedWarpOutput(options: SuggestedWarpOutputOptions): { rasterSize: any, geoTransform: any }; +export function verbose(): void; diff --git a/types/gdal/tsconfig.json b/types/gdal/tsconfig.json new file mode 100644 index 0000000000..5c11132a33 --- /dev/null +++ b/types/gdal/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gdal-tests.ts" + ] +} diff --git a/types/gdal/tslint.json b/types/gdal/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gdal/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ghauth/ghauth-tests.ts b/types/ghauth/ghauth-tests.ts new file mode 100644 index 0000000000..56bc0cd1b0 --- /dev/null +++ b/types/ghauth/ghauth-tests.ts @@ -0,0 +1,29 @@ +/// +import ghauth = require("ghauth"); +import { AuthOptions, TokenData } from "ghauth"; + +// Full +const authOptions1: AuthOptions = { + configName: "awesome", + noSave: true, + authUrl: "https://api.github.com/authorizations", + promptName: "GitHub", + scopes: ["user"], + note: "This token is for my awesome app", + userAgent: "My Awesome App", +}; + +ghauth(authOptions1, (err: Error, authData: TokenData) => { + authData.user; + authData.token; +}); + +// Required +const authOptions2: AuthOptions = { + configName: "awesome", +}; + +ghauth(authOptions2, (err: Error, authData: TokenData) => { + authData.user; + authData.token; +}); diff --git a/types/ghauth/index.d.ts b/types/ghauth/index.d.ts new file mode 100644 index 0000000000..3d91ab8ef5 --- /dev/null +++ b/types/ghauth/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for ghauth 3.2 +// Project: https://github.com/rvagg/ghauth +// Definitions by: Leko +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function ghauth(authOptions: ghauth.AuthOptions, callback: (err: Error, tokenData: ghauth.TokenData) => void): void; + +declare namespace ghauth { + interface AuthOptions { + configName: string; + + /** + * @default false + */ + noSave?: boolean; + + /** + * @default "https://api.github.com/authorizations" + */ + authUrl?: string; + + /** + * @default "GitHub" + */ + promptName?: string; + + /** + * @default [] + */ + scopes?: ReadonlyArray; + + /** + * @default "Node.js command-line app with ghauth" + */ + note?: string; + + /** + * @default "Magic Node.js application that does magic things with ghauth" + */ + userAgent?: string; + } + + interface TokenData { + user: string; + token: string; + } +} + +export = ghauth; diff --git a/types/ghauth/tsconfig.json b/types/ghauth/tsconfig.json new file mode 100644 index 0000000000..0b946b4ae8 --- /dev/null +++ b/types/ghauth/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ghauth-tests.ts" + ] +} diff --git a/types/ghauth/tslint.json b/types/ghauth/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ghauth/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/giraffe/index.d.ts b/types/giraffe/index.d.ts index 6b88b5d4b8..abce777c20 100644 --- a/types/giraffe/index.d.ts +++ b/types/giraffe/index.d.ts @@ -145,7 +145,19 @@ declare namespace Giraffe { namespace Contrib { - class Controller extends Backbone.Events implements GiraffeObject { + class Controller implements GiraffeObject, Backbone.Events { + on(eventName: string, callback?: (...args: any[]) => void, context?: any); + on(eventMap: Backbone.EventsHash); + on(eventName: any, callback?: any, context?: any) + off(eventName?: string, callback?: (...args: any[]) => void, context?: any) + trigger(eventName: string, ...args: any[]) + bind(eventName: string, callback: (...args: any[]) => void, context?: any) + unbind(eventName?: string, callback?: (...args: any[]) => void, context?: any) + once(events: string, callback: (...args: any[]) => void, context?: any): any; + listenTo(object: any, events: string, callback: (...args: any[]) => void): any; + listenToOnce(object: any, events: string, callback: (...args: any[]) => void): any; + stopListening(object?: any, events?: string, callback?: (...args: any[]) => void): any; + app: App; } diff --git a/types/gl-react-dom/GLViewDOM.d.ts b/types/gl-react-dom/GLViewDOM.d.ts new file mode 100644 index 0000000000..5ceef51ec8 --- /dev/null +++ b/types/gl-react-dom/GLViewDOM.d.ts @@ -0,0 +1,32 @@ +import * as React from 'react'; + +export type SupportedImage = 'image/png' | 'image/jpeg' | 'image/bmp' | 'image/webp' | 'image/ico'; +export type ValidQuality = 0.0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1.0; + +export interface GLViewDOMProps { + onContextCreate?: (gl: WebGLRenderingContext) => void; + onContextFailure?: (e: Error) => void; + onContextLost?: () => void; + onContextRestored?: (gl: WebGLRenderingContext) => void; + webglContextAttributes?: WebGLContextAttributes; + pixelRatio?: number; + width: number; + height: number; + style?: any; + debug?: number; +} + +export interface GLViewDOMState { + error: Error; +} + +export class GLViewDOM extends React.Component { + onRef: (ref: HTMLCanvasElement) => void; + debugError?: (error: Error) => void; + afterDraw?: () => void; + captureAsDataURL(type?: SupportedImage, quality?: ValidQuality): string; + captureAsBlob(callback: (data: Blob) => void, type?: SupportedImage, quality?: ValidQuality): Promise; + webglContextAttributes: WebGLContextAttributes; + canvas?: HTMLCanvasElement; + gl?: WebGLRenderingContext; +} diff --git a/types/gl-react-dom/gl-react-dom-tests.tsx b/types/gl-react-dom/gl-react-dom-tests.tsx new file mode 100644 index 0000000000..6d3852a156 --- /dev/null +++ b/types/gl-react-dom/gl-react-dom-tests.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Surface } from 'gl-react-dom'; +import { Shaders, GLSL, Node } from 'gl-react'; + +const shaders = Shaders.create({ + Test: { + frag: GLSL` + precision highp float; + varying vec2 uv; + void main() { + gl_FragColor = vec4(uv.x, uv.y, 0.5, 1.0); + }` + } +}); + +const App = () => ( +
+ + + +
+); + +const element = document.createElement('div'); +document.body.appendChild(element); +ReactDOM.render(, element); diff --git a/types/gl-react-dom/index.d.ts b/types/gl-react-dom/index.d.ts index 8d25b244ee..2f10c6439a 100644 --- a/types/gl-react-dom/index.d.ts +++ b/types/gl-react-dom/index.d.ts @@ -4,14 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as React from 'react'; import * as glReact from 'gl-react'; +import { GLViewDOM, GLViewDOMProps } from './GLViewDOM'; -export interface SurfaceProps extends glReact.SurfaceProps { - width: number; - height: number; -} +export interface SurfaceProps extends glReact.SurfaceProps, GLViewDOMProps {} -export class Surface extends glReact.Surface { +export class Surface extends glReact.Surface { props: SurfaceProps; } diff --git a/types/gl-react-dom/tsconfig.json b/types/gl-react-dom/tsconfig.json index 9c4d38ca44..49a1ee91ff 100644 --- a/types/gl-react-dom/tsconfig.json +++ b/types/gl-react-dom/tsconfig.json @@ -1,6 +1,7 @@ { "files": [ - "index.d.ts" + "index.d.ts", + "gl-react-dom-tests.tsx" ], "compilerOptions": { "module": "commonjs", diff --git a/types/gl-react-expo/GLViewNative.d.ts b/types/gl-react-expo/GLViewNative.d.ts new file mode 100644 index 0000000000..5320ccaaa2 --- /dev/null +++ b/types/gl-react-expo/GLViewNative.d.ts @@ -0,0 +1,17 @@ +import * as React from 'react'; +// Re-add this after fixing react-native types, and update it to ref's below +// import { GLView as EXGLView } from 'expo'; + +export interface GLViewNativeProps { + onContextCreate?: (gl: WebGLRenderingContext) => void; + style?: any; + children?: any; +} + +export class GLViewNative extends React.Component { + afterDraw?: () => void; + ref?: any; + onRef: (ref: any) => void; + onContextCreate: (gl: WebGLRenderingContext) => void; + capture(opt: any): Promise<{ uri: string, localUri: string, width: number, height: number }>; +} diff --git a/types/gl-react-expo/gl-react-expo-tests.tsx b/types/gl-react-expo/gl-react-expo-tests.tsx new file mode 100644 index 0000000000..2eb1fee9a9 --- /dev/null +++ b/types/gl-react-expo/gl-react-expo-tests.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Surface } from 'gl-react-expo'; +import { Shaders, GLSL, Node } from 'gl-react'; + +const shaders = Shaders.create({ + Test: { + frag: GLSL` + precision highp float; + varying vec2 uv; + void main() { + gl_FragColor = vec4(uv.x, uv.y, 0.5, 1.0); + }` + } +}); + +const App = () => ( +
+ + + +
+); + +const element = document.createElement('div'); +document.body.appendChild(element); +ReactDOM.render(, element); diff --git a/types/gl-react-expo/index.d.ts b/types/gl-react-expo/index.d.ts index 20a1e19928..d714aaf29e 100644 --- a/types/gl-react-expo/index.d.ts +++ b/types/gl-react-expo/index.d.ts @@ -4,5 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import { Surface } from 'gl-react'; -export { Surface }; +import * as glReact from 'gl-react'; +import { GLViewNative, GLViewNativeProps } from './GLViewNative'; + +export interface SurfaceProps extends glReact.SurfaceProps, GLViewNativeProps {} + +export class Surface extends glReact.Surface { + props: SurfaceProps; +} diff --git a/types/gl-react-expo/tsconfig.json b/types/gl-react-expo/tsconfig.json index 9c4d38ca44..95487128f4 100644 --- a/types/gl-react-expo/tsconfig.json +++ b/types/gl-react-expo/tsconfig.json @@ -1,6 +1,7 @@ { "files": [ - "index.d.ts" + "index.d.ts", + "gl-react-expo-tests.tsx" ], "compilerOptions": { "module": "commonjs", diff --git a/types/gl-react-headless/GLViewHeadless.d.ts b/types/gl-react-headless/GLViewHeadless.d.ts new file mode 100644 index 0000000000..9b90b25958 --- /dev/null +++ b/types/gl-react-headless/GLViewHeadless.d.ts @@ -0,0 +1,23 @@ +import * as React from 'react'; + +export interface GLViewHeadlessProps { + onContextCreate?: (gl: WebGLRenderingContext) => void; + onContextFailure?: (e: Error) => void; + onContextLost?: () => void; + onContextRestored?: (gl: WebGLRenderingContext) => void; + webglContextAttributes?: WebGLContextAttributes; + pixelRatio?: number; + width: number; + height: number; +} + +export class GLViewHeadless extends React.Component { + onRef: (ref: HTMLCanvasElement) => void; + captureAsDataURL(): string; + captureAsBlob(): Promise; + simulateContextLost(): void; + simulateContextRestored(): void; + webglContextAttributes: WebGLContextAttributes; + canvas?: HTMLCanvasElement; + gl?: WebGLRenderingContext; +} diff --git a/types/gl-react-headless/gl-react-headless-tests.tsx b/types/gl-react-headless/gl-react-headless-tests.tsx new file mode 100644 index 0000000000..58f0cbc13b --- /dev/null +++ b/types/gl-react-headless/gl-react-headless-tests.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Surface } from 'gl-react-headless'; +import { Shaders, GLSL, Node } from 'gl-react'; + +const shaders = Shaders.create({ + Test: { + frag: GLSL` + precision highp float; + varying vec2 uv; + void main() { + gl_FragColor = vec4(uv.x, uv.y, 0.5, 1.0); + }` + } +}); + +const App = () => ( +
+ + + +
+); + +const element = document.createElement('div'); +document.body.appendChild(element); +ReactDOM.render(, element); diff --git a/types/gl-react-headless/index.d.ts b/types/gl-react-headless/index.d.ts index a8b0ec5212..fe8b4648a1 100644 --- a/types/gl-react-headless/index.d.ts +++ b/types/gl-react-headless/index.d.ts @@ -4,14 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as React from 'react'; import * as glReact from 'gl-react'; +import { GLViewHeadless, GLViewHeadlessProps } from './GLViewHeadless'; -export interface SurfaceProps extends glReact.SurfaceProps { - width: number; - height: number; -} +export interface SurfaceProps extends glReact.SurfaceProps, GLViewHeadlessProps {} -export class Surface extends glReact.Surface { +export class Surface extends glReact.Surface { props: SurfaceProps; } diff --git a/types/gl-react-headless/tsconfig.json b/types/gl-react-headless/tsconfig.json index 9c4d38ca44..8a7f2a4b22 100644 --- a/types/gl-react-headless/tsconfig.json +++ b/types/gl-react-headless/tsconfig.json @@ -1,6 +1,7 @@ { "files": [ - "index.d.ts" + "index.d.ts", + "gl-react-headless-tests.tsx" ], "compilerOptions": { "module": "commonjs", diff --git a/types/gl-react-native/GLViewNative.d.ts b/types/gl-react-native/GLViewNative.d.ts new file mode 100644 index 0000000000..b4a4c75bc1 --- /dev/null +++ b/types/gl-react-native/GLViewNative.d.ts @@ -0,0 +1,12 @@ +import * as React from 'react'; + +export interface GLViewNativeProps { + onContextCreate?: (gl: WebGLRenderingContext) => void; + onContextFailure?: (e: Error) => void; + style?: any; + children?: any; +} + +export class GLViewNative extends React.Component { + afterDraw?: () => void; +} diff --git a/types/gl-react-native/gl-react-native-tests.tsx b/types/gl-react-native/gl-react-native-tests.tsx new file mode 100644 index 0000000000..f74c9dc926 --- /dev/null +++ b/types/gl-react-native/gl-react-native-tests.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Surface } from 'gl-react-native'; +import { Shaders, GLSL, Node } from 'gl-react'; + +const shaders = Shaders.create({ + Test: { + frag: GLSL` + precision highp float; + varying vec2 uv; + void main() { + gl_FragColor = vec4(uv.x, uv.y, 0.5, 1.0); + }` + } +}); + +const App = () => ( +
+ + + +
+); + +const element = document.createElement('div'); +document.body.appendChild(element); +ReactDOM.render(, element); diff --git a/types/gl-react-native/index.d.ts b/types/gl-react-native/index.d.ts index b9bce2a806..8f0c38a96d 100644 --- a/types/gl-react-native/index.d.ts +++ b/types/gl-react-native/index.d.ts @@ -4,5 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import { Surface } from 'gl-react'; -export { Surface }; +import * as glReact from 'gl-react'; +import { GLViewNative, GLViewNativeProps } from './GLViewNative'; + +export interface SurfaceProps extends glReact.SurfaceProps, GLViewNativeProps {} + +export class Surface extends glReact.Surface { + props: SurfaceProps; +} diff --git a/types/gl-react-native/tsconfig.json b/types/gl-react-native/tsconfig.json index 9c4d38ca44..0ffab2bab3 100644 --- a/types/gl-react-native/tsconfig.json +++ b/types/gl-react-native/tsconfig.json @@ -1,6 +1,7 @@ { "files": [ - "index.d.ts" + "index.d.ts", + "gl-react-native-tests.tsx" ], "compilerOptions": { "module": "commonjs", diff --git a/types/gl-react/index.d.ts b/types/gl-react/index.d.ts index e16b0d887c..84b82ddd2d 100644 --- a/types/gl-react/index.d.ts +++ b/types/gl-react/index.d.ts @@ -17,8 +17,8 @@ export interface BusProps { export class Bus extends React.Component { id: number; - context: { glParent: Surface | Node, glSurface: Surface }; - dependents: Array; + context: { glParent: Surface | Node, glSurface: Surface }; + dependents: Array>; glNode?: Node; glBusRootNode: any; @@ -43,11 +43,8 @@ export interface SurfaceProps { style?: any; preload?: any[]; visitor?: Visitor; - onLoad?: () => void; onLoadError?: (e: Error) => void; - onContextLost?: () => void; - onContextRestored?: () => void; } export interface SurfaceState { @@ -56,13 +53,14 @@ export interface SurfaceState { debug: boolean; } -export class Surface extends React.Component { - props: SurfaceProps; - state: SurfaceState; +export class Surface extends React.Component { id: number; - gl: WebGLRenderingContext; - RenderLessElement: any; + gl?: WebGLRenderingContext; + buffer: WebGLBuffer; + loaderResolver?: any; + glView: T; root: Node; + shaders: { [key: string]: any }; mapRenderableContent(inst: any): any; getVisitors(): Visitor[]; @@ -85,9 +83,9 @@ export type createSurface = ( mapRenderableContent: any, requestFrame: (callback: (time: number) => void) => number, cancelFrame: (id: number) => void -) => Surface; +) => Surface; -export type listSurfaces = () => Surface[]; +export type listSurfaces = () => Array>; export function GLSL(strings: TemplateStringsArray, ...values: any[]): string; @@ -108,8 +106,8 @@ export class NearestCopy extends React.Component { } export interface SurfaceContext { - glParent: Node | Surface | Bus; - glSurface: Surface; + glParent: Node | Surface | Bus; + glSurface: Surface; glSizable: { getGLSize: () => [number, number]; }; @@ -126,7 +124,7 @@ export interface Framebuffer { export interface NodeProps { shader: ShaderIdentifier | ShaderDefinition; uniformsOptions?: any; - uniforms: { [key: string]: any }; + uniforms?: { [key: string]: any }; ignoreUnusedUniforms?: string[] | boolean; sync?: boolean; width?: number; @@ -155,7 +153,7 @@ export class Node extends React.Component { [key: string]: Array; }; dependencies: Array; - dependents: Array; + dependents: Array>; } export interface ShaderIdentifier { @@ -193,13 +191,13 @@ export namespace Uniform { } export class Visitor { - onSurfaceMount(surface: Surface): void; - onSurfaceUnmount(surface: Surface): void; - onSurfaceGLContextChange(surface: Surface, gl?: WebGLRenderingContext): void; - onSurfaceDrawSkipped(surface: Surface): void; - onSurfaceDrawStart(surface: Surface): void; + onSurfaceMount(surface: Surface): void; + onSurfaceUnmount(surface: Surface): void; + onSurfaceGLContextChange(surface: Surface, gl?: WebGLRenderingContext): void; + onSurfaceDrawSkipped(surface: Surface): void; + onSurfaceDrawStart(surface: Surface): void; onSurfaceDrawError(e: Error): boolean; - onSurfaceDrawEnd(surface: Surface): void; + onSurfaceDrawEnd(surface: Surface): void; onNodeDrawSkipped(node: Node): void; onNodeDrawStart(node: Node): void; onNodeSyncDeps(node: Node, additions: Array, deletions: Array): void; diff --git a/types/google-apps-script/google-apps-script.slides.d.ts b/types/google-apps-script/google-apps-script.slides.d.ts index 90e034ff60..3d1aac9227 100644 --- a/types/google-apps-script/google-apps-script.slides.d.ts +++ b/types/google-apps-script/google-apps-script.slides.d.ts @@ -836,9 +836,11 @@ declare namespace GoogleAppsScript { getNotesMaster(): NotesMaster; getNotesPageHeight(): Number; getNotesPageWidth(): Number; + getPageElementById(id: string): PageElement; getPageHeight(): Number; getPageWidth(): Number; getSelection(): Selection; + getSlideById(id: string): Slide; getSlides(): Slide[]; getUrl(): string; getViewers(): Base.User[]; diff --git a/types/google-cloud__kms/google-cloud__kms-tests.ts b/types/google-cloud__kms/google-cloud__kms-tests.ts new file mode 100644 index 0000000000..96ab80c7c1 --- /dev/null +++ b/types/google-cloud__kms/google-cloud__kms-tests.ts @@ -0,0 +1,117 @@ +import kms = require('@google-cloud/kms'); + +let kmsClientV1: kms.v1.KeyManagementServiceClient; +kmsClientV1 = new kms.v1.KeyManagementServiceClient(); + +const credentials = { + type: 'service_account', + project_id: '****', + private_key_id: '****', + private_key: '****', + client_email: '****', + client_id: '****', + auth_uri: 'https://accounts.google.com/o/oauth2/auth', + token_uri: 'https://oauth2.googleapis.com/token', + auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs', + client_x509_cert_url: '****' +}; + +let kmsClient: kms.KeyManagementServiceClient; +kmsClient = new kms.KeyManagementServiceClient({ credentials }); + +async function exampleListKeyRings() { + const locationPath = kmsClient.locationPath('[PROJECT_ID]', '[LOCATION]'); + const [ asyncKeyRings ] = await kmsClient.listKeyRings({parent: locationPath}); + if (asyncKeyRings.length > 0) { + const keyRing = asyncKeyRings[ 0 ]; + console.log(`KeyRing: ${keyRing.name}`); + } + + kmsClient.listKeyRings({parent: locationPath}, (err, [ callbackKeyRings ]) => { + if (callbackKeyRings.length > 0) { + const keyRing = callbackKeyRings[ 0 ]; + console.log(`KeyRing: ${keyRing.name}`); + } + }); + + kmsClient.listKeyRings({parent: locationPath}, { timeout: 1000 }, (err, [ callbackWithOptionsKeyRings ]) => { + if (callbackWithOptionsKeyRings.length > 0) { + const keyRing = callbackWithOptionsKeyRings[ 0 ]; + console.log(`KeyRing: ${keyRing.name}`); + } + }); +} + +async function exampleListCryptoKeys() { + const keyRingPath = kmsClient.keyRingPath('[PROJECT_ID]', '[LOCATION]', '[KEYRING_ID]'); + const [ asyncKeys ] = await kmsClient.listCryptoKeys({parent: keyRingPath}); + if (asyncKeys.length > 0) { + const key = asyncKeys[ 0 ]; + console.log(`CryptoKey: ${key.name} Version: ${key.primary.name}`); + } + + kmsClient.listCryptoKeys({parent: keyRingPath}, (err, [ callbackKeys ]) => { + if (callbackKeys.length > 0) { + const key = callbackKeys[ 0 ]; + console.log(`CryptoKey: ${key.name} Version: ${key.primary.name}`); + } + }); + + kmsClient.listCryptoKeys({parent: keyRingPath}, { timeout: 1000 }, (err, [ callbackWithOptionsKeys ]) => { + if (callbackWithOptionsKeys.length > 0) { + const key = callbackWithOptionsKeys[ 0 ]; + console.log(`CryptoKey: ${key.name} Version: ${key.primary.name}`); + } + }); +} + +async function exampleEncrypt() { + const formattedName = kmsClient.cryptoKeyPath('[PROJECT_ID]', '[LOCATION]', '[KEYRING_ID]', '[KEY_ID]'); + const unencryptedText = new Buffer('Hello World'); + + const [ asyncEncryptResult ] = await kmsClient.encrypt({ name: formattedName, plaintext: unencryptedText.toString('base64') }); + if (asyncEncryptResult != null) { + console.log(`Encrypted: ${asyncEncryptResult.ciphertext.toString('base64')}`); + } + + kmsClient.encrypt({ name: formattedName, plaintext: unencryptedText.toString('base64') }, (err, [ callbackEncryptResult ]) => { + if (callbackEncryptResult != null) { + console.log(`Encrypted: ${callbackEncryptResult.ciphertext.toString('base64')}`); + } + }); + + kmsClient.encrypt({ name: formattedName, plaintext: unencryptedText.toString('base64') }, { timeout: 1000 }, (err, [ callbackWithOptionsEncryptResult ]) => { + if (callbackWithOptionsEncryptResult != null) { + console.log(`Encrypted: ${callbackWithOptionsEncryptResult.ciphertext.toString('base64')}`); + } + }); +} + +async function exampleDecrypt() { + // Example pulling a file from Cloud Storage + // const secretsStorage = new Storage({ credentials }); + // const bucket = secretsStorage.bucket('[KMS_STORAGE_BUCKET]'); + // const filePath = '[PATH_TO_KMS_ENCRYPTED_FILE'; + // const file = bucket.file(filePath); + // const buffers = await file.download(); + // const buffer = buffers[ 0 ]; + + const buffer = new Buffer('[ENCRYPTED_SOURCE_BUFFER]'); + const formattedName = kmsClient.cryptoKeyPath('[PROJECT_ID]', '[LOCATION]', '[KEYRING_ID]', '[KEY_ID]'); + const [ asyncDecryptResult ] = await kmsClient.decrypt({name: formattedName, ciphertext: buffer.toString('base64') }); + if (asyncDecryptResult != null) { + console.log(`Decrypted: ${asyncDecryptResult.plaintext}`); + } + + kmsClient.decrypt({ name: formattedName, ciphertext: buffer.toString('base64') }, (err, [ callbackDecryptResult ]) => { + if (callbackDecryptResult != null) { + console.log(`Decrypted: ${callbackDecryptResult.plaintext}`); + } + }); + + kmsClient.decrypt({ name: formattedName, ciphertext: buffer.toString('base64') }, (err, [ callbackWithOptionsDecryptResult ]) => { + if (callbackWithOptionsDecryptResult != null) { + console.log(`Decrypted: ${callbackWithOptionsDecryptResult.plaintext}`); + } + }); +} diff --git a/types/google-cloud__kms/index.d.ts b/types/google-cloud__kms/index.d.ts new file mode 100644 index 0000000000..237c7115a0 --- /dev/null +++ b/types/google-cloud__kms/index.d.ts @@ -0,0 +1,273 @@ +// Type definitions for @google-cloud/kms 0.2 +// Project: https://github.com/googleapis/nodejs-kms +// Definitions by: Ben Talbot +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import * as google_protobuf_timestamp_pb from "google-protobuf/google/protobuf/timestamp_pb"; + +export namespace v1 { + enum CryptoKeyVersionAlgorithm { + // Not specified. + CRYPTO_KEY_VERSION_ALGORITHM_UNSPECIFIED = 0, + + // Creates symmetric encryption keys. + GOOGLE_SYMMETRIC_ENCRYPTION = 1, + + // RSASSA-PSS 2048 bit key with a SHA256 digest. + RSA_SIGN_PSS_2048_SHA256 = 2, + + // RSASSA-PSS 3072 bit key with a SHA256 digest. + RSA_SIGN_PSS_3072_SHA256 = 3, + + // RSASSA-PSS 4096 bit key with a SHA256 digest. + RSA_SIGN_PSS_4096_SHA256 = 4, + + // RSASSA-PKCS1-v1_5 with a 2048 bit key and a SHA256 digest. + RSA_SIGN_PKCS1_2048_SHA256 = 5, + + // RSASSA-PKCS1-v1_5 with a 3072 bit key and a SHA256 digest. + RSA_SIGN_PKCS1_3072_SHA256 = 6, + + // RSASSA-PKCS1-v1_5 with a 4096 bit key and a SHA256 digest. + RSA_SIGN_PKCS1_4096_SHA256 = 7, + + // RSAES-OAEP 2048 bit key with a SHA256 digest. + RSA_DECRYPT_OAEP_2048_SHA256 = 8, + + // RSAES-OAEP 3072 bit key with a SHA256 digest. + RSA_DECRYPT_OAEP_3072_SHA256 = 9, + + // RSAES-OAEP 4096 bit key with a SHA256 digest. + RSA_DECRYPT_OAEP_4096_SHA256 = 10, + + // ECDSA on the NIST P-256 curve with a SHA256 digest. + EC_SIGN_P256_SHA256 = 12, + + // ECDSA on the NIST P-384 curve with a SHA384 digest. + EC_SIGN_P384_SHA384 = 13, + } + + enum CryptoKeyVersionState { + // Not specified. + CRYPTO_KEY_VERSION_STATE_UNSPECIFIED = 0, + + // This version is still being generated. It may not be used, enabled, + // disabled, or destroyed yet. Cloud KMS will automatically mark this + // version [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] as soon as the version is ready. + PENDING_GENERATION = 5, + + // This version may be used for cryptographic operations. + ENABLED = 1, + + // This version may not be used, but the key material is still available, + // and the version can be placed back into the [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] state. + DISABLED = 2, + + // This version is destroyed, and the key material is no longer stored. + // A version may not leave this state once entered. + DESTROYED = 3, + + // This version is scheduled for destruction, and will be destroyed soon. + // Call + // [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + // to put it back into the [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] state. + DESTROY_SCHEDULED = 4, + } + + enum CryptoKeyVersionView { + // Default view for each [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Does not include + // the [attestation][google.cloud.kms.v1.CryptoKeyVersion.attestation] field. + CRYPTO_KEY_VERSION_VIEW_UNSPECIFIED = 0, + + // Provides all fields in each [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], including the + // [attestation][google.cloud.kms.v1.CryptoKeyVersion.attestation]. + FULL = 1, + } + + enum ProtectionLevel { + // Not specified. + PROTECTION_LEVEL_UNSPECIFIED = 0, + + // Crypto operations are performed in software. + SOFTWARE = 1, + + // Crypto operations are performed in a Hardware Security Module. + HSM = 2, + } + + enum AttestationFormat { + ATTESTATION_FORMAT_UNSPECIFIED = 0, + + // Cavium HSM attestation compressed with gzip. Note that this format is + // defined by Cavium and subject to change at any time. + CAVIUM_V1_COMPRESSED = 3, + } + + interface KeyOperationAttestation { + format: AttestationFormat; + } + + interface CryptoKeyVersion { + name: string; + state: CryptoKeyVersionState; + protectionLevel: ProtectionLevel; + algorithm: CryptoKeyVersionAlgorithm; + attestation?: KeyOperationAttestation; + createTime: google_protobuf_timestamp_pb.Timestamp.AsObject; + generateTime: google_protobuf_timestamp_pb.Timestamp.AsObject; + destroyTime?: google_protobuf_timestamp_pb.Timestamp.AsObject; + destroyEventTime?: google_protobuf_timestamp_pb.Timestamp.AsObject; + } + + interface CryptoKeyVersionTemplate { + protectionLevel: ProtectionLevel; + algorithm: CryptoKeyVersionAlgorithm; + } + + enum CryptoKeyPurpose { + // Not specified. + CRYPTO_KEY_PURPOSE_UNSPECIFIED = 0, + + // [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this purpose may be used with + // [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] and + // [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + ENCRYPT_DECRYPT = 1, + + // [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this purpose may be used with + // [AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign] and + // [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + ASYMMETRIC_SIGN = 5, + + // [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this purpose may be used with + // [AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt] and + // [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + ASYMMETRIC_DECRYPT = 6, + } + + interface CryptoKey { + name: string; + primary: CryptoKeyVersion; + purpose: CryptoKeyPurpose; + createTime: google_protobuf_timestamp_pb.Timestamp.AsObject; + nextRotationTime?: google_protobuf_timestamp_pb.Timestamp.AsObject; + versionTemplate: CryptoKeyVersionTemplate; + labels: { [s: string]: string; }; + } + + interface KeyRing { + name: string; + createTime: google_protobuf_timestamp_pb.Timestamp.AsObject; + } + + namespace KeyManagementServiceClient { + interface ConfigurationObject { + credentials?: { + client_email?: string; + private_key?: string + }; + email?: string; + keyFilename?: string; + port?: number; + projectId?: string; + promise?: any; + servicePath?: string; + } + + interface EncryptRequest { + name: string; + plaintext: string; + additionalAuthenticatedData?: string; + } + interface EncryptResponse { + name: string; + ciphertext: Buffer; + } + type EncryptCallback = (err: Error | null, apiResponse: [EncryptResponse, any, any]) => void; + + interface DecryptRequest { + name: string; + ciphertext: string; + additionalAuthenticatedData?: string; + } + interface DecryptResponse { + plaintext: Buffer; + } + type DecryptCallback = (err: Error | null, apiResponse: [DecryptResponse, any, any]) => void; + + interface ListKeyRingsRequest { + parent: string; + page_size?: number; + page_token?: string; + } + type ListKeyRingsCallback = (err: Error | null, apiResponse: [KeyRing[], any, any]) => void; + + interface ListCryptoKeysRequest { + parent: string; + page_size?: number; + page_token?: string; + } + type ListCryptoKeysCallback = (err: Error | null, apiResponse: [CryptoKey[], any, any]) => void; + } + + class KeyManagementServiceClient { + constructor(options?: KeyManagementServiceClient.ConfigurationObject); + + keyRingPath(project: string, location: string, keyRing: string): string; + cryptoKeyPathPath(project: string, location: string, keyRing: string, cryptoKeyPath: string): string; + locationPath(project: string, location: string): string; + cryptoKeyPath(project: string, location: string, keyRing: string, cryptoKey: string): string; + cryptoKeyVersionPath(project: string, location: string, keyRing: string, cryptoKey: string, cryptoKeyVersion: string): string; + + encrypt(request: KeyManagementServiceClient.EncryptRequest, gaxOpts?: GAX.CallOptions): Promise<[KeyManagementServiceClient.EncryptResponse, any, any]>; + encrypt(request: KeyManagementServiceClient.EncryptRequest, callback: KeyManagementServiceClient.EncryptCallback): void; + encrypt(request: KeyManagementServiceClient.EncryptRequest, gaxOpts: GAX.CallOptions, callback: KeyManagementServiceClient.EncryptCallback): void; + + decrypt(request: KeyManagementServiceClient.DecryptRequest, gaxOpts?: GAX.CallOptions): Promise<[KeyManagementServiceClient.DecryptResponse, any, any]>; + decrypt(request: KeyManagementServiceClient.DecryptRequest, callback: KeyManagementServiceClient.DecryptCallback): void; + decrypt(request: KeyManagementServiceClient.DecryptRequest, gaxOpts: GAX.CallOptions, callback: KeyManagementServiceClient.DecryptCallback): void; + + listKeyRings(request: KeyManagementServiceClient.ListKeyRingsRequest, gaxOpts?: GAX.CallOptions): Promise<[KeyRing[], any, any]>; + listKeyRings(request: KeyManagementServiceClient.ListKeyRingsRequest, callback: KeyManagementServiceClient.ListKeyRingsCallback): void; + listKeyRings(request: KeyManagementServiceClient.ListKeyRingsRequest, gaxOpts: GAX.CallOptions, callback: KeyManagementServiceClient.ListKeyRingsCallback): void; + + listCryptoKeys(request: KeyManagementServiceClient.ListCryptoKeysRequest, gaxOpts?: GAX.CallOptions): Promise<[CryptoKey[], any, any]>; + listCryptoKeys(request: KeyManagementServiceClient.ListCryptoKeysRequest, callback: KeyManagementServiceClient.ListCryptoKeysCallback): void; + listCryptoKeys(request: KeyManagementServiceClient.ListCryptoKeysRequest, gaxOpts: GAX.CallOptions, callback: KeyManagementServiceClient.ListCryptoKeysCallback): void; + } +} + +export class KeyManagementServiceClient extends v1.KeyManagementServiceClient { + constructor(options?: v1.KeyManagementServiceClient.ConfigurationObject); +} + +export namespace GAX { + /** https://googleapis.github.io/gax-nodejs/global.html#CallOptions */ + interface CallOptions { + timeout?: number; + retry?: RetryOptions; + autoPaginate?: boolean; + pageToken?: object; + isBundling?: boolean; + longrunning?: BackoffSettings; + promise?: PromiseConstructor; // FIXME Unsure if this is the correct type; remove this comment if it is + } + + /** https://googleapis.github.io/gax-nodejs/global.html#RetryOptions */ + interface RetryOptions { + retryCodes: string[]; + backoffSettings: BackoffSettings; + } + + /** https://googleapis.github.io/gax-nodejs/global.html#BackoffSettings */ + interface BackoffSettings { + initialRetryDelayMillis: number; + retryDelayMultiplier: number; + maxRetryDelayMillis: number; + initialRpcTimeoutMillis: number; + maxRpcTimeoutMillis: number; + totalTimeoutMillis: number; + } +} diff --git a/types/google-cloud__storage/tsconfig.json b/types/google-cloud__kms/tsconfig.json similarity index 80% rename from types/google-cloud__storage/tsconfig.json rename to types/google-cloud__kms/tsconfig.json index fe05cce995..bb1ba097cc 100644 --- a/types/google-cloud__storage/tsconfig.json +++ b/types/google-cloud__kms/tsconfig.json @@ -14,8 +14,8 @@ ], "types": [], "paths": { - "@google-cloud/storage": [ - "google-cloud__storage" + "@google-cloud/kms": [ + "google-cloud__kms" ] }, "noEmit": true, @@ -23,6 +23,6 @@ }, "files": [ "index.d.ts", - "google-cloud__storage-tests.ts" + "google-cloud__kms-tests.ts" ] } \ No newline at end of file diff --git a/types/google-cloud__kms/tslint.json b/types/google-cloud__kms/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/google-cloud__kms/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/google-cloud__storage/google-cloud__storage-tests.ts b/types/google-cloud__storage/google-cloud__storage-tests.ts deleted file mode 100644 index 1db3e73284..0000000000 --- a/types/google-cloud__storage/google-cloud__storage-tests.ts +++ /dev/null @@ -1,592 +0,0 @@ -// import file system i/o api -import * as fs from "fs"; - -// import Google Cloud Storage -import { - Acl, - Bucket, - Channel, - File, - ApiResponse, - BucketConfig, - BucketFileOptions, - BucketGetOptions, - BucketMetadata, - BucketPrivacyOptions, - BucketQuery, - ChannelConfig, - DownloadOptions, - FileMetadata, - FilePrivateOptions, - ReadStreamOptions, - ResumableUploadOptions, - SignedPolicy, - SignedPolicyOptions, - SignedUrlConfig, - WriteStreamOptions, - UploadOptions -} from "@google-cloud/storage"; -import Storage = require("@google-cloud/storage"); - -/** - * Test the storage service. - */ -export class TestStorage { - // constants - static BUCKET_CONFIG: BucketConfig = { - multiRegional: true - }; - - // import Storage class - static gcs = new Storage(); - - constructor() { - // nothing to do - } - - /** Returns the bucket. */ - bucket(name: string): Bucket { - return TestStorage.gcs.bucket(name); - } - - /** Create a new bucket. */ - createBucket(name: string, config?: BucketConfig): Promise<[Bucket, ApiResponse]> { - // overwrite default values with custom config - config = Object.assign(TestStorage.BUCKET_CONFIG, config); - - return TestStorage.gcs.createBucket(name, config); - } - - /** - * Query for buckets. - */ - getBuckets(query?: BucketQuery): Promise<[Bucket[]]> { - return TestStorage.gcs.getBuckets(query); - } -} - -/** The bucket API wrapper. */ -export class TestBucket { - // the bucket in the cloud - bucket: Bucket; - - /** Create a bucket. */ - create(config?: BucketConfig): Promise<[Bucket, ApiResponse]> { - return this.bucket.create(config); - } - - /** Create a channel that will be notified when objects in this bucket changes. */ - createChannel(id: string, config: ChannelConfig): Promise<[Channel, ApiResponse]> { - return this.bucket.createChannel(id, config); - } - - /** Delete the bucket. */ - delete(): Promise<[ApiResponse]> { - return this.bucket.delete(); - } - - /** Iterate over the bucket's files, calling file.delete() on each. */ - deleteFiles(query?: BucketQuery): Promise { - return this.bucket.deleteFiles(query); - } - - /** Check if the bucket exists. */ - exists(): Promise<[boolean]> { - return this.bucket.exists(); - } - - /** Create a File object. */ - file(name: string, options?: BucketFileOptions): File { - return this.bucket.file(name); - } - - /** Get a bucket if it exists. */ - get(options?: BucketGetOptions): Promise<[Bucket, ApiResponse]> { - return this.bucket.get(options); - } - - /** Get File objects for the files currently in the bucket */ - getFiles(query?: BucketQuery): Promise<[File[]]> { - return this.bucket.getFiles(query); - } - - /** Get File objects for the files currently in the bucket as a readable object stream. */ - getFilesStream(query?: BucketQuery): fs.ReadStream { - return this.bucket.getFilesStream(query); - } - - /** Get the bucket's metadata. */ - getMetadata(): Promise<[BucketMetadata, ApiResponse]> { - return this.bucket.getMetadata(); - } - - /** Make the bucket listing private. */ - makePrivate(options?: BucketPrivacyOptions): Promise<[File[]]> { - return this.bucket.makePrivate(options); - } - - /** Make the bucket publicly readable. */ - makePublic(options?: BucketPrivacyOptions): Promise<[File[]]> { - return this.bucket.makePublic(options); - } - - /** Set the bucket's metadata. */ - setMetadata(metadata?: BucketMetadata): Promise<[ApiResponse]> { - return this.bucket.setMetadata(metadata); - } - - /** Upload a file. */ - upload(localPath: string, options?: UploadOptions): Promise<[File]> { - return this.bucket.upload(localPath, options); - } -} - -/** The file API wrapper. */ -export class TestFile { - // the file in the cloud - file: File; - - /** - * Copy this file to another file. - * By default, this will copy the file to the same bucket, but you can choose to copy it to another - * Bucket by providing a Bucket or File object or a URL starting with "gs:// ". - */ - copy(destination: string | Bucket | File): Promise<[File, ApiResponse]> { - return this.file.copy(destination); - } - - /** Create a unique resumable upload session URI. This is the first step when performing a resumable upload. */ - createResumableUpload(options?: ResumableUploadOptions): Promise<[string]> { - return this.file.createResumableUpload(options); - } - - /** - * Create a readable stream to read the contents of the remote file. - * It can be piped to a writable stream or listened to for 'data' events to read a file's contents. - */ - createReadStream(options?: ReadStreamOptions): fs.ReadStream { - return this.file.createReadStream(options); - } - - /** Create a writable stream to overwrite the contents of the file in your bucket. */ - createWriteStream(options?: WriteStreamOptions): fs.WriteStream { - return this.file.createWriteStream(options); - } - - /** Delete the file. */ - delete(): Promise<[ApiResponse]> { - return this.file.delete(); - } - - /** Convenience method to download a file into memory or to a local destination. */ - download(options?: DownloadOptions): Promise<[Buffer]> { - return this.file.download(options); - } - - /** Check if the file exists. */ - exists(): Promise<[boolean]> { - return this.file.exists(); - } - - /** Get a file object and its metadata if it exists. */ - get(): Promise<[File, ApiResponse]> { - return this.file.get(); - } - - /** Get the file's metadata. */ - getMetadata(): Promise<[FileMetadata, ApiResponse]> { - return this.file.getMetadata(); - } - - /** Get a signed policy document to allow a user to upload data with a POST request */ - getSignedPolicy(options?: SignedPolicyOptions): Promise<[SignedPolicy]> { - return this.file.getSignedPolicy(options); - } - - /** Get a signed URL to allow limited time access to the file */ - getSignedUrl(config: SignedUrlConfig): Promise<[string]> { - return this.file.getSignedUrl(config); - } - - /** Make a file private to the project and remove all other permissions. */ - makePrivate(options?: FilePrivateOptions): Promise<[ApiResponse]> { - return this.file.makePrivate(options); - } - - /** Set a file to be publicly readable and maintain all previous permissions. */ - makePublic(): Promise<[ApiResponse]> { - return this.file.makePublic(); - } - - /** - * Move this file to another location. - * By default, this will move the file to the same bucket, but you can choose to move it to - * another Bucket by providing a Bucket or File object or a URL beginning with "gs:// ". - */ - move(destination: string | Bucket | File): Promise<[File, ApiResponse]> { - return this.file.move(destination); - } - - /** Write arbitrary data to a file. */ - save(data: string, options?: WriteStreamOptions): Promise { - return this.file.save(data); - } - - /** The Storage API allows you to use a custom key for server-side encryption. */ - setEncryptionKey(encryptionKey: string | Buffer): File { - return this.file.setEncryptionKey(encryptionKey); - } - - /** - * Merge the given metadata with the current remote file's metadata. - * This will set metadata if it was previously unset or update previously set metadata. - * To unset previously set metadata, set its value to null. - */ - setMetadata(metadata: FileMetadata): Promise<[ApiResponse]> { - return this.file.setMetadata(metadata); - } -} - -const testStorage = new TestStorage().bucket("examplebucketname"); - -testStorage.iam.getPolicy(); - -testStorage.iam.setPolicy({ - bindings: [ - { - role: "roles/storage.admin", - members: ['serviceAccount:myotherproject@appspot.gserviceaccount.com'] - } - ] - }); - -testStorage.iam.testPermissions('storage.buckets.delete'); - -testStorage.iam.testPermissions(['storage.buckets.delete', 'storage.buckets.get']); - -// Example from https://cloud.google.com/storage/docs/creating-buckets#storage-create-bucket-code_samples -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - - // Creates a new bucket - storage - .createBucket(bucketName, { - location: 'ASIA', - storageClass: 'COLDLINE', - }) - .then(() => { - console.log(`Bucket ${bucketName} created.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/listing-buckets#storage-list-buckets-nodejs -{ - // Creates a client - const storage = new Storage(); - - // Lists all buckets in the current project - storage - .getBuckets() - .then(results => { - const buckets = results[0]; - - console.log('Buckets:'); - buckets.forEach(bucket => { - console.log(bucket.name); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/moving-buckets#storage-create-bucket-nodejs -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - - // Creates a new bucket - storage - .createBucket(bucketName, { - location: 'ASIA', - storageClass: 'COLDLINE', - }) - .then(() => { - console.log(`Bucket ${bucketName} created.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/deleting-buckets -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - - // Deletes the bucket - storage - .bucket(bucketName) - .delete() - .then(() => { - console.log(`Bucket ${bucketName} deleted.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/uploading-objects -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - const filename = 'Local file to upload, e.g. ./local/path/to/file.txt'; - - // Uploads a local file to the bucket - storage - .bucket(bucketName) - .upload(filename, { - // Support for HTTP requests made with `Accept-Encoding: gzip` - gzip: true, - metadata: { - // Enable long-lived HTTP caching headers - // Use only if the contents of the file will never change - // (If the contents will change, use cacheControl: 'no-cache') - cacheControl: 'public, max-age=31536000', - }, - }) - .then(() => { - console.log(`${filename} uploaded to ${bucketName}.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/listing-objects -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - - // Lists files in the bucket - storage - .bucket(bucketName) - .getFiles() - .then(results => { - const files = results[0]; - - console.log('Files:'); - files.forEach(file => { - console.log(file.name); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/listing-objects -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - const prefix = 'Prefix by which to filter, e.g. public/'; - const delimiter = 'Delimiter to use, e.g. /'; - - /** - * This can be used to list all blobs in a "folder", e.g. "public/". - * - * The delimiter argument can be used to restrict the results to only the - * "files" in the given "folder". Without the delimiter, the entire tree under - * the prefix is returned. For example, given these blobs: - * - * /a/1.txt - * /a/b/2.txt - * - * If you just specify prefix = '/a', you'll get back: - * - * /a/1.txt - * /a/b/2.txt - * - * However, if you specify prefix='/a' and delimiter='/', you'll get back: - * - * /a/1.txt - */ - const options = { - prefix, - delimiter - }; - - // Lists files in the bucket, filtered by a prefix - storage - .bucket(bucketName) - .getFiles(options) - .then(results => { - const files = results[0]; - - console.log('Files:'); - files.forEach(file => { - console.log(file.name); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/downloading-objects#storage-download-object-nodejs -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - const srcFilename = 'Remote file to download, e.g. file.txt'; - const destFilename = 'Local destination for file, e.g. ./local/path/to/file.txt'; - - const options = { - // The path to which the file should be downloaded, e.g. "./file.txt" - destination: destFilename, - }; - - // Downloads the file - storage - .bucket(bucketName) - .file(srcFilename) - .download(options) - .then(() => { - console.log( - `gs://${bucketName}/${srcFilename} downloaded to ${destFilename}.` - ); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/renaming-copying-moving-objects -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - const srcFilename = 'File to move, e.g. file.txt'; - const destFilename = 'Destination for file, e.g. moved.txt'; - - // Moves the file within the bucket - storage - .bucket(bucketName) - .file(srcFilename) - .move(destFilename) - .then(() => { - console.log( - `gs://${bucketName}/${srcFilename} moved to gs://${bucketName}/${destFilename}.` - ); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/renaming-copying-moving-objects -{ - // Creates a client - const storage = new Storage(); - - const srcBucketName = 'Name of the source bucket, e.g. my-bucket'; - const srcFilename = 'Name of the source file, e.g. file.txt'; - const destBucketName = 'Name of the destination bucket, e.g. my-other-bucket'; - const destFilename = 'Destination name of file, e.g. file.txt'; - - // Copies the file to the other bucket - storage - .bucket(srcBucketName) - .file(srcFilename) - .copy(storage.bucket(destBucketName).file(destFilename)) - .then(() => { - console.log( - `gs://${srcBucketName}/${srcFilename} copied to gs://${destBucketName}/${destFilename}.` - ); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/viewing-editing-metadata -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - const filename = 'File to access, e.g. file.txt'; - - // Gets the metadata for the file - storage - .bucket(bucketName) - .file(filename) - .getMetadata() - .then(results => { - const metadata = results[0]; - - console.log(`File: ${metadata.name}`); - console.log(`Bucket: ${metadata.bucket}`); - console.log(`Storage class: ${metadata.storageClass}`); - console.log(`Self link: ${metadata.selfLink}`); - console.log(`ID: ${metadata.id}`); - console.log(`Size: ${metadata.size}`); - console.log(`Updated: ${metadata.updated}`); - console.log(`Generation: ${metadata.generation}`); - console.log(`Metageneration: ${metadata.metageneration}`); - console.log(`Etag: ${metadata.etag}`); - console.log(`Owner: ${metadata.owner}`); - console.log(`Component count: ${metadata.component_count}`); - console.log(`Crc32c: ${metadata.crc32c}`); - console.log(`md5Hash: ${metadata.md5Hash}`); - console.log(`Cache-control: ${metadata.cacheControl}`); - console.log(`Content-type: ${metadata.contentType}`); - console.log(`Content-disposition: ${metadata.contentDisposition}`); - console.log(`Content-encoding: ${metadata.contentEncoding}`); - console.log(`Content-language: ${metadata.contentLanguage}`); - console.log(`Metadata: ${metadata.metadata}`); - console.log(`Media link: ${metadata.mediaLink}`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/deleting-objects -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - const filename = 'File to delete, e.g. file.txt'; - - // Deletes the file from the bucket - storage - .bucket(bucketName) - .file(filename) - .delete() - .then(() => { - console.log(`gs://${bucketName}/${filename} deleted.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} diff --git a/types/google-cloud__storage/index.d.ts b/types/google-cloud__storage/index.d.ts deleted file mode 100644 index 2053abcc62..0000000000 --- a/types/google-cloud__storage/index.d.ts +++ /dev/null @@ -1,469 +0,0 @@ -// Type definitions for @google-cloud/storage 1.7 -// Project: https://github.com/googleapis/nodejs-storage -// Definitions by: Brian Love -// Nathan Brooker Perry -// Matt Welke -// Futa Ogawa -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -/// - -import { ReadStream, WriteStream } from "fs"; -import { CoreOptions } from "request"; - -type PromiseLibrary = () => PromiseLike; - -declare namespace Storage { - /** - * A bucket in the cloud. - */ - class Bucket { - constructor(storage: Storage, name: string); - acl: Acl; - combine(sources: string[] | File[], destination: string | File): Promise<[File, ApiResponse]>; - create(config?: BucketConfig): Promise<[Bucket, ApiResponse]>; - createChannel(id: string, config: ChannelConfig): Promise<[Channel, ApiResponse]>; - delete(): Promise<[ApiResponse]>; - deleteFiles(query?: BucketQuery): Promise; - exists(): Promise<[boolean]>; - file(name: string, options?: BucketFileOptions): File; - get(options?: BucketGetOptions): Promise<[Bucket, ApiResponse]>; - getFiles(query?: BucketQuery): Promise<[File[]]>; - getFilesStream(query?: BucketQuery): ReadStream; - getMetadata(): Promise<[BucketMetadata, ApiResponse]>; - id: string; - iam: Iam; - makePrivate(options?: BucketPrivacyOptions): Promise<[File[]]>; - makePublic(options?: BucketPrivacyOptions): Promise<[File[]]>; - metadata: BucketMetadata; - name: string; - setMetadata(metadata?: BucketMetadata): Promise<[ApiResponse]>; - upload(localPath: string, options?: UploadOptions): Promise<[File]>; - } - - /** - * Bucket configuration. - */ - interface BucketConfig { - coldline?: boolean; - dra?: boolean; - location?: string; - multiRegional?: boolean; - nearline?: boolean; - regional?: boolean; - versioning?: { - enabled?: boolean - }; - // Note: This is not documented, but it is used in examples (https://cloud.google.com/nodejs/docs/reference/storage/1.7.x/Storage) - storageClass?: 'COLDLINE' | 'DURABLE_REDUCED_AVAILABILITY' | 'MULTI_REGIONAL' | 'NEARLINE' | 'REGIONAL'; - } - - /** - * Options for getting a file. - */ - interface BucketFileOptions { - generation?: string | number; - } - - /** - * Options for getting a bucket. - */ - interface BucketGetOptions { - autoCreate?: boolean; - } - - /** - * Bucket metadata. - */ - interface BucketMetadata { - etag?: string; - id?: string; - kind?: string; - location?: string; - metageneration?: string; - name?: string; - projectNumber?: string; - selfLink?: string; - storageClass?: string; - timeCreated?: string; - updated?: string; - } - - /** - * The options for making the bucket private. - */ - interface BucketPrivacyOptions { - includeFiles?: boolean; - force?: boolean; - } - - /** - * Query a bucket. - */ - interface BucketQuery { - autoPaginate?: boolean; - delimiter?: string; - directory?: string; - prefix?: string; - maxApiCalls?: number; - maxResults?: number; - pageToken?: string; - userProject?: string; - versions?: boolean; - } - - /** - * Options for specifying the content length range. - */ - interface ContentLengthRange { - max?: number; - min?: number; - } - - /** - * A file in the cloud. - */ - class File { - constructor(bucket: Bucket, name: string, options?: BucketFileOptions); - acl: Acl; - copy(destination: string | Bucket | File): Promise<[File, ApiResponse]>; - createReadStream(options?: ReadStreamOptions): ReadStream; - createResumableUpload(options?: ResumableUploadOptions): Promise<[string]>; - createWriteStream(options?: WriteStreamOptions): WriteStream; - delete(): Promise<[ApiResponse]>; - download(options?: DownloadOptions): Promise<[Buffer]>; - exists(): Promise<[boolean]>; - get(): Promise<[File, ApiResponse]>; - getMetadata(): Promise<[FileMetadata, ApiResponse]>; - getSignedPolicy(options?: SignedPolicyOptions): Promise<[SignedPolicy]>; - getSignedUrl(config: SignedUrlConfig): Promise<[string]>; - makePrivate(options?: FilePrivateOptions): Promise<[ApiResponse]>; - makePublic(): Promise<[ApiResponse]>; - move(destination: string | Bucket | File): Promise<[File, ApiResponse]>; - name: string; - save(data: string | Buffer, options?: WriteStreamOptions): Promise; - setEncryptionKey(encryptionKey: string | Buffer): File; - setMetadata(metadata: FileMetadata): Promise<[ApiResponse]>; - metadata?: FileMetadata; - } - - /** - * Access controls on the object, containing one or more objectAccessControls Resources. - */ - interface AclFileMetadata { - bucket?: string; - domain?: string; - email?: string; - entity?: string; - entityId?: string; - etag?: string; - generation?: number; - id?: string; - kind?: string; - object?: string; - projectTeam?: ProjectTeam; - role?: string; - selfLink?: string; - } - - /** - * The project team associated with the entity, if any. - */ - interface ProjectTeam { - projectNumber?: string; - team?: string; - } - - /** - * Metadata of customer-supplied encryption key, if the object is encrypted by such a key. - */ - interface CustomerEncryption { - encryptionAlgorithm?: string; - keySha256?: string; - } - - /** - * User-defined metadata. - */ - interface CustomFileMetadata { - [key: string]: string; - } - - /** - * The owner of the object. This will always be the uploader of the object. - */ - interface Owner { - entity?: string; - entityId?: string; - } - - /** - * File metadata. - */ - interface FileMetadata { - acl?: AclFileMetadata[]; - bucket?: string; - cacheControl?: string; - componentCount?: number; - // Note: this property is accessed in one of the examples - component_count?: number; - contentDisposition?: string; - contentEncoding?: string; - contentLanguage?: string; - contentType?: string; - crc32c?: string; - customerEncryption?: CustomerEncryption; - etag?: string; - generation?: number; - id?: string; - kind?: string; - kmsKeyName?: string; - md5Hash?: string; - mediaLink?: string; - metadata?: CustomFileMetadata; - metageneration?: number; - name?: string; - owner?: Owner; - selfLink?: string; - size?: null | number; - storageClass?: string; - timeCreated?: string; - timeDeleted?: string; - timeStorageClassUpdated?: string; - updated?: string; - } - - /** - * Options when setting the file as private. - */ - interface FilePrivateOptions { - strict?: boolean; - } - - /** - * A signed policy allowing a user to upload a file with a POST. - */ - interface SignedPolicy { - base64?: string; - signature?: string; - string?: string; - } - - /** - * Options when obtaining the signed policy. - */ - interface SignedPolicyOptions { - acl?: string; - contentLengthRange?: ContentLengthRange; - equals?: string[] | [string[]]; - expires?: number | string; - max?: number; - min?: number; - startsWith?: string[] | [string[]]; - successRedirect?: string; - successStatus?: string; - } - - /** - * Options when obtaining a temporary signed URL for a file. - */ - interface SignedUrlConfig { - action: string; - cname?: string; - contentMd5?: string; - contentType?: string; - expires: any; - extensionHeaders?: { [key: string]: string }; - promptSaveAs?: string; - responseDisposition?: string; - responseType?: string; - } - - /** - * Options when obtaining a resumable upload URI. - */ - interface ResumableUploadOptions { - metadata?: FileMetadata; - origin?: string; - predefinedAcl?: string; - private?: boolean; - public?: boolean; - } - - /** - * Access control list for storage buckets and files. - */ - interface Acl extends AclActions { - default: AclEntity; - owners: AclEntity; - readers: AclEntity; - writers: AclEntity; - } - - /** - * Actions that can be performed on all ACL entities, including the root Acl. - */ - interface AclActions { - add(options: AclOptions): Promise<[Acl, ApiResponse]>; - delete(options: AclOptions): Promise<[Acl, ApiResponse]>; - get(options: AclOptions): Promise<[Acl, ApiResponse]>; - update(options: AclOptions): Promise<[Acl, ApiResponse]>; - } - - /** - * An object of convenience methods to add or delete reader ACL permissions for a given entity. - */ - interface AclEntity extends AclActions { - addAllAuthenticatedUsers(): Promise<[Acl, ApiResponse]>; - addAllUsers(): Promise<[Acl, ApiResponse]>; - addDomain(entity: string): Promise<[Acl, ApiResponse]>; - addGroup(entity: string): Promise<[Acl, ApiResponse]>; - addProject(entity: string): Promise<[Acl, ApiResponse]>; - addUser(entity: string): Promise<[Acl, ApiResponse]>; - deleteAllAuthenticatedUsers(): Promise<[Acl, ApiResponse]>; - deleteAllUsers(): Promise<[Acl, ApiResponse]>; - deleteDomain(entity: string): Promise<[Acl, ApiResponse]>; - deleteGroup(entity: string): Promise<[Acl, ApiResponse]>; - deleteProject(entity: string): Promise<[Acl, ApiResponse]>; - deleteUser(entity: string): Promise<[Acl, ApiResponse]>; - } - - /** - * ACL options. - */ - interface AclOptions { - entity?: string; - role?: string; - generation?: number; - } - - /** - * The response object. - */ - interface ApiResponse { - etag?: string; - id?: string; - kind?: string; - location?: string; - metageneration?: string; - name?: string; - projectNumber?: string; - selfLink?: string; - storageClass?: string; - timeCreated?: string; - updated?: string; - } - - interface Credentials { - client_email?: string; - private_key?: string; - } - - interface ConfigurationObject { - autoRetry?: boolean; - credentials?: Credentials; - email?: string; - keyFilename?: string; - maxRetries?: number; - projectId?: string; - promise?: PromiseLibrary; - } - - /** - * The options when downloading a file. - */ - interface DownloadOptions extends ReadStreamOptions { - destination?: string; - } - - /** - * Options when reading a file stream. - */ - interface ReadStreamOptions { - end?: number; - start?: number; - validation?: string | boolean; - } - - /** - * Options when uploading file to bucket. - */ - interface UploadOptions extends WriteStreamOptions { - destination?: string | File; - encryptionKey?: string; - kmsKeyName?: string; - requestOptions?: CoreOptions; - } - - /** - * Options when writing to a file stream. - */ - interface WriteStreamOptions { - contentType?: string; - gzip?: string | boolean; - metadata?: FileMetadata; - offset?: string; - predefinedAcl?: string; - private?: boolean; - public?: boolean; - resumable?: boolean; - uri?: string; - userProject?: string; - validation?: string | boolean; - } - - /** - * This class allows you interact with Google Cloud Storage. - */ - class Channel { - constructor(storage: Storage, id: string, resourceId: string); - stop(): Promise<[ApiResponse]>; - } - - /** - * Channel configuration. - */ - interface ChannelConfig { - address: string; - } - - /** - * This class allows you to get Identity Access Management information. - */ - class Iam { - getPolicy(): Promise; - setPolicy(policy: IamPolicy): Promise<[IamPolicy, ApiResponse]>; - testPermissions(permission: string | string[]): Promise<[{[key: string]: boolean}, ApiResponse]>; - } - - /** - * IAM policy - */ - interface IamPolicy { - bindings: IamBinding[]; - } - - interface IamBinding { - role: string; - members: string[]; - } -} - -/** - * The Storage class allows you interact with Google Cloud Storage. - */ -declare class Storage { - constructor(config?: Storage.ConfigurationObject); - acl: Storage.Acl; - bucket(name: string | Storage.Bucket): Storage.Bucket; - channel(id: string, resourceId: string): Storage.Channel; - createBucket(name: string, metadata?: Storage.BucketConfig): Promise<[Storage.Bucket, Storage.ApiResponse]>; - getBuckets(query?: Storage.BucketQuery): Promise<[Storage.Bucket[]]>; - getBucketsStream(query?: Storage.BucketQuery): Promise<[ReadStream]>; - Channel: (storage: Storage, id: string, resourceId: string) => Storage.Channel; - File: (bucket: Storage.Bucket, name: string, opts: Storage.BucketFileOptions) => Storage.File; - Bucket: (storage: Storage, name: string) => Storage.Bucket; -} - -export = Storage; diff --git a/types/google-cloud__storage/tslint.json b/types/google-cloud__storage/tslint.json deleted file mode 100644 index b3dfb39122..0000000000 --- a/types/google-cloud__storage/tslint.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - // TODOs - "no-duplicate-imports": false, - "prefer-object-spread": false - } -} diff --git a/types/google-map-react/index.d.ts b/types/google-map-react/index.d.ts index a917ae426e..56686c94c1 100644 --- a/types/google-map-react/index.d.ts +++ b/types/google-map-react/index.d.ts @@ -131,6 +131,9 @@ export interface Props { onChildClick?(hoverKey: any, childProps: any): void; onChildMouseEnter?(hoverKey: any, childProps: any): void; onChildMouseLeave?(hoverKey: any, childProps: any): void; + onChildMouseDown?(childKey: any, childProps: any, mouse: any): void; + onChildMouseUp?(childKey: any, childProps: any, mouse: any): void; + onChildMouseMove?(childKey: any, childProps: any, mouse: any): void; onDrag?(args: any): void; onZoomAnimationStart?(args: any): void; onZoomAnimationEnd?(args: any): void; diff --git a/types/google.visualization/index.d.ts b/types/google.visualization/index.d.ts index e5e400bc44..878e17a011 100644 --- a/types/google.visualization/index.d.ts +++ b/types/google.visualization/index.d.ts @@ -597,6 +597,7 @@ declare namespace google { chartArea?: ChartArea; colors?: string[]; enableInteractivity?: boolean; + explorer?: ChartExplorer; focusTarget?: string; fontSize?: number; fontName?: string; diff --git a/types/got/got-tests.ts b/types/got/got-tests.ts index 934adfc9a8..55680e7d27 100644 --- a/types/got/got-tests.ts +++ b/types/got/got-tests.ts @@ -269,3 +269,4 @@ got('http://todomvc.com', { retry: 2 }); got('http://todomvc.com', { retry: { retries: 2, methods: ['GET'], statusCodes: [408, 504], maxRetryAfter: 1 } }); got('http://todomvc.com', { throwHttpErrors: false }); got('http://todomvc.com', { hooks: { beforeRequest: [ () => 'foo']} }); +got('http://todomvc.com', { timeout: 1 }).catch((e) => e instanceof got.TimeoutError); diff --git a/types/got/index.d.ts b/types/got/index.d.ts index 6b0929fdcf..d0cfc682dc 100644 --- a/types/got/index.d.ts +++ b/types/got/index.d.ts @@ -53,6 +53,10 @@ declare class CancelError extends StdError { name: 'CancelError'; } +declare class TimeoutError extends StdError { + name: 'TimeoutError'; +} + declare class StdError extends Error { code?: string; host?: string; @@ -75,6 +79,7 @@ declare const got: got.GotFn & MaxRedirectsError: typeof MaxRedirectsError; UnsupportedProtocolError: typeof UnsupportedProtocolError; CancelError: typeof CancelError; + TimeoutError: typeof TimeoutError; }; interface InternalRequestOptions extends https.RequestOptions { @@ -215,7 +220,7 @@ declare namespace got { removeListener(event: 'uploadProgress', listener: (progress: Progress) => void): this; } - type GotError = RequestError | ReadError | ParseError | HTTPError | MaxRedirectsError | UnsupportedProtocolError | CancelError; + type GotError = RequestError | ReadError | ParseError | HTTPError | MaxRedirectsError | UnsupportedProtocolError | CancelError | TimeoutError; interface Progress { percent: number; diff --git a/types/graphql-fields/graphql-fields-tests.ts b/types/graphql-fields/graphql-fields-tests.ts new file mode 100644 index 0000000000..811fe25ab2 --- /dev/null +++ b/types/graphql-fields/graphql-fields-tests.ts @@ -0,0 +1,8 @@ +import { GraphQLResolveInfo } from 'graphql'; +import graphqlFields = require('graphql-fields'); + +const info = ({} as any) as GraphQLResolveInfo; + +const fieldsWithSubFieldsArgs = graphqlFields(info, {}, { processArguments: true }); +const fieldsWithoutTypeName = graphqlFields(info, {}, { excludedFields: ['__typename'] }); +graphqlFields(info); diff --git a/types/graphql-fields/index.d.ts b/types/graphql-fields/index.d.ts new file mode 100644 index 0000000000..19e7f21dc4 --- /dev/null +++ b/types/graphql-fields/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for graphql-fields 1.3 +// Project: https://github.com/robrichard/graphql-fields#readme +// Definitions by: feinoujc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { GraphQLResolveInfo } from 'graphql'; + +declare function graphqlFields(info: GraphQLResolveInfo, obj?: object, opts?: graphqlFields.Options): any; + +declare namespace graphqlFields { + interface Options { + processArguments?: boolean; + excludedFields?: string[]; + } +} + +export = graphqlFields; diff --git a/types/graphql-fields/tsconfig.json b/types/graphql-fields/tsconfig.json new file mode 100644 index 0000000000..826e200b41 --- /dev/null +++ b/types/graphql-fields/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "esnext.asynciterable" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "graphql-fields-tests.ts" + ] +} diff --git a/types/graphql-fields/tslint.json b/types/graphql-fields/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/graphql-fields/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/graphql-relay/graphql-relay-tests.ts b/types/graphql-relay/graphql-relay-tests.ts index cebc90e2ca..e490329b65 100644 --- a/types/graphql-relay/graphql-relay-tests.ts +++ b/types/graphql-relay/graphql-relay-tests.ts @@ -11,6 +11,7 @@ import { GraphQLInputFieldConfigMap, GraphQLNonNull, GraphQLID, + GraphQLInt } from "graphql"; import { // Connections @@ -30,18 +31,19 @@ import { // Mutations mutationWithClientMutationId, } from "graphql-relay"; + // Connections // connectionArgs returns the arguments that fields should provide when they return a connection type that supports bidirectional pagination. -connectionArgs.first = 10; -connectionArgs.after = "a"; -connectionArgs.before = "b"; -connectionArgs.last = 10; +connectionArgs.first = { type: GraphQLInt }; +connectionArgs.after = { type: GraphQLString }; +connectionArgs.before = { type: GraphQLString }; +connectionArgs.last = { type: GraphQLInt }; // forwardConnectionArgs returns the arguments that fields should provide when they return a connection type that only supports forward pagination. -forwardConnectionArgs.after = "a"; -forwardConnectionArgs.first = 10; +forwardConnectionArgs.after = { type: GraphQLString }; +forwardConnectionArgs.first = { type: GraphQLInt }; // backwardConnectionArgs returns the arguments that fields should provide when they return a connection type that only supports backward pagination. -backwardConnectionArgs.before = "b"; -backwardConnectionArgs.last = 10; +backwardConnectionArgs.before = { type: GraphQLString }; +backwardConnectionArgs.last = { type: GraphQLInt }; // connectionDefinitions returns a connectionType and its associated edgeType, given a node type. const resolve: GraphQLFieldResolver = (source, args, context, info) => { context.flag = "f"; diff --git a/types/graphql-relay/index.d.ts b/types/graphql-relay/index.d.ts index d4bba06948..67edfa3df0 100644 --- a/types/graphql-relay/index.d.ts +++ b/types/graphql-relay/index.d.ts @@ -34,27 +34,20 @@ import { * whose return type is a connection type with forward pagination. */ export interface ForwardConnectionArgs { - after?: ConnectionCursor | null; - first?: number | null; + after: { type: GraphQLScalarType }; + first: { type: GraphQLScalarType }; } -export const forwardConnectionArgs: GraphQLFieldConfigArgumentMap & { - after?: ConnectionCursor | null; - first?: number | null; -}; +export const forwardConnectionArgs: GraphQLFieldConfigArgumentMap & ForwardConnectionArgs; /** * Returns a GraphQLFieldConfigArgumentMap appropriate to include on a field * whose return type is a connection type with backward pagination. */ export interface BackwardConnectionArgs { - before?: ConnectionCursor | null; - last?: number | null; + before: { type: GraphQLScalarType }; + last: { type: GraphQLScalarType }; } -export const backwardConnectionArgs: GraphQLFieldConfigArgumentMap & { - before?: ConnectionCursor | null; - last?: number | null; -}; - +export const backwardConnectionArgs: GraphQLFieldConfigArgumentMap & BackwardConnectionArgs; /** * Returns a GraphQLFieldConfigArgumentMap appropriate to include on a field * whose return type is a connection type with bidirectional pagination. diff --git a/types/grecaptcha/grecaptcha-tests.ts b/types/grecaptcha/grecaptcha-tests.ts index 288836d6b3..970660cc6c 100644 --- a/types/grecaptcha/grecaptcha-tests.ts +++ b/types/grecaptcha/grecaptcha-tests.ts @@ -18,11 +18,15 @@ const badge1: ReCaptchaV2.Badge = "bottomleft"; const badge2: ReCaptchaV2.Badge = "bottomright"; const badge3: ReCaptchaV2.Badge = "inline"; -const invisibleParams: ReCaptchaV2.Parameters = { +const invisibleParams1: ReCaptchaV2.Parameters = { sitekey: "siteKey", badge: badge1, }; +const invisibleParams2: ReCaptchaV2.Parameters = { + badge: badge2, +}; + const id1: number = grecaptcha.render("foo"); const id2: number = grecaptcha.render("foo", params); const id3: number = grecaptcha.render(document.getElementById("foo")); diff --git a/types/grecaptcha/index.d.ts b/types/grecaptcha/index.d.ts index c9dedbfb74..4430aa90e9 100644 --- a/types/grecaptcha/index.d.ts +++ b/types/grecaptcha/index.d.ts @@ -46,7 +46,7 @@ declare namespace ReCaptchaV2 { /** * Your sitekey. */ - sitekey: string; + sitekey?: string; /** * Optional. The color theme of the widget. * Accepted values: "light", "dark" diff --git a/types/gridstack/tslint.json b/types/gridstack/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/gridstack/tslint.json +++ b/types/gridstack/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/gulp-json-validator/gulp-json-validator-tests.ts b/types/gulp-json-validator/gulp-json-validator-tests.ts new file mode 100644 index 0000000000..74a00f03da --- /dev/null +++ b/types/gulp-json-validator/gulp-json-validator-tests.ts @@ -0,0 +1,6 @@ +import gulpJsonValidator = require("gulp-json-validator"); + +gulpJsonValidator(); // $ExpectType ReadWriteStream +gulpJsonValidator({}); // $ExpectType ReadWriteStream +gulpJsonValidator({ allowDuplicatedKeys: true }); // $ExpectType ReadWriteStream +gulpJsonValidator({ allowDuplicatedKeys: false }); // $ExpectType ReadWriteStream diff --git a/types/gulp-json-validator/index.d.ts b/types/gulp-json-validator/index.d.ts new file mode 100644 index 0000000000..26e31d8b43 --- /dev/null +++ b/types/gulp-json-validator/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for gulp-json-validator 1.2 +// Project: https://github.com/jackyjieliu/gulp-json-validator +// Definitions by: Peter Safranek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface GulpJsonValidatorOptions { + allowDuplicatedKeys?: boolean; +} + +declare function gulpJsonValidator(option?: GulpJsonValidatorOptions): NodeJS.ReadWriteStream; + +export = gulpJsonValidator; diff --git a/types/gulp-json-validator/tsconfig.json b/types/gulp-json-validator/tsconfig.json new file mode 100644 index 0000000000..76ee50c184 --- /dev/null +++ b/types/gulp-json-validator/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-json-validator-tests.ts" + ] +} diff --git a/types/gulp-json-validator/tslint.json b/types/gulp-json-validator/tslint.json new file mode 100644 index 0000000000..702f9354fc --- /dev/null +++ b/types/gulp-json-validator/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "file-name-casing": false + } +} diff --git a/types/hapi-auth-cookie/hapi-auth-cookie-tests.ts b/types/hapi-auth-cookie/hapi-auth-cookie-tests.ts new file mode 100644 index 0000000000..155bb928e3 --- /dev/null +++ b/types/hapi-auth-cookie/hapi-auth-cookie-tests.ts @@ -0,0 +1,33 @@ +import * as hapi from 'hapi'; +import * as auth from 'hapi-auth-cookie'; + +const server = new hapi.Server({ port: 8000 }); + +server.register({ + plugin: auth, +}); + +const options: auth.Options = { + clearInvalid: true, + cookie: 'session', + domain: '.typescript.org', + keepAlive: true, + password: 'abcdef', + redirectTo: '/login', + isSecure: true, + appendNext: false, + ttl: 259200000, + validateFunc: async () => { + return { valid: true }; + }, +}; + +server.auth.strategy('session', 'cookie', options); + +server.route({ method: 'get', path: '/', handler: async (request) => { + request.cookieAuth.set('key', 'value'); + request.cookieAuth.set({ user: request.params.user }); + request.cookieAuth.clear(); + request.cookieAuth.clear('key'); + request.cookieAuth.ttl(1000); +}}); diff --git a/types/hapi-auth-cookie/index.d.ts b/types/hapi-auth-cookie/index.d.ts new file mode 100644 index 0000000000..8184ffd2fe --- /dev/null +++ b/types/hapi-auth-cookie/index.d.ts @@ -0,0 +1,142 @@ +// Type definitions for hapi-auth-cookie 9.1 +// Project: https://github.com/hapijs/hapi-auth-cookie +// Definitions by: Silas Rech +// Simon Schick +// Matt Erickson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Request, ResponseObject, Plugin, ResponseToolkit, AuthCredentials, ServerStateCookieOptions } from 'hapi'; + +declare module 'hapi' { + interface ServerAuth { + strategy(name: string, scheme: 'cookie', options?: hapiAuthCookie.Options): void; + } + + interface PluginSpecificConfiguration { + 'hapi-auth-cookie'?: { + redirectTo?: boolean; + }; + } + + interface Request { + cookieAuth: { + set(session: object): void; + set(key: string, value: object | string): void; + clear(key?: string): void; + ttl(milliseconds: number): void; + }; + } +} + +declare namespace hapiAuthCookie { + interface ValidateResponse { valid: boolean; credentials?: AuthCredentials; } + type ValidateFunction = (request?: Request, session?: object) => Promise; + type RedirectToFunction = (request?: Request) => void; + + /** + * Options passed to 'hapi.auth.strategy' when this plugin is used + */ + interface Options { + /** + * The cookie name. + * + * @default 'sid' + */ + cookie?: string; + + /** + * Used for Iron cookie encoding. + * Should be at least 32 characters long. + */ + password: string; + + /** + * Sets the cookie expires time in milliseconds. + * Required when 'keepAlive' is true. + * Defaults to single browser session (ends when browser closes). + */ + ttl?: number; + + /** + * Sets the cookie Domain value. + * Defaults to none. + */ + domain?: string; + + /** + * Sets the cookie path value. + * + * @default '/' + */ + path?: string; + + /** + * Any authentication cookie that fails validation will be marked as expired in the response and cleared. + * + * @default false + */ + clearInvalid?: boolean; + + /** + * Automatically sets the session cookie after validation to extend the current session for a new TTL duration. + * + * @default false + */ + keepAlive?: boolean; + + /** + * If false omitted. + * Other options Strict or Lax. + * + * @default 'Strict' + */ + isSameSite?: ServerStateCookieOptions['isSameSite']; + + /** + * If false, the cookie is allowed to be transmitted over insecure connections which exposes it to attacks. + * + * @default true + */ + isSecure?: boolean; + + /** + * If false, the cookie will not include the 'HttpOnly' flag. + * + * @default true + */ + isHttpOnly?: boolean; + + /** + * Login URI or function that returns a URI to redirect unauthenticated requests to. + * Note that it will only trigger when the authentication mode is 'required'. + * Defaults to no redirection. + */ + redirectTo?: string | RedirectToFunction; + + /** + * Only works if 'redirectTo' is true + * If set to true, a string, or an object, appends the current request path to the query component of the 'redirectTo' URI. + */ + appendNext?: boolean | string; + + /** + * An optional session validation function used to validate the content of the session cookie on each request. + * Used to verify that the internal session state is still valid (e.g. user account still exists). + */ + validateFunc?: ValidateFunction; + + /** + * A name to use with decorating the request object. + * Using multiple decorator names for separate authentication strategies could allow a developer to call the methods for the wrong strategy. + * Potentially resulting in unintended authorized access. + * + * @default 'cookieAuth' + */ + requestDecoratorName?: string; + } +} + +declare const hapiAuthCookie: Plugin; + +export = hapiAuthCookie; diff --git a/types/hapi-auth-cookie/tsconfig.json b/types/hapi-auth-cookie/tsconfig.json new file mode 100644 index 0000000000..ae04bf4a42 --- /dev/null +++ b/types/hapi-auth-cookie/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hapi-auth-cookie-tests.ts" + ] +} diff --git a/types/hapi-auth-cookie/tslint.json b/types/hapi-auth-cookie/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hapi-auth-cookie/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 9bd9a14f41..3e323f8c44 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for hapi 17.6 +// Type definitions for hapi 17.8 // Project: https://github.com/hapijs/hapi // Definitions by: Rafael Souza Fijalkowski // Justin Simms @@ -42,6 +42,18 @@ import { PolicyOptionVariants, EnginePrototypeOrObject, PolicyOptions, EnginePro + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +/** + * one of + * a single plugin name string. + * an array of plugin name strings. + * an object where each key is a plugin name and each matching value is a + * {@link https://www.npmjs.com/package/semver version range string} which must match the registered + * plugin version. + */ +export type Dependencies = string | string[] | { + [key: string]: string; +}; + /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) */ @@ -126,7 +138,16 @@ export interface PluginBase { multiple?: boolean; /** (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via server.dependency(). */ - dependencies?: string | string[]; + dependencies?: Dependencies; + + /** + * Allows defining semver requirements for node and hapi. + * @default Allows all. + */ + requirements?: { + node?: string; + hapi?: string; + }; /** once - (optional) if true, will only register the plugin once per server. If set, overrides the once option passed to server.register(). Defaults to no override. */ once?: boolean; @@ -2013,6 +2034,15 @@ export interface ServerAuthSchemeObject { */ response?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + /** + * a method used to verify the authentication credentials provided + * are still valid (e.g. not expired or revoked after the initial authentication). + * the method throws an `Error` when the credentials passed are no longer valid (e.g. expired or + * revoked). Note that the method does not have access to the original request, only to the + * credentials and artifacts produced by the `authenticate()` method. + */ + verify?(auth: RequestAuth): Promise; + /** * An object with the following keys: * * payload @@ -2040,7 +2070,7 @@ export interface ServerAuth { * returned from its implementation function. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi) */ - api: Util.Dictionary; + api: Util.Dictionary; /** * Contains the default authentication configuration is a default strategy was set via @@ -2100,10 +2130,25 @@ export interface ServerAuth { * include verifying scope, entity, or other route properties. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) */ - test(strategy: string, request: Request): Promise; + test(strategy: string, request: Request): Promise; + + /** + * Verify a request's authentication credentials against an authentication strategy. + * Returns nothing if verification was successful, otherwise throws an error. + * + * Note that the `verify()` method does not take into account the route authentication configuration + * or any other information from the request other than the `request.auth` object. It also does not + * perform payload authentication. It is limited to verifying that the previously valid credentials + * are still valid (e.g. have not been revoked or expired). It does not include verifying scope, + * entity, or other route properties. + */ + verify(request: Request): Promise; } export type CachePolicyOptions = PolicyOptionVariants & { + /** + * @default '_default' + */ cache?: string; segment?: string; }; @@ -3299,7 +3344,7 @@ export class Server { /** * Server Auth: properties and methods */ - auth: ServerAuth; + readonly auth: ServerAuth; /** * Links another server to the initialize/start/stop state of the current server by calling the @@ -3539,7 +3584,7 @@ export class Server { /** * Used within a plugin to declare a required dependency on other plugins where: - * @param dependencies - a single string or an array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is + * @param dependencies - plugins which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is * initialized or started. * @param after - (optional) a function that is called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is * initialized or started. The function signature is async function(server) where: server - the server the dependency() method was called on. @@ -3549,7 +3594,7 @@ export class Server { * The method does not provide version dependency which should be implemented using npm peer dependencies. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) */ - dependency(dependencies: string | string[], after?: ((server: Server) => Promise)): void; + dependency(dependencies: Dependencies, after?: ((server: Server) => Promise)): void; /** * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where: diff --git a/types/hapi/test/server/server-auth-api.ts b/types/hapi/test/server/server-auth-api.ts index f1b51bda8c..4508c641c9 100644 --- a/types/hapi/test/server/server-auth-api.ts +++ b/types/hapi/test/server/server-auth-api.ts @@ -1,14 +1,18 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi import { - Request, - ResponseToolkit, Server, ServerAuthScheme, - ServerAuthSchemeObject, - ServerAuthSchemeOptions } from "hapi"; import * as Boom from "boom"; +declare module 'hapi' { + interface ServerAuthSchemeObjectApi { + settings: { + x: number; + }; + } +} + const scheme: ServerAuthScheme = (server, options) => { return { api: { diff --git a/types/hapi/test/server/server-auth-test.ts b/types/hapi/test/server/server-auth-test.ts index 5103d11c7e..4e2a175e1a 100644 --- a/types/hapi/test/server/server-auth-test.ts +++ b/types/hapi/test/server/server-auth-test.ts @@ -3,6 +3,12 @@ import { Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions } from "hapi"; import * as Boom from "boom"; +declare module 'hapi' { + interface AuthCredentials { + name?: string; + } +} + const server = new Server({ port: 8000, }); @@ -15,7 +21,7 @@ const scheme: ServerAuthScheme = (server, options) => { if (!authorization) { throw Boom.unauthorized(null, 'Custom'); } - return h.authenticated({ credentials: { user: { a: 1} } }); + return h.authenticated({ credentials: { name: 'john', } }); } }; }; diff --git a/types/hapi/test/server/server-auth-verify.ts b/types/hapi/test/server/server-auth-verify.ts new file mode 100644 index 0000000000..ec788fcb59 --- /dev/null +++ b/types/hapi/test/server/server-auth-verify.ts @@ -0,0 +1,26 @@ +import { Request, Server, RequestAuth } from "hapi"; +import * as Boom from "boom"; + +const server = new Server({ + port: 8000, +}); + +server.auth.scheme('custom', () => ({ + authenticate() { + throw Boom.unauthorized(null, 'hurr'); + }, + async verify(_auth: RequestAuth) { + throw Boom.unauthorized(null, 'durr'); + } +})); +server.auth.strategy('default', 'custom'); + +server.route({ + method: 'GET', + path: '/', + async handler(request: Request) { + request.server.auth.verify(request); + } +}); + +server.start(); diff --git a/types/hapi/test/server/server-plugins.ts b/types/hapi/test/server/server-plugins.ts index 8de3fdc24f..03a3c76907 100644 --- a/types/hapi/test/server/server-plugins.ts +++ b/types/hapi/test/server/server-plugins.ts @@ -33,22 +33,31 @@ const plugin1: Plugin = { server.plugins.example.other = 'other'; console.log(server.plugins.example.key); // 'value' console.log(server.plugins.example.other); // 'other' - } + }, }; const plugin2: Plugin = { name: 'plugin2', - register: async (server: Server, options: Plugin2) => {} + register: async (server: Server, options: Plugin2) => {}, + dependencies: { + plugin1: '*', + }, + requirements: { + node: '>=8', + hapi: '>=1337', + }, }; const plugin3: Plugin = { name: 'plugin3', - register: async (server: Server, options: Plugin3) => {} + register: async (server: Server, options: Plugin3) => {}, + dependencies: ['plugin2'], }; const plugin4: Plugin = { name: 'plugin4', - register: (server: Server, options: Plugin4) => {} + register: (server: Server, options: Plugin4) => {}, + dependencies: 'plugin3', }; const server = new Server({ diff --git a/types/hapi/tsconfig.json b/types/hapi/tsconfig.json index 2804e84871..9df329c575 100644 --- a/types/hapi/tsconfig.json +++ b/types/hapi/tsconfig.json @@ -41,6 +41,7 @@ "test/server/server-auth-api.ts", "test/server/server-auth-default.ts", "test/server/server-auth-test.ts", + "test/server/server-auth-verify.ts", "test/server/server-bind.ts", "test/server/server-cache-provision.ts", "test/server/server-cache.ts", diff --git a/types/hapi/v12/hapi-tests.ts b/types/hapi/v12/hapi-tests.ts index 32d1aff704..287a071d38 100644 --- a/types/hapi/v12/hapi-tests.ts +++ b/types/hapi/v12/hapi-tests.ts @@ -6,7 +6,7 @@ import * as Hapi from 'hapi'; // Create a server with a host and port var server = new Hapi.Server(); -server.connection({ +server.connection({ host: "localhost", port: 8000 }); diff --git a/types/hapi/v16/test/continuation/errors.ts b/types/hapi/v16/test/continuation/errors.ts index 165e5214df..2f9fedaaf5 100644 --- a/types/hapi/v16/test/continuation/errors.ts +++ b/types/hapi/v16/test/continuation/errors.ts @@ -26,7 +26,7 @@ const handleError: Hapi.ContinuationValueFunction = (err?: Boom.BoomError | null handleError(Boom.badData()); // Accepts an error with custom data -const errorWithData = Boom.badImplementation('', { custom1: 'test', customType: <'Custom1'>'Custom1', isCustom: true }); +const errorWithData = Boom.badImplementation('', { custom1: 'test', customType: 'Custom1' as 'Custom1', isCustom: true as true }); handleError(errorWithData); // Accepts an error with a more explicit type diff --git a/types/hapi/v16/test/route/additional-options.ts b/types/hapi/v16/test/route/additional-options.ts index ccbb36af15..7ab2171776 100644 --- a/types/hapi/v16/test/route/additional-options.ts +++ b/types/hapi/v16/test/route/additional-options.ts @@ -10,28 +10,28 @@ var authConfig: Hapi.RouteAdditionalConfigurationOptions = { var extConfigSingle: Hapi.RouteAdditionalConfigurationOptions = { ext: { type: 'onPreAuth', - method: function (request, reply) { + method: function (request, reply) { reply('ok'); - } + } as Hapi.ServerExtRequestHandler } } var extConfigMulti: Hapi.RouteAdditionalConfigurationOptions = { ext: [{ type: 'onPreAuth', - method: function (request, reply) { + method: function (request, reply) { reply('ok'); - } + } as Hapi.ServerExtRequestHandler }, { type: 'onPostAuth', - method: function (request, reply) { + method: function (request, reply) { reply('ok'); - } + } as Hapi.ServerExtRequestHandler }, { type: 'onPostStart', - method: function (server, next) { + method: function (server, next) { next(); - } + } as Hapi.ServerExtFunction }] } diff --git a/types/hapi/v16/test/route/public-interface.ts b/types/hapi/v16/test/route/public-interface.ts index f3878cea48..dad79e7306 100644 --- a/types/hapi/v16/test/route/public-interface.ts +++ b/types/hapi/v16/test/route/public-interface.ts @@ -2,7 +2,7 @@ import * as Hapi from '../../'; -var route = {}; +var route = {} as Hapi.RoutePublicInterface; var a: string = route.method; var a: string = route.path; @@ -14,4 +14,4 @@ if (typeof(route.vhost) == 'string') { var c: Hapi.ServerRealm = route.realm; var d: Hapi.RouteAdditionalConfigurationOptions = route.settings; var a: string = route.fingerprint; -var e: boolean = route.auth.access( {}); +var e: boolean = route.auth.access({} as Hapi.Request); diff --git a/types/hapi/v16/test/route/validate.ts b/types/hapi/v16/test/route/validate.ts index 06fefcc62e..42d6872570 100644 --- a/types/hapi/v16/test/route/validate.ts +++ b/types/hapi/v16/test/route/validate.ts @@ -55,10 +55,10 @@ const responseValidationFunction: Hapi.ValidationFunctionForRouteResponse>{ + response: { schema: responseValidationFunction, options: { myOption: 18 } - } + } as Hapi.RouteResponseConfigurationObject }; diff --git a/types/hapi/v16/test/server/listener.ts b/types/hapi/v16/test/server/listener.ts index 85ddb18bc6..84eda35ed5 100644 --- a/types/hapi/v16/test/server/listener.ts +++ b/types/hapi/v16/test/server/listener.ts @@ -15,5 +15,5 @@ io.sockets.on('connection', (socket) => { // a wrapper around socket.io. Much less likely is either // a type error in the TypeScript definitions of socket.io or // an error in the Hapi docs. - socket.emit( { msg: 'welcome' }); + socket.emit({ msg: 'welcome' } as any); }); diff --git a/types/hard-source-webpack-plugin/index.d.ts b/types/hard-source-webpack-plugin/index.d.ts index 3e02ee1d8a..4a83b58034 100644 --- a/types/hard-source-webpack-plugin/index.d.ts +++ b/types/hard-source-webpack-plugin/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for hard-source-webpack-plugin 0.9 +// Type definitions for hard-source-webpack-plugin 1.0 // Project: https://github.com/mzgoddard/hard-source-webpack-plugin#readme // Definitions by: woitechen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -15,7 +15,7 @@ declare namespace hard_source_webpack_plugin { } interface Options { cacheDirectory?: string; - configHash?: (webpackConfig?: webpack.Configuration) => string; + configHash?: string | ((webpackConfig?: webpack.Configuration) => string); environmentHash?: { root: string; directories: string[]; diff --git a/types/has-emoji/has-emoji-tests.ts b/types/has-emoji/has-emoji-tests.ts new file mode 100644 index 0000000000..f1453f4cf5 --- /dev/null +++ b/types/has-emoji/has-emoji-tests.ts @@ -0,0 +1,6 @@ +import hasEmoji = require('has-emoji'); + +// $ExpectType boolean +hasEmoji('Unicorn 🦄'); +// $ExpectType boolean +hasEmoji('Cat'); diff --git a/types/has-emoji/index.d.ts b/types/has-emoji/index.d.ts new file mode 100644 index 0000000000..2160e66497 --- /dev/null +++ b/types/has-emoji/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for has-emoji 1.0 +// Project: https://github.com/sindresorhus/has-emoji#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = hasEmoji; + +declare function hasEmoji(candidate: string): boolean; diff --git a/types/has-emoji/tsconfig.json b/types/has-emoji/tsconfig.json new file mode 100644 index 0000000000..646f983707 --- /dev/null +++ b/types/has-emoji/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "has-emoji-tests.ts" + ] +} diff --git a/types/has-emoji/tslint.json b/types/has-emoji/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/has-emoji/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hibp/hibp-tests.ts b/types/hibp/hibp-tests.ts new file mode 100644 index 0000000000..cdcd1851bf --- /dev/null +++ b/types/hibp/hibp-tests.ts @@ -0,0 +1,17 @@ +import * as hibp from 'hibp'; + +hibp +.search('someAccountOrEmail') +.then(data => { + if (data.breaches || data.pastes) { + // Bummer... + console.log(data); + } else { + // Phew! We're clear. + console.log('Good news — no pwnage found!'); + } +}) +.catch(err => { + // Something went wrong. + console.log(err.message); +}); diff --git a/types/hibp/index.d.ts b/types/hibp/index.d.ts new file mode 100644 index 0000000000..27819f1c96 --- /dev/null +++ b/types/hibp/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for hibp 7.2 +// Project: https://github.com/wkovacs64/hibp +// Definitions by: Silas Rech +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +export interface BreachOptions { + domain?: string; + truncate?: boolean; +} + +export interface Breach { + Name: string; + Title: string; + Domain: string; + BreachDate: string; + AddedDate: string; + ModifiedDate: string; + PwnCount: number; + Description: string; + LogoPath: string; + DataClasses: string[]; + IsVerified: boolean; + IsFabricated: boolean; + IsSensitive: boolean; + IsRetired: boolean; + IsSpamList: boolean; +} + +export interface Paste { + Id: string; + Source: string; + Title: string; + Date: string; + EmailCount: number; +} + +export interface Range { + suffix: string; + count: number; +} + +/** + * Fetches data for a specific breach event. + */ +export function breach(breachName: string): Promise; + +/** + * Fetches breach data for a specific account. + */ +export function breachedAccount(account: string, options?: BreachOptions): Promise; + +/** + * Fetches all breach events in the system. + */ +export function breaches(options?: { domain?: string }): Promise; + +/** + * Fetches all data classes in the system. + */ +export function dataClasses(): Promise; + +/** + * Fetches paste data for a specific email address. + */ +export function pasteAccount(email: string): Promise; + +/** + * Fetches the number of times the the given password has been exposed in a breach (0 indicating no exposure). + * The password is given in plain text, but only the first 5 characters of its SHA-1 hash will be submitted to the API. + */ +export function pwnedPassword(password: string): Promise; + +/** + * Fetches the SHA-1 hash suffixes for the given 5-character SHA-1 hash prefix. + * + * When a password hash with the same first 5 characters is found in the Pwned Passwords repository, + * the API will respond with an HTTP 200 and include the suffix of every hash beginning with the specified prefix, + * followed by a count of how many times it appears in the data set. + * + * This function parses the response and returns a more structured format. + */ +export function pwnedPasswordRange(prefix: string): Promise; + +/** + * Fetches all breaches and all pastes associated with the provided account (email address or username). + * + * Note that the remote API does not support querying pastes by username (only email addresses), + * so in the event the provided account is not a valid email address, + * only breach data is queried and the "pastes" field of the resulting object will always be null. + * + * This is exactly how searching via the current web interface behaves, which this convenience method is designed to mimic. + * + */ +export function search(account: string, options?: BreachOptions): Promise<{ breaches?: Breach[], pastes?: Paste[] }>; diff --git a/types/hibp/tsconfig.json b/types/hibp/tsconfig.json new file mode 100644 index 0000000000..58ecb92a11 --- /dev/null +++ b/types/hibp/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hibp-tests.ts" + ] +} diff --git a/types/hibp/tslint.json b/types/hibp/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hibp/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/highcharts/highcharts-more.d.ts b/types/highcharts/highcharts-more.d.ts index 630dbb5622..aaa2da832c 100644 --- a/types/highcharts/highcharts-more.d.ts +++ b/types/highcharts/highcharts-more.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highcharts 4.2.6 -// Project: http://www.highcharts.com/ -// Definitions by: Maciej Suchecki -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import * as Highcharts from "highcharts"; declare function HighchartsMore(H: Highcharts.Static): Highcharts.Static; diff --git a/types/highcharts/highstock.d.ts b/types/highcharts/highstock.d.ts index cc92bebe36..70ebfcb5c1 100644 --- a/types/highcharts/highstock.d.ts +++ b/types/highcharts/highstock.d.ts @@ -1,11 +1,3 @@ -// Type definitions for Highstock 2.1.6 -// Project: http://www.highcharts.com/ - -// Definitions by: David Deutsch -// Dave Baumann -// Richard Ison -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import * as Highcharts from "highcharts"; declare namespace Highstock { @@ -129,8 +121,7 @@ declare namespace Highstock { } interface Chart { - new (options: Options): ChartObject; - new (options: Options, callback: (chart: ChartObject) => void): ChartObject; + new (options: Options, callback?: (chart: ChartObject) => void): ChartObject; } interface Static extends Highcharts.Static { @@ -142,13 +133,6 @@ declare namespace Highstock { declare global { interface JQuery { highcharts(type: "StockChart"): Highstock.ChartObject; - /** - * Creates a new Highcharts.Chart for the current JQuery selector; usually - * a div selected by $('#container') - * @param options Options for this chart - * @return current selector the current JQuery selector - */ - highcharts(type: "StockChart", options: Highstock.Options): JQuery; /** * Creates a new Highcharts.Chart for the current JQuery selector; usually * a div selected by $('#container') @@ -156,11 +140,10 @@ declare global { * @param callback Callback function used to manipulate the constructed chart instance * @return current selector the current JQuery selector */ - highcharts(type: "StockChart", options: Highstock.Options, callback: (chart: Highstock.ChartObject) => void): JQuery; + highcharts(type: "StockChart", options: Highstock.Options, callback?: (chart: Highstock.ChartObject) => void): JQuery; highcharts(type: string): Highcharts.ChartObject; - highcharts(type: string, options: Highcharts.Options): JQuery; - highcharts(type: string, options: Highcharts.Options, callback: (chart: Highcharts.ChartObject) => void): JQuery; + highcharts(type: string, options: Highcharts.Options, callback?: (chart: Highcharts.ChartObject) => void): JQuery; } } diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 167d6532d3..c6aae1e77f 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Highcharts 5.0.13 +// Type definitions for Highcharts 5.0 // Project: http://www.highcharts.com/ // Definitions by: Damiano Gambarotto // Dan Lewi Harkestad @@ -4659,6 +4659,14 @@ declare namespace Highcharts { * allows setting a separate color for the line without altering the fillColor. */ lineColor?: string | Gradient; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; /** * A separate color for the negative part of the area. * @since 3.0 @@ -4757,6 +4765,10 @@ declare namespace Highcharts { * @since 2.3.0 */ grouping?: boolean; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; /** * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the * columns from becoming too wide when there is a small number of points in the chart. @@ -4764,6 +4776,10 @@ declare namespace Highcharts { * @since 4.1.8 */ maxPointWidth?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; /** * The minimal height for a column or width for a bar. By default, 0 values are not shown. To visualize a 0 (or * close to zero) point, set the minimal point length to a pixel value like 3. In stacked column charts, @@ -4858,6 +4874,10 @@ declare namespace Highcharts { * @since 3.0 */ displayNegative?: boolean; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; /** * Maximum bubble size. Bubbles will automatically size between the minSize and maxSize to reflect the z value of * each bubble. Can be either pixels (when no unit is given), or a percentage of the smallest one of the plot width @@ -4866,6 +4886,10 @@ declare namespace Highcharts { * @since 3.0 */ maxSize?: string | number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; /** * Minimum bubble size. Bubbles will automatically size between the minSize and maxSize to reflect the z value of * each bubble. Can be either pixels (when no unit is given), or a percentage of the smallest one of the plot width @@ -5151,6 +5175,14 @@ declare namespace Highcharts { * Options for the dial or arrow pointer of the gauge. */ dial?: Dial; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; /** * Allow the dial to overshoot the end of the perimeter axis by this many degrees. Say if the gauge axis goes from 0 * to 60, a value of 100, or 1000, will show 5 degrees beyond the end of the axis. Defaults to 0. @@ -5219,6 +5251,10 @@ declare namespace Highcharts { * @default 50 */ cropTreshold?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; /** * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the * columns from becoming too wide when there is a small number of points in the chart. @@ -5226,6 +5262,10 @@ declare namespace Highcharts { * @since 4.1.8 */ maxPointWidth?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; /** * The row size - how many Y axis units each heatmap row should span. * @default 1 @@ -5244,6 +5284,14 @@ declare namespace Highcharts { } interface LineChart extends SeriesChart { + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; /** * Whether to apply steps to the line. Possible values are left, center and right. Prior to 2.3.5, only left was * supported. @@ -5314,6 +5362,14 @@ declare namespace Highcharts { * @since 2.0 */ innerSize?: number | string; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; /** * The minimum size for a pie in response to auto margins. The pie will try to shrink to make room for data labels * in side the plot area, but only to this size. @@ -5361,6 +5417,14 @@ declare namespace Highcharts { * @default 0 */ lineWidth?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; } interface PyramidChart extends SeriesChart { @@ -5435,7 +5499,16 @@ declare namespace Highcharts { width?: number | string; } - interface ScatterChart extends SeriesChart { } + interface ScatterChart extends SeriesChart { + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; + } /** * A gauge showing values using a filled arc with colors indicating the value. The solid gauge plots values against the @@ -5471,7 +5544,16 @@ declare namespace Highcharts { wrap?: boolean; } - interface SplineChart extends SeriesChart { } + interface SplineChart extends SeriesChart { + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; + } /** * The size of the point shape is determined by its value relative to its siblings values. Requires the module @@ -5543,6 +5625,10 @@ declare namespace Highcharts { * Set options on specific levels. Takes precedence over series options, but not point options. */ levels?: TreeMapLevel[]; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; /** * The maximum allowed pixel width for a column, translated to the height of a bar in a bar chart. This prevents the * columns from becoming too wide when there is a small number of points in the chart. @@ -5550,6 +5636,10 @@ declare namespace Highcharts { * @since 4.1.8 */ maxPointWidth?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; /** * The sort index of the point inside the treemap level. * @since 4.1.10 @@ -5614,6 +5704,14 @@ declare namespace Highcharts { * @since 5.0.12 */ exposeElementToA11y?: boolean; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; /** * This option decides which algorithm is used for placement, and rotation of a word. The choice of algorith is * therefore a crucial part of the resulting layout of the wordcloud. It is possible for users to add their own @@ -5814,6 +5912,14 @@ declare namespace Highcharts { * The sequential index of the series in the legend. */ legendIndex?: number; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + maxFontSize?: number | null; + /** + * For area-like series, allow the font size to vary so that small areas get a smaller font size. The default applies this effect to area-like series but not line-like series. + */ + minFontSize?: number | null; /** * The name of the series as shown in the legend, tooltip etc. */ @@ -6638,16 +6744,10 @@ declare namespace Highcharts { /** * Set new categories for the axis. Redraws. * @param categories The new category names. + * @param redraw Whether to redraw the axis or wait for an explicit call to chart.redraw(). * @since 1.2.0 */ - setCategories(categories: string[]): void; - /** - * Set new categories for the axis. - * @param categories The new category names. - * @param redraw Whether to redraw the axis or wait for an explicit call to chart.redraw(). - * @since 1.2.0 - */ - setCategories(categories: string[], redraw: boolean): void; + setCategories(categories: string[], redraw?: boolean): void; /** * Set the minimum and maximum of the axes after render time. If the startOnTick and endOnTick options are true, the * minimum and maximum values are rounded off to the nearest tick. To prevent this, these options can be set to @@ -6757,22 +6857,6 @@ declare namespace Highcharts { * @since 3.0.8 */ drillUp(): void; - /** - * Exporting module required. Submit an SVG version of the chart to a server along with some parameters for - * conversion. - * @since 2.0 - */ - exportChart(): void; - /** - * Exporting module required. Submit an SVG version of the chart to a server along with some parameters for - * conversion. - * @param options Exporting options. Out of the exporting options, the following options can be given as parameters to the exportChart method. - * All options default to the values given in the exporting config options. filename: the filename for the export without extension, - * url: the URL for the server module to do the conversion, width: the width of the PNG or JPEG image generated on the server, - * type: the MIME type of the converted image, sourceWidth: the width of the source (in-page) chart, sourceHeight: the height of the source chart. - * @since 2.0 - */ - exportChart(options: ExportingOptions): void; /** * Exporting module required. Submit an SVG version of the chart to a server along with some parameters for * conversion. @@ -6783,31 +6867,17 @@ declare namespace Highcharts { * @param chartOptions Additional chart options for the exported chart. For example a different background color can be added here. * @since 2.0 */ - exportChart(options: ExportingOptions, chartOptions: Options): void; + exportChart(options?: ExportingOptions, chartOptions?: Options): void; /** * Export the chart to a PNG or SVG without sending it to a server. Requires * modules/exporting.js and modules/offline-exporting.js. - * @since 2.0 - */ - exportChartLocal(): void; - /** - * Export the chart to a PNG or SVG without sending it to a server. Requires - * modules/exporting.js and modules/offline-exporting.js. - * @param options Exporting options. Same as - * the exportChart params. - * @since 2.0 - */ - exportChartLocal(options: ExportingOptions): void; - /** - * Export the chart to a PNG or SVG without sending it to a server. - * Requires modules/exporting.js and modules/offline-exporting.js. * @param options Exporting options. Same as * the exportChart params. * @param chartOptions Additional chart options for the * exported chart. Same as the exportChart params. * @since 2.0 */ - exportChartLocal(options: ExportingOptions, chartOptions: Options): void; + exportChartLocal(options?: ExportingOptions, chartOptions?: Options): void; /** * Get an axis, series or point by its id as given in the configuration options. * @param id The id of the axis, series or point to get. @@ -6951,23 +7021,12 @@ declare namespace Highcharts { /** * This is the constructor for creating a new chart object. * @param options The chart options - */ - new (options: Options): ChartObject; - /** - * This is the constructor for creating a new chart object. - * @param options The chart options * @param callback A function to execute when the chart object is finished loading and rendering. In most cases the chart is built in one thread, * but in Internet Explorer version 8 or less the chart is sometimes initiated before the document is ready, * and in these cases the chart object will not be finished directly after callingnew Highcharts.Chart(). * s a consequence, code that relies on the newly built Chart object should always run in the callback. Defining a chart.event.load handler is equivalent. */ - new (options: Options, callback: (chart: ChartObject) => void): ChartObject; - /** - * This is the constructor for creating a new chart object. - * @param renderTo The id or a reference to a DOM element where the chart should be rendered (since v4.2.0). - * @param options The chart options - */ - new (renderTo: string | HTMLElement, options: Options): ChartObject; + new (options: Options, callback?: (chart: ChartObject) => void): ChartObject; /** * This is the constructor for creating a new chart object. * @param renderTo The id or a reference to a DOM element where the chart should be rendered (since v4.2.0). @@ -6977,7 +7036,7 @@ declare namespace Highcharts { * and in these cases the chart object will not be finished directly after callingnew Highcharts.Chart(). * As a consequence, code that relies on the newly built Chart object should always run in the callback. Defining a chart.event.load handler is equivalent. */ - new (renderTo: string | HTMLElement, options: Options, callback: (chart: ChartObject) => void): ChartObject; + new (renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; } /** @@ -7551,13 +7610,6 @@ declare namespace Highcharts { declare global { interface JQuery { highcharts(): Highcharts.ChartObject; - /** - * Creates a new Highcharts.Chart for the current JQuery selector; usually - * a div selected by $('#container') - * @param options Options for this chart - * @return current {JQuery} selector the current JQuery selector - */ - highcharts(options: Highcharts.Options): JQuery; /** * Creates a new Highcharts.Chart for the current JQuery selector; usually * a div selected by $('#container') @@ -7565,7 +7617,7 @@ declare global { * @param callback Callback function used to manipulate the constructed chart instance * @return current {JQuery} selector the current JQuery selector */ - highcharts(options: Highcharts.Options, callback: (chart: Highcharts.ChartObject) => void): JQuery; + highcharts(options: Highcharts.Options, callback?: (chart: Highcharts.ChartObject) => void): JQuery; } } diff --git a/types/highcharts/modules/boost.d.ts b/types/highcharts/modules/boost.d.ts index e0a3480f95..2e4da45b13 100644 --- a/types/highcharts/modules/boost.d.ts +++ b/types/highcharts/modules/boost.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highcharts 4.2.6 (boost module) -// Project: http://www.highcharts.com/ -// Definitions by: Daniel Martin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import { Static } from "highcharts"; declare function HighchartsBoost(H: Static): Static; diff --git a/types/highcharts/modules/drilldown.d.ts b/types/highcharts/modules/drilldown.d.ts index adf9bae6f8..46115cb4ad 100644 --- a/types/highcharts/modules/drilldown.d.ts +++ b/types/highcharts/modules/drilldown.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highcharts Drilldown 4.2.7 -// Project: http://www.highcharts.com/ -// Definitions by: Konstantin Rohde -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import { Static } from "highcharts"; declare function HighchartsDrilldown(H: Static): Static; diff --git a/types/highcharts/modules/exporting.d.ts b/types/highcharts/modules/exporting.d.ts index b4b0124a66..18f9615d41 100644 --- a/types/highcharts/modules/exporting.d.ts +++ b/types/highcharts/modules/exporting.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highcharts 4.2.6 (exporting module) -// Project: http://www.highcharts.com/ -// Definitions by: Maciej Suchecki -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import { Static } from "highcharts"; declare function HighchartsExporting(H: Static): Static; diff --git a/types/highcharts/modules/map/index.d.ts b/types/highcharts/modules/map/index.d.ts index ecf553945b..12b2ca0a7e 100644 --- a/types/highcharts/modules/map/index.d.ts +++ b/types/highcharts/modules/map/index.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highmaps 4.2.7 -// Project: http://www.highcharts.com/products/highmaps -// Definitions by: Albert Ozimek -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import * as highcharts from 'highcharts'; import * as geojson from 'geojson'; diff --git a/types/highcharts/modules/no-data-to-display.d.ts b/types/highcharts/modules/no-data-to-display.d.ts index f79ce249d1..bb8d406e03 100644 --- a/types/highcharts/modules/no-data-to-display.d.ts +++ b/types/highcharts/modules/no-data-to-display.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highcharts No Data to Display 4.2.7 -// Project: http://www.highcharts.com/ -// Definitions by: Andrey Zolotin , Rowell Heria -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import { Static } from "highcharts"; declare module "highcharts" { diff --git a/types/highcharts/modules/offline-exporting.d.ts b/types/highcharts/modules/offline-exporting.d.ts index ee38e1c91b..5f536a8588 100644 --- a/types/highcharts/modules/offline-exporting.d.ts +++ b/types/highcharts/modules/offline-exporting.d.ts @@ -1,8 +1,3 @@ -// Type definitions for Highcharts 4.2.6 (offline exporting module) -// Project: http://www.highcharts.com/ -// Definitions by: Daniel Martin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - import { Static } from "highcharts"; declare function HighchartsOfflineExporting(H: Static): Static; diff --git a/types/highcharts/test/highstock.ts b/types/highcharts/test/highstock.ts index f1a464f491..af9de8d1f9 100644 --- a/types/highcharts/test/highstock.ts +++ b/types/highcharts/test/highstock.ts @@ -66,10 +66,10 @@ $(() => { } }, - series: [ { + series: [{ name: 'USD to EUR', data: someData, lineColor: "blue" - }] + } as Highcharts.AreaRangeChartSeriesOptions] }); }); diff --git a/types/highcharts/test/index.ts b/types/highcharts/test/index.ts index 1eaa5da438..1474ee7e9c 100644 --- a/types/highcharts/test/index.ts +++ b/types/highcharts/test/index.ts @@ -40,15 +40,15 @@ function originalTests() { renderTo: "container" }, xAxis: {}, - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], description: "foo", type: "line", allowPointSelect: true - }] + } as Highcharts.LineChartSeriesOptions] }); - chart1.addSeries({ + chart1.addSeries({ enableMouseTracking: true, data: [1, 2, 3, 4, 5], description: "some description" @@ -61,7 +61,7 @@ function originalTests() { height: 400, spacingRight: 20 }, - xAxis: [ { + xAxis: [{ description: 'x-foo', min: 1, max: 1000, @@ -71,7 +71,7 @@ function originalTests() { gridLineWidth: 1, type: 'logarithmic' }], - yAxis: [ { + yAxis: [{ description: 'y-foo', min: 1, max: 1000, @@ -85,7 +85,7 @@ function originalTests() { legend: { enabled: false }, - series: [ { + series: [{ data: [ [550, 870], [738, 362], [719, 711], [547, 665], [595, 197], [332, 144], [581, 555], [196, 862], [6, 837], [400, 924], [888, 148], [785, 730], @@ -114,12 +114,12 @@ function originalTests() { renderTo: "container" }, xAxis: {}, - series: [ { + series: [{ data: [[1, 1, 2], [2, 2, 3], [3, 2, 3]], description: "foo", type: "columnrange", allowPointSelect: true - }] + } as Highcharts.ColumnRangeChartSeriesOptions] }); const chart4 = new Highcharts.Chart({ @@ -127,12 +127,12 @@ function originalTests() { renderTo: "container" }, xAxis: {}, - series: [ { + series: [{ data: [["01-01-2018", 1, 2], ["02-01-2018", 2, 3], ["03-01-2018", 2, 3]], description: "column range data", type: "columnrange", allowPointSelect: true - }] + } as Highcharts.ColumnRangeChartSeriesOptions] }); const div: HTMLDivElement = null as any; @@ -146,7 +146,7 @@ function originalTests() { }, xAxis: [{ }], - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] }; @@ -164,47 +164,47 @@ function originalTests() { const renderToIdChart = new Highcharts.Chart("container", { xAxis: {}, - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true - }] + } as Highcharts.LineChartSeriesOptions] }); const renderToElementChart = new Highcharts.Chart(div, { xAxis: {}, - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true - }] + } as Highcharts.LineChartSeriesOptions] }); const createWithFunction = Highcharts.chart({ xAxis: {}, - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true - }] + } as Highcharts.LineChartSeriesOptions] }); const createWithFunctionRenderToId = Highcharts.chart("container", { xAxis: {}, - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true - }] + } as Highcharts.LineChartSeriesOptions] }); const createWithFunctionRenderToElement = Highcharts.chart(div, { xAxis: {}, - series: [ { + series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], type: "line", allowPointSelect: true - }] + } as Highcharts.LineChartSeriesOptions] }); } @@ -245,7 +245,7 @@ function test_ChartOptions() { duration: 500, easing: "linear" }, - backgroundColor: { + backgroundColor: { linearGradient: { x1: 0, y1: 0, @@ -261,7 +261,7 @@ function test_ChartOptions() { colorCount: 42, defaultSeriesType: "deprecated", description: "an arbitrary description", - events: { + events: { addSeries: () => { }, afterPrint: () => { }, beforePrint: () => { }, @@ -281,21 +281,21 @@ function test_ChartOptions() { marginLeft: 10, marginRight: 10, marginTop: 10, - options3d: { + options3d: { alpha: 20, beta: 20, depth: 50, enabled: true, frame: { - back: { + back: { color: "black", size: 2 }, - bottom: { + bottom: { color: "black", size: 2 }, - side: { + side: { color: "black", size: 2 } @@ -309,7 +309,7 @@ function test_ChartOptions() { plotBackgroundImage: "http://image.url/image.jpg", plotBorderColor: "grey", plotBorderWidth: 5, - plotShadow: { + plotShadow: { color: "magenta", offsetX: 10, offsetY: 10, @@ -319,15 +319,15 @@ function test_ChartOptions() { polar: true, reflow: false, renderTo: "elementId", - resetZoomButton: { - position: { + resetZoomButton: { + position: { align: "left", verticalAlign: "top", x: 5, y: 5 }, relativeTo: "chart", - theme: { + theme: { display: "hidden", fill: "black", stroke: "white", @@ -394,7 +394,7 @@ function test_ChartOptions() { }); // animation example - $('#container').highcharts( { + $('#container').highcharts({ chart: { animation: { duration: 1500, @@ -479,7 +479,7 @@ function test_ChartOptions() { chart: { events: { addSeries() { - const label = ( this).renderer.label('A series was added, about to redraw chart', 100, 120) + const label = (this as Highcharts.ChartObject).renderer.label('A series was added, about to redraw chart', 100, 120) .attr({ fill: Highcharts.getOptions().colors[0], padding: 10, @@ -729,21 +729,21 @@ function test_Data() { } }, series: [ - { + { lineWidth: 1 }, - { + { type: 'areaspline', color: '#c4392d', negativeColor: '#5679c4', fillOpacity: 0.5 - } + } as Highcharts.AreaSplineChartSeriesOptions ] }); // limited data example $('#container').highcharts({ - data: { + data: { csv: document.getElementById('csv').innerHTML, startRow: 114, endRow: 134, @@ -753,7 +753,7 @@ function test_Data() { xAxis: { allowDecimals: false }, - series: [ { + series: [{ name: 'Annual mean' }] }); @@ -784,14 +784,14 @@ function test_Drilldown() { type: 'category' }, plotOptions: { - series: { + series: { borderWidth: 0, dataLabels: { enabled: true } - } + } as Highcharts.ColumnChart }, - series: [ { + series: [{ name: '2010', data: [{ name: 'Republican', @@ -806,7 +806,7 @@ function test_Drilldown() { y: 4, drilldown: 'other-2010' }] - }, { + }, { name: '2014', data: [{ name: 'Republican', @@ -823,7 +823,7 @@ function test_Drilldown() { }] }], drilldown: { - series: [ { + series: [{ id: 'republican-2010', data: [ ['East', 4], @@ -831,7 +831,7 @@ function test_Drilldown() { ['North', 1], ['South', 4] ] - }, { + }, { id: 'democrats-2010', data: [ ['East', 6], @@ -839,7 +839,7 @@ function test_Drilldown() { ['North', 2], ['South', 4] ] - }, { + }, { id: 'other-2010', data: [ ['East', 2], @@ -847,7 +847,7 @@ function test_Drilldown() { ['North', 3], ['South', 2] ] - }, { + }, { id: 'republican-2014', data: [ ['East', 2], @@ -855,7 +855,7 @@ function test_Drilldown() { ['North', 1], ['South', 7] ] - }, { + }, { id: 'democrats-2014', data: [ ['East', 4], @@ -863,7 +863,7 @@ function test_Drilldown() { ['North', 5], ['South', 3] ] - }, { + }, { id: 'other-2014', data: [ ['East', 7], @@ -881,14 +881,14 @@ function test_Drilldown() { type: 'column' }, plotOptions: { - series: { + series: { borderWidth: 0, dataLabels: { enabled: true } - } + } as Highcharts.ColumnChart }, - series: [ { + series: [{ name: 'Things', colorByPoint: true, data: [{ @@ -903,7 +903,7 @@ function test_Drilldown() { name: 'Cars', y: 4 }] - }], + } as Highcharts.ColumnChartSeriesOptions], drilldown: { activeAxisLabelStyle: { textDecoration: 'none', @@ -976,7 +976,7 @@ function test_Exporting() { series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }], - exporting: { + exporting: { error: () => { console.log('succesfully asserted exporting.error'); }, @@ -987,7 +987,7 @@ function test_Exporting() { chartOptions: { subtitle: null } - } + } as Highcharts.ExportingOptions }); } @@ -1113,12 +1113,12 @@ function test_AreaOptions() { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, plotOptions: { - series: { + series: { fillColor: { linearGradient: [0, 0, 0, 300], stops: [ [0, Highcharts.getOptions().colors[0]], - [1, ( Highcharts.Color(Highcharts.getOptions().colors[0])).setOpacity(0).get('rgba')] + [1, ((Highcharts.Color(Highcharts.getOptions().colors[0])) as Highcharts.Gradient).setOpacity(0).get('rgba')] ] }, fillOpacity: 0.1, @@ -1129,7 +1129,7 @@ function test_AreaOptions() { threshold: 100, trackByArea: true, stickyTracking: false // to show the difference in tracking - } + } as Highcharts.AreaChartSeriesOptions }, series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] @@ -1146,7 +1146,7 @@ function test_AreaRange() { type: "arearange", zoomType: 'x' }, - series: [ { + series: [{ data: (((arr: number[], len: number) => { for (let i = 0; i < len; i = i + 1) { arr.push(i); @@ -1191,7 +1191,7 @@ function test_AreaRange() { legend: { enabled: false }, - series: [ { + series: [{ name: 'Temperatures', data, dataLabels: { @@ -1199,7 +1199,7 @@ function test_AreaRange() { yHigh: 20, yLow: -20 } - }] + } as Highcharts.AreaRangeChartSeriesOptions] }); }); } @@ -1215,7 +1215,7 @@ function test_Bar() { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, plotOptions: { - series: { + series: { borderColor: '#303030', borderRadius: 5, borderWidth: 2, @@ -1240,7 +1240,7 @@ function test_Bar() { } } } - } + } as Highcharts.BarChartSeriesOptions }, series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] @@ -1274,7 +1274,7 @@ function test_Bar() { // grouping example Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, (color: string) => { - return ( Highcharts.Color(color)) + return (Highcharts.Color(color) as Highcharts.Gradient) .setOpacity(0.5) .get('rgba'); }); @@ -1309,19 +1309,19 @@ function test_Bar() { shadow: false } }, - series: [ { + series: [{ name: 'Tokyo', data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], pointPadding: 0 - }, { + } as Highcharts.BarChartSeriesOptions, { name: 'New York', data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3], pointPadding: 0.1 - }, { + }, { name: 'London', data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2], pointPadding: 0.2 - }, { + }, { name: 'Berlin', data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1], pointPadding: 0.3 @@ -1407,7 +1407,7 @@ function test_Bubble() { maxSize: 50 } }, - series: [ { + series: [{ data: [ [9, 81, 13], [98, 5, 39], @@ -1430,7 +1430,7 @@ function test_Bubble() { zMin: 0, zMax: 100, zThreshold: 0 - }] + } as Highcharts.BubbleChartSeriesOptions] }); // size by absolute value example @@ -1444,7 +1444,7 @@ function test_Bubble() { subtitle: { text: 'Size is computed by absolute value on negative bubbles' }, - series: [ { + series: [{ data: [ [-5, 0, -5], [-4, 0, -4], @@ -1460,7 +1460,7 @@ function test_Bubble() { ], sizeByAbsoluteValues: true, negativeColor: '#FF0000' - }] + } as Highcharts.BubbleChartSeriesOptions] }); } @@ -1479,7 +1479,7 @@ function test_ColumnCrispFalse() { } return arr; }; - const chart = new Highcharts.Chart( { + const chart = new Highcharts.Chart({ title: { text: 'Crisp columns are disabled' }, @@ -1527,7 +1527,7 @@ function test_ErrorBar() { tooltip: { shared: true }, - series: [ { + series: [{ name: 'Temperature', type: 'spline', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6], @@ -1537,7 +1537,7 @@ function test_ErrorBar() { tooltip: { pointFormat: ' {series.name} : {point.y:.1f}°C
' } - }, { + } as Highcharts.SplineChartSeriesOptions, { color: '#FF0000', name: 'Temperature error', type: 'errorbar', @@ -1549,7 +1549,7 @@ function test_ErrorBar() { stemDashStyle: "Solid", stemWidth: 3, whiskerLength: 0 - }] + } as Highcharts.ErrorBarChartSeriesOptions] }); } @@ -1568,7 +1568,7 @@ function test_FindNearestPointBy() { } }, - series: [ { + series: [{ findNearestPointBy: 'x', // Hover at [3.5, 6] to demo x-dimension search // Compare to Series 2 behavior at [5.5, 3] @@ -1584,7 +1584,7 @@ function test_FindNearestPointBy() { [6, 6], [7, 6] ] - }, { + } as Highcharts.IndividualSeriesOptions, { findNearestPointBy: 'xy', // Hover at [1, 4] to demo xy-dimension search. // Useful when having multiple points on the same x-value. @@ -1600,7 +1600,7 @@ function test_FindNearestPointBy() { [6, 3], [7, 3] ] - }] + } as Highcharts.IndividualSeriesOptions] }); } @@ -1618,7 +1618,7 @@ function test_Funnel() { x: -50 }, plotOptions: { - series: { + series: { dataLabels: { enabled: true, format: ' {point.name} ({point.y:,.0f})', @@ -1630,7 +1630,7 @@ function test_Funnel() { reversed: false, height: "10%", width: 100 - } + } as Highcharts.FunnelChartSeriesOptions }, legend: { enabled: false @@ -1701,10 +1701,10 @@ function test_Gauge() { } } }, - series: [ { + series: [{ data: [80], overshoot: 5 - }] + } as Highcharts.GaugeChartSeriesOptions] }); } @@ -1757,14 +1757,14 @@ function test_HeatMap() { ], min: -5 }, - series: [ { + series: [{ borderWidth: 0, colsize: 24 * 36e5, // one day tooltip: { headerFormat: 'Temperature
', pointFormat: '{point.x:%e %b, %Y} {point.y}:00: {point.value} ℃ ' } - }] + } as Highcharts.HeatMapSeriesOptions] }); } @@ -1779,17 +1779,17 @@ function test_Line() { xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, - series: [ { + series: [{ data: [1, 2, 3, 4, null, 6, 7, null, 9], step: 'right', name: 'Right', linecap: 'round' - }, { + } as Highcharts.LineChartSeriesOptions, { data: [5, 6, 7, 8, null, 10, 11, null, 13], step: 'center', name: 'Center', linecap: 'round' - }, { + }, { data: [9, 10, 11, 12, null, 14, 15, null, 17], step: 'left', name: 'Left', @@ -1829,7 +1829,7 @@ function test_Pie() { } } }, - series: [ { + series: [{ name: "Brands", colorByPoint: true, data: [{ @@ -1853,7 +1853,7 @@ function test_Pie() { name: "Proprietary or Undetectable", y: 0.2 }] - }] + } as Highcharts.PieChartSeriesOptions] }); // semi circle @@ -1888,7 +1888,7 @@ function test_Pie() { center: ['50%', '75%'] } }, - series: [ { + series: [{ type: 'pie', name: 'Browser share', innerSize: '50%', @@ -2161,10 +2161,10 @@ function test_Waterfall() { } function test_AccessibilityOptions() { - const accessibilityOptions: Highcharts.AccessibilityOptions = { + const accessibilityOptions: Highcharts.AccessibilityOptions = { describeSingleSeries: true, enabled: true, - keyboardNavigation: { + keyboardNavigation: { enabled: true, skipNullPoints: true }, @@ -2177,7 +2177,7 @@ function test_AccessibilityOptions() { seriesDescriptionFormatter: () => { } }; - const chart = new Highcharts.Chart( { + const chart = new Highcharts.Chart({ accessibility: accessibilityOptions }); } @@ -2435,31 +2435,31 @@ function test_AxisObject() { axis.toPixels(10, true); axis.toValue(10); axis.toValue(10, true); - axis.update( {}); - axis.update( {}, true); + axis.update({}); + axis.update({}, true); } function test_ChartObject() { const chart = $("#container").highcharts(); - chart.addAxis( {}); - chart.addAxis( {}, true); - chart.addAxis( {}, true, false); - chart.addAxis( {}, true, true, false); - chart.addAxis( {}, true, true, { duration: 50 }); - chart.addSeries( {}); - chart.addSeries( {}, false); - chart.addSeries( {}, false, false); - chart.addSeries( {}, false, { duration: 50 }); - chart.addSeriesAsDrilldown( {}, {}); + chart.addAxis({}); + chart.addAxis({}, true); + chart.addAxis({}, true, false); + chart.addAxis({}, true, true, false); + chart.addAxis({}, true, true, { duration: 50 }); + chart.addSeries({}); + chart.addSeries({}, false); + chart.addSeries({}, false, false); + chart.addSeries({}, false, { duration: 50 }); + chart.addSeriesAsDrilldown({} as Highcharts.PointObject, {}); const container = chart.container; console.log(container.id); chart.destroy(); chart.drillUp(); - chart.exportChart( {}, {}); - chart.exportChartLocal( {}, {}); + chart.exportChart({}, {}); + chart.exportChartLocal({}, {}); const object = chart.get('axisIdOrSeriesIdOrPointId'); const svg1 = chart.getSVG(); - const svg2 = chart.getSVG( {}); + const svg2 = chart.getSVG({}); const selectedPoints = chart.getSelectedPoints(); const selectedSeries = chart.getSelectedSeries(); chart.hideLoading(); @@ -2480,11 +2480,11 @@ function test_ChartObject() { const firstXAxis = chart.xAxis[0]; const firstYAxis = chart.yAxis[0]; const legend = chart.legend; - chart.update( {}); - chart.update( {}, true); - chart.update( {}, true, true); - chart.update( {}, true, true, true); - chart.update( {}, true, true, { + chart.update({}); + chart.update({}, true); + chart.update({}, true, true); + chart.update({}, true, true, true); + chart.update({}, true, true, { duration: 3000, }); } @@ -2564,7 +2564,7 @@ function test_NumericSymbolMagnitude() { } function test_PaneBackground() { - const pane = { + const pane = { backgroundColor: 'blue', borderColor: 'white', borderWidth: 5, @@ -2576,7 +2576,7 @@ function test_PaneBackground() { } function test_PointObject() { - const point = $('#container').highcharts().get('point1'); + const point = $('#container').highcharts().get('point1') as Highcharts.PointObject; const category = point.category; const percentage = point.percentage; point.index; @@ -2608,7 +2608,7 @@ function test_RendererObject() { const renderer = $('#container').highcharts().renderer; renderer.arc(0, 0, 20, 10, 0, Math.PI); renderer.circle(0, 0, 100); - renderer.definition( {}); + renderer.definition({}); renderer.g('groupName'); renderer.image('http://source', 20, 20, 100, 100); renderer.label('Label', 200, 100, 'rect', 0, 0, false, false, 'class'); @@ -2618,15 +2618,15 @@ function test_RendererObject() { } function test_ResponsiveOptions() { - const responsiveOptions: Highcharts.ResponsiveOptions = { + const responsiveOptions: Highcharts.ResponsiveOptions = { rules: [ - { - chartOptions: { + { + chartOptions: { chart: { description: 'just a test' } }, - condition: { + condition: { callback: () => { }, maxHeight: 420, maxWidth: 420, @@ -2637,13 +2637,13 @@ function test_ResponsiveOptions() { ] }; - const chart = new Highcharts.Chart( { + const chart = new Highcharts.Chart({ responsive: responsiveOptions }); } function test_SeriesObject() { - const series = $('#container').highcharts().get('series1'); + const series = $('#container').highcharts().get('series1') as Highcharts.SeriesObject; series.addPoint(0); series.addPoint([0, 0]); series.addPoint({}); diff --git a/types/highcharts/tslint.json b/types/highcharts/tslint.json index cfc8218eab..113c45ef94 100644 --- a/types/highcharts/tslint.json +++ b/types/highcharts/tslint.json @@ -3,12 +3,11 @@ "rules": { // TODOs "ban-types": false, - "unified-signatures": false, "no-empty-interface": false, - "dt-header": false, "no-declare-current-package": false, "no-object-literal-type-assertion": false, "no-self-import": false, - "no-unnecessary-generics": false + "no-unnecessary-generics": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/html-webpack-plugin/html-webpack-plugin-tests.ts b/types/html-webpack-plugin/html-webpack-plugin-tests.ts index 461e43c2af..7abb6a4ed6 100644 --- a/types/html-webpack-plugin/html-webpack-plugin-tests.ts +++ b/types/html-webpack-plugin/html-webpack-plugin-tests.ts @@ -103,7 +103,7 @@ const plugins: HtmlWebpackPlugin[] = optionsArray.map(options => new HtmlWebpack // Webpack plugin `apply` function function apply(compiler: Compiler) { compiler.hooks.compilation.tap('SomeWebpackPlugin', (compilation: compilation.Compilation) => { - ( compilation.hooks).htmlWebpackPluginAfterHtmlProcessing.tap( + (compilation.hooks as HtmlWebpackPlugin.Hooks).htmlWebpackPluginAfterHtmlProcessing.tap( 'MyPlugin', (data) => { data.html += 'The Magic Footer'; diff --git a/types/http-assert/http-assert-tests.ts b/types/http-assert/http-assert-tests.ts index a0e159aeed..b2cc7ae301 100644 --- a/types/http-assert/http-assert-tests.ts +++ b/types/http-assert/http-assert-tests.ts @@ -5,7 +5,7 @@ try { httpAssert.equal('hello', 'hello'); httpAssert(false, 401, 'authentication failed'); } catch (err) { - console.log(( err).status); - console.log(( err).message); - console.log(( err).expose); + console.log((err as HttpError).status); + console.log((err as HttpError).message); + console.log((err as HttpError).expose); } diff --git a/types/humanize-url/humanize-url-tests.ts b/types/humanize-url/humanize-url-tests.ts new file mode 100644 index 0000000000..7556cfb1c4 --- /dev/null +++ b/types/humanize-url/humanize-url-tests.ts @@ -0,0 +1,4 @@ +import humanizeUrl = require('humanize-url'); + +// $ExpectType string +humanizeUrl('https://www.sindresorhus.com/'); diff --git a/types/humanize-url/index.d.ts b/types/humanize-url/index.d.ts new file mode 100644 index 0000000000..c00f5c982f --- /dev/null +++ b/types/humanize-url/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for humanize-url 2.0 +// Project: https://github.com/sindresorhus/humanize-url#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = humanizeUrl; + +declare function humanizeUrl(url: string): string; diff --git a/types/humanize-url/tsconfig.json b/types/humanize-url/tsconfig.json new file mode 100644 index 0000000000..dd9fec46b6 --- /dev/null +++ b/types/humanize-url/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "humanize-url-tests.ts" + ] +} diff --git a/types/humanize-url/tslint.json b/types/humanize-url/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/humanize-url/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hyper-aws4/hyper-aws4-tests.ts b/types/hyper-aws4/hyper-aws4-tests.ts new file mode 100644 index 0000000000..14caa34a9f --- /dev/null +++ b/types/hyper-aws4/hyper-aws4-tests.ts @@ -0,0 +1,12 @@ +import { sign, Request } from "hyper-aws4"; + +const signOption: Request = { + url: "https://us-west-1.hyper.sh/version", + method: "GET", + credential: { + accessKey: "6DPLADBPWYXDUVXLX34EJXBL", + secretKey: "2ldD1Yz0nzATl9vvagBwYTjglXBjVOWU8gV8aMm5" + } +}; + +sign(signOption); diff --git a/types/hyper-aws4/index.d.ts b/types/hyper-aws4/index.d.ts new file mode 100644 index 0000000000..bf2a0fafa8 --- /dev/null +++ b/types/hyper-aws4/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for hyper-aws4 1.1 +// Project: https://github.com/Tim-Zhang/hyper-aws4#readme +// Definitions by: BamButz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Credentials { + accessKey: string; + secretKey: string; +} + +export interface Header { + [header: string]: string; +} + +export type HttpMethods = "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; + +export interface Request { + url: string; + method?: HttpMethods; + body?: string; + headers?: Header; + credential?: Credentials; +} + +export function sign(request: Request, credential?: Credentials): Header; diff --git a/types/hyper-aws4/tsconfig.json b/types/hyper-aws4/tsconfig.json new file mode 100644 index 0000000000..6df2d811c1 --- /dev/null +++ b/types/hyper-aws4/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "hyper-aws4-tests.ts" + ] +} diff --git a/types/hyper-aws4/tslint.json b/types/hyper-aws4/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hyper-aws4/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index 84433c26ec..d2e0b4ee6b 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for i18next 11.9 +// Type definitions for i18next 12.1 // Project: http://i18next.com // Definitions by: Michael Ledin // Budi Irawan @@ -160,6 +160,12 @@ declare namespace i18next { */ resources?: Resource; + /** + * Allow initializing with bundled resources while using a backend to load non bundled ones. + * @default false + */ + partialBundledLanguages?: boolean; + /** * language to use (overrides language detection) * @default undefined diff --git a/types/iframe-resizer/iframe-resizer-tests.ts b/types/iframe-resizer/iframe-resizer-tests.ts index 218a7f71cd..2f459c16a7 100644 --- a/types/iframe-resizer/iframe-resizer-tests.ts +++ b/types/iframe-resizer/iframe-resizer-tests.ts @@ -1,9 +1,9 @@ -import { IFrameComponent, IFrameOptions, iframeResizer } from "iframe-resizer"; +import iframeResizer = require("iframe-resizer"); function testOne(): void { const iframe: HTMLIFrameElement = document.createElement('iframe'); - const options: IFrameOptions = {log: true}; - const components: IFrameComponent[] = iframeResizer(options, iframe); + const options: iframeResizer.IFrameOptions = {log: true}; + const components: iframeResizer.IFrameComponent[] = iframeResizer(options, iframe); if (components) { components.forEach(component => console.log(component.iFrameResizer)); } else { @@ -13,7 +13,7 @@ function testOne(): void { function testTwo(): void { const iframe: HTMLIFrameElement = document.createElement('iframe'); - const components: IFrameComponent[] = iframeResizer({ + const components: iframeResizer.IFrameComponent[] = iframeResizer({ initCallback: () => { console.log('Init'); }, diff --git a/types/iframe-resizer/index.d.ts b/types/iframe-resizer/index.d.ts index 6e67a5b592..5f3cb19c7d 100644 --- a/types/iframe-resizer/index.d.ts +++ b/types/iframe-resizer/index.d.ts @@ -3,275 +3,315 @@ // Definitions by: Armin Baljic // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// tslint:disable-next-line:interface-name -export interface IFrameObject { - close(): void; - moveToAnchor(anchor: string): void; - resize(): void; - sendMessage(message: any, targetOrigin?: string): void; +declare namespace iframeResizer { + // tslint:disable-next-line:interface-name + interface IFrameObject { + close(): void; + + moveToAnchor(anchor: string): void; + + resize(): void; + + sendMessage( + message: any, + targetOrigin?: string + ): void; + } + + // tslint:disable-next-line:interface-name + interface IFrameComponent extends HTMLIFrameElement { + iFrameResizer: IFrameObject; + } + + // tslint:disable-next-line:interface-name + interface IFrameOptions { + /** + * When enabled changes to the Window size or the DOM will cause the iFrame to resize to the new content size. + * Disable if using size method with custom dimensions. + */ + autoResize?: boolean; + /** + * Override the body background style in the iFrame. + */ + bodyBackground?: string; + /** + * Override the default body margin style in the iFrame. A string can be any valid value for the + * CSS margin attribute, for example '8px 3em'. A number value is converted into px. + */ + bodyMargin?: number | string; + /** + * Override the default body padding style in the iFrame. A string can be any valid value for the + * CSS margin attribute, for example '8px 3em'. A number value is converted into px. + */ + bodyPadding?: number | string; + /** + * When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag. + * If your iFrame navigates between different domains, ports or protocols; then you will need to + * provide an array of URLs or disable this option. + */ + checkOrigin?: boolean | string[]; + /** + * When enabled in page linking inside the iFrame and from the iFrame to the parent page will be enabled. + */ + inPageLinks?: boolean; + /** + * Height calculation method. + */ + heightCalculationMethod?: HeightCalculationMethod; + /** + * Set iFrame Id + */ + id?: string; + /** + * In browsers that don't support mutationObserver, such as IE10, the library falls back to using + * setInterval, to check for changes to the page size. + */ + interval?: number; + /** + * Setting the log option to true will make the scripts in both the host page and the iFrame output + * everything they do to the JavaScript console so you can see the communication between the two scripts. + */ + log?: boolean; + /** + * Set maximum height of iFrame. + */ + maxHeight?: number; + /** + * Set maximum width of iFrame. + */ + maxWidth?: number; + /** + * Set minimum height of iFrame. + */ + minHeight?: number; + /** + * Set minimum width of iFrame. + */ + minWidth?: number; + /** + * Listen for resize events from the parent page, or the iFrame. Select the 'child' value if the iFrame + * can be resized independently of the browser window. Selecting this value can cause issues with some + * height calculation methods on mobile devices. + */ + resizeFrom?: 'parent' | 'child'; + /** + * Enable scroll bars in iFrame. + */ + scrolling?: boolean | 'auto'; + /** + * Resize iFrame to content height. + */ + sizeHeight?: boolean; + /** + * Resize iFrame to content width. + */ + sizeWidth?: boolean; + /** + * Set the number of pixels the iFrame content size has to change by, before triggering a resize of the iFrame. + */ + tolerance?: number; + /** + * Width calculation method. + */ + widthCalculationMethod?: WidthCalculationMethod; + + /** + * Called when iFrame is closed via parentIFrame.close() or iframe.iframeResizer.close() methods. + */ + closedCallback?(iframeId: string): void; + + /** + * Initial setup callback function. + */ + initCallback?(iframe: IFrameComponent): void; + + /** + * Receive message posted from iFrame with the parentIFrame.sendMessage() method. + */ + messageCallback?(data: IFrameMessageData): void; + + /** + * Function called after iFrame resized. Passes in messageData object containing the iFrame, height, width + * and the type of event that triggered the iFrame to resize. + */ + resizedCallback?(data: IFrameResizedData): void; + + /** + * Called before the page is repositioned after a request from the iFrame, due to either an in page link, + * or a direct request from either parentIFrame.scrollTo() or parentIFrame.scrollToOffset(). + * If this callback function returns false, it will stop the library from repositioning the page, so that + * you can implement your own animated page scrolling instead. + */ + scrollCallback?(data: IFrameScrollData): boolean; + } + + // tslint:disable-next-line:interface-name + interface IFramePageOptions { + /** + * This option allows you to restrict the domain of the parent page, + * to prevent other sites mimicking your parent page. + */ + targetOrigin?: string; + + /** + * Receive message posted from the parent page with the iframe.iFrameResizer.sendMessage() method. + */ + messageCallback?(message: any): void; + + /** + * This function is called once iFrame-Resizer has been initialized after receiving a call from the parent page. + */ + readyCallback?(): void; + + /** + * These option can be used to override the option set in the parent page + */ + heightCalculationMethod?: HeightCalculationMethod | (() => number); + /** + * These option can be used to override the option set in the parent page + */ + widthCalculationMethod?: WidthCalculationMethod | (() => number); + } + + type HeightCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | + 'max' | 'min' | 'grow' | 'lowestElement' | 'taggedElement'; + + type WidthCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | + 'max' | 'min' | 'scroll' | 'rightMostElement' | 'taggedElement'; + + // tslint:disable-next-line:interface-name + interface IFramePage { + /** + * Turn autoResizing of the iFrame on and off. Returns bool of current state. + */ + autoResize(resize?: boolean): boolean; + + /** + * Remove the iFrame from the parent page. + */ + close(): void; + + /** + * Returns the ID of the iFrame that the page is contained in. + */ + getId(): string; + + /** + * Ask the containing page for its positioning coordinates. + * + * Your callback function will be recalled when the parent page is scrolled or resized. + * + * Pass false to disable the callback. + */ + getPageInfo(callback: ((data: PageInfo) => void) | false): void; + + /** + * Scroll the parent page to the coordinates x and y + */ + scrollTo( + x: number, + y: number + ): void; + + /** + * Scroll the parent page to the coordinates x and y relative to the position of the iFrame. + */ + scrollToOffset( + x: number, + y: number + ): void; + + /** + * Send data to the containing page, message can be any data type that can be serialized into JSON. The `targetOrigin` + * option is used to restrict where the message is sent to; to stop an attacker mimicking your parent page. + * See the MDN documentation on postMessage for more details. + */ + sendMessage( + message: any, + targetOrigin?: string + ): void; + + /** + * Change the method use to workout the height of the iFrame. + */ + setHeightCalculationMethod(method: HeightCalculationMethod): void; + + /** + * Change the method use to workout the width of the iFrame. + */ + setWidthCalculationMethod(method: WidthCalculationMethod): void; + + /** + * Set default target origin. + */ + setTargetOrigin(targetOrigin: string): void; + + /** + * Manually force iFrame to resize. To use passed arguments you need first to disable the `autoResize` option to + * prevent auto resizing and enable the `sizeWidth` option if you wish to set the width. + */ + size( + customHeight?: string, + customWidth?: string + ): void; + } + + interface PageInfo { + /** + * The height of the iframe in pixels + */ + iframeHeight: number; + /** + * The width of the iframe in pixels + */ + iframeWidth: number; + /** + * The height of the viewport in pixels + */ + clientHeight: number; + /** + * The width of the viewport in pixels + */ + clientWidth: number; + /** + * The number of pixels between the left edge of the containing page and the left edge of the iframe + */ + offsetLeft: number; + /** + * The number of pixels between the top edge of the containing page and the top edge of the iframe + */ + offsetTop: number; + /** + * The number of pixels between the left edge of the iframe and the left edge of the iframe viewport + */ + scrollLeft: number; + /** + * The number of pixels between the top edge of the iframe and the top edge of the iframe viewport + */ + scrollTop: number; + } + + // tslint:disable-next-line:interface-name + interface IFrameResizedData { + iframe: IFrameComponent; + height: number; + width: number; + type: string; + } + + // tslint:disable-next-line:interface-name + interface IFrameMessageData { + iframe: IFrameComponent; + message: any; + } + + // tslint:disable-next-line:interface-name + interface IFrameScrollData { + x: number; + y: number; + } } -// tslint:disable-next-line:interface-name -export interface IFrameComponent extends HTMLIFrameElement { - iFrameResizer: IFrameObject; -} - -// tslint:disable-next-line:interface-name -export interface IFrameOptions { - /** - * When enabled changes to the Window size or the DOM will cause the iFrame to resize to the new content size. - * Disable if using size method with custom dimensions. - */ - autoResize?: boolean; - /** - * Override the body background style in the iFrame. - */ - bodyBackground?: string; - /** - * Override the default body margin style in the iFrame. A string can be any valid value for the - * CSS margin attribute, for example '8px 3em'. A number value is converted into px. - */ - bodyMargin?: number | string; - /** - * Override the default body padding style in the iFrame. A string can be any valid value for the - * CSS margin attribute, for example '8px 3em'. A number value is converted into px. - */ - bodyPadding?: number | string; - /** - * When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag. - * If your iFrame navigates between different domains, ports or protocols; then you will need to - * provide an array of URLs or disable this option. - */ - checkOrigin?: boolean | string[]; - /** - * When enabled in page linking inside the iFrame and from the iFrame to the parent page will be enabled. - */ - inPageLinks?: boolean; - /** - * Height calculation method. - */ - heightCalculationMethod?: HeightCalculationMethod; - /** - * Set iFrame Id - */ - id?: string; - /** - * In browsers that don't support mutationObserver, such as IE10, the library falls back to using - * setInterval, to check for changes to the page size. - */ - interval?: number; - /** - * Setting the log option to true will make the scripts in both the host page and the iFrame output - * everything they do to the JavaScript console so you can see the communication between the two scripts. - */ - log?: boolean; - /** - * Set maximum height of iFrame. - */ - maxHeight?: number; - /** - * Set maximum width of iFrame. - */ - maxWidth?: number; - /** - * Set minimum height of iFrame. - */ - minHeight?: number; - /** - * Set minimum width of iFrame. - */ - minWidth?: number; - /** - * Listen for resize events from the parent page, or the iFrame. Select the 'child' value if the iFrame - * can be resized independently of the browser window. Selecting this value can cause issues with some - * height calculation methods on mobile devices. - */ - resizeFrom?: 'parent' | 'child'; - /** - * Enable scroll bars in iFrame. - */ - scrolling?: boolean | 'auto'; - /** - * Resize iFrame to content height. - */ - sizeHeight?: boolean; - /** - * Resize iFrame to content width. - */ - sizeWidth?: boolean; - /** - * Set the number of pixels the iFrame content size has to change by, before triggering a resize of the iFrame. - */ - tolerance?: number; - /** - * Width calculation method. - */ - widthCalculationMethod?: WidthCalculationMethod; - /** - * Called when iFrame is closed via parentIFrame.close() or iframe.iframeResizer.close() methods. - */ - closedCallback?(iframeId: string): void; - /** - * Initial setup callback function. - */ - initCallback?(iframe: IFrameComponent): void; - /** - * Receive message posted from iFrame with the parentIFrame.sendMessage() method. - */ - messageCallback?(data: IFrameMessageData): void; - /** - * Function called after iFrame resized. Passes in messageData object containing the iFrame, height, width - * and the type of event that triggered the iFrame to resize. - */ - resizedCallback?(data: IFrameResizedData): void; - /** - * Called before the page is repositioned after a request from the iFrame, due to either an in page link, - * or a direct request from either parentIFrame.scrollTo() or parentIFrame.scrollToOffset(). - * If this callback function returns false, it will stop the library from repositioning the page, so that - * you can implement your own animated page scrolling instead. - */ - scrollCallback?(data: IFrameScrollData): boolean; -} - -// tslint:disable-next-line:interface-name -export interface IFramePageOptions { - /** - * This option allows you to restrict the domain of the parent page, - * to prevent other sites mimicking your parent page. - */ - targetOrigin?: string; - /** - * Receive message posted from the parent page with the iframe.iFrameResizer.sendMessage() method. - */ - messageCallback?(message: any): void; - /** - * This function is called once iFrame-Resizer has been initialized after receiving a call from the parent page. - */ - readyCallback?(): void; - /** - * These option can be used to override the option set in the parent page - */ - heightCalculationMethod?: HeightCalculationMethod | (() => number); - /** - * These option can be used to override the option set in the parent page - */ - widthCalculationMethod?: WidthCalculationMethod | (() => number); -} - -export type HeightCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | - 'max' | 'min' | 'grow' | 'lowestElement' | 'taggedElement'; - - export type WidthCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | - 'max' | 'min' | 'scroll' | 'rightMostElement' | 'taggedElement'; - -// tslint:disable-next-line:interface-name -export interface IFramePage { - /** - * Turn autoResizing of the iFrame on and off. Returns bool of current state. - */ - autoResize(resize?: boolean): boolean; - /** - * Remove the iFrame from the parent page. - */ - close(): void; - /** - * Returns the ID of the iFrame that the page is contained in. - */ - getId(): string; - /** - * Ask the containing page for its positioning coordinates. - * - * Your callback function will be recalled when the parent page is scrolled or resized. - * - * Pass false to disable the callback. - */ - getPageInfo(callback: ((data: PageInfo) => void) | false): void; - /** - * Scroll the parent page to the coordinates x and y - */ - scrollTo(x: number, y: number): void; - /** - * Scroll the parent page to the coordinates x and y relative to the position of the iFrame. - */ - scrollToOffset(x: number, y: number): void; - /** - * Send data to the containing page, message can be any data type that can be serialized into JSON. The `targetOrigin` - * option is used to restrict where the message is sent to; to stop an attacker mimicking your parent page. - * See the MDN documentation on postMessage for more details. - */ - sendMessage(message: any, targetOrigin?: string): void; - /** - * Change the method use to workout the height of the iFrame. - */ - setHeightCalculationMethod(method: HeightCalculationMethod): void; - /** - * Change the method use to workout the width of the iFrame. - */ - setWidthCalculationMethod(method: WidthCalculationMethod): void; - /** - * Set default target origin. - */ - setTargetOrigin(targetOrigin: string): void; - /** - * Manually force iFrame to resize. To use passed arguments you need first to disable the `autoResize` option to - * prevent auto resizing and enable the `sizeWidth` option if you wish to set the width. - */ - size(customHeight?: string, customWidth?: string): void; -} - -export interface PageInfo { - /** - * The height of the iframe in pixels - */ - iframeHeight: number; - /** - * The width of the iframe in pixels - */ - iframeWidth: number; - /** - * The height of the viewport in pixels - */ - clientHeight: number; - /** - * The width of the viewport in pixels - */ - clientWidth: number; - /** - * The number of pixels between the left edge of the containing page and the left edge of the iframe - */ - offsetLeft: number; - /** - * The number of pixels between the top edge of the containing page and the top edge of the iframe - */ - offsetTop: number; - /** - * The number of pixels between the left edge of the iframe and the left edge of the iframe viewport - */ - scrollLeft: number; - /** - * The number of pixels between the top edge of the iframe and the top edge of the iframe viewport - */ - scrollTop: number; -} - -// tslint:disable-next-line:interface-name -export interface IFrameResizedData { - iframe: IFrameComponent; - height: number; - width: number; - type: string; -} - -// tslint:disable-next-line:interface-name -export interface IFrameMessageData { - iframe: IFrameComponent; - message: any; -} - -// tslint:disable-next-line:interface-name -export interface IFrameScrollData { - x: number; - y: number; -} - -export function iframeResizer(options: IFrameOptions, target: string | HTMLElement): IFrameComponent[]; +declare function iframeResizer(options: iframeResizer.IFrameOptions, target: string | HTMLElement): iframeResizer.IFrameComponent[]; +export = iframeResizer; +export as namespace iframeResizer; diff --git a/types/imap-simple/index.d.ts b/types/imap-simple/index.d.ts index 3bde57c113..398bcb6a26 100644 --- a/types/imap-simple/index.d.ts +++ b/types/imap-simple/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for imap-simple v3.1.0 +// Type definitions for imap-simple v4.2.0 // Project: https://github.com/chadxz/imap-simple // Definitions by: Jeffery Grajkowski +// Ilari Aarnio // Definitions: https://github.com/psnider/DefinitelyTyped/imap-simple /// @@ -42,6 +43,18 @@ export class ImapSimple extends NodeJS.EventEmitter { openBox(boxName: string, callback: (err: Error, boxName: string) => void): void; openBox(boxName: string): Promise; + /** Create a mailbox, calling the provided callback with signature (err, boxName), or resolves the returned promise with boxName. */ + addBox(boxName: string, callback: (err: Error, boxName: string) => void): void; + addBox(boxName: string): Promise; + + /** Delete a mailbox, calling the provided callback with signature (err, boxName), or resolves the returned promise with boxName. */ + delBox(boxName: string, callback: (err: Error, boxName: string) => void): void; + delBox(boxName: string): Promise; + + /** Returns the full list of mailboxes (folders). Upon success, either the provided callback will be called with signature (err, boxes), or the returned promise will be resolved with boxes. Boxes is the exact object returned from the node-imap getBoxes() result. */ + getBoxes(callback: (err: Error, boxes: Imap.MailBoxes) => void): void; + getBoxes(): Promise; + /** Search for and retrieve mail in the previously opened mailbox. */ search(searchCriteria: any[], fetchOptions: Imap.FetchOptions, callback: (err: Error, messages: Message[]) => void): void; search(searchCriteria: any[], fetchOptions: Imap.FetchOptions): Promise; @@ -57,6 +70,10 @@ export class ImapSimple extends NodeJS.EventEmitter { addMessageLabel(source: string | string[], label: string | string[], callback: (err: Error) => void): void; addMessageLabel(source: string | string[], label: string | string[]): Promise; + /** Appends the argument message to the currently open mailbox or another mailbox. Message is a RFC-822 compatible MIME message. Valid options are mailbox, flags and date. When completed, either calls the provided callback with signature (err), or resolves the returned promise. */ + append(message: any, options: Imap.AppendOptions, callback: (err: Error) => void): void; + append(message: any, options: Imap.AppendOptions): Promise; + /** Moves the specified message(s) in the currently open mailbox to another mailbox. source corresponds to a node-imap MessageSource which specifies the messages to be moved. When completed, either calls the provided callback with signature (err), or resolves the returned promise. */ moveMessage(source: string | string[], boxName: string, callback: (err: Error) => void): void; moveMessage(source: string | string[], boxName: string): Promise; @@ -66,8 +83,8 @@ export class ImapSimple extends NodeJS.EventEmitter { addFlags(source: string | string[], flag: string | string[]): Promise; /** Removes the provided flag(s) from the specified message(s). uid is the uid of the message you want to remove the flag from or an array of uids. flag is either a string or array of strings indicating the flags to remove. */ - delFlags(source: string | string[], flag: string | string[], callback: (err: Error) => void): void; - delFlags(source: string | string[], flag: string | string[]): Promise; + delFlags(uid: string | string[], flag: string | string[], callback: (err: Error) => void): void; + delFlags(uid: string | string[], flag: string | string[]): Promise; } export namespace errors { diff --git a/types/ini/index.d.ts b/types/ini/index.d.ts index f534ff1b8d..4efacfe182 100644 --- a/types/ini/index.d.ts +++ b/types/ini/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for ini v1.3.3 // Project: https://github.com/isaacs/ini // Definitions by: Marcin Porębski +// Chris Arnesen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface EncodeOptions { @@ -8,9 +9,13 @@ interface EncodeOptions { whitespace: boolean } -export function decode(inistring: string): any; -export function parse(initstring: string): any; -export function encode(object: any, options?: EncodeOptions): string; -export function stringify(object: any, options?: EncodeOptions): string; +export function decode(str: string): { + [key: string]: any; +}; +export function parse(str: string): { + [key: string]: any; +}; +export function encode(object: any, options?: EncodeOptions | string): string; +export function stringify(object: any, options?: EncodeOptions | string): string; export function safe(val: string): string; export function unsafe(val: string): string; diff --git a/types/intercom-client/Lead.d.ts b/types/intercom-client/Lead.d.ts new file mode 100644 index 0000000000..aa4e4a2cfa --- /dev/null +++ b/types/intercom-client/Lead.d.ts @@ -0,0 +1,49 @@ +import { Company } from "./Company"; +import { Avatar, LocationData, Segment, SocialProfile, Tag } from './User'; + +export type LeadIdentifier = { "id": string } | { "user_id": string }; + +export interface Lead { + "type": "contact", + readonly "id": string, + "user_id": string | null, + "email": string | null, + "phone": string | null, + "name": string | null, + readonly "updated_at": number, + "last_seen_ip": string | null, + "unsubscribed_from_emails": boolean, + "last_request_at": number | null, + readonly "created_at": number, + "user_agent_data": string | null, + "custom_attributes": { + [key: string]: any + }, + "avatar": Avatar, + "location_data": LocationData | {}, + "social_profiles": { + "type": "social_profile.list", + "social_profiles": SocialProfile[] + }, + "companies": { + "type": "company.list", + "companies": Company[] + }, + "segments": { + "type": "segment.list", + "segments": Segment[] + + }, + "tags": { + "type": "tag.list", + "tags": Tag[] + }, + "referrer": string | null, +} + +export interface List { + "type": "user.list", + "total_count": number, + "contacts": Lead[], + "pages": { "next"?: string, "page": number, "per_page": number, "total_pages": number } +} diff --git a/types/intercom-client/index.d.ts b/types/intercom-client/index.d.ts index b776165c55..8c81fd989c 100644 --- a/types/intercom-client/index.d.ts +++ b/types/intercom-client/index.d.ts @@ -6,6 +6,7 @@ /// import { List as UserList, User, UserIdentifier } from './User'; +import { List as LeadList, Lead, LeadIdentifier } from './Lead'; import { CompanyIdentifier, List as CompanyList, Company } from './Company'; import { TagIdentifier, List as TagList, Tag, TagOper } from './Tag'; import { List as EventList, Event, ListParam as EventListParam } from './Event'; @@ -33,6 +34,8 @@ export class Client { companies: Companies; tags: Tags; events: Events; + contacts: Leads; + leads: Leads; } export class ApiResponse extends IncomingMessage { @@ -51,17 +54,46 @@ export class Users { find(identifier: UserIdentifier): Promise>; find(identifier: UserIdentifier, cb: callback>): void; - list(): Promise>; - list(cb: callback>): void; + list(): Promise>; + list(cb: callback>): void; listBy(params: {tag_id?: string, segment_id?: string}): Promise>; listBy(params: {tag_id?: string, segment_id?: string}, cb: callback>): void; scroll: Scroll; - archive(): Promise; + archive(identifier: UserIdentifier): Promise>; + archive(identifier: UserIdentifier, cb: callback>): void; + + requestPermanentDeletion(id: string): Promise<{ id: number }>; + requestPermanentDeletion(id: string, cb: callback<{ id: number }>): void; + + requestPermanentDeletionByParams(identifier: UserIdentifier): Promise<{ id: number }>; + requestPermanentDeletionByParams(identifier: UserIdentifier, cb: callback<{ id: number }>): void; +} + +export class Leads { + create(lead: Partial): Promise>; + create(lead: Partial, cb: callback>): void; + + update(lead: UserIdentifier & Partial): Promise>; + update(lead: UserIdentifier & Partial, cb: callback>): void; + + list(): Promise>; + list(cb: callback>): void; + + listBy(params: { email?: string, tag_id?: string, segment_id?: string }): Promise>; + listBy(params: { email?: string, tag_id?: string, segment_id?: string }, cb: callback>): void; + + find(identifier: LeadIdentifier): Promise> + find(identifier: LeadIdentifier, cb: callback>): void; + + delete(id: string): Promise>; + delete(id: string, cb: callback>): void; + + convert(params: { contact: LeadIdentifier, user: UserIdentifier }): Promise>; + convert(params: { contact: LeadIdentifier, user: UserIdentifier }, cb: callback>): void; - requestPermanentDeletion(): Promise<{id: number}>; } export class Companies { diff --git a/types/interpret/index.d.ts b/types/interpret/index.d.ts new file mode 100644 index 0000000000..de51c842f8 --- /dev/null +++ b/types/interpret/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for interpret 1.1 +// Project: https://github.com/tkellen/node-interpret +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export interface Hook { + (m: { extensions: string } | NodeModule): any; + install(m?: { extension: string; [key: string]: any }): void; +} + +export type RegisterFn = (hook: Hook) => void; + +export interface ExtensionDescriptor { + module: string; + register: RegisterFn; +} + +export type Extension = string | ExtensionDescriptor | Array; +export interface Extensions { + [extension: string]: Extension | null; +} + +export const extensions: Extensions; +export const jsVariants: Extensions; diff --git a/types/interpret/interpret-tests.ts b/types/interpret/interpret-tests.ts new file mode 100644 index 0000000000..2ac4cc0081 --- /dev/null +++ b/types/interpret/interpret-tests.ts @@ -0,0 +1,50 @@ +import { extensions, jsVariants, Extensions } from 'interpret'; + +// $ExpectType Extensions +extensions; +// $ExpectType Extensions +jsVariants; + +const myExts: Extensions = { + '.babel.js': [ + { + module: 'babel-register', + register(hook) { + hook({ extensions: '.js' }); + }, + }, + ], + '.co': 'coco', + '.coffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], + '.esm.js': { + module: 'esm', + register(hook) { + const esmLoader = hook(module); + require.extensions['.js'] = esmLoader('module')._extensions['.js']; + }, + }, + '.js': null, + '.jsx': [ + { + module: 'node-jsx', + register(hook) { + hook.install({ extension: '.jsx', harmony: true }); + }, + }, + ], + '.toml': { + module: 'toml-require', + register(hook) { + hook.install(); + }, + }, + '.ts': [ + 'typescript-require', + { + module: '@babel/register', + register(hook) { + hook({ extensions: '.ts' }); + }, + }, + ], +}; diff --git a/types/interpret/tsconfig.json b/types/interpret/tsconfig.json new file mode 100644 index 0000000000..970cf59fd9 --- /dev/null +++ b/types/interpret/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "interpret-tests.ts" + ] +} diff --git a/types/interpret/tslint.json b/types/interpret/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/interpret/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/intl-tel-input/v13/tslint.json b/types/intl-tel-input/v13/tslint.json index b6afb8acee..d2632b3e92 100644 --- a/types/intl-tel-input/v13/tslint.json +++ b/types/intl-tel-input/v13/tslint.json @@ -75,6 +75,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/intro.js/index.d.ts b/types/intro.js/index.d.ts index ec27d19439..40603bed1d 100644 --- a/types/intro.js/index.d.ts +++ b/types/intro.js/index.d.ts @@ -7,7 +7,11 @@ declare namespace IntroJs { interface Step { intro: string; element?: string|HTMLElement|Element; - position?: string; + position?: "top"|"left"|"right"|"bottom"|"bottom-left-aligned"|"bottom-middle-aligned"|"bottom-right-aligned"|"auto"; + tooltipClass?: string; + highlightClass?: string; + scrollTo?: "off"|"tooltip"|"element"; + disableInteraction?: boolean; } interface Hint { diff --git a/types/intro.js/intro.js-tests.ts b/types/intro.js/intro.js-tests.ts index d40fbe3f36..44b2f238d3 100644 --- a/types/intro.js/intro.js-tests.ts +++ b/types/intro.js/intro.js-tests.ts @@ -31,13 +31,22 @@ intro.setOptions({ position: 'left' }, { - element : '#step4', - intro : "Another step.", - position: 'bottom' + element : '#step4', + intro : "Another step.", + position : 'bottom', + tooltipClass : 'step4Class', + highlightClass: '' }, { - element: '#step5', - intro : 'Get it, use it.' + element : '#step4', + intro : "Another step.", + position: 'bottom', + scrollTo: 'tooltip' + }, + { + element : '#step5', + intro : 'Get it, use it.', + disableInteraction: true } ], hints: [ diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts new file mode 100644 index 0000000000..cee6ce75a6 --- /dev/null +++ b/types/iobroker/index.d.ts @@ -0,0 +1,1443 @@ +// Type definitions for ioBroker 1.4 +// Project: https://github.com/ioBroker/ioBroker +// Definitions by: AlCalzone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +// Note: This is not the definition for the package `iobroker`, +// which is just an installer, not a library. +// The definitions may change with updates to ioBroker.js-controller + +/// +import * as fs from "fs"; + +// tslint:disable:no-namespace +declare global { + namespace ioBroker { + enum StateQuality { + good = 0x00, // or undefined or null + bad = 0x01, + general_problem = 0x01, + general_device_problem = 0x41, + general_sensor_problem = 0x81, + device_not_connected = 0x42, + sensor_not_connected = 0x82, + device_reports_error = 0x44, + sensor_reports_error = 0x84, + } + + interface State { + /** The value of the state. */ + val: any; + + /** Direction flag: false for desired value and true for actual value. Default: false. */ + ack: boolean; + + /** Unix timestamp. Default: current time */ + ts: number; + + /** Unix timestamp of the last time the value changed */ + lc: number; + + /** Name of the adapter instance which set the value, e.g. "system.adapter.web.0" */ + from: string; + + /** Optional time in seconds after which the state is reset to null */ + expire?: number; + + /** Optional quality of the state value */ + q?: StateQuality; + + /** Optional comment */ + c?: string; + } + + /** Provides low-level access to the ioBroker states DB */ + interface States { + /** + * Returns a list of states with the given ids + * @param keys IDs of the states to be retrieved + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getStates(keys: string[], callback: GetStatesCallback2, dontModify?: any): void; + + /** + * Returns the state with the given id + * @param id ID of the state to be retrieved + * @param callback Is called when the operation has finished (successfully or not) + */ + getState(id: string, callback: GetStateCallback): void; + + /** + * Stores a state in the db + * @param id ID of the state to be stored + * @param state The state to be stored in the db + * @param callback Is called when the operation has finished (successfully or not) + */ + setState(id: string, state?: string | number | boolean | State | Partial, callback?: SetStateCallback): void; + + /** + * Updates a state in memory without triggering a save + * @param id ID of the state to be stored + * @param state The state to be updated + * @param callback Is called when the operation has finished (successfully or not) + */ + setRawState(id: string, state: State, callback?: SetStateCallback): void; + + /** + * Deletes a state + * @param id ID of the state to be stored + * @param callback Is called when the operation has finished (successfully or not) + */ + delState(id: string, callback: DeleteStateCallback): void; + + /** + * Retrieves all ids of states matching @link{pattern} + * @param pattern The pattern to match against + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; + + /** + * Subscribe to changes of all states matching @link{pattern} + * @param pattern The pattern to match against + * @param callback Is called when the operation has finished (successfully or not) + */ + subscribe(pattern: string, cb: EmptyCallback): void; + /** + * Unsubscribe from changes of all states matching @link{pattern} + * @param pattern The pattern to match against + * @param callback Is called when the operation has finished (successfully or not) + */ + unsubscribe(pattern: string, cb: EmptyCallback): void; + + /** + * Register an adapter instance as subscribable. + * This means that the instance can read information about all subscriptions to its states + * and will be notified of changes. + * @param instance Adapter instance to register, e.g. "admin.0" + * @param cb Is called when the operation has finished (successfully or not) + */ + registerAdapterSubs(instance: string, cb?: (error: null, success: boolean) => void): void; + + /** + * Unregister an adapter instance as subscribable. + * @param instance Adapter instance to unregister, e.g. "admin.0" + * @param cb Is called when the operation has finished (successfully or not) + */ + unregisterAdapterSubs(instance: string, cb?: (error: null, success: boolean) => void): void; + + /** + * EDUCATED GUESS: Notify all clients about changes to an object + * @param type object type + * @param id State/object id + * @param obj The changed object + */ + publishAll(type: string, id: string, obj: Message): void; + + // TODO: Documentation for these functions is missing + pushMessage(id: string, state: Message, callback: SetStateCallback): void; + lenMessage(id: string, callback: GenericCallback): void; + getMessage(id: string, callback: GenericCallback): void; + delMessage(id: string, messageId: number, callback: ErrorCallback): void; + clearAllMessages(callback?: EmptyCallback): void; + subscribeMessage(id: string, cb: EmptyCallback): void; + unsubscribeMessage(id: string, cb: EmptyCallback): void; + + pushLog(id: string, log: Log, callback: SetStateCallback): void; + lenLog(id: string, callback: GenericCallback): void; + getLog(id: string, callback: GenericCallback): void; + delLog(id: string, logId: string, callback: ErrorCallback): void; + clearAllLogs(callback?: EmptyCallback): void; + subscribeLog(id: string, cb: EmptyCallback): void; + unsubscribeLog(id: string, cb: EmptyCallback): void; + + getSession(id: string, callback: GetSessionCallback): void; + setSession(id: string, expire: number, callback?: EmptyCallback): void; + setSession(id: string, expire: number, obj: Session, callback?: EmptyCallback): void; + destroySession(id: string, callback?: EmptyCallback): void; + + /** + * Retrieves a copy of the object with the given ID + * @param id Id of the object to find + * @param callback Is called when the operation has finished (successfully or not) + */ + getConfig(id: string, callback: GetObjectCallback): void; + + /** + * Returns a list of config keys matching + * @param pattern Pattern to match against + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getConfigKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; + + /** + * Returns a list of objects with the given ids + * @param keys IDs of the objects to be retrieved + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getConfigs(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; + + /** + * Creates or overwrites a config object in the object db + * @param id ID of the object + * @param obj Object to store + * @param callback Is called when the operation has finished (successfully or not) + */ + setConfig(id: string, obj: ioBroker.Object, callback: SetObjectCallback): void; + + /** + * Deletes a config object in the object db + * @param id ID of the object + * @param callback Is called when the operation has finished (successfully or not) + */ + delConfig(id: string, callback: ErrorCallback): void; + + /** + * Subscribe to config object changes + * @param pattern The pattern to match against + */ + subscribeConfig(pattern: string, callback: EmptyCallback): void; + + /** + * Unsubscribe from config object changes + * @param pattern The pattern to match against + */ + unsubscribeConfig(pattern: string, callback: EmptyCallback): void; + + /** + * Writes a binary state into Redis + * @param id The id of the state + * @param data The data to be written + * @param callback Is called when the operation has finished (successfully or not) + */ + setBinaryState(id: string, data: Buffer, callback: SetStateCallback): void; + + /** + * Reads a binary state from Redis + * @param id The id of the state + * @param callback Is called when the operation has finished (successfully or not) + */ + getBinaryState(id: string, callback: GetBinaryStateCallback): void; + + /** + * Deletes a binary state from Redis + * @param id The id of the state to be deleted + * @param callback Is called when the operation has finished (successfully or not) + */ + delBinaryState(id: string, callback: DeleteStateCallback): void; + + /** Destructor of the class. Call this before shutting down */ + destroy(): void; + } // end interface States + + type Session = any; // TODO: implement + + type ObjectType = "state" | "channel" | "device"; + type CommonType = "number" | "string" | "boolean" | "array" | "object" | "mixed" | "file"; + + // Maybe this should extend Record, + // but the extra properties aren't defined anywhere, + // so I'd rather force the user to explicitly state + // he knows what he's doing by casting to any + interface ObjectCommon { + /** name of this object */ + name: string; + + // Icon and role aren't defined in SCHEMA.md, + // but they are being used by some adapters + /** Icon for this object */ + icon?: string; + /** role of the object */ + role?: string; + } + + interface StateCommon extends ObjectCommon { + /** Type of this state. See https://github.com/ioBroker/ioBroker/blob/master/doc/SCHEMA.md#state-commonrole for a detailed description */ + type?: CommonType; + /** minimum value */ + min?: number; + /** maximum value */ + max?: number; + /** unit of the value */ + unit?: string; + /** the default value */ + def?: any; + /** description of this state */ + desc?: string; + + /** if this state is readable */ + read: boolean; + /** if this state is writable */ + write: boolean; + /** role of the state (used in user interfaces to indicate which widget to choose) */ + role: string; + + /** + * Dictionary of possible values for this state in the form + *
+             * {
+             *     "internal value 1": "displayed value 1",
+             *     "internal value 2": "displayed value 2",
+             *     ...
+             * }
+             * 
+ * In old ioBroker versions, this could also be a string of the form + * "val1:text1;val2:text2" (now deprecated) + */ + states?: Record | string; + + /** ID of a helper state indicating if the handler of this state is working */ + workingID?: string; + + /** attached history information */ + history?: any; + } + interface ChannelCommon extends ObjectCommon { + /** description of this channel */ + desc?: string; + } + type OtherCommon = ObjectCommon & { + [propName: string]: any; + }; + + interface BaseObject { + /** The ID of this object */ + _id: string; + native: Record; + enums?: Record; + type: string; // specified in the derived interfaces + common: ObjectCommon; + acl?: ObjectACL; + } + + interface StateObject extends BaseObject { + type: "state"; + common: StateCommon; + acl?: StateACL; + } + interface PartialStateObject extends Partial> { + common?: Partial; + acl?: Partial; + } + + interface ChannelObject extends BaseObject { + type: "channel"; + common: ChannelCommon; + } + interface PartialChannelObject extends Partial> { + common?: Partial; + } + + interface DeviceObject extends BaseObject { + type: "device"; + common: ObjectCommon; // TODO: any definition for device? + } + interface PartialDeviceObject extends Partial> { + common?: Partial; + } + + interface OtherObject extends BaseObject { + type: "adapter" | "config" | "enum" | "group" | "host" | "info" | "instance" | "meta" | "script" | "user"; + common: OtherCommon; + } + interface PartialOtherObject extends Partial> { + common?: Partial; + } + + type Object = StateObject | ChannelObject | DeviceObject | OtherObject; + // In set[Foreign]Object[NotExists] methods, the ID and acl of the object is optional + interface SettableObject extends Pick> { + _id?: ioBroker.Object["_id"]; + acl?: ioBroker.Object["acl"]; + } + type PartialObject = PartialStateObject | PartialChannelObject | PartialDeviceObject | PartialOtherObject; + + /** Defines access rights for a single file */ + interface FileACL { + /** Full name of the user who owns this file, e.g. "system.user.admin" */ + owner: string; + /** Full name of the group who owns this file, e.g. "system.group.administrator" */ + ownerGroup: string; + /** Linux-type permissions defining access to this file */ + permissions: number; + } + /** Defines access rights for a single file, applied to a user or group */ + interface EvaluatedFileACL extends FileACL { + /** Whether the user may read the file */ + read: boolean; + /** Whether the user may write the file */ + write: boolean; + } + + /** Defines access rights for a single object */ + interface ObjectACL { + /** Full name of the user who owns this object, e.g. "system.user.admin" */ + owner: string; + /** Full name of the group who owns this object, e.g. "system.group.administrator" */ + ownerGroup: string; + /** Linux-type permissions defining access to this object */ + object: number; + } + /** Defines access rights for a single state object */ + interface StateACL extends ObjectACL { + /** Linux-type permissions defining access to this state */ + state: number; + } + + /** Defines access rights for a single object type */ + interface ObjectOperationPermissions { + /** Whether a user may enumerate objects of this type */ + list: boolean; + /** Whether a user may read objects of this type */ + read: boolean; + /** Whether a user may write objects of this type */ + write: boolean; + /** Whether a user may create objects of this type */ + create: boolean; + /** Whether a user may delete objects of this type */ + "delete": boolean; + } + + /** Defines the rights a user or group has to change objects */ + interface ObjectPermissions { + /** The access rights for files */ + file: ObjectOperationPermissions; + /** The access rights for objects */ + object: ObjectOperationPermissions; + /** The access rights for users/groups */ + users: ObjectOperationPermissions; + /** The access rights for states */ + state?: ObjectOperationPermissions; + } + /** Defined the complete set of access rights a user has */ + interface PermissionSet extends ObjectPermissions { + /** The name of the user this ACL is for */ + user: string; + /** The name of the groups this ACL was merged from */ + groups: string[]; + /** The access rights for certain commands */ + other: { + execute: boolean, + http: boolean, + sendto: boolean, + }; + } + + interface Permission { + /** The type of the permission */ + type: string; + /** Which kind of operation is required */ + operation: string; + } + interface ObjectOrStatePermission extends Permission { + type: "object" | "file" | "users" | "state"; + operation: "list" | "read" | "write" | "create" | "delete"; + } + interface OtherPermission extends Permission { + type: "other"; + operation: "execute" | "http" | "sendto"; + } + interface CommandsPermissions { + // TODO: Are all properties required or is a partial object ok? + getObject: ObjectOrStatePermission; + getObjects: ObjectOrStatePermission; + getObjectView: ObjectOrStatePermission; + setObject: ObjectOrStatePermission; + subscribeObjects: ObjectOrStatePermission; + unsubscribeObjects: ObjectOrStatePermission; + getStates: ObjectOrStatePermission; + getState: ObjectOrStatePermission; + setState: ObjectOrStatePermission; + getStateHistory: ObjectOrStatePermission; + subscribe: ObjectOrStatePermission; + unsubscribe: ObjectOrStatePermission; + getVersion: Permission; + httpGet: OtherPermission; + sendTo: OtherPermission; + sendToHost: OtherPermission; + readFile: ObjectOrStatePermission; + readFile64: ObjectOrStatePermission; + writeFile: ObjectOrStatePermission; + writeFile64: ObjectOrStatePermission; + unlink: ObjectOrStatePermission; + rename: ObjectOrStatePermission; + mkdir: ObjectOrStatePermission; + readDir: ObjectOrStatePermission; + chmodFile: ObjectOrStatePermission; + authEnabled: Permission; + disconnect: Permission; + listPermissions: Permission; + getUserPermissions: ObjectOrStatePermission; + } + + type UserGroup = any; // TODO find out how this looks like + // interface UserGroup { } + + /** Contains information about a user */ + interface User { + /** Which groups this user belongs to */ + groups: UserGroup[]; + /** Access rights of this user */ + acl: ObjectPermissions; + } + + /** Parameters for @link{Objects.getObjectView} */ + interface GetObjectViewParams { + /** First id to include in the return list */ + startkey: string; + /** Last id to include in the return list */ + endkey: string; + } + + /** Parameters for @link{Objects.getObjectList} */ + interface GetObjectListParams extends GetObjectViewParams { + /** Whether docs should be included in the return list */ // TODO: What are docs? + include_docs: boolean; + } + + /** Provides low-level access to the ioBroker objects db */ + interface Objects { + /** + * For a given user, returns the groups he belongs to, and his access rights + * @param user Name of the user. Has to start with "system.user." + * @param callback The callback function to be invoked with the return values + */ + getUserGroup(user: string, callback: GetUserGroupCallback): void; + + /** + * Determines the mime type for a given file extension + * @param ext File extension, including the leading dot, e.g. ".zip" + */ + getMimeType(ext: string): { mimeType: string, isBinary: boolean }; + + /** + * Writes a file. + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param data Contents of the file + * @param options (optional) MIME type of the file (string). Or some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + writeFile(id: string, name: string, data: Buffer | string, callback: ErrorCallback): void; + writeFile(id: string, name: string, data: Buffer | string, options: string | unknown, callback: ErrorCallback): void; + + /** + * Reads a file. + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + readFile(id: string, name: string, callback: ReadFileCallback): void; + readFile(id: string, name: string, options: unknown, callback: ReadFileCallback): void; + + /** + * Deletes a file. + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + unlink(id: string, name: string, callback: ErrorCallback): void; + unlink(id: string, name: string, options: unknown, callback: ErrorCallback): void; + /** + * Deletes a file. + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + delFile(id: string, name: string, callback: ErrorCallback): void; + delFile(id: string, name: string, options: unknown, callback: ErrorCallback): void; + + /** + * Finds all files and directories starting with + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File or directory name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + readDir(id: string, name: string, callback: ReadDirCallback): void; + readDir(id: string, name: string, options: unknown, callback: ReadDirCallback): void; + + /** + * Renames a file or directory + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param oldName Old file or directory name + * @param newName Name to rename to + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + rename(id: string, oldName: string, newName: string, callback: ErrorCallback): void; + rename(id: string, oldName: string, newName: string, options: unknown, callback: ErrorCallback): void; + + /** + * Creates an empty file with the given name + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name File name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + touch(id: string, name: string, callback: ErrorCallback): void; + touch(id: string, name: string, options: unknown, callback: ErrorCallback): void; + + /** + * Deletes all files in the root directory matching + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name Pattern to match against + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + rm(id: string, name: string, callback: RmCallback): void; + rm(id: string, name: string, options: unknown, callback: RmCallback): void; + + /** + * Creates an empty directory with the given name + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name Directory name + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + mkDir(id: string, name: string, callback: ErrorCallback): void; + mkDir(id: string, name: string, options: unknown, callback: ErrorCallback): void; + + /** + * Takes possession all files in the root directory matching + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name Pattern to match against + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + chownFile(id: string, name: string, callback: ChownFileCallback): void; + chownFile(id: string, name: string, options: unknown, callback: ChownFileCallback): void; + + /** + * Changes access rights of all files in the root directory matching + * @param id Name of the root directory. This should be the adapter instance, e.g. "admin.0" + * @param name Pattern to match against + * @param options Mode of the access change as a number or hexadecimal string + * @param callback Is called when the operation has finished (successfully or not) + */ + chmodFile(id: string, name: string, options: { mode: number | string } | Record, callback: ChownFileCallback): void; + + // not documented. enabled = true seems to disable the cache + // enableFileCache(enabled, options, callback) + + /** + * Subscribe to object changes + * @param pattern The pattern to match against + */ + subscribeConfig(pattern: string, callback: EmptyCallback): void; + subscribeConfig(pattern: string, options: unknown, callback: EmptyCallback): void; + /** + * Subscribe to object changes + * @param pattern The pattern to match against + */ + subscribe(pattern: string, callback: EmptyCallback): void; + subscribe(pattern: string, options: unknown, callback: EmptyCallback): void; + + /** + * Unsubscribe from object changes + * @param pattern The pattern to match against + */ + unsubscribeConfig(pattern: string, callback: EmptyCallback): void; + unsubscribeConfig(pattern: string, options: unknown, callback: EmptyCallback): void; + /** + * Unsubscribe from object changes + * @param pattern The pattern to match against + */ + unsubscribe(pattern: string, callback: EmptyCallback): void; + unsubscribe(pattern: string, options: unknown, callback: EmptyCallback): void; + + /** + * Takes possession of all objects matching + * @param pattern Pattern to match against + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + chownObject(pattern: string, callback: ChownObjectCallback): void; + chownObject(pattern: string, options: unknown, callback: ChownObjectCallback): void; + + /** + * Changes access rights of all objects matching + * @param pattern Pattern to match against + * @param options Mode of the access change as a number or hexadecimal string + * @param callback Is called when the operation has finished (successfully or not) + */ + chmodObject(pattern: string, callback: ChownObjectCallback): void; + chmodObject(pattern: string, options: unknown, callback: ChownObjectCallback): void; + + /** + * Retrieves a copy of the object with the given ID + * @param id Id of the object to find + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getObject(id: string, callback: GetObjectCallback): void; + getObject(id: string, options: unknown, callback: GetObjectCallback): void; + /** + * Retrieves a copy of the object with the given ID + * @param id Id of the object to find + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getConfig(id: string, callback: GetObjectCallback): void; + getConfig(id: string, options: unknown, callback: GetObjectCallback): void; + + /** + * Returns a list of config keys matching + * @param pattern Pattern to match against + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getConfigKeys(pattern: string, callback: GetConfigKeysCallback, dontModify?: any): void; + getConfigKeys(pattern: string, options: unknown, callback: GetConfigKeysCallback, dontModify?: any): void; + + /** + * Returns a list of objects with the given ids + * @param keys IDs of the objects to be retrieved + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getObjects(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; + getObjects(keys: string[], options: unknown, callback: GetObjectsCallback2, dontModify?: any): void; + /** + * Returns a list of objects with the given ids + * @param keys IDs of the objects to be retrieved + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + * @param dontModify unused + */ + getConfigs(keys: string[], callback: GetObjectsCallback2, dontModify?: any): void; + getConfigs(keys: string[], options: unknown, callback: GetObjectsCallback2, dontModify?: any): void; + + /** + * Creates or overwrites an object in the object db + * @param id ID of the object + * @param obj Object to store + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + setObject(id: string, obj: ioBroker.SettableObject, callback: SetObjectCallback): void; + setObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback: SetObjectCallback): void; + /** + * Creates or overwrites an object in the object db + * @param id ID of the object + * @param obj Object to store + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + setConfig(id: string, obj: ioBroker.SettableObject, callback: SetObjectCallback): void; + setConfig(id: string, obj: ioBroker.SettableObject, options: unknown, callback: SetObjectCallback): void; + + /** + * Deletes an object in the object db + * @param id ID of the object + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + delObject(id: string, callback: ErrorCallback): void; + delObject(id: string, options: unknown, callback: ErrorCallback): void; + /** + * Deletes an object in the object db + * @param id ID of the object + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + delConfig(id: string, callback: ErrorCallback): void; + delConfig(id: string, options: unknown, callback: ErrorCallback): void; + + /** + * Returns a list of objects with id between params.startkey and params.endkey + * @param params Parameters determining the objects included in the return list. Null to include all objects + * @param options (optional) If the returned list should be sorted. And some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getObjectList(params: GetObjectListParams | null, callback: GetObjectListCallback): void; + getObjectList(params: GetObjectListParams | null, options: { sorted?: boolean } | Record, callback: GetObjectListCallback): void; + + /** + * Query a predefined object view (similar to SQL stored procedures) and return the results + * For a detailed description refer to https://github.com/ioBroker/ioBroker/wiki/Adapter-Development-Documentation#object-fields + * or http://guide.couchdb.org/editions/1/en/views.html + * @param design The namespace of the object view, as defined in io-package.json. Usually the adapter name, e.g. "hm-rpc" + * @param search The name of the object view. + * @param params Parameters to additionally filter out objects from the return list. Null to include all objects + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getObjectView(design: string, search: string, params: GetObjectViewParams | null, callback: GetObjectViewCallback): void; + getObjectView(design: string, search: string, params: GetObjectViewParams | null, options: unknown, callback: GetObjectViewCallback): void; + + /** + * Extends an object in the object db with new properties + * @param id ID of the object + * @param obj Object to extend the original one with. May be just parts of an object. + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + extendObject(id: string, obj: PartialObject, callback: ExtendObjectCallback): void; + extendObject(id: string, obj: PartialObject, options: unknown, callback: ExtendObjectCallback): void; + + /** + * Finds an object by ID or name. If multiple objects were found, return the first one + * @param idOrName ID or name of the object + * @param type If != null, only return an object with a common.type equal to this + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + findObject(idOrName: string, type: CommonType | null, callback: FindObjectCallback): void; + findObject(idOrName: string, type: CommonType | null, options: unknown, callback: FindObjectCallback): void; + + // I'd rather not document a function with the name "destroyDB" + + /** Destructor of the class. Call this before shutting down. */ + destroy(): void; + } // end interface Objects + + type LogLevel = "silly" | "debug" | "info" | "warn" | "error"; + interface Logger { + /** log message with silly level */ + silly(message: string): void; + /** log message with debug level */ + debug(message: string): void; + /** log message with info level (default output level for all adapters) */ + info(message: string): void; + /** log message with warning severity */ + warn(message: string): void; + /** log message with error severity */ + error(message: string): void; + + /** Verbosity of the log output */ + level: LogLevel; + } + + interface Certificates { + /** private key file */ + key: string | Buffer; + /** public certificate */ + cert: string | Buffer; + /** chained CA certificates */ + ca: Array; + } + + /** Callback information for a passed message */ + interface MessageCallbackInfo { + /** The original message payload */ + message: string | object; + /** ID of this callback */ + id: number; + // ??? + ack: boolean; + /** Timestamp of this message */ + time: number; + } + type MessageCallback = (result?: any) => void; + + /** A message being passed between adapter instances */ + interface Message { + /** The command to be executed */ + command: string; + /** The message payload */ + message: string | object; + /** The source of this message */ + from: string; + /** ID of this message */ + _id: number; + /** Callback information. This is set when the source expects a response */ + callback: MessageCallbackInfo; + } + + type Log = any; // TODO: define this https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/states/statesInMemServer.js#L873 + + type EnumList = string | string[]; + + type Enum = any; // TODO: implement this + + interface DirectoryEntry { + file: string; + stats: fs.Stats; + isDir: boolean; + acl: any; // access control list object + modifiedAt: number; + createdAt: number; + } + + interface GetHistoryOptions { + instance?: string; + start?: number; + end?: number; + step?: number; + count?: number; + from?: boolean; + ack?: boolean; + q?: boolean; + addID?: boolean; + limit?: number; + ignoreNull: boolean; + sessionId?: any; + aggregate?: "minmax" | "min" | "max" | "average" | "total" | "count" | "none"; + } + + interface AdapterOptions { + /** The name of the adapter */ + name: string; + + /** path to adapter */ + dirname?: string; + + /** if the global system config should be included in the created object. Default: false */ + systemConfig?: boolean; + + /** provide alternative global configuration for the adapter. Default: null */ + config?: any; + + /** instance of the created adapter. Default: null */ + instance?: number; + + /** If the adapter needs access to the formatDate function to format dates according to the global settings. Default: false */ + useFormatDate?: boolean; + + /** If the adapter collects logs from all adapters (experts only). Default: false */ + logTransporter?: boolean; + + /** Handler for changes of subscribed objects */ + objectChange?: ObjectChangeHandler; + /** Handler for received adapter messages. Can only be used if messagebox in io-package.json is set to true. */ + message?: MessageHandler; + /** Handler for changes of subscribed states */ + stateChange?: StateChangeHandler; + /** Will be called when the adapter is intialized */ + ready?: ReadyHandler; + /** Will be called on adapter termination */ + unload?: UnloadHandler; + + /** if true, stateChange will be called with an id that has no namespace, e.g. "state" instead of "adapter.0.state". Default: false */ + noNamespace?: boolean; + } // end interface AdapterOptions + + // tslint:disable-next-line:no-empty-interface + interface AdapterConfig { + // This is a stub to be augmented in every adapter + } + + interface Adapter { + /** The name of the adapter */ + name: string; + /** The name of the host where the adapter is running */ + host: string; + /** instance number of this adapter instance */ + instance: number; + /** Namespace of adapter objects: "." */ + readonly namespace: string; + /** native part of the adapter settings */ + config: AdapterConfig; + /** common part of the adapter settings */ + common: any; + /** system part of the adapter settings */ + systemConfig?: any; + /** path to the adapter folder */ + adapterDir: string; + /** content of io-package.json */ + ioPack: any; + /** content of package.json */ + pack: any; + /** access to the logging functions */ + log: Logger; + /** adapter version */ + version: any; + states: States; + objects: Objects; + /** if the adapter is connected to the host */ + connected: boolean; + + /* =============================== + Functions defined in adapter.js + =============================== */ + + /** + * Helper function that looks for first free TCP port starting with the given one. + * @param port - The port to start with + * @param callback - gets called when a free port is found + */ + getPort(port: number, callback: (port: number) => void): void; + + /** Stops the adapter. Note: Is not always defined. */ + stop?: () => void; + + // ============================== + // GENERAL + + /** Validates username and password */ + checkPassword(user: string, password: string, callback: (result: boolean) => void): void; + checkPassword(user: string, password: string, options: unknown, callback: (result: boolean) => void): void; + /** Sets a new password for the given user */ + setPassword(user: string, password: string, options?: unknown, callback?: (err?: any) => void): void; + /** Checks if a user exists and is in the given group. */ + checkGroup(user: string, group: string, callback: (result: boolean) => void): void; + checkGroup(user: string, group: string, options: unknown, callback: (result: boolean) => void): void; + /** Determines the users permissions */ + calculatePermissions(user: string, commandsPermissions: CommandsPermissions, callback: (result: PermissionSet) => void): void; + calculatePermissions(user: string, commandsPermissions: CommandsPermissions, options: unknown, callback: (result: PermissionSet) => void): void; + /** Returns SSL certificates by name (private key, public cert and chained certificate) for creation of HTTPS servers */ + getCertificates(publicName: string, privateName: string, chainedName: string, callback: (err: string | null, certs?: Certificates, useLetsEncryptCert?: boolean) => void): void; + + /** + * Sends a message to a specific instance or all instances of some specific adapter. + * @param instanceName The instance to send this message to. + * If the ID of an instance is given (e.g. "admin.0"), only this instance will receive the message. + * If the name of an adapter is given (e.g. "admin"), all instances of this adapter will receive it. + * @param command (optional) Command name of the target instance. Default: "send" + * @param message The message (e.g. params) to send. + */ + sendTo(instanceName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + sendTo(instanceName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + + /** + * Sends a message to a specific host or all hosts. + */ + sendToHost(hostName: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + sendToHost(hostName: string, command: string, message: string | object, callback?: MessageCallback | MessageCallbackInfo): void; + + /** Convert ID to {device: D, channel: C, state: S} */ + idToDCS(id: string): { + device: string; + channel: string; + state: string; + }; + + // ============================== + // own objects + + /** Reads an object from the object db */ + getObject(id: string, callback: GetObjectCallback): void; + getObject(id: string, options: unknown, callback: GetObjectCallback): void; + /** Creates or overwrites an object in the object db */ + setObject(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; + setObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; + /** Creates an object in the object db. Existing objects are not overwritten. */ + setObjectNotExists(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; + setObjectNotExists(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; + /** Get all states, channels and devices of this adapter */ + getAdapterObjects(callback: (objects: Record) => void): void; + /** Extend an object and create it if it might not exist */ + extendObject(id: string, objPart: PartialObject, callback?: SetObjectCallback): void; + extendObject(id: string, objPart: PartialObject, options: unknown, callback?: SetObjectCallback): void; + /** + * Deletes an object from the object db + * @param id - The id of the object without namespace + */ + delObject(id: string, callback?: ErrorCallback): void; + delObject(id: string, options: unknown, callback?: ErrorCallback): void; + + // ============================== + // foreign objects + + // tslint:disable:unified-signatures + /** Reads an object (which might not belong to this adapter) from the object db */ + getForeignObject(id: string, callback: GetObjectCallback): void; + getForeignObject(id: string, options: unknown, callback: GetObjectCallback): void; + /** Get foreign objects by pattern, by specific type and resolve their enums. */ + getForeignObjects(pattern: string, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, options: unknown, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, options: unknown, callback: GetObjectsCallback): void; + getForeignObjects(pattern: string, type: ObjectType, enums: EnumList, options: unknown, callback: GetObjectsCallback): void; + /** Creates or overwrites an object (which might not belong to this adapter) in the object db */ + setForeignObject(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; + setForeignObject(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; + /** Creates an object (which might not belong to this adapter) in the object db. Existing objects are not overwritten. */ + setForeignObjectNotExists(id: string, obj: ioBroker.SettableObject, callback?: SetObjectCallback): void; + setForeignObjectNotExists(id: string, obj: ioBroker.SettableObject, options: unknown, callback?: SetObjectCallback): void; + /** Extend an object (which might not belong to this adapter) and create it if it might not exist */ + extendForeignObject(id: string, objPart: PartialObject, callback?: SetObjectCallback): void; + extendForeignObject(id: string, objPart: PartialObject, options: unknown, callback?: SetObjectCallback): void; + // tslint:enable:unified-signatures + /** + * Finds an object by its ID or name + * @param type - common.type of the state + */ + findForeignObject(idOrName: string, type: string, callback: FindObjectCallback): void; + findForeignObject(idOrName: string, type: string, options: unknown, callback: FindObjectCallback): void; + /** + * Deletes an object (which might not belong to this adapter) from the object db + * @param id - The id of the object including namespace + */ + delForeignObject(id: string, callback?: ErrorCallback): void; + delForeignObject(id: string, options: unknown, callback?: ErrorCallback): void; + + // ============================== + // states + + // Multiple signatures help understanding what the parameters are about + // tslint:disable:unified-signatures + /** Writes a value into the states DB. */ + setState(id: string, state: string | number | boolean | State | Partial, callback?: SetStateCallback): void; + setState(id: string, state: string | number | boolean | State | Partial, ack: boolean, callback?: SetStateCallback): void; + setState(id: string, state: string | number | boolean | State | Partial, options: unknown, callback?: SetStateCallback): void; + setState(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown, callback?: SetStateCallback): void; + /** Writes a value into the states DB only if it has changed. */ + setStateChanged(id: string, state: string | number | boolean | State | Partial, callback?: SetStateChangedCallback): void; + setStateChanged(id: string, state: string | number | boolean | State | Partial, ack: boolean, callback?: SetStateChangedCallback): void; + setStateChanged(id: string, state: string | number | boolean | State | Partial, options: unknown, callback?: SetStateChangedCallback): void; + setStateChanged(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown, callback?: SetStateChangedCallback): void; + /** Writes a value (which might not belong to this adapter) into the states DB. */ + setForeignState(id: string, state: string | number | boolean | State | Partial, callback?: SetStateCallback): void; + setForeignState(id: string, state: string | number | boolean | State | Partial, ack: boolean, callback?: SetStateCallback): void; + setForeignState(id: string, state: string | number | boolean | State | Partial, options: unknown, callback?: SetStateCallback): void; + setForeignState(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown, callback?: SetStateCallback): void; + /** Writes a value (which might not belong to this adapter) into the states DB only if it has changed. */ + setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, callback?: SetStateChangedCallback): void; + setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, ack: boolean, callback?: SetStateChangedCallback): void; + setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, options: unknown, callback?: SetStateChangedCallback): void; + setForeignStateChanged(id: string, state: string | number | boolean | State | Partial, ack: boolean, options: unknown, callback?: SetStateChangedCallback): void; + // tslint:enable:unified-signatures + + /** Read a value from the states DB. */ + getState(id: string, callback: GetStateCallback): void; + getState(id: string, options: unknown, callback: GetStateCallback): void; + /** Read a value (which might not belong to this adapter) from the states DB. */ + getForeignState(id: string, callback: GetStateCallback): void; + getForeignState(id: string, options: unknown, callback: GetStateCallback): void; + /** Read all states of this adapter which match the given pattern */ + getStates(pattern: string, callback: GetStatesCallback): void; + getStates(pattern: string, options: unknown, callback: GetStatesCallback): void; + /** Read all states (which might not belong to this adapter) which match the given pattern */ + getForeignStates(pattern: string, callback: GetStatesCallback): void; + getForeignStates(pattern: string, options: unknown, callback: GetStatesCallback): void; + + /** Deletes a state from the states DB, but not the associated object. Consider using @link{deleteState} instead */ + delState(id: string, callback?: ErrorCallback): void; + delState(id: string, options: unknown, callback?: ErrorCallback): void; + /** Deletes a state from the states DB, but not the associated object */ + delForeignState(id: string, callback?: ErrorCallback): void; + delForeignState(id: string, options: unknown, callback?: ErrorCallback): void; + + getHistory(id: string, options: GetHistoryOptions, callback: GetHistoryCallback): void; + + // MISSING: + // pushFifo and similar https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4105 + // logRedirect https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4294 + // requireLog https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4336 + // processLog https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/adapter.js#L4360 + + /** + * Writes a binary state into Redis + * @param id The id of the state + * @param binary The data to be written + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + setBinaryState(id: string, binary: Buffer, callback: SetStateCallback): void; + setBinaryState(id: string, binary: Buffer, options: unknown, callback: SetStateCallback): void; + /** + * Reads a binary state from Redis + * @param id The id of the state + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getBinaryState(id: string, callback: GetBinaryStateCallback): void; + getBinaryState(id: string, options: unknown, callback: GetBinaryStateCallback): void; + + // ============================== + // enums + + /** Returns the enum tree, filtered by the optional enum name */ + getEnum(callback: GetEnumCallback): void; + getEnum(name: string, callback: GetEnumCallback): void; + getEnum(name: string, options: unknown, callback: GetEnumCallback): void; + getEnums(callback: GetEnumsCallback): void; + getEnums(enumList: EnumList, callback: GetEnumsCallback): void; + getEnums(enumList: EnumList, options: unknown, callback: GetEnumsCallback): void; + + addChannelToEnum(enumName: string, addTo: string, parentDevice: string, channelName: string, options?: unknown, callback?: ErrorCallback): void; + deleteChannelFromEnum(enumName: string, parentDevice: string, channelName: string, options?: unknown, callback?: ErrorCallback): void; + + addStateToEnum(enumName: string, addTo: string, parentDevice: string, parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void; + deleteStateFromEnum(enumName: string, parentDevice: string, parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void; + + // ============================== + // subscriptions + + /** Subscribe to changes of objects in this instance */ + subscribeObjects(pattern: string, options?: unknown): void; + /** Subscribe to changes of objects (which might not belong to this adapter) */ + subscribeForeignObjects(pattern: string, options?: unknown): void; + /** Unsubscribe from changes of objects in this instance */ + unsubscribeObjects(pattern: string, options?: unknown): void; + /** Unsubscribe from changes of objects (which might not belong to this adapter) */ + unsubscribeForeignObjects(pattern: string, options?: unknown): void; + + /** Subscribe to changes of states in this instance */ + subscribeStates(pattern: string, options?: unknown, callback?: ErrorCallback): void; + /** Subscribe to changes of states (which might not belong to this adapter) */ + subscribeForeignStates(pattern: string, options?: unknown, callback?: ErrorCallback): void; + /** + * Subscribe from changes of states in this instance + * @param pattern - Must match the pattern used to subscribe + */ + unsubscribeStates(pattern: string, options?: unknown, callback?: ErrorCallback): void; + /** + * Subscribe from changes of states (which might not belong to this adapter) + * @param pattern - Must match the pattern used to subscribe + */ + unsubscribeForeignStates(pattern: string, options?: unknown, callback?: ErrorCallback): void; + + // ============================== + // devices and channels + + /** creates an object with type device */ + createDevice(deviceName: string, common?: any, native?: any, options?: unknown, callback?: SetObjectCallback): void; + /** deletes a device, its channels and states */ + deleteDevice(deviceName: string, options?: unknown, callback?: ErrorCallback): void; + /** gets the devices of this instance */ + + /** creates an object with type channel */ + createChannel(parentDevice: string, channelName: string, roleOrCommon?: string | object, native?: any, options?: unknown, callback?: SetObjectCallback): void; + /** deletes a channel and its states */ + deleteChannel(channelName: string, options?: unknown, callback?: ErrorCallback): void; + deleteChannel(parentDevice: string, channelName: string, options?: unknown, callback?: ErrorCallback): void; + + /** creates a state and the corresponding object */ + createState(parentDevice: string, parentChannel: string, stateName: string, roleOrCommon?: string | object, native?: any, options?: unknown, callback?: SetObjectCallback): void; + /** deletes a state */ + deleteState(stateName: string, options?: unknown, callback?: ErrorCallback): void; + deleteState(parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void; + deleteState(parentDevice: string, parentChannel: string, stateName: string, options?: unknown, callback?: ErrorCallback): void; + + /** + * Returns a list of all devices in this adapter instance + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getDevices(callback: GetObjectsCallback3): void; + getDevices(options: unknown, callback: GetObjectsCallback3): void; + + /** + * Returns a list of all channels in this adapter instance + * @param parentDevice (optional) Name of the parent device to filter the channels by + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getChannels(callback: GetObjectsCallback3): void; + getChannels(parentDevice: string | null, callback: GetObjectsCallback3): void; + getChannels(parentDevice: string | null, options: unknown, callback: GetObjectsCallback3): void; + /** + * Returns a list of all channels in this adapter instance + * @param parentDevice (optional) Name of the parent device to filter the channels by + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getChannelsOf(callback: GetObjectsCallback3): void; + getChannelsOf(parentDevice: string | null, callback: GetObjectsCallback3): void; + getChannelsOf(parentDevice: string | null, options: unknown, callback: GetObjectsCallback3): void; + + /** + * Returns a list of all states in this adapter instance + * @param parentDevice (optional) Name of the parent device to filter the channels by + * @param parentChannel (optional) Name of the parent channel to filter the channels by + * @param options (optional) Some internal options. + * @param callback Is called when the operation has finished (successfully or not) + */ + getStatesOf(callback: GetObjectsCallback3): void; + getStatesOf(parentDevice: string | null, callback: GetObjectsCallback3): void; + getStatesOf(parentDevice: string | null, parentChannel: string | null, callback: GetObjectsCallback3): void; + getStatesOf(parentDevice: string | null, parentChannel: string | null, options: unknown, callback: GetObjectsCallback3): void; + + // ============================== + // filesystem + + /** + * reads the content of directory from DB for given adapter and path + * @param adapter - adapter name. If adapter name is null, default will be the name of the current adapter. + * @param path - path to direcory without adapter name. E.g. If you want to read "/vis.0/main/views.json", here must be "/main/views.json" and _adapter must be equal to "vis.0". + */ + readDir(adapterName: string, path: string, callback: ReadDirCallback): void; + readDir(adapterName: string, path: string, options: unknown, callback: ReadDirCallback): void; + mkDir(adapterName: string, path: string, callback: ErrorCallback): void; + mkDir(adapterName: string, path: string, options: unknown, callback: ErrorCallback): void; + + readFile(adapterName: string, path: string, callback: ReadFileCallback): void; + readFile(adapterName: string, path: string, options: unknown, callback: ReadFileCallback): void; + writeFile(adapterName: string, path: string, data: Buffer | string, callback: ErrorCallback): void; + // options see https://github.com/ioBroker/ioBroker.js-controller/blob/master/lib/objects/objectsInMemServer.js#L599 + writeFile(adapterName: string, path: string, data: Buffer | string, options: unknown, callback: ErrorCallback): void; + + delFile(adapterName: string, path: string, callback: ErrorCallback): void; + delFile(adapterName: string, path: string, options: unknown, callback: ErrorCallback): void; + unlink(adapterName: string, path: string, callback: ErrorCallback): void; + unlink(adapterName: string, path: string, options: unknown, callback: ErrorCallback): void; + + rename(adapterName: string, oldName: string, newName: string, callback: ErrorCallback): void; + rename(adapterName: string, oldName: string, newName: string, options: unknown, callback: ErrorCallback): void; + + /** + * Changes access rights of all files in the adapter directory + * @param adapter Name of the adapter instance, e.g. "admin.0". Defaults to the namespace of this adapter. + * @param path Pattern to match the file path against + * @param options Mode of the access change as a number or hexadecimal string + * @param callback Is called when the operation has finished (successfully or not) + */ + chmodFile(adapter: string | null, path: string, options: { mode: number | string } | Record, callback: ChownFileCallback): void; + + // ============================== + // formatting + + formatValue(value: number | string, format: any): string; + formatValue(value: number | string, decimals: number, format: any): string; + formatDate(dateObj: string | Date | number, format: string): string; + formatDate(dateObj: string | Date | number, isDuration: boolean | string, format: string): string; + + // ============================================= + // Events exposed through EventEmitter interface + // ============================================= + on(event: "ready", handler: ReadyHandler): this; + on(event: "unload", handler: UnloadHandler): this; + on(event: "stateChange", handler: StateChangeHandler): this; + on(event: "objectChange", handler: ObjectChangeHandler): this; + on(event: "message", handler: MessageHandler): this; + + removeListener(event: "ready", handler: ReadyHandler): this; + removeListener(event: "unload", handler: UnloadHandler): this; + removeListener(event: "stateChange", handler: StateChangeHandler): this; + removeListener(event: "objectChange", handler: ObjectChangeHandler): this; + removeListener(event: "message", handler: MessageHandler): this; + + removeAllListeners(event?: "ready" | "unload" | "stateChange" | "objectChange" | "message"): this; + } // end interface Adapter + + type ReadyHandler = () => void; + type ObjectChangeHandler = (id: string, obj: ioBroker.Object | null | undefined) => void; + type StateChangeHandler = (id: string, obj: State | null | undefined) => void; + type MessageHandler = (obj: Message) => void; + type UnloadHandler = (callback: EmptyCallback) => void; + + type EmptyCallback = () => void; + type ErrorCallback = (err?: string) => void; + // TODO: Redefine callbacks as subclass of GenericCallback + type GenericCallback = (err: string | null, result?: T) => void; + + type SetObjectCallback = (err: string | null, obj: { id: string }) => void; + type GetObjectCallback = (err: string | null, obj: ioBroker.Object | null | undefined) => void; + type GetEnumCallback = (err: string | null, enums: Record, requestedEnum: string) => void; + type GetEnumsCallback = ( + err: string | null, + result: { + [groupName: string]: Record, + }, + ) => void; + type GetObjectsCallback = (err: string | null, objects: Record) => void; + + type FindObjectCallback = ( + /** If an error happened, this contains the message */ + err: string | null, + /** If an object was found, this contains the ID */ + id?: string, + /** If an object was found, this contains the common.name */ + name?: string, + ) => void; + + interface GetObjectsItem { + /** The ID of this object */ + id: string; + /** A copy of the object from the DB */ + value: T; + } + // This is a version used by GetDevices/GetChannelsOf/GetStatesOf + type GetObjectsCallback3 = (err: string | null, result?: Array>) => void; + + type GetStateCallback = (err: string | null, state: State | null | undefined) => void; + type GetStatesCallback = (err: string | null, states: Record) => void; + /** Version of the callback used by States.getStates */ + type GetStatesCallback2 = (err: string | null, states: State[]) => void; + type GetBinaryStateCallback = (err: string | null, state?: Buffer) => void; + type SetStateCallback = (err: string | null, id?: string) => void; + type SetStateChangedCallback = (err: string | null, id: string, notChanged: boolean) => void; + type DeleteStateCallback = (err: string | null, id?: string) => void; + type GetHistoryCallback = (err: string | null, result: Array<(State & { id?: string })>, step: number, sessionId?: string) => void; + + /** Contains the return values of readDir */ + interface ReadDirResult { + /** Name of the file or directory */ + file: string; + /** File system stats */ + stats: fs.Stats; + /** Whether this is a directory or a file */ + isDir: boolean; + /** Access rights */ + acl: EvaluatedFileACL; + /** Date of last modification */ + modifiedAt: number; + /** Date of creation */ + createdAt: number; + } + type ReadDirCallback = (err: string | null, entries?: ReadDirResult[]) => void; + type ReadFileCallback = (err: string | null, file?: Buffer | string, mimeType?: string) => void; + + /** Contains the return values of chownFile */ + interface ChownFileResult { + /** The parent directory of the processed file or directory */ + path: string; + /** Name of the file or directory */ + file: string; + /** File system stats */ + stats: fs.Stats; + /** Whether this is a directory or a file */ + isDir: boolean; + /** Access rights */ + acl: FileACL; + /** Date of last modification */ + modifiedAt: number; + /** Date of creation */ + createdAt: number; + } + type ChownFileCallback = (err: string | null, entries?: ChownFileResult[], id?: string) => void; + + /** Contains the return values of rm */ + interface RmResult { + /** The parent directory of the deleted file or directory */ + path: string; + /** The name of the deleted file or directory */ + file: string; + /** Whether the deleted object was a directory or a file */ + isDir: boolean; + } + type RmCallback = (err: string | null, entries?: RmResult[]) => void; + + type GetUserGroupCallback = (objectsInstance: Objects, user: User, groups: UserGroup[], acl: ObjectPermissions) => void; + + type ChownObjectCallback = (err: string | null, list?: ioBroker.Object[]) => void; + + type GetConfigKeysCallback = (err: string | null, list?: string[]) => void; + // this is a version of the callback used by Objects.getObjects + type GetObjectsCallback2 = (err: string | null, objects?: Array<(ioBroker.Object | { err: string })>) => void; + + interface GetObjectViewItem { + /** The ID of this object */ + id: string; + /** A copy of the object from the DB or some aggregation result */ + value: ioBroker.Object | unknown; // TODO: find out how the non-Object return result looks like + } + type GetObjectViewCallback = (err: string | null, result?: { rows: GetObjectViewItem[] }) => void; + + interface GetObjectListItem extends GetObjectViewItem { + /** A copy of the object */ + value: ioBroker.Object; + /** The same as @link{value} */ + doc: ioBroker.Object; + } + type GetObjectListCallback = (err: string | null, result?: { rows: GetObjectListItem[] }) => void; + + type ExtendObjectCallback = (err: string | null, result?: { id: string, value: ioBroker.Object }, id?: string) => void; + + type GetSessionCallback = (session: Session) => void; + } // end namespace ioBroker +} // end declare global diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts new file mode 100644 index 0000000000..997775c76f --- /dev/null +++ b/types/iobroker/iobroker-tests.ts @@ -0,0 +1,199 @@ +// For now, this "utils" module is necessary, as it is included in every adapter +// Once this PR is merged and @types/iobroker is available, it will become part of +// `iobroker.adapter-core`, which brings typings for it +declare const utils: { + readonly controllerDir: string; + getConfig(): string; + + // tslint:disable:unified-signatures + adapter(adapterName: string): ioBroker.Adapter; + adapter(adapterOptions: ioBroker.AdapterOptions): ioBroker.Adapter; + // tslint:enable:unified-signatures +}; + +declare function assertNever(val: never): never; + +// Let the tests begin +let adapter: ioBroker.Adapter; + +// Test constructors +adapter = utils.adapter("my-adapter-name"); +adapter = utils.adapter({ + name: "my-adapter-name" +}); +adapter = utils.adapter({ + name: "my-adapter-name", + ready: readyHandler, + stateChange: stateChangeHandler, + objectChange: objectChangeHandler, + message: messageHandler, + unload: unloadHandler, +}); + +// Test EventEmitter definitions +adapter + .on("ready", readyHandler) + .on("stateChange", stateChangeHandler) + .on("objectChange", objectChangeHandler) + .on("message", messageHandler) + .on("unload", unloadHandler) + ; +adapter + .removeListener("ready", readyHandler) + .removeListener("stateChange", stateChangeHandler) + .removeListener("objectChange", objectChangeHandler) + .removeListener("message", messageHandler) + .removeListener("unload", unloadHandler) + ; +adapter.removeAllListeners(); + +function readyHandler() { } + +function stateChangeHandler(id: string, state: ioBroker.State | null | undefined) { + // Test State properties + if (state) { + state.ack; + state.c && state.c.toLowerCase(); + state.expire && state.expire.toFixed(); + state.from.toLowerCase(); + state.lc.toFixed(); + state.q && state.q.toFixed(); + state.ts.toFixed(); + state.val; + } +} + +function objectChangeHandler(id: string, object: ioBroker.Object | null | undefined) { + // Test properties of all objects + if (object) { + object._id.toLowerCase(); + object.common.name.toLowerCase(); + object.common.role && object.common.role.toLowerCase(); + object.common.icon && object.common.icon.toLowerCase(); + object.native.toString(); + object.enums && object.enums.toString(); + if (object.acl) { + object.acl.object.toFixed(); + object.acl.owner.toLowerCase(); + object.acl.ownerGroup.toLowerCase(); + } + // Test different object kinds + switch (object.type) { + case "adapter": + case "config": + case "enum": + case "group": + case "host": + case "info": + case "instance": + case "meta": + case "script": + case "user": + // nothing special here, update these tests when we have specialized definitions + break; + + case "state": + if (object.acl) object.acl.state.toFixed(); + object.common.def; + object.common.desc && object.common.desc.toLowerCase(); + object.common.history; + object.common.max && object.common.max.toFixed(); + object.common.min && object.common.min.toFixed(); + object.common.read.valueOf(); + object.common.states && object.common.states.toString(); + object.common.type && object.common.type.toLowerCase(); + object.common.unit && object.common.unit.toLowerCase(); + object.common.workingID && object.common.workingID.toLowerCase(); + object.common.write.valueOf(); + break; + + case "channel": + object.common.desc && object.common.desc.toLowerCase(); + break; + + case "device": + // nothing special here, update these tests when we have specialized definitions + break; + } + } +} + +function messageHandler(msg: ioBroker.Message) { + msg._id.toFixed(); + msg.callback.ack.valueOf(); + msg.callback.id.toFixed(); + msg.callback.message.toString(); + msg.callback.time.toFixed(); + msg.command.toLowerCase(); + msg.from.toLowerCase(); + msg.message.toString(); +} + +function unloadHandler(callback: ioBroker.EmptyCallback) { + adapter.log.info("shutting down"); + callback(); +} + +// Test the most important methods +adapter.setState("state.name", "value"); +adapter.setState("state.name", "value", true); +adapter.setState("state.name", "value", (err, id) => { }); +adapter.setState("state.name", { val: "value", ack: true }); +adapter.setState("state.name", { val: "value", ack: true }, (err, id) => { }); + +adapter.setStateChanged("state.name", "value"); +adapter.setStateChanged("state.name", "value", true); +adapter.setStateChanged("state.name", "value", (err, id) => { }); +adapter.setStateChanged("state.name", { val: "value", ack: true }); +adapter.setStateChanged("state.name", { val: "value", ack: true }, (err, id) => { }); + +adapter.setForeignState("state.name", "value"); +adapter.setForeignState("state.name", "value", true); +adapter.setForeignState("state.name", "value", (err, id) => { }); +adapter.setForeignState("state.name", { val: "value", ack: true }); +adapter.setForeignState("state.name", { val: "value", ack: true }, (err, id) => { }); + +adapter.setForeignStateChanged("state.name", "value"); +adapter.setForeignStateChanged("state.name", "value", true); +adapter.setForeignStateChanged("state.name", "value", (err, id) => { }); +adapter.setForeignStateChanged("state.name", { val: "value", ack: true }); +adapter.setForeignStateChanged("state.name", { val: "value", ack: true }, (err, id) => { }); + +adapter.setObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }); +adapter.setObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { }); +adapter.setForeignObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }); +adapter.setForeignObject("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { }); + +adapter.setObjectNotExists("obj.id", { type: "state", common: { name: "foo" }, native: {} }); +adapter.setObjectNotExists("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { }); +adapter.setForeignObjectNotExists("obj.id", { type: "state", common: { name: "foo" }, native: {} }); +adapter.setForeignObjectNotExists("obj.id", { type: "state", common: { name: "foo" }, native: {} }, (err, id) => { }); + +adapter.getObject("obj.id", (err, obj) => { }); +adapter.getForeignObject("obj.id", (err, obj) => { }); + +adapter.subscribeObjects("*"); +adapter.subscribeStates("*"); +adapter.subscribeForeignObjects("*"); +adapter.subscribeForeignStates("*"); +adapter.unsubscribeObjects("*"); +adapter.unsubscribeStates("*"); +adapter.unsubscribeForeignObjects("*"); +adapter.unsubscribeForeignStates("*"); + +adapter.log.info("msg"); +adapter.log.debug("msg"); +adapter.log.warn("msg"); +adapter.log.error("msg"); +adapter.log.silly("msg"); + +switch (adapter.log.level) { + case "debug": + case "error": + case "info": + case "silly": + case "warn": + break; + default: + assertNever(adapter.log.level); +} diff --git a/types/iobroker/tsconfig.json b/types/iobroker/tsconfig.json new file mode 100644 index 0000000000..5d7e32bdb6 --- /dev/null +++ b/types/iobroker/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "iobroker-tests.ts" + ] +} diff --git a/types/iobroker/tslint.json b/types/iobroker/tslint.json new file mode 100644 index 0000000000..bdafdd99b4 --- /dev/null +++ b/types/iobroker/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // This package has its own type `Object` which is not equal to the global `Object` type + // To avoid any confusion, it is referenced as `ioBroker.Object` instead of just `Object` + "no-unnecessary-qualifier": false + } +} diff --git a/types/irc/irc-tests.ts b/types/irc/irc-tests.ts index b2603e7037..284bb190c7 100644 --- a/types/irc/irc-tests.ts +++ b/types/irc/irc-tests.ts @@ -13,15 +13,15 @@ function test_bot() { console.log("Connected"); }); - bot.addListener('error', ((message: irc.IMessage) => { + bot.addListener('error', ((message: irc.IMessage) => { console.error('ERROR: %s: %s', message.command, message.args.join(' ')); - })); + }) as irc.handlers.IError); - bot.addListener('message#blah', ((from: string, message: string) => { + bot.addListener('message#blah', ((from: string, message: string) => { console.log('<%s> %s', from, message); - })); + }) as irc.handlers.IMessageChannel); - bot.addListener('message', ((from: string, to: string, message: string) => { + bot.addListener('message', ((from: string, to: string, message: string) => { console.log('%s => %s: %s', from, to, message); if (to.match(/^[#&]/)) { @@ -40,23 +40,23 @@ function test_bot() { // private message console.log('private message'); } - })); + }) as irc.handlers.IRecievedMessage); - bot.addListener('pm', ((nick: string, message: string) => { + bot.addListener('pm', ((nick: string, message: string) => { console.log('Got private message from %s: %s', nick, message); - })); + }) as irc.handlers.IPm); - bot.addListener('join', ((channel: string, who: string) => { + bot.addListener('join', ((channel: string, who: string) => { console.log('%s has joined %s', who, channel); - })); + }) as irc.handlers.IJoin); - bot.addListener('part', ((channel: string, who: string, reason: string) => { + bot.addListener('part', ((channel: string, who: string, reason: string) => { console.log('%s has left %s: %s', who, channel, reason); - })); + }) as irc.handlers.IPart); - bot.addListener('kick', ((channel: string, who: string, by: string, reason: string) => { + bot.addListener('kick', ((channel: string, who: string, by: string, reason: string) => { console.log('%s was kicked from %s by %s: %s', who, channel, by, reason); - })); + }) as irc.handlers.IKick); } function test_secure() { diff --git a/types/iri/index.d.ts b/types/iri/index.d.ts new file mode 100644 index 0000000000..93183bcfad --- /dev/null +++ b/types/iri/index.d.ts @@ -0,0 +1,89 @@ +// Type definitions for iri 1.3 +// Project: https://github.com/awwright/node-iri +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export class IRI { + /** + * The constructor takes a single argument, a URI or IRI string: + */ + constructor(iri: string); + /** + * Returns UTF-16 IRI + */ + toString(): string; + /** + * Returns the IRI without the fragment component. Useful for dereferencing URLs on a network. + */ + defrag(): IRI; + /** + * IRIs with a fragment are not absolute. + */ + isAbsolute(): boolean; + /** + * Resolves the IRI against itself, having the effect of stripping the fragment and checking that the supplied IRI is valid (absolute). + */ + toAbsolute(): IRI; + /** + * Resolves the IRI against itself, having the effect of stripping the fragment and checking that the supplied IRI is valid (absolute). + */ + authority(): string | null; + /** + * Returns the fragment component of the IRI. + */ + fragment(): string | null; + /** + * Returns the hier-part of the IRI, the hierarchial component: Everything between the scheme and query, including leading `//` for the host, if it exists. + */ + hierpart(): string; + /** + * Returns the host component of the URI, either a domain name or string-formatted IP address. Excludes port number and username/password. + */ + host(): string; + /** + * Returns the path component of the hier-part. Does not include the authority/host, query, or fragment. + */ + path(): string; + /** + * Returns the port component of the authority as a string, or `null` if there is no port. + */ + port(): string | null; + /** + * Returns the query component of the IRI including leading "?", or `null` if there is no query component. + */ + query(): string | null; + /** + * Resolve the provided URI/IRI reference against this IRI. + */ + resolveReference(ref: string | IRI): IRI; + /** + * Returns the scheme of the IRI, e.g. "https", "file", or "urn". + */ + scheme(): string | null; + /** + * Returns the username/password component of the IRI. + */ + userinfo(): string | null; + /** + * Returns a URI formatted string with only 7-bit characters. + */ + toURIString(): string; + /** + * Decodes URI-encoded UTF-8 characters and returns a unicode string (Strings in ECMAScript/JavaScript are UTF-16). + */ + toIRIString(): string; + /** + * Returns a new IRI object with URI-encoded UTF-8 characters decoded. + */ + toIRI(): IRI; +} + +/** + * Returns an iri.IRI object with UTF-8 escaped characterd decoded. + */ +export function fromURI(uri: string): IRI; + +/** + * Returns an IRI string decoded from the given URI. + */ +export function toIRIString(uri: string): string; diff --git a/types/iri/iri-tests.ts b/types/iri/iri-tests.ts new file mode 100644 index 0000000000..97a460e02c --- /dev/null +++ b/types/iri/iri-tests.ts @@ -0,0 +1,43 @@ +import { IRI, fromURI, toIRIString } from 'iri'; + +const iri = new IRI('iri'); +// $ExpectType string +iri.toString(); +// $ExpectType IRI +iri.defrag(); +// $ExpectType boolean +iri.isAbsolute(); +// $ExpectType IRI +iri.toAbsolute(); +// $ExpectType string | null +iri.authority(); +// $ExpectType string | null +iri.fragment(); +// $ExpectType string +iri.hierpart(); +// $ExpectType string +iri.host(); +// $ExpectType string +iri.path(); +// $ExpectType string | null +iri.port(); +// $ExpectType string | null +iri.query(); +// $ExpectType IRI +iri.resolveReference('ref'); +iri.resolveReference(iri); +// $ExpectType string | null +iri.scheme(); +// $ExpectType string | null +iri.userinfo(); +// $ExpectType string +iri.toURIString(); +// $ExpectType string +iri.toIRIString(); +// $ExpectType IRI +iri.toIRI(); + +// $ExpectType IRI +fromURI('u'); +// $ExpectType string +toIRIString('u'); diff --git a/types/iri/tsconfig.json b/types/iri/tsconfig.json new file mode 100644 index 0000000000..09b1e0069e --- /dev/null +++ b/types/iri/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "iri-tests.ts" + ] +} diff --git a/types/iri/tslint.json b/types/iri/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/iri/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index e9dba1e2cd..a87b8b3a86 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -639,6 +639,7 @@ declare namespace jasmine { calls: Calls; mostRecentCall: { args: any[]; }; argsForCall: any[]; + withArgs(...args: any[]): Spy; } type SpyObj = T & { diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index ba8763ce3d..92f9a21db8 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -469,6 +469,40 @@ describe("A spy, when configured with an alternate implementation", () => { }); }); +describe("A spy, when configured with alternate implementations for specified arguments", () => { + var foo: any, bar: any, fetchedBar: any; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + }, + getBar: () => { + return bar; + } + }; + + spyOn(foo, "getBar") + .withArgs(1, "2") + .and.callFake(() => 1002); + + foo.setBar(123); + fetchedBar = foo.getBar(1, "2"); + }); + + it("tracks that the spy was called", () => { + expect(foo.getBar).toHaveBeenCalled(); + }); + + it("should not effect other functions", () => { + expect(bar).toEqual(123); + }); + + it("when called returns the requested value", () => { + expect(fetchedBar).toEqual(1002); + }); +}); + describe("A spy, when configured to throw a value", () => { var foo: any, bar: any; diff --git a/types/jest-when/index.d.ts b/types/jest-when/index.d.ts index af62a95830..f484502f4d 100644 --- a/types/jest-when/index.d.ts +++ b/types/jest-when/index.d.ts @@ -8,6 +8,11 @@ export interface PartialMockInstance { mockReturnValue: jest.MockInstance['mockReturnValue']; + mockReturnValueOnce: jest.MockInstance['mockReturnValueOnce']; + mockResolvedValue: jest.MockInstance['mockResolvedValue']; + mockResolvedValueOnce: jest.MockInstance['mockResolvedValueOnce']; + mockRejectedValue: jest.MockInstance['mockRejectedValue']; + mockRejectedValueOnce: jest.MockInstance['mockRejectedValueOnce']; } export interface When { diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 2b378a6048..d434b5e198 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -251,7 +251,7 @@ declare namespace jest { * @param fn The function for your test * @param timeout The timeout for an async function test */ - (name: string, fn: ProvidesCallback, timeout?: number): void; + (name: string, fn?: ProvidesCallback, timeout?: number): void; /** * Only runs this test in the current file. */ diff --git a/types/jju/index.d.ts b/types/jju/index.d.ts new file mode 100644 index 0000000000..f8bf96d639 --- /dev/null +++ b/types/jju/index.d.ts @@ -0,0 +1,213 @@ +// Type definitions for jju 1.4 +// Project: https://github.com/rlidwka/jju +// Definitions by: Elizabeth Craig +// Alex Kocharin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Disabling unified-signatures rule so different documentation can be provided for each signature. +// tslint:disable:unified-signatures + +export interface ParseOptions { + /** + * What to do with reserved keys (default 'ignore'). + * - "ignore" - ignore reserved keys + * - "throw" - throw SyntaxError in case of reserved keys + * - "replace" - replace reserved keys, this is the default JSON.parse behaviour, unsafe + */ + reserved_keys?: 'ignore' | 'throw' | 'replace'; + + /** + * Create object as `Object.create(null)` instead of `{}`. + * - If reserved_keys != 'replace', default is false. + * - If reserved_keys == 'replace', default is true. + * + * It is usually unsafe and not recommended to change this option to false in the last case. + */ + null_prototype?: boolean; + + /** + * Reviver function (follows the JSON spec). This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + reviver?: (key: any, value: any) => any; + + /** + * Operation mode (default 'json5'). Set to 'json' if you want to throw on non-strict json files. + */ + mode?: 'json5' | 'json' | 'cjson'; +} + +export interface StringifyOptions { + /** + * Output ascii only (default false). + * If this option is enabled, output will not have any characters except 0x20-0x7f. + */ + ascii?: boolean; + + /** + * This option follows JSON specification. + * @default '\t' + */ + indent?: string | number | boolean; + + /** + * Enquoting char. + * - If `mode` is 'json', default is " + * - Otherwise, default is ' + */ + quote?: '"' | "'"; + + /** + * Whether keys quoting in objects is required or not. + * If you want `{"q": 1}` instead of `{q: 1}`, set it to true. + * - If `mode` is 'json', default is true + * - Otherwise, default is false + */ + quote_keys?: boolean; + + /** + * Sort all keys while stringifying. + * By default sort order will depend on implementation--with v8 it's insertion order. + * If set to true, all keys (but not arrays) will be sorted alphabetically. + * You can provide your own sorting function as well. + * @default false + */ + sort_keys?: boolean | ((a: any, b: any) => number); + + /** + * Replacer function or array. This option follows JSON specification. + * If a function, used to transform the results. + * If an array, acts as a approved list for selecting the object properties that will be stringified. + */ + replacer?: ((key: string, value: any) => any) | Array; + + /** + * Don't output trailing comma. If this option is set, arrays like `[1,2,3,]` will never be generated. + * Otherwise they may be generated for pretty printing. + * - If `mode` is JSON, default is true + * - Otherwise, default is false + */ + no_trailing_comma?: boolean; + + /** + * Operation mode. Set it to 'json' if you want correct json in the output. + * If it is 'json', following options are implied: + * - options.quote = '"' + * - options.no_trailing_comma = true + * - options.quote_keys = true + * - '\x' literals are not used + */ + mode?: 'json' | 'json5' | 'cjson'; +} + +/** + * Represents a token in a JSON file. + */ +export interface Token { + /** Raw text of this token. If you join all raws, you will get the original document. */ + raw: string; + /** Type of the token. */ + type: 'whitespace' | 'comment' | 'key' | 'literal' | 'separator' | 'newline'; + /** Path to the current token in the syntax tree. */ + stack: string[]; + /** Value of the token if token is a key or literal. */ + value?: any; +} + +/** + * Object defining a programming style in which the JSON document was written. + */ +export interface JsonStyle { + /** Preferred indentation. */ + indent: string; + /** Preferred newline. */ + newline: string; + /** " or ' depending on which quote is preferred. */ + quote: string; + /** True if unquoted keys were used at least once. */ + quote_keys: boolean; + /** True if input has a whitespace token. */ + has_whitespace: boolean; + /** True if input has a comment token. */ + has_comments: boolean; + /** True if input has a newline token. */ + has_newlines: boolean; + /** True if input has at least one trailing comma. */ + has_trailing_comma: boolean; +} + +/** + * Parse json/json5 text and returns a javascript value it corresponds to. + * @param text Text to parse + * @param options Parser options + */ +export function parse(text: string, options?: ParseOptions): any; +/** + * Compatibility syntax (follows JSON specification). + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ +export function parse(text: string, reviver?: (key: any, value: any) => any): any; + +/** + * Convert javascript value to an appropriate json/json5 text. + * @param value Value to serialize + * @param options Serializer options + */ +export function stringify(value: any, options?: StringifyOptions): string; +/** + * Compatibility syntax (follows JSON specification). + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ +export function stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; +/** + * Compatibility syntax (follows JSON specification). + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ +export function stringify(value: any, replacer?: Array | null, space?: string | number): string; + +/** + * Parse json/json5 text and return an array of tokens it consists of. + * @param text Text to tokenize + * @param options Parser options + */ +export function tokenize(text: string, options?: ParseOptions): Token[]; + +/** + * Parse json/json5 text and try to guess indentation, quoting style, etc. + * @param text Text to analyze + * @param options Parser options + */ +export function analyze(text: string, options?: ParseOptions): JsonStyle; + +/** + * Change json/json5 text, preserving original formatting as much as possible. + * @param text Original text + * @param new_value New value you want to set + * @param options Parser and stringifier options + * + * @example + * // here is your original JSON document: + * var input = '{"foo": "bar", "baz": 123}' + * + * // you need to parse it first: + * var json = jju.parse(input, {mode: 'json'}) + * // json is { foo: 'bar', baz: 123 } + * + * // then you can change it as you like: + * json.foo = 'quux' + * json.hello = 'world' + * + * // then you run an update function to change the original json: + * var output = jju.update(input, json, {mode: 'json'}) + * // output is '{"foo": "quux", "baz": 123, "hello": "world"}' + */ +export function update(text: string, new_value: any, options?: ParseOptions & StringifyOptions): string; diff --git a/types/jju/jju-tests.ts b/types/jju/jju-tests.ts new file mode 100644 index 0000000000..0de4d973b1 --- /dev/null +++ b/types/jju/jju-tests.ts @@ -0,0 +1,4 @@ +import * as jju from 'jju'; + +jju.parse('{}'); // $ExpectType any +jju.stringify({}); // $ExpectType string diff --git a/types/jju/tsconfig.json b/types/jju/tsconfig.json new file mode 100644 index 0000000000..08bb6638c7 --- /dev/null +++ b/types/jju/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jju-tests.ts" + ] +} diff --git a/types/jju/tslint.json b/types/jju/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jju/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/johnny-five/index.d.ts b/types/johnny-five/index.d.ts index 6a00952153..a770cd2126 100644 --- a/types/johnny-five/index.d.ts +++ b/types/johnny-five/index.d.ts @@ -365,22 +365,22 @@ export declare class LCD { rows: number; cols: number; - print(message: string): void; - useChar(char: string): void; - clear(): void; - cursor(row: number, col: number): void; - home(): void; - on(): void; - off(): void; - display(): void; - noDisplay(): void; - blink(): void; - noBlink(): void; - autoscroll(): void; - noAutoscroll(): void; - bgColor(color: any): void; - noBacklight(): void; - backlight(): void; + print(message: string): this; + useChar(char: string): this; + clear(): this; + cursor(row: number, col: number): this; + home(): this; + on(): this; + off(): this; + display(): this; + noDisplay(): this; + blink(): this; + noBlink(): this; + autoscroll(): this; + noAutoscroll(): this; + bgColor(color: any): this; + noBacklight(): this; + backlight(): this; } export interface LedOption { diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 096847a82c..404e0339ef 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -504,6 +504,11 @@ export interface NumberSchema extends AnySchema { */ integer(): this; + /** + * Allows the number to be outside of JavaScript's safety range (Number.MIN_SAFE_INTEGER & Number.MAX_SAFE_INTEGER). + */ + unsafe(enabled?: boolean): this; + /** * Specifies the maximum number of decimal places where: * @param limit - the maximum number of decimal places allowed. diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 716fc70c16..e21310396b 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -618,6 +618,7 @@ numSchema = numSchema.greater(ref); numSchema = numSchema.less(num); numSchema = numSchema.less(ref); numSchema = numSchema.integer(); +numSchema = numSchema.unsafe(); numSchema = numSchema.precision(num); numSchema = numSchema.multiple(num); numSchema = numSchema.positive(); diff --git a/types/jquery-focus-exit/index.d.ts b/types/jquery-focus-exit/index.d.ts index 8787136a4e..d4da0a1f18 100644 --- a/types/jquery-focus-exit/index.d.ts +++ b/types/jquery-focus-exit/index.d.ts @@ -14,7 +14,7 @@ export interface FocusElements { declare global { interface JQuery { focusExit(options?: { debug: boolean }): JQuery; - on(event: 'focusExit', handler: ((event: JQuery.Event, data: FocusElements) => void)): JQuery; - one(event: 'focusin', handler: ((event: JQuery.Event) => void)): JQuery; + on(event: 'focusExit', handler: ((event: JQuery.TriggeredEvent, data: FocusElements) => void)): JQuery; + one(event: 'focusin', handler: ((event: JQuery.TriggeredEvent) => void)): JQuery; } } diff --git a/types/jquery-mouse-exit/index.d.ts b/types/jquery-mouse-exit/index.d.ts index f0ba17996e..651a7b3f85 100644 --- a/types/jquery-mouse-exit/index.d.ts +++ b/types/jquery-mouse-exit/index.d.ts @@ -18,6 +18,6 @@ export type FocusElements = Partial<{ declare global { interface JQuery { mouseExit(options?: Options): JQuery; - on(event: 'mouseExit', handler: ((event: JQuery.Event, data: FocusElements) => void)): JQuery; + on(event: 'mouseExit', handler: ((event: JQuery.TriggeredEvent, data: FocusElements) => void)): JQuery; } } diff --git a/types/jquery.colorpicker/tslint.json b/types/jquery.colorpicker/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/jquery.colorpicker/tslint.json +++ b/types/jquery.colorpicker/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jquery.fancytree/tslint.json b/types/jquery.fancytree/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/jquery.fancytree/tslint.json +++ b/types/jquery.fancytree/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jquery.pjax/tslint.json b/types/jquery.pjax/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/jquery.pjax/tslint.json +++ b/types/jquery.pjax/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jquery/JQuery.d.ts b/types/jquery/JQuery.d.ts index 7453457953..78602a2d8b 100644 --- a/types/jquery/JQuery.d.ts +++ b/types/jquery/JQuery.d.ts @@ -530,7 +530,10 @@ $( document ).ajaxComplete(function( event, request, settings ) { }); ``` */ - ajaxComplete(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings) => void | false): this; + ajaxComplete(handler: (this: Document, + event: JQuery.TriggeredEvent, + jqXHR: JQuery.jqXHR, + ajaxOptions: JQuery.AjaxSettings) => void | false): this; /** * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. * @param handler The function to be invoked. @@ -543,7 +546,11 @@ $( document ).ajaxError(function( event, request, settings ) { }); ``` */ - ajaxError(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxSettings: JQuery.AjaxSettings, thrownError: string) => void | false): this; + ajaxError(handler: (this: Document, + event: JQuery.TriggeredEvent, + jqXHR: JQuery.jqXHR, + ajaxSettings: JQuery.AjaxSettings, + thrownError: string) => void | false): this; /** * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. * @param handler The function to be invoked. @@ -556,7 +563,10 @@ $( document ).ajaxSend(function( event, request, settings ) { }); ``` */ - ajaxSend(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings) => void | false): this; + ajaxSend(handler: (this: Document, + event: JQuery.TriggeredEvent, + jqXHR: JQuery.jqXHR, + ajaxOptions: JQuery.AjaxSettings) => void | false): this; /** * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. * @param handler The function to be invoked. @@ -595,7 +605,11 @@ $( document ).ajaxSuccess(function( event, request, settings ) { }); ``` */ - ajaxSuccess(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings, data: JQuery.PlainObject) => void | false): this; + ajaxSuccess(handler: (this: Document, + event: JQuery.TriggeredEvent, + jqXHR: JQuery.jqXHR, + ajaxOptions: JQuery.AjaxSettings, + data: JQuery.PlainObject) => void | false): this; /** * Perform a custom animation of a set of CSS properties. * @param properties An object of CSS properties and values that the animation will move toward. @@ -1329,9 +1343,12 @@ $( "p" ).before( $( "b" ) ); * * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ - bind(eventType: string, - eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + bind( + eventType: TType, + eventData: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach a handler to an event for the elements. * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. @@ -1458,8 +1475,13 @@ $( "button" ).click(function() { ``` */ - bind(eventType: string, - handler_preventBubble: JQuery.EventHandler | JQuery.EventHandlerBase> | false | null | undefined): this; + bind( + eventType: TType, + handler_preventBubble: JQuery.TypeEventHandler | + false | + null | + undefined + ): 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. @@ -1485,7 +1507,7 @@ $( "div.test" ).bind({ }); ``` */ - bind(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; + bind(events: JQuery.TypeEventHandlers): this; /** * Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -1499,7 +1521,7 @@ $( "div.test" ).bind({ * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ blur(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -1515,7 +1537,8 @@ $( "div.test" ).bind({ $( "p" ).blur(); ``` */ - blur(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + blur(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "change" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -1529,7 +1552,7 @@ $( "p" ).blur(); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ change(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "change" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -1588,7 +1611,8 @@ $( "input[type='text']" ).change(function() { }); ``` */ - change(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + change(handler?: JQuery.TypeEventHandler | + false): this; /** * Get the children of each element in the set of matched elements, optionally filtered by a selector. * @param selector A string containing a selector expression to match elements against. @@ -1841,7 +1865,7 @@ $( "#stop" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ click(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "click" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -1891,7 +1915,8 @@ $( "p" ).click(function() { $( "p" ).click(); ``` */ - click(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + click(handler?: JQuery.TypeEventHandler | + false): this; /** * Create a deep copy of the set of matched elements. * @param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The @@ -2065,7 +2090,7 @@ $( "#frameDemo" ).contents().find( "a" ).css( "background-color", "#BADA55" ); ``` */ - contents(): JQuery; + contents(): JQuery; /** * Bind an event handler to the "contextmenu" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -2079,7 +2104,7 @@ $( "#frameDemo" ).contents().find( "a" ).css( "background-color", "#BADA55" ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ contextmenu(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "contextmenu" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -2133,7 +2158,8 @@ div.contextmenu(function() { ``` */ - contextmenu(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + contextmenu(handler?: JQuery.TypeEventHandler | + false): this; /** * Set one or more CSS properties for the set of matched elements. * @param propertyName A CSS property name. @@ -2594,7 +2620,7 @@ $( "button" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ dblclick(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -2648,7 +2674,8 @@ divdbl.dblclick(function() { ``` */ - dblclick(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + dblclick(handler?: JQuery.TypeEventHandler | + false): this; /** * Set a timer to delay execution of subsequent items in the queue. * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. @@ -2713,10 +2740,13 @@ $( "button" ).click(function() { * * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ - delegate(selector: JQuery.Selector, - eventType: string, - eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + delegate( + selector: JQuery.Selector, + eventType: TType, + eventData: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. * @param selector A selector to filter the elements that trigger the event. @@ -2828,9 +2858,12 @@ $( "button" ).click(function() { ``` */ - delegate(selector: JQuery.Selector, - eventType: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + delegate( + selector: JQuery.Selector, + eventType: TType, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. * @param selector A selector to filter the elements that trigger the event. @@ -2844,7 +2877,8 @@ $( "button" ).click(function() { * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ delegate(selector: JQuery.Selector, - events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; + events: JQuery.TypeEventHandlers + ): this; /** * Execute the next function on the queue for the matched elements. * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. @@ -4264,7 +4298,7 @@ $( "p span" ).first().addClass( "highlight" ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focus(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focus" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -4316,7 +4350,8 @@ $( document ).ready(function() { }); ``` */ - focus(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + focus(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "focusin" event. * @param eventData An object containing data that will be passed to the event handler. @@ -4330,7 +4365,7 @@ $( document ).ready(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focusin(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focusin" event. * @param handler A function to execute each time the event is triggered. @@ -4370,7 +4405,8 @@ $( "p" ).focusin(function() { ``` */ - focusin(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + focusin(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "focusout" JavaScript event. * @param eventData An object containing data that will be passed to the event handler. @@ -4384,7 +4420,7 @@ $( "p" ).focusin(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focusout(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focusout" JavaScript event. * @param handler A function to execute each time the event is triggered. @@ -4445,7 +4481,8 @@ $( "p" ) ``` */ - focusout(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + focusout(handler?: JQuery.TypeEventHandler | + false): this; /** * Retrieve one of the elements matched by the jQuery object. * @param index A zero-based integer indicating which element to retrieve. @@ -4888,12 +4925,11 @@ $( "button" ).click(function() { */ hide(duration_complete_options?: JQuery.Duration | ((this: TElement) => void) | JQuery.EffectsOptions): this; /** - * Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. - * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. + * @param handlerIn A function to execute when the mouse pointer enters the element. * @param handlerOut A function to execute when the mouse pointer leaves the element. * @see \`{@link https://api.jquery.com/hover/ }\` * @since 1.0 - * @since 1.4 * @deprecated ​ Deprecated. * * **Cause**: The `.hover()` method is a shorthand for the use of the `mouseover`/`mouseout` events. It is often a poor user interface choice because it does not allow for any small amounts of delay between when the mouse enters or exits an area and when the event fires. This can make it quite difficult to use with UI widgets such as drop-down menus. For more information on the problems of hovering, see the \`{@link http://cherne.net/brian/resources/jquery.hoverIntent.html hoverIntent plugin}\`. @@ -4961,6 +4997,21 @@ $( "td" ).hover( ```javascript $( "td" ).off( "mouseenter mouseleave" ); ``` + */ + hover(handlerIn: JQuery.TypeEventHandler | + false, + handlerOut: JQuery.TypeEventHandler | + false): this; + /** + * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. + * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + * @see \`{@link https://api.jquery.com/hover/ }\` + * @since 1.4 + * @deprecated ​ Deprecated. + * + * **Cause**: The `.hover()` method is a shorthand for the use of the `mouseover`/`mouseout` events. It is often a poor user interface choice because it does not allow for any small amounts of delay between when the mouse enters or exits an area and when the event fires. This can make it quite difficult to use with UI widgets such as drop-down menus. For more information on the problems of hovering, see the \`{@link http://cherne.net/brian/resources/jquery.hoverIntent.html hoverIntent plugin}\`. + * + * **Solution**: Review uses of `.hover()` to determine if they are appropriate, and consider use of plugins such as `hoverIntent` as an alternative. The direct replacement for `.hover(fn1, fn2)`, is `.on("mouseenter", fn1).on("mouseleave", fn2)`. * @example ​ ````Slide the next sibling LI up or down on hover, and toggle a class. ```html @@ -5016,10 +5067,8 @@ $( "li" ) ``` */ - // HACK: The type parameter T is not used but ensures the 'event' callback parameter is typed correctly. - // tslint:disable-next-line:no-unnecessary-generics - hover(handlerInOut: JQuery.EventHandler | JQuery.EventHandlerBase> | false, - handlerOut?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + hover(handlerInOut: JQuery.TypeEventHandler | + false): this; /** * Set the HTML contents of each element in the set of matched elements. * @param htmlString_function _@param_ `htmlString_function` @@ -5833,7 +5882,7 @@ $( "li" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keydown(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -5905,7 +5954,8 @@ $( "#other" ).click(function() { ``` */ - keydown(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + keydown(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -5919,7 +5969,7 @@ $( "#other" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keypress(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -5991,7 +6041,8 @@ $( "#other" ).click(function() { ``` */ - keypress(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + keypress(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6005,7 +6056,7 @@ $( "#other" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keyup(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6078,7 +6129,8 @@ $( "#other").click(function() { ``` */ - keyup(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + keyup(handler?: JQuery.TypeEventHandler | + false): this; /** * Reduce the set of matched elements to the final one in the set. * @see \`{@link https://api.jquery.com/last/ }\` @@ -6367,7 +6419,7 @@ $( "input" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mousedown(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6405,7 +6457,8 @@ $( "p" ) ``` */ - mousedown(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mousedown(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6419,7 +6472,7 @@ $( "p" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseenter(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. * @param handler A function to execute each time the event is triggered. @@ -6500,7 +6553,8 @@ $( "div.enterleave" ) ``` */ - mouseenter(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseenter(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6514,7 +6568,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseleave(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. * @param handler A function to execute each time the event is triggered. @@ -6593,7 +6647,8 @@ $( "div.enterleave" ) ``` */ - mouseleave(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseleave(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6607,7 +6662,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mousemove(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6671,7 +6726,8 @@ $( "div" ).mousemove(function( event ) { ``` */ - mousemove(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mousemove(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6685,7 +6741,7 @@ $( "div" ).mousemove(function( event ) { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseout(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6766,7 +6822,8 @@ $( "div.enterleave" ) ``` */ - mouseout(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseout(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6780,7 +6837,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseover(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6861,7 +6918,8 @@ $( "div.enterleave" ) ``` */ - mouseover(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseover(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6875,7 +6933,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseup(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6913,7 +6971,8 @@ $( "p" ) ``` */ - mouseup(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseup(handler?: JQuery.TypeEventHandler | + false): 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. * @param selector A string containing a selector expression to match elements against. @@ -7245,7 +7304,10 @@ $( "body" ).on( "click", "p", foo ); $( "body" ).off( "click", "p", foo ); ``` */ - off(events: string, selector: JQuery.Selector, handler: JQuery.EventHandlerBase> | false): this; + off(events: string, + selector: JQuery.Selector, + handler: JQuery.TypeEventHandler | + false): this; /** * Remove an event handler. * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as @@ -7275,7 +7337,10 @@ $( "form" ).on( "keypress.validator", "input[type='text']", validate ); $( "form" ).off( ".validator" ); ``` */ - off(events: string, selector_handler?: JQuery.Selector | JQuery.EventHandlerBase> | false): this; + off(events: string, + selector_handler?: JQuery.Selector | + JQuery.TypeEventHandler | + false): this; /** * Remove an event handler. * @param events An object where the string keys represent one or more space-separated event types and optional @@ -7284,7 +7349,8 @@ $( "form" ).off( ".validator" ); * @see \`{@link https://api.jquery.com/off/ }\` * @since 1.7 */ - off(events: JQuery.PlainObject> | false>, selector?: JQuery.Selector): this; + off(events: JQuery.TypeEventHandlers, + selector?: JQuery.Selector): this; /** * Remove an event handler. * @param event A jQuery.Event object. @@ -7295,7 +7361,7 @@ $( "form" ).off( ".validator" ); $( "p" ).off(); ``` */ - off(event?: JQuery.Event): this; + off(event?: JQuery.TriggeredEvent): this; /** * Set the current coordinates of every element in the set of matched elements, relative to the document. * @param coordinates_function _@param_ `coordinates_function` @@ -7468,10 +7534,30 @@ $( "*", document.body ).click(function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: string, - selector: JQuery.Selector | null, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + on( + events: TType, + selector: JQuery.Selector, + data: TData, + handler: JQuery.TypeEventHandler + ): this; + /** + * Attach an event handler function for one or more events to the selected elements. + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the + * selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. + * @see \`{@link https://api.jquery.com/on/ }\` + * @since 1.7 + */ + on( + events: TType, + selector: null | undefined, + data: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7484,7 +7570,7 @@ $( "*", document.body ).click(function( event ) { * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\` in place of \`{@link JQueryEventObject }\`. */ on(events: string, - selector: JQuery.Selector | null, + selector: JQuery.Selector | null | undefined, data: any, handler: ((event: JQueryEventObject) => void)): this; /** @@ -7547,14 +7633,41 @@ $( "body" ).on( "click", "a", function( event ) { }); ``` */ - on(events: string, - selector: JQuery.Selector, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + on( + events: TType, + selector: JQuery.Selector, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the - * selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. + * @see \`{@link https://api.jquery.com/on/ }\` + * @since 1.7 + * @example ​ ````Pass data to the event handler, which is specified here by name: +```javascript +function myHandler( event ) { + alert( event.data.foo ); +} +$( "p" ).on( "click", { foo: "bar" }, myHandler ); +``` + */ + on( + events: TType, + data: TData, + handler: JQuery.TypeEventHandler + ): this; + /** + * Attach an event handler function for one or more events to the selected elements. + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector_data _@param_ `selector_data` + *
+ * * `selector` — A selector string to filter the descendants of the selected elements that trigger the event. If the + * selector is null or omitted, the event is always triggered when it reaches the selected element.
+ * * `data` — Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 @@ -7609,37 +7722,6 @@ $( "body" ).on( "click", "a", function( event ) { event.preventDefault(); }); ``` - */ - on(events: string, - selector: JQuery.Selector, - // tslint:disable-next-line:unified-signatures - handler: ((event: JQueryEventObject) => void)): this; - /** - * Attach an event handler function for one or more events to the selected elements. - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. - * @see \`{@link https://api.jquery.com/on/ }\` - * @since 1.7 - * @example ​ ````Pass data to the event handler, which is specified here by name: -```javascript -function myHandler( event ) { - alert( event.data.foo ); -} -$( "p" ).on( "click", { foo: "bar" }, myHandler ); -``` - */ - on(events: string, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; - /** - * Attach an event handler function for one or more events to the selected elements. - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. - * @see \`{@link https://api.jquery.com/on/ }\` - * @since 1.7 - * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\` in place of \`{@link JQueryEventObject }\`. * @example ​ ````Pass data to the event handler, which is specified here by name: ```javascript function myHandler( event ) { @@ -7649,8 +7731,7 @@ $( "p" ).on( "click", { foo: "bar" }, myHandler ); ``` */ on(events: string, - // tslint:disable-next-line:unified-signatures - data: any, + selector_data: any, handler: ((event: JQueryEventObject) => void)): this; /** * Attach an event handler function for one or more events to the selected elements. @@ -7743,8 +7824,11 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { }); ``` */ - on(events: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + on( + events: TType, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7837,7 +7921,6 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { ``` */ on(events: string, - // tslint:disable-next-line:unified-signatures handler: ((event: JQueryEventObject) => void)): this; /** * Attach an event handler function for one or more events to the selected elements. @@ -7849,9 +7932,26 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - selector: JQuery.Selector | null, - data: TData): this; + on( + events: JQuery.TypeEventHandlers, + selector: JQuery.Selector, + data: TData + ): this; + /** + * Attach an event handler function for one or more events to the selected elements. + * @param events An object in which the string keys represent one or more space-separated event types and optional + * namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If + * the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + * @see \`{@link https://api.jquery.com/on/ }\` + * @since 1.7 + */ + on( + events: JQuery.TypeEventHandlers, + selector: null | undefined, + data: TData + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -7861,9 +7961,9 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - // tslint:disable-next-line:unified-signatures - selector: JQuery.Selector): this; + on(events: JQuery.TypeEventHandlers, + selector: JQuery.Selector + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -7872,8 +7972,10 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - data: TData): this; + on( + events: JQuery.TypeEventHandlers, + data: TData + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -7922,7 +8024,7 @@ $( "div.test" ).on({ ``` */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; + on(events: JQuery.TypeEventHandlers): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7933,10 +8035,30 @@ $( "div.test" ).on({ * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: string, - selector: JQuery.Selector | null, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + one( + events: TType, + selector: JQuery.Selector, + data: TData, + handler: JQuery.TypeEventHandler + ): this; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the + * selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. + * @see \`{@link https://api.jquery.com/one/ }\` + * @since 1.7 + */ + one( + events: TType, + selector: null | undefined, + data: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7947,9 +8069,12 @@ $( "div.test" ).on({ * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: string, + one( + events: TType, selector: JQuery.Selector, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + handler: JQuery.TypeEventHandler | + false + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7958,9 +8083,12 @@ $( "div.test" ).on({ * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: string, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + one( + events: TType, + data: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -8049,8 +8177,11 @@ $(".target").one("click mouseenter", function() { ``` */ - one(events: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + one( + events: TType, + handler: JQuery.TypeEventHandler| + false + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -8061,9 +8192,26 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - selector: JQuery.Selector | null, - data: TData): this; + one( + events: JQuery.TypeEventHandlers, + selector: JQuery.Selector, + data: TData + ): this; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * @param events An object in which the string keys represent one or more space-separated event types and optional + * namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If + * the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + * @see \`{@link https://api.jquery.com/one/ }\` + * @since 1.7 + */ + one( + events: JQuery.TypeEventHandlers, + selector: null | undefined, + data: TData + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -8073,8 +8221,7 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - // tslint:disable-next-line:unified-signatures + one(events: JQuery.TypeEventHandlers, selector: JQuery.Selector): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. @@ -8084,8 +8231,10 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - data: TData): this; + one( + events: JQuery.TypeEventHandlers, + data: TData + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -8093,7 +8242,7 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; + one(events: JQuery.TypeEventHandlers): this; /** * Set the CSS outer height of each element in the set of matched elements. * @param value_function _@param_ `value_function` @@ -9851,7 +10000,7 @@ $( "button" ).on( "click", function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ resize(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -9869,7 +10018,8 @@ $( window ).resize(function() { }); ``` */ - resize(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + resize(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -9883,7 +10033,7 @@ $( window ).resize(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ scroll(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -9933,7 +10083,8 @@ $( window ).scroll(function() { ``` */ - scroll(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + scroll(handler?: JQuery.TypeEventHandler | + false): this; /** * Set the current horizontal position of the scroll bar for each of the set of matched elements. * @param value An integer indicating the new position to set the scroll bar to. @@ -10107,7 +10258,7 @@ $( "p:last" ).text( "scrollTop:" + p.scrollTop() ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ select(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "select" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -10156,7 +10307,8 @@ $( ":input" ).select(function() { $( "input" ).select(); ``` */ - select(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + select(handler?: JQuery.TypeEventHandler | + false): this; /** * Encode a set of form elements as a string for submission. * @see \`{@link https://api.jquery.com/serialize/ }\` @@ -11127,7 +11279,7 @@ $( "#toggle" ).on( "click", function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ submit(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "submit" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -11196,7 +11348,8 @@ $( "form" ).submit(function() { $( "form:first" ).submit(); ``` */ - submit(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + submit(handler?: JQuery.TypeEventHandler | + false): this; /** * Set the content of each element in the set of matched elements to the specified text. * @param text_function _@param_ `text_function` @@ -11704,7 +11857,7 @@ $( "body" ).trigger({ }); ``` */ - trigger(eventType_event: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): this; + trigger(eventType_event: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): this; /** * Execute all handlers attached to an element for an event. * @param eventType_event _@param_ `eventType_event` @@ -11747,7 +11900,7 @@ $( "input" ).focus(function() { ``` */ - triggerHandler(eventType_event: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): any; + triggerHandler(eventType_event: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): any; /** * Remove a previously-attached event handler from the elements. * @param event A string containing one or more DOM event types, such as "click" or "submit," or custom event names. @@ -11815,7 +11968,10 @@ $( "p" ).bind( "click", foo ); // ... Now foo will be called when paragraphs are $( "p" ).unbind( "click", foo ); // ... foo will no longer be called. ``` */ - unbind(event: string, handler: JQuery.EventHandlerBase> | false): this; + unbind(event: string, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Remove a previously-attached event handler from the elements. * @param event A string containing one or more DOM event types, such as "click" or "submit," or custom event names. @@ -11836,7 +11992,7 @@ $( "p" ).unbind(); $( "p" ).unbind( "click" ); ``` */ - unbind(event?: string | JQuery.Event): this; + unbind(event?: string | JQuery.TriggeredEvent): this; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. * @param selector A selector which will be used to filter the event results. @@ -11906,12 +12062,18 @@ $( "body" ).delegate( "p", "click", foo ); $( "body" ).undelegate( "p", "click", foo ); ``` */ - undelegate(selector: JQuery.Selector, eventType: string, handler: JQuery.EventHandlerBase> | false): this; + undelegate(selector: JQuery.Selector, + eventType: string, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. * @param selector A selector which will be used to filter the event results. - * @param eventTypes A string containing a JavaScript event type, such as "click" or "keydown" - * An object of one or more event types and previously bound functions to unbind from them. + * @param eventType_events _@param_ `eventType_events` + *
+ * * `eventType` — A string containing a JavaScript event type, such as "click" or "keydown"
+ * * `events` — An object of one or more event types and previously bound functions to unbind from them. * @see \`{@link https://api.jquery.com/undelegate/ }\` * @since 1.4.2 * @since 1.4.3 @@ -11921,7 +12083,9 @@ $( "body" ).undelegate( "p", "click", foo ); * * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ - undelegate(selector: JQuery.Selector, eventTypes: string | JQuery.PlainObject> | false>): this; + undelegate(selector: JQuery.Selector, + eventType_events: string | + JQuery.TypeEventHandlers): this; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. * @param namespace A selector which will be used to filter the event results. diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 515715bf14..b1f63f3ecf 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -2430,7 +2430,7 @@ function JQuery() { $(document).ajaxComplete(function(event, jqXHR, ajaxOptions) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2446,7 +2446,7 @@ function JQuery() { $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2464,7 +2464,7 @@ function JQuery() { $(document).ajaxSend(function(event, jqXHR, ajaxOptions) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2500,7 +2500,7 @@ function JQuery() { $(document).ajaxSuccess(function(event, jqXHR, ajaxOptions, data) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -3883,21 +3883,11 @@ function JQuery() { function events() { // [bind() overloads] https://github.com/jquery/api.jquery.com/issues/1048 function bind() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').bind('myEvent', 'myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').bind('myEvent', 'myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -3905,77 +3895,51 @@ function JQuery() { $('p').bind('myEvent', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').bind('myEvent', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery $('p').bind('myEvent', false); + // $ExpectType JQuery + $('p').bind('myEvent', null); + + // $ExpectType JQuery + $('p').bind('myEvent', undefined); + // $ExpectType JQuery $('p').bind({ myEvent1: false, myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); - - // $ExpectType JQuery - $('p').bind('myEvent', null); - - // $ExpectType JQuery - $('p').bind('myEvent', undefined); - } + } function delegate() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('table').delegate('td', 'myEvent', 'myData', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').delegate('td', 'myEvent', 'myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery $('table').delegate('td', 'myEvent', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').delegate('td', 'myEvent', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -3984,44 +3948,32 @@ function JQuery() { // $ExpectType JQuery $('table').delegate('td', { - myEvent1(event) { - // $ExpectType HTMLElement + myEvent1: false, + myEvent2(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent2: false, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); } function off() { - function defaultContext_defaultData(this: HTMLElement, event: JQuery.Event) { } + function defaultData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function defaultContext_customData(this: HTMLElement, event: JQuery.Event) { } - - function customContext_defaultData(this: J1, event: JQuery.Event) { } - - function customContext_customData(this: J1, event: JQuery.Event) { } - - interface J1 { kind: 'J1'; } + function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_defaultData); + $('table').off('myEvent', 'td', 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); + $('table').off('myEvent', 'td', customData); // $ExpectType JQuery $('table').off('myEvent', 'td', false); @@ -4030,16 +3982,10 @@ function JQuery() { $('table').off('myEvent', 'td'); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_defaultData); + $('table').off('myEvent', defaultData); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_customData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_customData); + $('table').off('myEvent', customData); // $ExpectType JQuery $('table').off('myEvent', false); @@ -4050,52 +3996,30 @@ function JQuery() { // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }, 'td'); // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }); + const ev: JQuery.TriggeredEvent = undefined!; // $ExpectType JQuery - $('table').off($.Event('myEvent')); + $('table').off(ev); // $ExpectType JQuery $('table').off(); } function on() { - interface J1 { kind: 'J1'; } - - // $ExpectType JQuery $('table').on('myEvent', 'td', 'myData', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', 'td', 'myData', function(event: JQueryEventObject) { - // $ExpectType HTMLElement - this; - // $ExpectType JQueryEventObject - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', 'td', 'myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4103,12 +4027,29 @@ function JQuery() { $('table').on('myEvent', null, 'myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', undefined, 'myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TriggeredEvent + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', 'td', 'myData', function(event: JQueryEventObject) { + // $ExpectType any + this; + // $ExpectType JQueryEventObject event; }); // $ExpectType JQuery $('table').on('myEvent', null, 'myData', function(event: JQueryEventObject) { + // TODO: Why is this HTMLElement? The callback signature doesn't even have `this` declared. // $ExpectType HTMLElement this; // $ExpectType JQueryEventObject @@ -4116,34 +4057,19 @@ function JQuery() { }); // $ExpectType JQuery - $('table').on('myEvent', null, 'myData', function(this: J1, event) { - // $ExpectType J1 + $('table').on('myEvent', undefined, 'myData', function(event: JQueryEventObject) { + // TODO: Why is this HTMLElement? The callback signature doesn't even have `this` declared. + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType JQueryEventObject event; }); // $ExpectType JQuery $('table').on('myEvent', 'td', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', 'td', function(event: JQueryEventObject) { - // $ExpectType HTMLElement - this; - // $ExpectType JQueryEventObject - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', 'td', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4154,7 +4080,15 @@ function JQuery() { $('table').on('myEvent', 3, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', 'td', function(event: JQueryEventObject) { + // $ExpectType any + this; + // $ExpectType JQueryEventObject event; }); @@ -4167,20 +4101,15 @@ function JQuery() { }); // $ExpectType JQuery - $('table').on('myEvent', 3, function(this: J1, event) { - // $ExpectType J1 + $('table').on('myEvent', function(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery - $('table').on('myEvent', function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event - event; - }); + $('table').on('myEvent', false); // $ExpectType JQuery $('table').on('myEvent', function(event: JQueryEventObject) { @@ -4214,30 +4143,19 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', false); - // $ExpectType JQuery $('table').on({ myEvent1: false, myEvent2(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 'td', 'myData'); @@ -4248,13 +4166,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, null, 'myData'); @@ -4265,13 +4183,30 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent + event; + } + }, undefined, 'myData'); + + // $ExpectType JQuery + $('table').on({ + myEvent1: false, + myEvent2(event) { + // $ExpectType any + this; + // $ExpectType TriggeredEvent + event; + }, + click(event) { + // $ExpectType any + this; + // $ExpectType ClickEvent event; } }, 'td'); @@ -4282,13 +4217,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 3); @@ -4299,34 +4234,37 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); + + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31124 + function issue_31124(el: Element, mouseX: number) { + $(el) + .on("mousedown touchstart", (evt) => { + // tslint:disable-next-line:prefer-conditional-expression + if (evt.type === "mousedown") { + mouseX = (evt.originalEvent as MouseEvent).clientX; + } else { + mouseX = (evt.originalEvent as TouchEvent).touches[0].clientX; + } + }); + } } function one() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('table').one('myEvent', 'td', 'myData', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', 'td', 'myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4334,31 +4272,23 @@ function JQuery() { $('table').one('myEvent', null, 'myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery - $('table').one('myEvent', null, 'myData', function(this: J1, event) { - // $ExpectType J1 + $('table').one('myEvent', undefined, 'myData', function(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery $('table').one('myEvent', 'td', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', 'td', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4369,15 +4299,7 @@ function JQuery() { $('table').one('myEvent', 3, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', 3, function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4385,15 +4307,7 @@ function JQuery() { $('table').one('myEvent', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4404,15 +4318,15 @@ function JQuery() { $('table').one({ myEvent1: false, myEvent2(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 'td', 'myData'); @@ -4423,13 +4337,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, null, 'myData'); @@ -4440,13 +4354,30 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent + event; + } + }, undefined, 'myData'); + + // $ExpectType JQuery + $('table').one({ + myEvent1: false, + myEvent2(event) { + // $ExpectType any + this; + // $ExpectType TriggeredEvent + event; + }, + click(event) { + // $ExpectType any + this; + // $ExpectType ClickEvent event; } }, 'td'); @@ -4457,13 +4388,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 3); @@ -4474,13 +4405,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); @@ -4551,27 +4482,15 @@ function JQuery() { } function unbind() { - function defaultContext_defaultData(this: HTMLElement, event: JQuery.Event) { } + function defaultData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function defaultContext_customData(this: HTMLElement, event: JQuery.Event) { } - - function customContext_defaultData(this: J1, event: JQuery.Event) { } - - function customContext_customData(this: J1, event: JQuery.Event) { } - - interface J1 { kind: 'J1'; } + function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } // $ExpectType JQuery - $('p').unbind('myEvent', defaultContext_defaultData); + $('p').unbind('myEvent', defaultData); // $ExpectType JQuery - $('p').unbind('myEvent', defaultContext_customData); - - // $ExpectType JQuery - $('p').unbind('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('p').unbind('myEvent', customContext_customData); + $('p').unbind('myEvent', customData); // $ExpectType JQuery $('p').unbind('myEvent', false); @@ -4579,35 +4498,24 @@ function JQuery() { // $ExpectType JQuery $('p').unbind('myEvent'); + const ev: JQuery.TriggeredEvent = undefined!; // $ExpectType JQuery - $('p').unbind($.Event('myEvent')); + $('p').unbind(ev); // $ExpectType JQuery $('p').unbind(); } function undelegate() { - function defaultContext_defaultData(this: HTMLElement, event: JQuery.Event) { } + function defaultData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function defaultContext_customData(this: HTMLElement, event: JQuery.Event) { } - - function customContext_defaultData(this: J1, event: JQuery.Event) { } - - function customContext_customData(this: J1, event: JQuery.Event) { } - - interface J1 { kind: 'J1'; } + function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } // $ExpectType JQuery - $('table').undelegate('td', 'click', defaultContext_defaultData); + $('table').undelegate('td', 'click', defaultData); // $ExpectType JQuery - $('table').undelegate('td', 'click', defaultContext_customData); - - // $ExpectType JQuery - $('table').undelegate('td', 'click', customContext_defaultData); - - // $ExpectType JQuery - $('table').undelegate('td', 'click', customContext_customData); + $('table').undelegate('td', 'click', customData); // $ExpectType JQuery $('table').undelegate('td', 'click', false); @@ -4618,10 +4526,8 @@ function JQuery() { // $ExpectType JQuery $('table').undelegate('td', { myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }); // $ExpectType JQuery @@ -4632,21 +4538,11 @@ function JQuery() { } function blur() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').blur('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').blur('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType BlurEvent event; }); @@ -4654,15 +4550,7 @@ function JQuery() { $('p').blur(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').blur(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType BlurEvent event; }); @@ -4674,21 +4562,11 @@ function JQuery() { } function change() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').change('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').change('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ChangeEvent event; }); @@ -4696,15 +4574,7 @@ function JQuery() { $('p').change(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').change(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ChangeEvent event; }); @@ -4716,21 +4586,11 @@ function JQuery() { } function click() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').click('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').click('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ClickEvent event; }); @@ -4738,15 +4598,7 @@ function JQuery() { $('p').click(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').click(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ClickEvent event; }); @@ -4758,21 +4610,11 @@ function JQuery() { } function contextmenu() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').contextmenu('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').contextmenu('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ContextMenuEvent event; }); @@ -4780,15 +4622,7 @@ function JQuery() { $('p').contextmenu(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').contextmenu(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ContextMenuEvent event; }); @@ -4800,21 +4634,11 @@ function JQuery() { } function dblclick() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').dblclick('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').dblclick('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType DoubleClickEvent event; }); @@ -4822,15 +4646,7 @@ function JQuery() { $('p').dblclick(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').dblclick(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType DoubleClickEvent event; }); @@ -4842,21 +4658,11 @@ function JQuery() { } function focus() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').focus('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focus('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusEvent event; }); @@ -4864,15 +4670,7 @@ function JQuery() { $('p').focus(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focus(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusEvent event; }); @@ -4884,21 +4682,11 @@ function JQuery() { } function focusin() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').focusin('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusin('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusInEvent event; }); @@ -4906,15 +4694,7 @@ function JQuery() { $('p').focusin(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusin(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusInEvent event; }); @@ -4926,21 +4706,11 @@ function JQuery() { } function focusout() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').focusout('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusout('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusOutEvent event; }); @@ -4948,15 +4718,7 @@ function JQuery() { $('p').focusout(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusout(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusOutEvent event; }); @@ -4968,21 +4730,11 @@ function JQuery() { } function keydown() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').keydown('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keydown('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyDownEvent event; }); @@ -4990,15 +4742,7 @@ function JQuery() { $('p').keydown(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keydown(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyDownEvent event; }); @@ -5010,21 +4754,11 @@ function JQuery() { } function keypress() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').keypress('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keypress('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyPressEvent event; }); @@ -5032,15 +4766,7 @@ function JQuery() { $('p').keypress(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keypress(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyPressEvent event; }); @@ -5052,21 +4778,11 @@ function JQuery() { } function keyup() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').keyup('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keyup('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyUpEvent event; }); @@ -5074,15 +4790,7 @@ function JQuery() { $('p').keyup(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keyup(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyUpEvent event; }); @@ -5094,21 +4802,11 @@ function JQuery() { } function mousedown() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mousedown('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousedown('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseDownEvent event; }); @@ -5116,15 +4814,7 @@ function JQuery() { $('p').mousedown(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousedown(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseDownEvent event; }); @@ -5136,21 +4826,11 @@ function JQuery() { } function mouseenter() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseenter('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseenter('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }); @@ -5158,15 +4838,7 @@ function JQuery() { $('p').mouseenter(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseenter(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }); @@ -5178,21 +4850,11 @@ function JQuery() { } function mouseleave() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseleave('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseleave('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5200,15 +4862,7 @@ function JQuery() { $('p').mouseleave(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseleave(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5220,21 +4874,11 @@ function JQuery() { } function mousemove() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mousemove('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousemove('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseMoveEvent event; }); @@ -5242,15 +4886,7 @@ function JQuery() { $('p').mousemove(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousemove(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseMoveEvent event; }); @@ -5262,21 +4898,11 @@ function JQuery() { } function mouseout() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseout('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseout('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseOutEvent event; }); @@ -5284,15 +4910,7 @@ function JQuery() { $('p').mouseout(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseout(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseOutEvent event; }); @@ -5304,21 +4922,11 @@ function JQuery() { } function mouseover() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseover('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseover('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseOverEvent event; }); @@ -5326,15 +4934,7 @@ function JQuery() { $('p').mouseover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseOverEvent event; }); @@ -5346,21 +4946,11 @@ function JQuery() { } function mouseup() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseup('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseup('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseUpEvent event; }); @@ -5368,15 +4958,7 @@ function JQuery() { $('p').mouseup(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseup(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseUpEvent event; }); @@ -5388,21 +4970,11 @@ function JQuery() { } function resize() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').resize('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').resize('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ResizeEvent event; }); @@ -5410,15 +4982,7 @@ function JQuery() { $('p').resize(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').resize(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ResizeEvent event; }); @@ -5430,21 +4994,11 @@ function JQuery() { } function scroll() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').scroll('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').scroll('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ScrollEvent event; }); @@ -5452,15 +5006,7 @@ function JQuery() { $('p').scroll(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').scroll(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ScrollEvent event; }); @@ -5472,21 +5018,11 @@ function JQuery() { } function select() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').select('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').select('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType SelectEvent event; }); @@ -5494,15 +5030,7 @@ function JQuery() { $('p').select(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').select(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType SelectEvent event; }); @@ -5514,21 +5042,11 @@ function JQuery() { } function submit() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').submit('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').submit('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType SubmitEvent event; }); @@ -5536,15 +5054,7 @@ function JQuery() { $('p').submit(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').submit(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType SubmitEvent event; }); @@ -5556,32 +5066,16 @@ function JQuery() { } function hover() { - interface J1 { kind: 'J1'; } - interface J2 { kind: 'J2'; } - // $ExpectType JQuery $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; - }, function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5589,41 +5083,7 @@ function JQuery() { $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }, function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; - }, function(this: J2, event) { - // $ExpectType J2 - this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event - event; - }, false); - - // $ExpectType JQuery - $('p').hover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }, false); @@ -5631,15 +5091,7 @@ function JQuery() { $('p').hover(false, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(false, function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5650,16 +5102,23 @@ function JQuery() { $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseEnterEvent | MouseLeaveEvent event; - }); - // $ExpectType JQuery - $('p').hover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; + switch (event.type) { + case 'mouseover': + // $ExpectType MouseEnterEvent + event; + break; + case 'mouseout': + // $ExpectType MouseLeaveEvent + event; + break; + default: + // $ExpectType never + event; + break; + } }); // $ExpectType JQuery @@ -8398,51 +7857,186 @@ function JQuery_Effects() { function JQuery_Event() { function call_signature() { - // $ExpectType Event & Coordinates + // $ExpectType Event & Coordinates $.Event('keydown', $('p').offset()); - - // $ExpectType Event & { type: string; } - $.Event({ - type: 'keydown' - }); } function constructor() { - // $ExpectType Event & Coordinates + // $ExpectType Event & Coordinates new $.Event('keydown', $('p').offset()); - - // $ExpectType Event & { type: string; } - new $.Event({ - type: 'keydown' - }); } // https://stackoverflow.com/questions/49892574/trigger-a-jquery-3-event-with-ctrlkey-set function stackoverflow_49892574() { - const event = $.Event("keydown"); + const event = $.Event("keydown"); event.which = 77; event.ctrlKey = true; $(window).trigger(event); } } +function JQuery_TypeEventHandlers() { + const events: JQuery.TypeEventHandlers = { + change(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ChangeEvent + event; + }, + resize(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ResizeEvent + event; + }, + scroll(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ScrollEvent + event; + }, + select(event) { + // $ExpectType HTMLElement + this; + // $ExpectType SelectEvent + event; + }, + submit(event) { + // $ExpectType HTMLElement + this; + // $ExpectType SubmitEvent + event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; + }, + contextmenu(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ContextMenuEvent + event; + }, + dblclick(event) { + // $ExpectType HTMLElement + this; + // $ExpectType DoubleClickEvent + event; + }, + mousedown(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseDownEvent + event; + }, + mouseenter(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseEnterEvent + event; + }, + mouseleave(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseLeaveEvent + event; + }, + mousemove(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseMoveEvent + event; + }, + mouseout(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseOutEvent + event; + }, + mouseover(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseOverEvent + event; + }, + mouseup(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseUpEvent + event; + }, + keydown(event) { + // $ExpectType HTMLElement + this; + // $ExpectType KeyDownEvent + event; + }, + keypress(event) { + // $ExpectType HTMLElement + this; + // $ExpectType KeyPressEvent + event; + }, + keyup(event) { + // $ExpectType HTMLElement + this; + // $ExpectType KeyUpEvent + event; + }, + touchcancel(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchCancelEvent + event; + }, + touchend(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchEndEvent + event; + }, + touchmove(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchMoveEvent + event; + }, + touchstart(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchStartEvent + event; + }, + blur(event) { + // $ExpectType HTMLElement + this; + // $ExpectType BlurEvent + event; + }, + focus(event) { + // $ExpectType HTMLElement + this; + // $ExpectType FocusEvent + event; + }, + focusin(event) { + // $ExpectType HTMLElement + this; + // $ExpectType FocusInEvent + event; + }, + focusout(event) { + // $ExpectType HTMLElement + this; + // $ExpectType FocusOutEvent + event; + } + }; +} + function JQuery_EventExtensions() { - function fixHooks() { - jQuery.event.fixHooks.drop = { - props: ['dataTransfer'], - filter(event, originalEvent) { - // $ExpectType Event - event; - // $ExpectType Event - originalEvent; - }, - }; - - // Weak type test. This may be removed if the TypeScript requirement is increased to 2.4+. - // $ExpectError - jQuery.event.fixHooks.drop = ['dataTransfer']; - } - function special() { jQuery.event.special.multiclick = { noBubble: true, @@ -8455,7 +8049,7 @@ function JQuery_EventExtensions() { data; // $ExpectType string namespaces; - // $ExpectType EventHandler + // $ExpectType EventHandlerBase> eventHandle; return false; @@ -8481,7 +8075,7 @@ function JQuery_EventExtensions() { trigger(event, data) { // $ExpectType EventTarget this; - // $ExpectType Event + // $ExpectType Event event; // $ExpectType any data; @@ -8489,7 +8083,7 @@ function JQuery_EventExtensions() { return false; }, _default(event, data) { - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType any data; @@ -8497,7 +8091,7 @@ function JQuery_EventExtensions() { return false; }, handle(event, data) { - // $ExpectType Event & { handleObj: HandleObject; } + // $ExpectType TriggeredEvent & { handleObj: HandleObject; } event; // $ExpectType any data; @@ -8505,7 +8099,7 @@ function JQuery_EventExtensions() { preDispatch(event) { // $ExpectType EventTarget this; - // $ExpectType Event + // $ExpectType Event event; return false; @@ -8513,7 +8107,7 @@ function JQuery_EventExtensions() { postDispatch(event) { // $ExpectType EventTarget this; - // $ExpectType Event + // $ExpectType Event event; } }; diff --git a/types/jquery/misc.d.ts b/types/jquery/misc.d.ts index 7b09b6a4dc..ebba2f7a31 100644 --- a/types/jquery/misc.d.ts +++ b/types/jquery/misc.d.ts @@ -3981,49 +3981,97 @@ $( "input" ).click(function() { // This should be a class but doesn't work correctly under the JQuery namespace. Event should be an inner class of jQuery. - // Static members + /** + * jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods. + * + * Those properties are all documented, and accompanied by examples, on the \`{@link http://api.jquery.com/category/events/event-object/ Event object}\` page. + * + * The standard events in the Document Object Model are: `blur`, `focus`, `load`, `resize`, `scroll`, `unload`, `beforeunload`, `click`, `dblclick`, `mousedown`, `mouseup`, `mousemove`, `mouseover`, `mouseout`, `mouseenter`, `mouseleave`, `change`, `select`, `submit`, `keydown`, `keypress`, and `keyup`. Since the DOM event names have predefined meanings for some elements, using them for other purposes is not recommended. jQuery's event model can trigger an event by any name on an element, and it is propagated up the DOM tree to which that element belongs, if any. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + */ interface EventStatic { - // tslint:disable-next-line:no-unnecessary-generics - (event: string, properties?: T): Event & T; - // tslint:disable-next-line:no-unnecessary-generics - (properties: T): Event & T; - // tslint:disable-next-line:no-unnecessary-generics - new (event: string, properties?: T): Event & T; - // tslint:disable-next-line:no-unnecessary-generics - new (properties: T): Event & T; + /** + * The jQuery.Event constructor is exposed and can be used when calling trigger. The new operator is optional. + * + * Check \`{@link https://api.jquery.com/trigger/ trigger}\`'s documentation to see how to combine it with your own event object. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + * @since 1.6 + * @example +```javascript +//Create a new jQuery.Event object without the "new" operator. +var e = jQuery.Event( "click" ); +​ +// trigger an artificial click event +jQuery( "body" ).trigger( e ); +``` + * @example +```javascript +// Create a new jQuery.Event object with specified event properties. +var e = jQuery.Event( "keydown", { keyCode: 64 } ); +​ +// trigger an artificial keydown event with keyCode 64 +jQuery( "body" ).trigger( e ); +``` + */ + (event: string, properties?: T): Event & T; + /** + * The jQuery.Event constructor is exposed and can be used when calling trigger. The new operator is optional. + * + * Check \`{@link https://api.jquery.com/trigger/ trigger}\`'s documentation to see how to combine it with your own event object. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + * @since 1.6 + * @example +```javascript +//Create a new jQuery.Event object without the "new" operator. +var e = jQuery.Event( "click" ); +​ +// trigger an artificial click event +jQuery( "body" ).trigger( e ); +``` + * @example +```javascript +// Create a new jQuery.Event object with specified event properties. +var e = jQuery.Event( "keydown", { keyCode: 64 } ); +​ +// trigger an artificial keydown event with keyCode 64 +jQuery( "body" ).trigger( e ); +``` + */ + new (event: string, properties?: T): Event & T; } - // Instance members + /** + * jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods. + * + * Those properties are all documented, and accompanied by examples, on the \`{@link http://api.jquery.com/category/events/event-object/ Event object}\` page. + * + * The standard events in the Document Object Model are: `blur`, `focus`, `load`, `resize`, `scroll`, `unload`, `beforeunload`, `click`, `dblclick`, `mousedown`, `mouseup`, `mousemove`, `mouseover`, `mouseout`, `mouseenter`, `mouseleave`, `change`, `select`, `submit`, `keydown`, `keypress`, and `keyup`. Since the DOM event names have predefined meanings for some elements, using them for other purposes is not recommended. jQuery's event model can trigger an event by any name on an element, and it is propagated up the DOM tree to which that element belongs, if any. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + * @see \`{@link TriggeredEvent }\` + */ interface Event { // region Copied properties // #region Copied properties - // region Event - // #region Event + // Event - bubbles?: boolean; - cancelable?: boolean; - eventPhase?: number; + bubbles: boolean | undefined; + cancelable: boolean | undefined; + eventPhase: number | undefined; - // #endregion + // UIEvent - // region UIEvent - // #region UIEvent + detail: number | undefined; + view: Window | undefined; - detail?: number; - view?: Window; + // MouseEvent - // #endregion - - // region MouseEvent - // #region MouseEvent - - button?: number; - buttons?: number; - clientX?: number; - clientY?: number; - offsetX?: number; - offsetY?: number; + button: number | undefined; + buttons: number | undefined; + clientX: number | undefined; + clientY: number | undefined; + offsetX: number | undefined; + offsetY: number | undefined; /** * The mouse position relative to the left edge of the document. * @see \`{@link https://api.jquery.com/event.pageX/ }\` @@ -4059,7 +4107,7 @@ $( document ).on( "mousemove", function( event ) { ``` */ - pageX: number; + pageX: number | undefined; /** * The mouse position relative to the top edge of the document. * @see \`{@link https://api.jquery.com/event.pageY/ }\` @@ -4095,49 +4143,93 @@ $( document ).on( "mousemove", function( event ) { ``` */ - pageY: number; - screenX?: number; - screenY?: number; + pageY: number | undefined; + screenX: number | undefined; + screenY: number | undefined; /** @deprecated */ - toElement?: Element; + toElement: Element | undefined; - // #endregion + // PointerEvent - // region PointerEvent - // #region PointerEvent + pointerId: number | undefined; + pointerType: string | undefined; - pointerId?: number; - pointerType?: string; - - // #endregion - - // region KeyboardEvent - // #region KeyboardEvent + // KeyboardEvent /** @deprecated */ - char?: string; + char: string | undefined; /** @deprecated */ - charCode?: number; - key?: string; + charCode: number | undefined; + key: string | undefined; /** @deprecated */ - keyCode?: number; + keyCode: number | undefined; - // #endregion + // TouchEvent - // region TouchEvent - // #region TouchEvent + changedTouches: TouchList | undefined; + targetTouches: TouchList | undefined; + touches: TouchList | undefined; - changedTouches?: TouchList; - targetTouches?: TouchList; - touches?: TouchList; + // MouseEvent, KeyboardEvent - // #endregion + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: number | undefined; - // region MouseEvent, KeyboardEvent, TouchEvent - // #region MouseEvent, KeyboardEvent, TouchEvent + // MouseEvent, KeyboardEvent, TouchEvent - altKey?: boolean; - ctrlKey?: boolean; + altKey: boolean | undefined; + ctrlKey: boolean | undefined; /** * Indicates whether the META key was pressed when the event fired. * @see \`{@link https://api.jquery.com/event.metaKey/ }\` @@ -4174,77 +4266,11 @@ $( "#checkMetaKey" ).click(function( event ) { ``` */ - metaKey: boolean; - shiftKey?: boolean; + metaKey: boolean | undefined; + shiftKey: boolean | undefined; // #endregion - // #endregion - - /** - * The namespace specified when the event was triggered. - * @see \`{@link https://api.jquery.com/event.namespace/ }\` - * @since 1.4.3 - * @example ​ ````Determine the event namespace used. -```html - - - - - event.namespace demo - - - -​ - -

-​ - -​ - - -``` - */ - namespace: string; - /** - * The last value returned by an event handler that was triggered by this event, unless the value was undefined. - * @see \`{@link https://api.jquery.com/event.result/ }\` - * @since 1.3 - * @example ​ ````Display previous handler's return value -```html - - - - - event.result demo - - - -​ - -

-​ - -​ - - -``` - */ - result: any; /** * The difference in milliseconds between the time the browser created the event and January 1, 1970. * @see \`{@link https://api.jquery.com/event.timeStamp/ }\` @@ -4301,58 +4327,6 @@ $( "a" ).click(function( event ) { ``` */ type: string; - /** - * For key or mouse events, this property indicates the specific key or button that was pressed. - * @see \`{@link https://api.jquery.com/event.which/ }\` - * @since 1.1.3 - * @example ​ ````Log which key was depressed. -```html - - - - - event.which demo - - - -​ - -
-​ - -​ - - -``` - * @example ​ ````Log which mouse button was depressed. -```html - - - - - event.which demo - - - -​ - -
-​ - -​ - - -``` - */ - which: number; /** * Returns whether event.preventDefault() was ever called on this event object. * @see \`{@link https://api.jquery.com/event.isDefaultPrevented/ }\` @@ -4545,11 +4519,17 @@ $( "p" ).click(function( event ) { stopPropagation(): void; } - // Generic members - interface Event< - TTarget = EventTarget, - TData = null - > { + // #endregion + + /** + * Base type for jQuery events that have been triggered (including events triggered on plain objects). + */ + interface TriggeredEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends Event { /** * The current DOM element within the event bubbling phase. * @see \`{@link https://api.jquery.com/event.currentTarget/ }\` @@ -4560,51 +4540,8 @@ $( "p" ).click(function( event ) { alert( event.currentTarget === this ); // true }); ``` - */ - currentTarget: TTarget; - /** - * An optional object of data passed to an event method when the current executing handler is bound. - * @see \`{@link https://api.jquery.com/event.data/ }\` - * @since 1.1 - * @example ​ ````Within a for loop, pass the value of i to the .on() method so that the current iteration's value is preserved. -```html - - - - - event.data demo - - - -​ - - - - - -​ -
-​ - -​ - - -``` - */ - data: TData; + */ + currentTarget: TCurrentTarget; /** * The element where the currently-called jQuery event handler was attached. * @see \`{@link https://api.jquery.com/event.delegateTarget/ }\` @@ -4615,21 +4552,8 @@ $( ".box" ).on( "click", "button", function( event ) { $( event.delegateTarget ).css( "background-color", "red" ); }); ``` - */ - delegateTarget: TTarget; - originalEvent: _Event; - /** - * The other DOM element involved in the event, if any. - * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` - * @since 1.1.4 - * @example ​ ````On mouseout of anchors, alert the element type being entered. -```javascript -$( "a" ).mouseout(function( event ) { - alert( event.relatedTarget.nodeName ); // "DIV" -}); -``` - */ - relatedTarget: TTarget | null; + */ + delegateTarget: TDelegateTarget; /** * The DOM element that initiated the event. * @see \`{@link https://api.jquery.com/event.target/ }\` @@ -4707,37 +4631,1728 @@ $( "ul" ).click( handler ).find( "ul" ).hide(); ``` - */ + */ target: TTarget; + + /** + * An optional object of data passed to an event method when the current executing handler is bound. + * @see \`{@link https://api.jquery.com/event.data/ }\` + * @since 1.1 + * @example ​ ````Within a for loop, pass the value of i to the .on() method so that the current iteration's value is preserved. +```html + + + + + event.data demo + + + +​ + + + + + +​ +
+​ + +​ + + +``` + */ + data: TData; + + /** + * The namespace specified when the event was triggered. + * @see \`{@link https://api.jquery.com/event.namespace/ }\` + * @since 1.4.3 + * @example ​ ````Determine the event namespace used. +```html + + + + + event.namespace demo + + + +​ + +

+​ + +​ + + +``` + */ + namespace?: string; + originalEvent?: _Event; + /** + * The last value returned by an event handler that was triggered by this event, unless the value was undefined. + * @see \`{@link https://api.jquery.com/event.result/ }\` + * @since 1.3 + * @example ​ ````Display previous handler's return value +```html + + + + + event.result demo + + + +​ + +

+​ + +​ + + +``` + */ + result?: any; } - interface EventLike { - type: string; + // region Event + // #region Event + + interface EventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TriggeredEvent { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: undefined; + + // Event + + bubbles: boolean; + cancelable: boolean; + eventPhase: number; + + // UIEvent + + detail: undefined; + view: undefined; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: undefined; + ctrlKey: undefined; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: undefined; + shiftKey: undefined; + + originalEvent?: _Event; + } + + interface ChangeEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'change'; + } + + interface ResizeEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'resize'; + } + + interface ScrollEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'scroll'; + } + + interface SelectEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'select'; + } + + interface SubmitEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'submit'; } // #endregion - interface EventHandler extends EventHandlerBase> { } + // region UIEvent + // #region UIEvent + + interface UIEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TriggeredEvent { + // Event + + bubbles: boolean; + cancelable: boolean; + eventPhase: number; + + // UIEvent + + detail: number; + view: Window; + + originalEvent?: _UIEvent; + } + + // region MouseEvent + // #region MouseEvent + + interface MouseEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: EventTarget | null; + + // MouseEvent + + button: number; + buttons: number; + clientX: number; + clientY: number; + offsetX: number; + offsetY: number; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: number; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: number; + screenX: number; + screenY: number; + /** @deprecated */ + toElement: Element; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: number; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: boolean; + ctrlKey: boolean; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: boolean; + shiftKey: boolean; + + originalEvent?: _MouseEvent; + } + + interface ClickEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'click'; + } + + interface ContextMenuEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'contextmenu'; + } + + interface DoubleClickEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'dblclick'; + } + + interface MouseDownEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'mousedown'; + } + + interface MouseEnterEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + // Special handling by jQuery. + type: 'mouseover'; + } + + interface MouseLeaveEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + // Special handling by jQuery. + type: 'mouseout'; + } + + interface MouseMoveEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'mousemove'; + } + + interface MouseOutEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + type: 'mouseout'; + } + + interface MouseOverEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + type: 'mouseover'; + } + + interface MouseUpEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'mouseup'; + } + + // #endregion + + // region KeyboardEvent + // #region KeyboardEvent + + interface KeyboardEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: undefined; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: string | undefined; + /** @deprecated */ + charCode: number; + key: string; + /** @deprecated */ + keyCode: number; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: number; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: boolean; + ctrlKey: boolean; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: boolean; + shiftKey: boolean; + + originalEvent?: _KeyboardEvent; + } + + interface KeyDownEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends KeyboardEventBase { + type: 'keydown'; + } + + interface KeyPressEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends KeyboardEventBase { + type: 'keypress'; + } + + interface KeyUpEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends KeyboardEventBase { + type: 'keyup'; + } + + // #endregion + + // region TouchEvent + // #region TouchEvent + + interface TouchEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: undefined; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: TouchList; + targetTouches: TouchList; + touches: TouchList; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: boolean; + ctrlKey: boolean; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: boolean; + shiftKey: boolean; + + originalEvent?: _TouchEvent; + } + + interface TouchCancelEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { + type: 'touchcancel'; + } + + interface TouchEndEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { + type: 'touchend'; + } + + interface TouchMoveEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { + type: 'touchmove'; + } + + interface TouchStartEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { + type: 'touchstart'; + } + + // #endregion + + // region FocusEvent + // #region FocusEvent + + interface FocusEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: EventTarget | null; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: undefined; + ctrlKey: undefined; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: undefined; + shiftKey: undefined; + + originalEvent?: _FocusEvent; + } + + interface BlurEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'blur'; + } + + interface FocusEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'focus'; + } + + interface FocusInEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'focusin'; + } + + interface FocusOutEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'focusout'; + } + + // #endregion + + // #endregion + + interface TypeToTriggeredEventMap< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget + > { + // Event + + change: ChangeEvent; + resize: ResizeEvent; + scroll: ScrollEvent; + select: SelectEvent; + submit: SubmitEvent; + + // UIEvent + + // MouseEvent + + click: ClickEvent; + contextmenu: ContextMenuEvent; + dblclick: DoubleClickEvent; + mousedown: MouseDownEvent; + mouseenter: MouseEnterEvent; + mouseleave: MouseLeaveEvent; + mousemove: MouseMoveEvent; + mouseout: MouseOutEvent; + mouseover: MouseOverEvent; + mouseup: MouseUpEvent; + + // KeyboardEvent + + keydown: KeyDownEvent; + keypress: KeyPressEvent; + keyup: KeyUpEvent; + + // TouchEvent + + touchcancel: TouchCancelEvent; + touchend: TouchEndEvent; + touchmove: TouchMoveEvent; + touchstart: TouchStartEvent; + + // FocusEvent + + blur: BlurEvent; + focus: FocusEvent; + focusin: FocusInEvent; + focusout: FocusOutEvent; + + [type: string]: TriggeredEvent; + } // Extra parameters can be passed from trigger() type EventHandlerBase = (this: TContext, t: T, ...args: any[]) => any; + type EventHandler< + TCurrentTarget, + TData = undefined + > = EventHandlerBase>; + + type TypeEventHandler< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget, + TType extends keyof TypeToTriggeredEventMap + > = EventHandlerBase[TType]>; + + interface TypeEventHandlers< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget + > extends _TypeEventHandlers { + // No idea why it's necessary to include `object` in the union but otherwise TypeScript complains that + // derived types of Event are not assignable to Event. + [type: string]: TypeEventHandler | + false | + undefined | + object; + } + + type _TypeEventHandlers< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget + > = { + [TType in keyof TypeToTriggeredEventMap]?: + TypeEventHandler | + false | + object; + }; + // region Event extensions // #region Event extensions interface EventExtensions { - /** - * jQuery defines an \`{@link https://api.jquery.com/category/events/event-object/ Event object}\` that represents a cross-browser subset of the information available when an event occurs. The `jQuery.event.props` property is an array of string names for properties that are always copied when jQuery processes a native browser event. (Events fired in code by `.trigger()` do not use this list, since the code can construct a `jQuery.Event` object with the needed values and trigger using that object.) - * - * To add a property name to this list, use `jQuery.event.props.push( "newPropertyName" )`. However, be aware that every event processed by jQuery will now attempt to copy this property name from the native browser event to jQuery's constructed event. If the property does not exist for that event type, it will get an undefined value. Adding many properties to this list can significantly reduce event delivery performance, so for infrequently-needed properties it is more efficient to use the value directly from `event.originalEvent` instead. If properties must be copied, you are strongly advised to use `jQuery.event.fixHooks` as of version 1.7. - * @see \`{@link https://learn.jquery.com/events/event-extensions/#jquery-event-props-array }\` - */ - props: string[]; - /** - * The `fixHooks` interface provides a per-event-type way to extend or normalize the event object that jQuery creates when it processes a _native_ browser event. - * @see \`{@link https://learn.jquery.com/events/event-extensions/#jquery-event-fixhooks-object }\` - */ - fixHooks: FixHooks; /** * The jQuery special event hooks are a set of per-event-name functions and properties that allow code to control the behavior of event processing within jQuery. The mechanism is similar to `fixHooks` in that the special event information is stored in `jQuery.event.special.NAME`, where `NAME` is the name of the special event. Event names are case sensitive. * @@ -4747,75 +6362,6 @@ $( "ul" ).click( handler ).find( "ul" ).hide(); special: SpecialEventHooks; } - // region Fix hooks - // #region Fix hooks - - // Workaround for TypeScript 2.3 which does not have support for weak types handling. - type FixHook = { - /** - * Strings representing properties that should be copied from the browser's event object to the jQuery event object. If omitted, no additional properties are copied beyond the standard ones that jQuery copies and normalizes (e.g. `event.target` and `event.relatedTarget`). - */ - props: string[]; - } | { - /** - * jQuery calls this function after it constructs the `jQuery.Event` object, copies standard properties from `jQuery.event.props`, and copies the `fixHooks`-specific props (if any) specified above. The function can create new properties on the event object or modify existing ones. The second argument is the browser's native event object, which is also available in `event.originalEvent`. - * - * Note that for all events, the browser's native event object is available in `event.originalEvent`; if the jQuery event handler examines the properties there instead of jQuery's normalized `event` object, there is no need to create a `fixHooks` entry to copy or modify the properties. - * @example ​ ````For example, to set a hook for the "drop" event that copies the `dataTransfer` property, assign an object to `jQuery.event.fixHooks.drop`: -```javascript -jQuery.event.fixHooks.drop = { - props: [ "dataTransfer" ] -}; -``` - -Since fixHooks is an advanced feature and rarely used externally, jQuery does not include code or -interfaces to deal with conflict resolution. If there is a chance that some other code may be assigning -`fixHooks` to the same events, the code should check for an existing hook and take appropriate measures. -A simple solution might look like this: - -```javascript -if ( jQuery.event.fixHooks.drop ) { - throw new Error( "Someone else took the jQuery.event.fixHooks.drop hook!" ); -} - -jQuery.event.fixHooks.drop = { - props: [ "dataTransfer" ] -}; -``` - -When there are known cases of different plugins wanting to attach to the drop hook, this solution might be more appropriate: - -```javascript -var existingHook = jQuery.event.fixHooks.drop; - -if ( !existingHook ) { - jQuery.event.fixHooks.drop = { - props: [ "dataTransfer" ] - }; -} else { - if ( existingHook.props ) { - existingHook.props.push( "dataTransfer" ); - } else { - existingHook.props = [ "dataTransfer" ]; - } -} -``` - */ - filter(event: Event, originalEvent: _Event): void; - } | { - [key: string]: never; - }; - - /** - * The `fixHooks` interface provides a per-event-type way to extend or normalize the event object that jQuery creates when it processes a _native_ browser event. - * @see \`{@link https://learn.jquery.com/events/event-extensions/#jquery-event-fixhooks-object }\` - */ - interface FixHooks { - [event: string]: FixHook; - } - - // #endregion - // region Special event hooks // #region Special event hooks @@ -4879,13 +6425,13 @@ if ( !existingHook ) { * The trigger hook is called early in the process of triggering an event, just after the `jQuery.Event` object is constructed and before any handlers have been called. It can process the triggered event in any way, for example by calling `event.stopPropagation()` or `event.preventDefault()` before returning. If the hook returns `false`, jQuery does not perform any further event triggering actions and returns immediately. Otherwise, it performs the normal trigger processing, calling any event handlers for the element and bubbling the event (unless propagation is stopped in advance or `noBubble` was specified for the special event) to call event handlers attached to parent elements. * @see \`{@link https://learn.jquery.com/events/event-extensions/#trigger-function-event-jquery-event-data-object }\` */ - trigger(this: TTarget, event: Event, data: TData): void | false; + trigger(this: TTarget, event: Event, data: TData): void | false; } | { /** * When the `.trigger()` method finishes running all the event handlers for an event, it also looks for and runs any method on the target object by the same name unless of the handlers called `event.preventDefault()`. So, `.trigger( "submit" )` will execute the `submit()` method on the element if one exists. When a `_default` hook is specified, the hook is called just prior to checking for and executing the element's default method. If this hook returns the value `false` the element's default method will be called; otherwise it is not. * @see \`{@link https://learn.jquery.com/events/event-extensions/#_default-function-event-jquery-event-data-object }\` */ - _default(event: Event, data: TData): void | false; + _default(event: TriggeredEvent, data: TData): void | false; } | { /** * jQuery calls a handle hook when the event has occurred and jQuery would normally call the user's event handler specified by `.on()` or another event binding method. If the hook exists, jQuery calls it _instead_ of that event handler, passing it the event and any data passed from `.trigger()` if it was not a native event. The `this` keyword is the DOM element being handled, and `event.handleObj` property has the detailed event information. @@ -4893,11 +6439,11 @@ if ( !existingHook ) { * Based in the information it has, the handle hook should decide whether to call the original handler function which is in `event.handleObj.handler`. It can modify information in the event object before calling the original handler, but _must restore_ that data before returning or subsequent unrelated event handlers may act unpredictably. In most cases, the handle hook should return the result of the original handler, but that is at the discretion of the hook. The handle hook is unique in that it is the only special event function hook that is called under its original special event name when the type is mapped using `bindType` and `delegateType`. For that reason, it is almost always an error to have anything other than a handle hook present if the special event defines a `bindType` and `delegateType`, since those other hooks will never be called. * @see \`{@link https://learn.jquery.com/events/event-extensions/#handle-function-event-jquery-event-data-object }\` */ - handle(this: TTarget, event: Event & { handleObj: HandleObject; }, ...data: TData[]): void; + handle(this: TTarget, event: TriggeredEvent & { handleObj: HandleObject; }, ...data: TData[]): void; } | { - preDispatch(this: TTarget, event: Event): false | void; + preDispatch(this: TTarget, event: Event): false | void; } | { - postDispatch(this: TTarget, event: Event): void; + postDispatch(this: TTarget, event: Event): void; } | { [key: string]: never; }; @@ -4989,8 +6535,12 @@ if ( !existingHook ) { declare const jQuery: JQueryStatic; declare const $: JQueryStatic; -// Used by JQuery.Event type _Event = Event; +type _UIEvent = UIEvent; +type _MouseEvent = MouseEvent; +type _KeyboardEvent = KeyboardEvent; +type _TouchEvent = TouchEvent; +type _FocusEvent = FocusEvent; // region ES5 compatibility // #region ES5 compatibility diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index 7ecb1733a7..77d412f8e1 100644 --- a/types/jquery/test/example-tests.ts +++ b/types/jquery/test/example-tests.ts @@ -384,7 +384,7 @@ function examples() { } function bind_2() { - function handler(event: JQuery.Event) { + function handler(event: JQuery.TriggeredEvent) { alert(event.data.foo); } @@ -830,7 +830,7 @@ function examples() { var len = kids.addClass('hilite').length; $('#results span:first').text(len); - $('#results span:last').text(event.target.tagName); + $('#results span:last').text((event.target as Element).tagName); event.preventDefault(); }); @@ -1578,7 +1578,7 @@ function examples() { function event_related_target_0() { $('a').mouseout(function(event) { - alert(( event.relatedTarget).nodeName); // "DIV" + alert((event.relatedTarget as HTMLElement).nodeName); // "DIV" }); } @@ -1614,12 +1614,12 @@ function examples() { function event_target_0() { $('body').click(function(event) { - $('#log').html('clicked: ' + event.target.nodeName); + $('#log').html('clicked: ' + (event.target as Node).nodeName); }); } function event_target_1() { - function handler(event: JQuery.Event) { + function handler(event: JQuery.TriggeredEvent) { var target = $(event.target); if (target.is('li')) { target.children().toggle(); @@ -3018,10 +3018,10 @@ function examples() { function jQuery_proxy_0() { var me = { type: 'zombie', - test: function(event: JQuery.Event) { + test: function(event: JQuery.TriggeredEvent) { // Without proxy, `this` would refer to the event target // use event.target to reference that element. - var element = event.target; + var element = event.target as Element; $(element).css('background-color', 'red'); // With proxy, `this` refers to the me object encapsulating @@ -3033,7 +3033,7 @@ function examples() { var you = { type: 'person', - test: function(event: JQuery.Event) { + test: function(event: JQuery.TriggeredEvent) { $('#log').append(this.type + ' '); }, }; @@ -3075,7 +3075,7 @@ function examples() { type: 'dog', // Note that event comes *after* one and two - test: function(one: typeof you, two: typeof they, event: JQuery.Event) { + test: function(one: typeof you, two: typeof they, event: JQuery.TriggeredEvent) { $('#log') // `one` maps to `you`, the 1st additional @@ -3796,7 +3796,7 @@ function examples() { } function on_1() { - function myHandler(event: JQuery.Event) { + function myHandler(event: JQuery.TriggeredEvent) { alert(event.data.foo); } diff --git a/types/jquery/test/learn-tests.ts b/types/jquery/test/learn-tests.ts index 8ef5eb2cfa..b1a0353b4e 100644 --- a/types/jquery/test/learn-tests.ts +++ b/types/jquery/test/learn-tests.ts @@ -21,24 +21,6 @@ jQuery("a").greenify(); // Makes all the links green. // Events -function fixHooks() { - function setHook() { - jQuery.event.fixHooks.drop = { - props: ["dataTransfer"] - }; - } - - function conflictResolution() { - if (jQuery.event.fixHooks.drop) { - throw new Error("Someone else took the jQuery.event.fixHooks.drop hook!"); - } - - jQuery.event.fixHooks.drop = { - props: ["dataTransfer"] - }; - } -} - function special() { function defineSpecialEvent() { jQuery.event.special.pushy = { @@ -53,7 +35,7 @@ function special() { bindType: "click", handle(event) { const handleObj = event.handleObj; - const targetData = jQuery.data(event.target); + const targetData = jQuery.data(event.target as Element); let ret = null; // If a multiple of the click count, run the handler diff --git a/types/jquery/test/longdesc-tests.ts b/types/jquery/test/longdesc-tests.ts index bb3bb4c83c..e1ee36a575 100644 --- a/types/jquery/test/longdesc-tests.ts +++ b/types/jquery/test/longdesc-tests.ts @@ -538,7 +538,7 @@ function longdesc() { $('#foo').slideUp(300).delay(800).fadeIn(400); } - function delegate_0(elements: HTMLElement[], selector: string, events: any, data: any, handler: JQuery.EventHandler) { + function delegate_0(elements: HTMLElement[], selector: string, events: string, data: any, handler: JQuery.TypeEventHandler) { // jQuery 1.4.3+ $(elements).delegate(selector, events, data, handler); // jQuery 1.7+ @@ -886,7 +886,7 @@ function longdesc() { var currentRequests: JQuery.PlainObject = {}; $.ajaxPrefilter(function(options, originalOptions, jqXHR) { - if (( options).abortOnRetry) { + if ((options as any).abortOnRetry) { if (currentRequests[options.url!]) { currentRequests[options.url!].abort(); } @@ -1297,7 +1297,7 @@ function longdesc() { return $.css(elem, borderRadius!); }, set: function(elem, value) { - ( elem.style)[borderRadius!] = value; + (elem.style as any)[borderRadius!] = value; }, }; } @@ -2016,7 +2016,7 @@ function longdesc() { } function on_3() { - function greet(event: JQuery.Event) { + function greet(event: JQuery.TriggeredEvent) { alert('Hello ' + event.data.name); } diff --git a/types/js-url/index.d.ts b/types/js-url/index.d.ts index d5bf93257d..69583e1553 100644 --- a/types/js-url/index.d.ts +++ b/types/js-url/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for url v1.8.6 // Project: https://github.com/websanova/js-url -// Definitions by: MIZUNE Pine +// Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface UrlStatic { diff --git a/types/jsdom/jsdom-tests.ts b/types/jsdom/jsdom-tests.ts index d20232e36f..1420723b8d 100644 --- a/types/jsdom/jsdom-tests.ts +++ b/types/jsdom/jsdom-tests.ts @@ -120,7 +120,7 @@ function test_runVMScript() { dom.runVMScript(s); dom.runVMScript(s); - ( dom.window).ran === 3; + (dom.window as any).ran === 3; } function test_reconfigure() { diff --git a/types/jsforce/api/chatter.d.ts b/types/jsforce/api/chatter.d.ts index 4e0982ca24..c712187559 100644 --- a/types/jsforce/api/chatter.d.ts +++ b/types/jsforce/api/chatter.d.ts @@ -41,6 +41,8 @@ export class Request implements Promise { then(onfulfilled?: ((value: T) => (PromiseLike | TResult1)) | null | undefined, onrejected?: ((reason: any) => (PromiseLike | TResult2)) | null | undefined): Promise; + finally(onfinally?: () => void): Promise; + thenCall(callback?: (err: Error, records: T) => void): Query; readonly [Symbol.toStringTag]: 'Promise'; diff --git a/types/jsforce/api/metadata.d.ts b/types/jsforce/api/metadata.d.ts index 15f0fe249e..c6aec12e7e 100644 --- a/types/jsforce/api/metadata.d.ts +++ b/types/jsforce/api/metadata.d.ts @@ -124,6 +124,8 @@ export class AsyncResultLocator extends EventEmitter implements Promise { then(onfulfilled?: ((value: T) => (PromiseLike | TResult1)) | null | undefined, onrejected?: ((reason: any) => (PromiseLike | TResult2)) | null | undefined): Promise; + finally(onfinally?: () => void): Promise; + readonly [Symbol.toStringTag]: "Promise"; } diff --git a/types/json-server/index.d.ts b/types/json-server/index.d.ts new file mode 100644 index 0000000000..c52a4b220e --- /dev/null +++ b/types/json-server/index.d.ts @@ -0,0 +1,72 @@ +// Type definitions for json-server 0.14 +// Project: https://github.com/typicode/json-server +// Definitions by: Jeremy Bensimon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { NextHandleFunction } from 'connect'; +import { Application, RequestHandler, Router } from 'express'; + +/** + * Returns an Express server. + */ +export function create(): Application; + +/** + * Returns middlewares used by JSON Server. + */ +export function defaults(options?: MiddlewaresOptions): RequestHandler[]; + +/** + * Returns JSON Server router. + * @param source Either a path to a json file (e.g. `'db.json'`) or an object in memory + * @param options Set foreign key suffix (default: `'Id'`) + */ +export function router(source: string | object, options?: { foreignKeySuffix: string }): Router; + +/** + * Add custom rewrite rules. + */ +export function rewriter(rules: { [rule: string]: string }): Router; + +/** + * Returns body-parser middleware used by JSON Server router. + * + * @returns + * ``` + * [bodyParser.json({ limit: '10mb', extended: false }), bodyParser.urlencoded({ extended: false })] + * ``` + */ +export const bodyParser: [NextHandleFunction, NextHandleFunction]; + +export interface MiddlewaresOptions { + /** + * Path to static files + * @default "public" (if folder exists) + */ + static?: string; + + /** + * Enable logger middleware + * @default true + */ + logger?: boolean; + + /** + * Enable body-parser middleware + * @default true + */ + bodyParser?: boolean; + + /** + * Disable CORS + * @default false + */ + noCors?: boolean; + + /** + * Accept only GET requests + * @default false + */ + readOnly?: boolean; +} diff --git a/types/json-server/json-server-tests.ts b/types/json-server/json-server-tests.ts new file mode 100644 index 0000000000..d68484b1ff --- /dev/null +++ b/types/json-server/json-server-tests.ts @@ -0,0 +1,41 @@ +import * as jsonServer from 'json-server'; + +const server = jsonServer.create(); + +const inMemoryDbRouter = jsonServer.router({ todos: [] as any[], users: [] as any[] }); + +const router = jsonServer.router('db.json', { foreignKeySuffix: '_id' }); + +const middlewaresOptions: jsonServer.MiddlewaresOptions = { + bodyParser: true, + logger: false, + noCors: true, + readOnly: true, + static: 'assets', +}; + +const middlewares = jsonServer.defaults(middlewaresOptions); + +const rewriter = jsonServer.rewriter({ + '/api/*': '/$1', + '/blog/:resource/:id/show': '/:resource/:id', +}); + +server.use(jsonServer.bodyParser); + +server.use((req, res, next) => { + if (req.method === 'POST') { + req.body.createdAt = Date.now(); + } + next(); +}); + +server.use(rewriter); + +server.use(middlewares); + +server.use(router); + +server.listen(3000, () => { + console.log('JSON Server is running'); +}); diff --git a/types/json-server/tsconfig.json b/types/json-server/tsconfig.json new file mode 100644 index 0000000000..e923ac1d7a --- /dev/null +++ b/types/json-server/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "json-server-tests.ts"] +} diff --git a/types/json-server/tslint.json b/types/json-server/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/json-server/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/json_ml/index.d.ts b/types/json_ml/index.d.ts new file mode 100644 index 0000000000..7cab812880 --- /dev/null +++ b/types/json_ml/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for json_ml 0.0 +// Project: https://github.com/59naga/json-ml +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +/// + +export type Node = string | [string, ...any[]]; +export function parse(xml: string, trim?: boolean): Node[]; +export function stringify( + object: Node[], + replacer?: ((node: Cheerio) => any) | null, + indent?: number +): string; diff --git a/types/json_ml/json_ml-tests.ts b/types/json_ml/json_ml-tests.ts new file mode 100644 index 0000000000..05ca64da4a --- /dev/null +++ b/types/json_ml/json_ml-tests.ts @@ -0,0 +1,20 @@ +/// +import { Node, parse, stringify } from "json_ml"; + +const nodes: Node[] = parse( + '
  • First Item
  • Second Item
  • ThirdItem
' +); +stringify(nodes, el => (el.is("li") ? null : el), 2); + +stringify( + [ + [ + "ul", + ["li", { style: "color: red" }], + ["li", { title: "Some hover text", style: "color: green" }], + ["li", ["span", { class: "code-example-third" }]] + ] + ], + null, + 2 +); diff --git a/types/json_ml/tsconfig.json b/types/json_ml/tsconfig.json new file mode 100644 index 0000000000..951405762a --- /dev/null +++ b/types/json_ml/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "json_ml-tests.ts"] +} diff --git a/types/json_ml/tslint.json b/types/json_ml/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/json_ml/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/karma-chai-sinon/index.d.ts b/types/karma-chai-sinon/index.d.ts index 0b14373a99..9a14f659e2 100644 --- a/types/karma-chai-sinon/index.d.ts +++ b/types/karma-chai-sinon/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/tubalmartin/karma-chai-sinon // Definitions by: Václav Ostrožlík // Definitions: https://github.com/borisyankov/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 /// import Sinon = require('sinon'); diff --git a/types/karma-coverage/index.d.ts b/types/karma-coverage/index.d.ts index 50be80d5cf..8382ec7b12 100644 --- a/types/karma-coverage/index.d.ts +++ b/types/karma-coverage/index.d.ts @@ -1,27 +1,22 @@ -// Type definitions for karma-coverage v0.5.3 +// Type definitions for karma-coverage 1.1 // Project: https://github.com/karma-runner/karma-coverage // Definitions by: Tanguy Krotoff +// Yaroslav Admin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as karma from 'karma'; +import 'karma'; import * as istanbul from 'istanbul'; -declare namespace karmaCoverage { - interface Karma extends karma.Karma { } - - interface Config extends karma.Config { - set: (config: ConfigOptions) => void; - } - - interface ConfigOptions extends karma.ConfigOptions { +declare module 'karma' { + interface ConfigOptions { /** * See https://github.com/karma-runner/karma-coverage/blob/master/docs/configuration.md */ - coverageReporter?: (Reporter | Reporter[]); + coverageReporter?: KarmaCoverageReporter & { reporters?: KarmaCoverageReporter[] }; } - interface Reporter { + interface KarmaCoverageReporter { type?: string; dir?: string; subdir?: string | ((browser: string) => string); @@ -33,7 +28,3 @@ declare namespace karmaCoverage { [moreSettings: string]: any; } } - -declare var karmaCoverage: karmaCoverage.Karma; - -export = karmaCoverage; diff --git a/types/karma-coverage/karma-coverage-tests.ts b/types/karma-coverage/karma-coverage-tests.ts index 4f0b187a7a..36d7d85415 100644 --- a/types/karma-coverage/karma-coverage-tests.ts +++ b/types/karma-coverage/karma-coverage-tests.ts @@ -1,6 +1,6 @@ -import * as karma from 'karma-coverage'; +import * as karma from 'karma'; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/README.md#basic +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/README.md#basic module.exports = function(config: karma.Config) { config.set({ files: [ @@ -20,13 +20,13 @@ module.exports = function(config: karma.Config) { // optionally, configure the reporter coverageReporter: { - type : 'html', - dir : 'coverage/' + type: 'html', + dir: 'coverage/' } }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/README.md#advanced-multiple-reporters +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/README.md#advanced-multiple-reporters module.exports = function(config: karma.Config) { config.set({ files: [ @@ -56,7 +56,7 @@ module.exports = function(config: karma.Config) { }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/README.md#dont-minify-instrumenter-output +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/README.md#dont-minify-instrumenter-output module.exports = function(config: karma.Config) { config.set({ coverageReporter: { @@ -67,7 +67,7 @@ module.exports = function(config: karma.Config) { }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#subdir +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#subdir module.exports = function(config: karma.Config) { config.set({ coverageReporter: { @@ -93,7 +93,7 @@ module.exports = function(config: karma.Config) { coverageReporter: { dir: 'coverage', subdir: function(browser) { - // normalization process to keep a consistent browser name accross different + // normalization process to keep a consistent browser name across different // OS return browser.toLowerCase().split(/[ /-]/)[0]; } @@ -102,18 +102,18 @@ module.exports = function(config: karma.Config) { }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#file +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#file module.exports = function(config: karma.Config) { config.set({ coverageReporter: { - type : 'text', - dir : 'coverage/', - file : 'coverage.txt' + type: 'text', + dir: 'coverage/', + file: 'coverage.txt' } }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#check +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#check module.exports = function(config: karma.Config) { config.set({ coverageReporter: { @@ -146,7 +146,7 @@ module.exports = function(config: karma.Config) { }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#watermarks +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#watermarks module.exports = function(config: karma.Config) { config.set({ coverageReporter: { @@ -160,24 +160,36 @@ module.exports = function(config: karma.Config) { }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#sourcestore -module.exports = function(config: karma.Config) { +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#includeallsources +module.exports = function (config: karma.Config) { config.set({ coverageReporter: { - type : 'text', - dir : 'coverage/', - file : 'coverage.txt', - sourceStore : require('istanbul').Store.create('fslookup') + type: 'text', + dir: 'coverage/', + file: 'coverage.txt', + includeAllSources: true } }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#reporters +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#sourcestore module.exports = function(config: karma.Config) { config.set({ coverageReporter: { - reporters:[ - {type: 'html', dir:'coverage/'}, + type: 'text', + dir: 'coverage/', + file: 'coverage.txt', + sourceStore: require('istanbul').Store.create('fslookup') + } + }); +}; + +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#reporters +module.exports = function(config: karma.Config) { + config.set({ + coverageReporter: { + reporters: [ + {type: 'html', dir: 'coverage/'}, {type: 'teamcity'}, {type: 'text-summary'} ], @@ -185,7 +197,7 @@ module.exports = function(config: karma.Config) { }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#instrumenter +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#instrumenter module.exports = function(config: karma.Config) { config.set({ coverageReporter: { diff --git a/types/karma/index.d.ts b/types/karma/index.d.ts index ba258f0997..0da2803283 100644 --- a/types/karma/index.d.ts +++ b/types/karma/index.d.ts @@ -13,58 +13,55 @@ import Promise = require('bluebird'); import https = require('https'); import { Appender } from 'log4js'; -declare namespace karma { - interface Karma { - /** - * `start` method is deprecated since 0.13. It will be removed in 0.14. - * Please use - * - * server = new Server(config, [done]) - * server.start() - * - * instead. - */ - server: DeprecatedServer; - Server: Server; - runner: Runner; - stopper: Stopper; - launcher: Launcher; - VERSION: string; - constants: Constants; - } +/** + * `start` method is deprecated since 0.13. It will be removed in 0.14. + * Please use + * + * server = new Server(config, [done]) + * server.start() + * + * instead. + * + * @deprecated + */ +export const server: DeprecatedServer; - interface Constants { - VERSION: string; - DEFAULT_PORT: number; - DEFAULT_HOSTNAME: string; - DEFAULT_LISTEN_ADDR: string; - LOG_DISABLE: string; - LOG_ERROR: string; - LOG_WARN: string; - LOG_INFO: string; - LOG_DEBUG: string; - LOG_LOG: string; - LOG_PRIORITIES: string[]; - COLOR_PATTERN: string; - NO_COLOR_PATTERN: string; - CONSOLE_APPENDER: { +export const runner: Runner; +export const stopper: Stopper; + +export const VERSION: string; +export const constants: Constants; + +export interface Constants { + VERSION: string; + DEFAULT_PORT: number; + DEFAULT_HOSTNAME: string; + DEFAULT_LISTEN_ADDR: string; + LOG_DISABLE: string; + LOG_ERROR: string; + LOG_WARN: string; + LOG_INFO: string; + LOG_DEBUG: string; + LOG_LOG: string; + LOG_PRIORITIES: string[]; + COLOR_PATTERN: string; + NO_COLOR_PATTERN: string; + CONSOLE_APPENDER: { + type: string; + layout: { type: string; - layout: { - type: string; - pattern: string; - }; + pattern: string; }; - EXIT_CODE: string; - } + }; + EXIT_CODE: string; +} - interface LauncherStatic { - generateId(): string; - // TODO: injector should be of type `di.Injector` - new (emitter: NodeJS.EventEmitter, injector: any): Launcher; - } +export namespace launcher { + class Launcher { + static generateId(): string; + + constructor(emitter: NodeJS.EventEmitter, injector: any); - interface Launcher { - Launcher: LauncherStatic; // TODO: Can this return value ever be typified? launch(names: string[], protocol: string, hostname: string, port: number, urlRoot: string): any[]; kill(id: string, callback: () => void): boolean; @@ -73,403 +70,403 @@ declare namespace karma { areAllCaptured(): boolean; markCaptured(id: string): void; } - - interface DeprecatedServer { - start(options?: any, callback?: ServerCallback): void; - } - - interface Runner { - run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void; - } - - interface Stopper { - /** - * This function will signal a running server to stop. The equivalent of karma stop. - */ - stop(options?: ConfigOptions, callback?: ServerCallback): void; - } - - interface TestResults { - disconnected: boolean; - error: boolean; - exitCode: number; - failed: number; - success: number; - } - - interface Server extends NodeJS.EventEmitter { - // TODO: Figure out how to convert Server to class and remove suppression - // tslint:disable-next-line:no-misused-new - new (options?: ConfigOptions | ConfigFile, callback?: ServerCallback): Server; - /** - * Start the server - */ - start(): void; - /** - * Get properties from the injector - * @param token - */ - get(token: string): any; - /** - * Force a refresh of the file list - */ - refreshFiles(): Promise; - - on(event: string, listener: (...args: any[]) => void): this; - - /** - * Listen to the 'run_complete' event. - */ - on(event: 'run_complete', listener: (browsers: any, results: TestResults) => void): this; - - /** - * Backward-compatibility with karma-intellij bundled with WebStorm. - * Deprecated since version 0.13, to be removed in 0.14 - */ - // static start(): void; - } - - type ServerCallback = (exitCode: number) => void; - - interface Config { - set: (config: ConfigOptions) => void; - LOG_DISABLE: string; - LOG_ERROR: string; - LOG_WARN: string; - LOG_INFO: string; - LOG_DEBUG: string; - } - - interface ConfigFile { - configFile: string; - } - - interface ConfigOptions { - /** - * @description Enable or disable watching files and executing the tests whenever one of these files changes. - * @default true - */ - autoWatch?: boolean; - /** - * @description When Karma is watching the files for changes, it tries to batch multiple changes into a single run - * so that the test runner doesn't try to start and restart running tests more than it should. - * The configuration setting tells Karma how long to wait (in milliseconds) after any changes have occurred - * before starting the test process again. - * @default 250 - */ - autoWatchBatchDelay?: number; - /** - * @default '' - * @description The root path location that will be used to resolve all relative paths defined in files and exclude. - * If the basePath configuration is a relative path then it will be resolved to - * the __dirname of the configuration file. - */ - basePath?: string; - /** - * @default 2000 - * @description How long does Karma wait for a browser to reconnect (in ms). - *

- * With a flaky connection it is pretty common that the browser disconnects, - * but the actual test execution is still running without any problems. Karma does not treat a disconnection - * as immediate failure and will wait browserDisconnectTimeout (ms). - * If the browser reconnects during that time, everything is fine. - *

- */ - browserDisconnectTimeout?: number; - /** - * @default 0 - * @description The number of disconnections tolerated. - *

- * The disconnectTolerance value represents the maximum number of tries a browser will attempt - * in the case of a disconnection. Usually any disconnection is considered a failure, - * but this option allows you to define a tolerance level when there is a flaky network link between - * the Karma server and the browsers. - *

- */ - browserDisconnectTolerance?: number; - /** - * @default 10000 - * @description How long will Karma wait for a message from a browser before disconnecting from it (in ms). - *

- * If, during test execution, Karma does not receive any message from a browser within - * browserNoActivityTimeout (ms), it will disconnect from the browser - *

- */ - browserNoActivityTimeout?: number; - /** - * @default [] - * Possible Values: - *
    - *
  • Chrome (launcher comes installed with Karma)
  • - *
  • ChromeCanary (launcher comes installed with Karma)
  • - *
  • PhantomJS (launcher comes installed with Karma)
  • - *
  • Firefox (launcher requires karma-firefox-launcher plugin)
  • - *
  • Opera (launcher requires karma-opera-launcher plugin)
  • - *
  • Internet Explorer (launcher requires karma-ie-launcher plugin)
  • - *
  • Safari (launcher requires karma-safari-launcher plugin)
  • - *
- * @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser - * which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well. - * You can capture any browser manually by opening the browser and visiting the URL where - * the Karma web server is listening (by default it is http://localhost:9876/). - */ - browsers?: string[]; - /** - * @default 60000 - * @description Timeout for capturing a browser (in ms). - *

- * The captureTimeout value represents the maximum boot-up time allowed for a - * browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma - * will kill it and try to launch it again and, after three attempts to capture it, Karma will give up. - *

- */ - captureTimeout?: number; - client?: ClientOptions; - /** - * @default true - * @description Enable or disable colors in the output (reporters and logs). - */ - colors?: boolean; - /** - * @default 'Infinity' - * @description How many browsers Karma launches in parallel. - * Especially on services like SauceLabs and Browserstack, it makes sense only to launch a limited - * amount of browsers at once, and only start more when those have finished. Using this configuration, - * you can specify how many browsers should be running at once at any given point in time. - */ - concurrency?: number; - customLaunchers?: { [key: string]: CustomLauncher }; - /** - * @default [] - * @description List of files/patterns to exclude from loaded files. - */ - exclude?: string[]; - /** - * @default [] - * @description List of files/patterns to load in the browser. - */ - files?: Array; - /** - * @default [] - * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']... - * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM). - */ - frameworks?: string[]; - /** - * @default 'localhost' - * @description Hostname to be used when capturing browsers. - */ - hostname?: string; - /** - * @default {} - * @description Options object to be used by Node's https class. - * Object description can be found in the - * [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener) - */ - httpsServerOptions?: https.ServerOptions; - /** - * @default config.LOG_INFO - * Possible values: - *
    - *
  • config.LOG_DISABLE
  • - *
  • config.LOG_ERROR
  • - *
  • config.LOG_WARN
  • - *
  • config.LOG_INFO
  • - *
  • config.LOG_DEBUG
  • - *
- * @description Level of logging. - */ - logLevel?: string; - /** - * @default [{type: 'console'}] - * @description A list of log appenders to be used. See the documentation for [log4js] for more information. - */ - loggers?: { [name: string]: Appender } | Appender[]; - /** - * @default [] - * @description List of names of additional middleware you want the - * Karma server to use. Middleware will be used in the order listed. - * You must have installed the middleware via a plugin/framework - * (either inline or via NPM). Additional information can be found in - * [plugins](http://karma-runner.github.io/2.0/config/plugins.html). - * The plugin must provide an express/connect middleware function - * (details about this can be found in the - * [Express](http://expressjs.com/guide/using-middleware.html) docs). - */ - middleware?: string[]; - /** - * @default {} - * @description Redefine default mapping from file extensions to MIME-type. - * Set property name to required MIME, provide Array of extensions (without dots) as it's value. - */ - mime?: {[type: string]: string[]}; - /** - * @default ['karma-*'] - * @description List of plugins to load. A plugin can be a string (in which case it will be required - * by Karma) or an inlined plugin - Object. - * By default, Karma loads all sibling NPM modules which have a name starting with karma-*. - * Note: Just about all plugins in Karma require an additional library to be installed (via NPM). - */ - plugins?: any[]; - /** - * @default 9876 - * @description The port where the web server will be listening. - */ - port?: number; - /** - * @default {'**\/*.coffee': 'coffee'} - * @description A map of preprocessors to use. - * - * Preprocessors can be loaded through [plugins]. - * - * Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults) - * require an additional library to be installed (via NPM). - * - * Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance, - * if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug - * your tests, you'll discover that your expected source code is completely changed from what you expected. Because - * of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list, - * but your interactive debugging does not. - * - */ - preprocessors?: { [name: string]: string | string[] }; - /** - * @default 'http:' - * Possible Values: - *
    - *
  • http:
  • - *
  • https:
  • - *
- * @description Protocol used for running the Karma webserver. - * Determines the use of the Node http or https class. - * Note: Using 'https:' requires you to specify httpsServerOptions. - */ - protocol?: string; - /** - * @default {} - * @description A map of path-proxy pairs. - */ - proxies?: { [path: string]: string }; - /** - * @default true - * @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found. - */ - proxyValidateSSL?: boolean; - /** - * @default 0 - * @description Karma will report all the tests that are slower than given time limit (in ms). - * This is disabled by default (since the default value is 0). - */ - reportSlowerThan?: number; - /** - * @default ['progress'] - * Possible Values: - *
    - *
  • dots
  • - *
  • progress
  • - *
- * @description A list of reporters to use. - * Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins. - * Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM). - */ - reporters?: string[]; - /** - * @default false - * @description Continuous Integration mode. - * If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending - * on whether all tests passed or any tests failed. - */ - singleRun?: boolean; - /** - * @default ['polling', 'websocket'] - * @description An array of allowed transport methods between the browser and testing server. This configuration setting - * is handed off to [socket.io](http://socket.io/) (which manages the communication - * between browsers and the testing server). - */ - transports?: string[]; - /** - * @default '/' - * @description The base url, where Karma runs. - * All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as - * sometimes you might want to proxy a url that is already taken by Karma. - */ - urlRoot?: string; - } - - interface ClientOptions { - /** - * @default undefined - * @description When karma run is passed additional arguments on the command-line, they - * are passed through to the test adapter as karma.config.args (an array of strings). - * The client.args option allows you to set this value for actions other than run. - * How this value is used is up to your test adapter - you should check your adapter's - * documentation to see how (and if) it uses this value. - */ - args?: string[]; - /** - * @default true - * @description Run the tests inside an iFrame or a new window - * If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an - * iFrame and may need a new window to run. - */ - useIframe?: boolean; - /** - * @default true - * @description Capture all console output and pipe it to the terminal. - */ - captureConsole?: boolean; - /** - * @default false - * @description Run the tests on the same window as the client, without using iframe or a new window - */ - runInParent?: boolean; - /** - * @default true - * @description Clear the context window - * If true, Karma clears the context window upon the completion of running the tests. - * If false, Karma does not clear the context window upon the completion of running the tests. - * Setting this to false is useful when embedding a Jasmine Spec Runner Template. - */ - clearContext?: boolean; - } - - interface FilePattern { - /** - * The pattern to use for matching. This property is mandatory. - */ - pattern: string; - /** - * @default true - * @description If autoWatch is true all files that have set watched to true will be watched - * for changes. - */ - watched?: boolean; - /** - * @default true - * @description Should the files be included in the browser using \n' + + "but do b.ca", + { + ignoreTags: ["script", "style"] + } +); + +/* nl2br */ + +/* tagName */ + +linkifyHtml("github.com", { + tagName: "span" +}); + +linkifyHtml("#swag", { + tagName: { + hashtag: "span" + } +}); + +/* target */ + +linkifyHtml("github.com", { + target: "_parent" +}); + +linkifyHtml("test-email@example.com", { + target: { + url: "_parent", + email: null + } +}); + +/* validate */ + +// Don't linkify links that don't begin in a protocol +// e.g., "http://google.com" will be linkified, but "google.com" will not. +linkifyHtml("www.google.com", { + validate: { + url(value) { + return /^(http|ftp)s?:\/\//.test(value); + } + } +}); diff --git a/types/linkifyjs/tsconfig.json b/types/linkifyjs/tsconfig.json new file mode 100644 index 0000000000..52b1940fcd --- /dev/null +++ b/types/linkifyjs/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "html.d.ts", + "linkifyjs-tests.ts" + ] +} diff --git a/types/linkifyjs/tslint.json b/types/linkifyjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/linkifyjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts new file mode 100644 index 0000000000..2b3fd1da28 --- /dev/null +++ b/types/list-stream/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for list-stream 1.0 +// Project: https://github.com/rvagg/list-stream +// Definitions by: Christian Sporer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +/// + +import { Duplex, DuplexOptions } from "stream"; + +interface ListStreamMethod { + (callback?: (err: Error, data: any[]) => void): ListStream; + (options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream; +} + +interface ListStreamConstructor extends ListStreamMethod { + new(callback?: (err: Error, data: any[]) => void): ListStream; + new(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream; + + obj: ListStreamMethod; +} + +declare let ListStream: ListStreamConstructor; + +interface ListStream extends Duplex { + append(chunk: any): void; + duplicate(): ListStream; + end(): void; + get(index: number): any; + length: number; +} + +export = ListStream; diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts new file mode 100644 index 0000000000..8b6ae25435 --- /dev/null +++ b/types/list-stream/list-stream-tests.ts @@ -0,0 +1,2 @@ +import "./test/import-tests"; +import "./test/require-tests"; diff --git a/types/list-stream/test/import-tests.ts b/types/list-stream/test/import-tests.ts new file mode 100644 index 0000000000..3648097ad6 --- /dev/null +++ b/types/list-stream/test/import-tests.ts @@ -0,0 +1,54 @@ +import ListStream from "list-stream"; + +let chunk: any = "chunk"; +let listStream: ListStream; +let num = 1; + +listStream = ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream.obj((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); + +listStream = ListStream.obj(); +listStream.write({ key: "value" }); + +listStream.append(chunk); + +listStream = listStream.duplicate(); + +listStream.end(); + +chunk = listStream.get(num); + +num = listStream.length; diff --git a/types/list-stream/test/require-tests.ts b/types/list-stream/test/require-tests.ts new file mode 100644 index 0000000000..8966e1e5a3 --- /dev/null +++ b/types/list-stream/test/require-tests.ts @@ -0,0 +1,54 @@ +import ListStream = require("list-stream"); + +let chunk: any = "chunk"; +let listStream: ListStream; +let num = 1; + +listStream = ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream.obj((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); + +listStream = ListStream.obj(); +listStream.write({ key: "value" }); + +listStream.append(chunk); + +listStream = listStream.duplicate(); + +listStream.end(); + +chunk = listStream.get(num); + +num = listStream.length; diff --git a/types/list-stream/tsconfig.json b/types/list-stream/tsconfig.json new file mode 100644 index 0000000000..00fe9a2e23 --- /dev/null +++ b/types/list-stream/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "test/import-tests.ts", + "test/require-tests.ts", + "index.d.ts", + "list-stream-tests.ts" + ] +} diff --git a/types/list-stream/tslint.json b/types/list-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/list-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/lodash/common/lang.d.ts b/types/lodash/common/lang.d.ts index 9afe554b28..723388c9cc 100644 --- a/types/lodash/common/lang.d.ts +++ b/types/lodash/common/lang.d.ts @@ -1020,7 +1020,7 @@ declare module "../index" { // isMatchWith - type isMatchWithCustomizer = (value: any, other: any, indexOrKey: PropertyName) => boolean; + type isMatchWithCustomizer = (value: any, other: any, indexOrKey: PropertyName, object: object, source: object) => boolean; interface LoDashStatic { /** diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 4f7f229fe6..9d2547dcf4 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -4205,7 +4205,7 @@ fp.now(); // $ExpectType number // _.isMatchWith { - const testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string|symbol) => true; + const testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string|symbol, object: object, source: object) => true; _.isMatchWith({}, {}, testIsMatchCustiomizerFn); // $ExpectType boolean _({}).isMatchWith({}, testIsMatchCustiomizerFn); // $ExpectType boolean diff --git a/types/ltx/index.d.ts b/types/ltx/index.d.ts index 33311a3175..1c313c5541 100644 --- a/types/ltx/index.d.ts +++ b/types/ltx/index.d.ts @@ -1,17 +1,17 @@ -// Type definitions for ltx 2.6 +// Type definitions for ltx 2.8 // Project: github.com/node-xmpp/ltx/ // Definitions by: PJakcson +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 -export {Element } from './lib/Element'; -export {nameEqual, attrsEqual, childrenEqual, equal} from './lib/equal'; -export {isNode, isElement, isText} from './lib/is'; -export {clone} from './lib/clone'; -export {createElement} from './lib/createElement'; -export {escapeXML, unescapeXML, escapeXMLText, unescapeXMLText} from './lib/escape'; -export {Parser} from './lib/Parser'; -export {parse} from './lib/parse'; -export {tag} from './lib/tag'; -export {tagString} from './lib/tagString'; -export {stringify} from './lib/stringify'; +export * from './lib/Element'; +export * from './lib/equal'; +export * from './lib/is'; +export * from './lib/clone'; +export * from './lib/createElement'; +export * from './lib/escape'; +export * from './lib/Parser'; +export * from './lib/parse'; +export * from './lib/tag'; +export * from './lib/tagString'; +export * from './lib/stringify'; diff --git a/types/ltx/lib/Element.d.ts b/types/ltx/lib/Element.d.ts index 203eaa93b6..7f0d3de62e 100644 --- a/types/ltx/lib/Element.d.ts +++ b/types/ltx/lib/Element.d.ts @@ -1,21 +1,26 @@ +import { clone } from './clone'; + +export type Node = Element | TextNode; +export type TextNode = string | number; + /** * Element * * Attributes are in the element.attrs object. Children is a list of * either other Elements or Strings for text content. - **/ -export declare class Element { + */ +export class Element { name: string; - parent: Element; + parent: Element | null; children: Element[]; - attrs: any; + attrs: { [attrName: string]: any }; - constructor(name: string, attrs?: any); + constructor(name: string, attrs?: string | { [attrName: string]: any }); /** * if (element.is('message', 'jabber:client')) ... - **/ - is(name: string, xmlns?: any): boolean; + */ + is(name: string, xmlns?: string): boolean; /** * without prefix. @@ -24,50 +29,44 @@ export declare class Element { /** * retrieves the namespace of the current element, upwards recursively - **/ - getNS(): any; + */ + getNS(): string | undefined; /** * find the namespace to the given prefix, upwards recursively - **/ - findNS(prefix: string): any; + */ + findNS(prefix: string): string | undefined; /** * Recursiverly gets all xmlns defined, in the form of {url:prefix} - **/ - getXmlns(): any; + */ + getXmlns(): { [key: string]: string }; - setAttrs(attrs: any): void; + setAttrs(attrs: string | { [attrName: string]: any }): void; /** - * xmlns can be null, returns the matching attribute. - **/ - getAttr(name: string, xmlns?: any): any; + * returns the matching attribute. + */ + getAttr(name: string, xmlns?: string): any; - /** - * xmlns can be null - **/ - getChild(name: string, xmlns?: any): Element; + getChild(name: string, xmlns?: string): Element | undefined; - /** - * xmlns can be null - **/ - getChildren(name: string, xmlns?: any): Element[]; + getChildren(name: string, xmlns?: string): Element[]; - /** - * xmlns and recursive can be null - **/ - getChildByAttr(attr: any, val: any, xmlns?: any, recursive?: any): Element; + getChildByAttr( + attr: string, + val: any, + xmlns?: string, + recursive?: boolean + ): Element | undefined; + getChildrenByAttr(attr: string, val: any, xmlns?: string, recursive?: boolean): Element[]; - /** - * xmlns and recursive can be null - **/ - getChildrenByAttr(attr: any, val: any, xmlns?: any, recursive?: any): Element[]; + getChildrenByFilter(filter: (child: Node) => boolean, recursive?: boolean): Element[]; getText(): string; - getChildText(name: string, xmlns?: any): string; + getChildText(name: string, xmlns?: string): string | null; /** * Return all direct descendents that are Elements. @@ -77,37 +76,39 @@ export declare class Element { getChildElements(): Element[]; /** returns uppermost parent */ - root(): Element; + root(): Element | this; - tree(): Element; + tree(): Element | this; /** just parent or itself */ - up(): Element; + up(): Element | this; /** create child node and return it */ - c(name: string, attrs?: any): Element; + c(name: string, attrs?: { [key: string]: any }): Element; + + cnode(child: T): T; /** add text node and return element */ - t(text: string): Element; + t(text: TextNode): this; /** * Either: * el.remove(childEl) * el.remove('author', 'urn:...') */ - remove(el: Element, xmlns?: any): Element; + remove(el: Element | string, xmlns?: string): this; - clone(): Element; + clone: typeof clone; - text(val: string): string; + text(val?: string): string; - attr(attr: any, val: any): any; + attr(attr: string, val?: any): any; toString(): string; - toJSON(): any; + toJSON(): ElementJson; - write(writer: any): void; + write(writer: (part: string) => void): void; nameEquals(el: Element): boolean; @@ -117,3 +118,9 @@ export declare class Element { equals(el: Element): boolean; } + +export interface ElementJson { + name: string; + attrs: { [attrName: string]: any }; + children: Array; +} diff --git a/types/ltx/lib/Parser.d.ts b/types/ltx/lib/Parser.d.ts index 083e3ace66..463029286f 100644 --- a/types/ltx/lib/Parser.d.ts +++ b/types/ltx/lib/Parser.d.ts @@ -1,5 +1,15 @@ /// import { EventEmitter } from 'events'; -export declare class Parser extends EventEmitter { - constructor(options?: any); +import { Element } from './Element'; + +export class Parser extends EventEmitter { + constructor(options?: ParserOptions); + + write(data: string): void; + end(data: string): void; +} + +export interface ParserOptions { + Parser?: typeof Parser; + Element?: typeof Element; } diff --git a/types/ltx/lib/clone.d.ts b/types/ltx/lib/clone.d.ts index 41193a3f40..15369e00d5 100644 --- a/types/ltx/lib/clone.d.ts +++ b/types/ltx/lib/clone.d.ts @@ -1 +1,3 @@ -export declare function clone(el: any): any; +import { Element } from './Element'; + +export function clone(el: T): T; diff --git a/types/ltx/lib/createElement.d.ts b/types/ltx/lib/createElement.d.ts index c372f11150..21527ae1b6 100644 --- a/types/ltx/lib/createElement.d.ts +++ b/types/ltx/lib/createElement.d.ts @@ -1,2 +1,6 @@ -import { Element } from './Element'; -export declare function createElement(name: string, attrs: any): Element; +import { Element, Node } from './Element'; +export function createElement( + name: string, + attrs?: string | { [attrName: string]: any }, + ...children: Node[] +): Element; diff --git a/types/ltx/lib/equal.d.ts b/types/ltx/lib/equal.d.ts index 520555e098..f7548c526b 100644 --- a/types/ltx/lib/equal.d.ts +++ b/types/ltx/lib/equal.d.ts @@ -1,4 +1,6 @@ -export declare function nameEqual(a: any, b: any): boolean; -export declare function attrsEqual(a: any, b: any): boolean; -export declare function childrenEqual(a: any, b: any): boolean; -export declare function equal(a: any, b: any): boolean; +import { Element } from './Element'; + +export function nameEqual(a: Element, b: Element): boolean; +export function attrsEqual(a: Element, b: Element): boolean; +export function childrenEqual(a: Element, b: Element): boolean; +export function equal(a: Element, b: Element): boolean; diff --git a/types/ltx/lib/escape.d.ts b/types/ltx/lib/escape.d.ts index 4bc45c223a..d390e860ed 100644 --- a/types/ltx/lib/escape.d.ts +++ b/types/ltx/lib/escape.d.ts @@ -1,4 +1,4 @@ -export declare function escapeXML(s: string): string; -export declare function unescapeXML(s: string): string; -export declare function escapeXMLText(s: string): string; -export declare function unescapeXMLText(s: string): string; +export function escapeXML(s: string): string; +export function unescapeXML(s: string): string; +export function escapeXMLText(s: string): string; +export function unescapeXMLText(s: string): string; diff --git a/types/ltx/lib/is.d.ts b/types/ltx/lib/is.d.ts index 6515d23f80..e62d919267 100644 --- a/types/ltx/lib/is.d.ts +++ b/types/ltx/lib/is.d.ts @@ -1,3 +1,5 @@ -export declare function isNode(el: any): boolean; -export declare function isElement(el: any): boolean; -export declare function isText(el: any): boolean; +import { Element, Node } from './Element'; + +export function isNode(el: any): el is Node; +export function isElement(el: any): el is Element; +export function isText(el: any): el is string; diff --git a/types/ltx/lib/parse.d.ts b/types/ltx/lib/parse.d.ts index cc4073113a..0e0a9b17cb 100644 --- a/types/ltx/lib/parse.d.ts +++ b/types/ltx/lib/parse.d.ts @@ -1 +1,4 @@ -export declare function parse(data: any, options?: any): any; +import { ParserOptions, Parser } from './Parser'; +import { Element } from './Element'; + +export function parse(data: string, options?: ParserOptions | Parser): Element; diff --git a/types/ltx/lib/stringify.d.ts b/types/ltx/lib/stringify.d.ts index 770f7d324f..9913f2318c 100644 --- a/types/ltx/lib/stringify.d.ts +++ b/types/ltx/lib/stringify.d.ts @@ -1 +1,3 @@ -export declare function stringify(el: any, indent: any, level: any): string; +import { Element } from './Element'; + +export function stringify(el: Element, indent?: number, level?: number): string; diff --git a/types/ltx/lib/tag.d.ts b/types/ltx/lib/tag.d.ts index 8bbcb6fe7b..11a9784bf0 100644 --- a/types/ltx/lib/tag.d.ts +++ b/types/ltx/lib/tag.d.ts @@ -1 +1,3 @@ -export declare function tag(d: any): any; +import { Element } from './Element'; + +export function tag(literals: string[], ...substitutions: string[]): Element; diff --git a/types/ltx/lib/tagString.d.ts b/types/ltx/lib/tagString.d.ts index 44036ce037..619ccbdb23 100644 --- a/types/ltx/lib/tagString.d.ts +++ b/types/ltx/lib/tagString.d.ts @@ -1 +1 @@ -export declare function tagString(d: any): string; +export function tagString(literals: string[], ...substitutions: string[]): string; diff --git a/types/ltx/ltx-tests.ts b/types/ltx/ltx-tests.ts index 522b7673c8..a7342ef54b 100644 --- a/types/ltx/ltx-tests.ts +++ b/types/ltx/ltx-tests.ts @@ -1,21 +1,147 @@ import * as ltx from 'ltx'; -ltx.parse(''); +let el: ltx.Element = null as any; +let maybeEl: ltx.Element | undefined = null as any; +let els: ltx.Element[] = []; +let bool: boolean; +const any: any = null; +let str: string = null as any; -const getChildTextElement = ltx.parse('body text') as ltx.Element; -if (getChildTextElement.getChildText('child') !== 'body text') { - throw new Error("body does not match"); +el = ltx.clone(el); + +bool = ltx.nameEqual(el, el); +bool = ltx.attrsEqual(el, el); +bool = ltx.childrenEqual(el, el); +bool = ltx.equal(el, el); + +el = ltx.createElement('el'); +el = ltx.createElement('el', 'xml'); +el = ltx.createElement('el', { foo: 'bar' }); +el = ltx.createElement('el', { foo: 'bar' }, el); +el = ltx.createElement('el', { foo: 'bar' }, 'hi'); + +if (ltx.isNode(any)) { + // $ExpectType Node + any; +} +if (ltx.isElement(any)) { + // $ExpectType Element + any; +} +if (ltx.isText(any)) { + // $ExpectType string + any; } -const p = new ltx.Parser(); +str = ltx.escapeXML(str); +str = ltx.unescapeXML(str); +str = ltx.escapeXMLText(str); +str = ltx.unescapeXMLText(str); + +el = ltx.parse(''); +el = ltx.parse('', (null as any) as ltx.Parser); +el = ltx.parse('', { Parser: (null as any) as typeof ltx.Parser }); +el = ltx.parse('', { Element: (null as any) as typeof ltx.Element }); + +el = ltx.tag(['document'], 'foo'); +str = ltx.tagString(['document'], 'foo'); + +str = ltx.stringify(el); +str = ltx.stringify(el, 1); +str = ltx.stringify(el, 1, 1); + +const getChildTextElement = ltx.parse('body text'); +if (getChildTextElement.getChildText('child') !== 'body text') { + throw new Error('body does not match'); +} + +let p: ltx.Parser; +p = new ltx.Parser(); +p = new ltx.Parser({ Parser: (null as any) as typeof ltx.Parser }); +p = new ltx.Parser({ Element: (null as any) as typeof ltx.Element }); p.on('tree', (ignored: any) => {}); - p.on('error', (ignored: any) => {}); -const el = new ltx.Element('root').c('children'); -el.c('child', {age: 5}).t('Hello').up() - .c('child', {age: 7}).t('Hello').up() - .c('child', {age: 99}).t('Hello').up(); +el = new ltx.Element('root').c('children'); -el.root().toString(); +bool = el.is('el'); +bool = el.is('el', 'ns'); +str = el.getName(); +let s: string | undefined = el.getNS(); +s = el.findNS('ns'); +const xmlns: { [key: string]: string } = el.getXmlns(); +el.setAttrs('ho'); +el.setAttrs({ my: 'attr' }); +el.getAttr('ho'); +el.getAttr('ho', 'ns'); +maybeEl = el.getChild('el'); +maybeEl = el.getChild('el', 'ns'); +els = el.getChildren('el'); +els = el.getChildren('el', 'ns'); +maybeEl = el.getChildByAttr('my', 'attr'); +maybeEl = el.getChildByAttr('my', 'attr', 'ns'); +maybeEl = el.getChildByAttr('my', 'attr', 'ns', true); +els = el.getChildrenByAttr('my', 'attr'); +els = el.getChildrenByAttr('my', 'attr', 'ns'); +els = el.getChildrenByAttr('my', 'attr', 'ns', true); +els = el.getChildrenByFilter(child => { + // $ExpectType Node + child; + return true; +}); +els = el.getChildrenByFilter(child => { + // $ExpectType Node + child; + return true; +}, true); +str = el.getText(); +let maybeS: string | null = el.getChildText('hi'); +maybeS = el.getChildText('hi', 'ns'); +els = el.getChildElements(); + +class MyEl extends ltx.Element { + foo: 'bar'; +} +let myEl = new MyEl('el'); + +// $ExpectType Element | MyEl +myEl.root(); +// $ExpectType Element | MyEl +myEl.tree(); +// $ExpectType Element | MyEl +myEl.up(); + +el = el.c('hi'); +el = el.c('hi', { my: 'attr' }); +myEl = myEl.cnode(myEl); +myEl = myEl.t('hi'); +myEl = myEl.t(1); +myEl = myEl.remove(el); +myEl = myEl.remove('el'); +myEl = myEl.remove('el', 'ns'); +myEl = myEl.clone(myEl); +str = el.text(); +str = el.text('val'); +el.attr('my'); +el.attr('my', 'attr'); +str = el.toString(); +const json: ltx.ElementJson = el.toJSON(); +el.write(part => { + // $ExpectType string + part; +}); +bool = el.nameEquals(el); +bool = el.attrsEquals(el); +bool = el.childrenEquals(el); +bool = el.equals(el); + +el.c('child', { age: 5 }) + .t('Hello') + .up() + .c('child', { age: 7 }) + .t('Hello') + .up() + .c('child', { age: 99 }) + .t('Hello') + .up(); diff --git a/types/ltx/tslint.json b/types/ltx/tslint.json index 5bb1e8735d..f93cf8562a 100644 --- a/types/ltx/tslint.json +++ b/types/ltx/tslint.json @@ -1,9 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - // All are TODOs - "jsdoc-format": false, - "no-consecutive-blank-lines": false, - "strict-export-declare-modifiers": false - } + "extends": "dtslint/dt.json" } diff --git a/types/lunr/index.d.ts b/types/lunr/index.d.ts index da87ae95d8..415c7c1d8f 100644 --- a/types/lunr/index.d.ts +++ b/types/lunr/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for lunr.js 2.1 +// Type definitions for lunr.js 2.3 // Project: https://github.com/olivernn/lunr.js -// Definitions by: Sean Tan +// Definitions by: Sean Tan , Andrés Pérez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -127,9 +127,14 @@ declare namespace lunr { * All fields should be added before adding documents to the index. Adding fields after * a document has been indexed will have no effect on already indexed documents. * + * Fields can be boosted at build time. This allows terms within that field to have more + * importance when ranking search results. Use a field boost to specify that matches + * within one field are more important than other fields. + * * @param field - The name of a field to index in all documents. + * @param attributes - Optional attributes associated with this field. */ - field(field: string): void; + field(field: string, attributes?: object): void; /** * A parameter to tune the amount of field length normalisation that is applied when @@ -160,9 +165,13 @@ declare namespace lunr { * it should have all fields defined for indexing, though null or undefined values will not * cause errors. * + * Entire documents can be boosted at build time. Applying a boost to a document indicates that + * this document should rank higher in search results than other documents. + * * @param doc - The document to add to the index. + * @param attributes - Optional attributes associated with this document. */ - add(doc: object): void; + add(doc: object, attributes?: object): void; /** * Builds the index, creating an instance of lunr.Index. diff --git a/types/lunr/lunr-tests.ts b/types/lunr/lunr-tests.ts index ade45cae64..a14fd1947f 100644 --- a/types/lunr/lunr-tests.ts +++ b/types/lunr/lunr-tests.ts @@ -4,11 +4,18 @@ function basic_test() { const index = lunr(function() { this.field("title"); this.field("body"); + this.field("content", { + boost: 2, + extractor: (doc: object) => "oof" + }); this.ref("id"); this.add({ id: 1, title: "Foo", body: "Foo foo foo!" + }, + { + boost: 2 }); this.add({ id: 2, diff --git a/types/mailgun-js/index.d.ts b/types/mailgun-js/index.d.ts index 3244639aed..7c6284059e 100644 --- a/types/mailgun-js/index.d.ts +++ b/types/mailgun-js/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for mailgun-js 0.16 // Project: https://github.com/bojand/mailgun-js // Definitions by: Sampson Oliver +// Andi Pätzold // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -49,6 +50,8 @@ declare namespace Mailgun { getType(): string; } + type AttachmentData = string | Buffer | NodeJS.ReadWriteStream | Attachment; + interface MailgunExport { new (options: ConstructorParams): Mailgun; (options: ConstructorParams): Mailgun; @@ -63,7 +66,8 @@ declare namespace Mailgun { subject?: string; text?: string; html?: string; - attachment?: string | Buffer | NodeJS.ReadWriteStream | Attachment; + attachment?: AttachmentData | ReadonlyArray; + inline?: AttachmentData | ReadonlyArray; } interface BatchData extends SendData { @@ -125,8 +129,29 @@ declare namespace Mailgun { unparseable: string[]; } + type ValidationCallback = (error: Error, body: ValidateResponse) => void; + + interface ValidationOptionsPublic { + api_key?: string; + mailbox_verification?: boolean | "true" | "false"; + } + + interface ValidationOptionsPrivate { + mailbox_verification?: boolean | "true" | "false"; + } + interface ValidateResponse { + address: string; + did_you_mean: string | null; + is_disposable_address: boolean; + is_role_address: boolean; is_valid: boolean; + mailbox_verification: "true" | "false" | "unknown" | null; + parts: { + display_name: string | null; + domain: string; + local_part: string; + }; } } @@ -140,15 +165,18 @@ declare namespace Mailgun { bodySignature: string ): boolean; - parse( - addressList: string[], - callback?: (error: Error, body: validation.ValidateResponse) => void - ): Promise; + parse(addressList: string[], callback?: validation.ValidationCallback): Promise; - validate( - address: string, - callback?: (error: Error, body: validation.ValidateResponse) => void - ): Promise; + validate(address: string, callback: validation.ValidationCallback): void; + validate(address: string, opts: validation.ValidationOptionsPublic, callback: validation.ValidationCallback): void; + // tslint:disable-next-line unified-signatures + validate(address: string, isPrivate: boolean, callback: validation.ValidationCallback): void; + validate(address: string, isPrivate: false, opts: validation.ValidationOptionsPublic, callback: validation.ValidationCallback): void; + validate(address: string, isPrivate: true, opts: validation.ValidationOptionsPrivate, callback: validation.ValidationCallback): void; + + validate(address: string, opts?: validation.ValidationOptionsPublic): Promise; + validate(address: string, isPrivate: false, opts?: validation.ValidationOptionsPublic): Promise; + validate(address: string, isPrivate: true, opts?: validation.ValidationOptionsPrivate): Promise; } interface Lists { diff --git a/types/mailgun-js/mailgun-js-tests.ts b/types/mailgun-js/mailgun-js-tests.ts index 8a625bc8ef..0d830308d1 100644 --- a/types/mailgun-js/mailgun-js-tests.ts +++ b/types/mailgun-js/mailgun-js-tests.ts @@ -25,7 +25,39 @@ const exampleSendData: mailgunFactory.messages.SendData = { attachment: new mailgun.Attachment({ data: "filepath", filename: "my_custom_name.png" - }) + }), + inline: [ + new mailgun.Attachment({ + data: "filepath", + filename: "my_custom_name_2.png" + }), + "my_custom_file_3.png", + Buffer.from("plain text") + ] }; mailgun.messages().send(exampleSendData, (err, body) => {}); + +let validationResultPromise: Promise; +validationResultPromise = mailgun.validate("foo@mailgun.net"); +validationResultPromise = mailgun.validate("foo@mailgun.net", true); +validationResultPromise = mailgun.validate("foo@mailgun.net", true, { mailbox_verification: true }); +validationResultPromise = mailgun.validate("foo@mailgun.net", { mailbox_verification: false, api_key: "..." }); +mailgun.validate("foo@mailgun.net", (error, body) => {}); +mailgun.validate("foo@mailgun.net", true, (error, body) => {}); +mailgun.validate("foo@mailgun.net", true, { mailbox_verification: true }, (error, body) => {}); +mailgun.validate("foo@mailgun.net", { mailbox_verification: false, api_key: "..." }, (error, body) => {}); + +const validationResult6: mailgunFactory.validation.ValidateResponse = { + address: "foo@mailgun.net", + did_you_mean: "bar@mailgun.net", + is_disposable_address: false, + is_role_address: true, + is_valid: true, + mailbox_verification: "true", + parts: { + display_name: "foo", + domain: "mailgun.net", + local_part: "foo" + } +}; diff --git a/types/maker.js/maker.js-tests.ts b/types/maker.js/maker.js-tests.ts index f5f9d9db16..ba02fdef89 100644 --- a/types/maker.js/maker.js-tests.ts +++ b/types/maker.js/maker.js-tests.ts @@ -100,9 +100,9 @@ function test() { function testKit() { makerjs.kit.construct(null, null); makerjs.kit.getParameterValues(null); - ({}).max; - ({}).metaParameters; - ({}).notes; + ({} as MakerJs.IMetaParameter).max; + ({} as MakerJs.IKit).metaParameters; + ({} as MakerJs.IKit).notes; } function testMeasure() { diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 91fb68cd96..384cea55b6 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1071,7 +1071,7 @@ declare namespace mapboxgl { export interface MapSourceDataEvent extends MapboxEvent { dataType: 'source'; isSourceLoaded: boolean; - source: Style; + source: Source; sourceId: string; sourceDataType: 'metadata' | 'content'; tile: any; @@ -1319,6 +1319,7 @@ declare namespace mapboxgl { 'fill-extrusion-height-transition'?: Transition; 'fill-extrusion-base'?: number | StyleFunction | Expression; 'fill-extrusion-base-transition'?: Transition; + 'fill-extrusion-vertical-gradient'?: boolean; } export interface LineLayout { diff --git a/types/mapbox-gl/mapbox-gl-tests.ts b/types/mapbox-gl/mapbox-gl-tests.ts index 422b255900..d119c76bd5 100644 --- a/types/mapbox-gl/mapbox-gl-tests.ts +++ b/types/mapbox-gl/mapbox-gl-tests.ts @@ -465,10 +465,10 @@ expectType(mapboxgl.Point.convert(pointlike)); expectType((url: string) => ({ url })); expectType((url: string, resourceType: mapboxgl.ResourceType) => ({ - url, - credentials: 'same-origin', - headers: { 'Accept-Encoding': 'compress' }, - method: 'POST', + url, + credentials: 'same-origin', + headers: { 'Accept-Encoding': 'compress' }, + method: 'POST', collectResourceTiming: true, })); diff --git a/types/mapbox/index.d.ts b/types/mapbox/index.d.ts index 334d644e21..97da469e4a 100644 --- a/types/mapbox/index.d.ts +++ b/types/mapbox/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for Mapbox 1.6 // Project: https://www.mapbox.com/mapbox.js/ // Definitions by: Maxime Fabre +// Florian Luccioni // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -153,6 +154,20 @@ declare global { getGeoJSON(): any; } + // StyleLayer + ////////////////////////////////////////////////////////////////////// + + /** + * L.mapbox.styleLayer provides a way to integrate styles created with Mapbox Studio into your map. + */ + function styleLayer(url: string, options?: StyleLayerOptions): StyleLayer; + + interface StyleLayerOptions extends Leaflet.TileLayerOptions { + sanitizer?(template: string): string; + } + + type StyleLayer = Leaflet.TileLayer; + ////////////////////////////////////////////////////////////////////// ////////////////////////////// GEOCODING ///////////////////////////// ////////////////////////////////////////////////////////////////////// diff --git a/types/mapbox/mapbox-tests.ts b/types/mapbox/mapbox-tests.ts index ab9ad6c5de..a9610ba5c4 100644 --- a/types/mapbox/mapbox-tests.ts +++ b/types/mapbox/mapbox-tests.ts @@ -4,6 +4,8 @@ const mapboxTiles = L.tileLayer('https://{s}.tiles.mapbox.com/v3/examples.map-i8 const map = L.map('map').addLayer(mapboxTiles).setView(new L.LatLng([42.3610, -71.0587]), 15); +const lightTiles = L.mapbox.styleLayer('mapbox://styles/mapbox/light-v9').addTo(map); + const coordinates = document.getElementById('coordinates'); const marker = L.marker(new L.LatLng([0, 0]), { diff --git a/types/marked/index.d.ts b/types/marked/index.d.ts index d558348db9..7eddfb4919 100644 --- a/types/marked/index.d.ts +++ b/types/marked/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for Marked 0.4 +// Type definitions for Marked 0.5 // Project: https://github.com/markedjs/marked // Definitions by: William Orr // BendingBender // CrossR +// Mike Wickett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace marked; @@ -34,6 +35,15 @@ declare namespace marked { */ function lexer(src: string, options?: MarkedOptions): TokensList; + /** + * @param src String of markdown source to be compiled + * @param links Array of links + * @param options Hash of options + * @return String of compiled HTML + */ + + function inlineLexer(src: string, links: string[], options?: MarkedOptions): string; + /** * Compiles markdown to HTML. * diff --git a/types/matcher/index.d.ts b/types/matcher/index.d.ts new file mode 100644 index 0000000000..08e4e91f8f --- /dev/null +++ b/types/matcher/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for matcher 1.1 +// Project: https://github.com/sindresorhus/matcher#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = matcher; + +declare function matcher(inputs: string[], patterns: string[], options?: matcher.Options): string[]; + +declare namespace matcher { + function isMatch(input: string, pattern: string, options?: Options): boolean; + + interface Options { + caseSensitive?: boolean; + } +} diff --git a/types/matcher/matcher-tests.ts b/types/matcher/matcher-tests.ts new file mode 100644 index 0000000000..fbadf58e1e --- /dev/null +++ b/types/matcher/matcher-tests.ts @@ -0,0 +1,10 @@ +import matcher = require('matcher'); + +// $ExpectType string[] +matcher(['foo', 'bar', 'moo'], ['*oo', '!foo']); +matcher(['foo', 'bar', 'moo'], ['!*oo']); +matcher(['foo', 'bar', 'moo'], ['!*oo'], { caseSensitive: true }); + +// $ExpectType boolean +matcher.isMatch('unicorn', 'uni*'); +matcher.isMatch('UNICORN', 'UNI*', { caseSensitive: true }); diff --git a/types/matcher/tsconfig.json b/types/matcher/tsconfig.json new file mode 100644 index 0000000000..efa5f37200 --- /dev/null +++ b/types/matcher/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "matcher-tests.ts" + ] +} diff --git a/types/matcher/tslint.json b/types/matcher/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/matcher/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index 6cb49323fa..a8ec6114eb 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Ilya Shestakov , // Andy Patterson , // Brad Besserman +// Pawel Krol // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -2571,6 +2572,23 @@ declare namespace math { * ‘string’, ‘Array’, ‘Date’. */ typeof(x: any): string; + + /** + * Import functions from an object or a module + * To avoid errors when using one of the imported functions extend module like this: + * + * @example + * // imported_math_functions.ts + * declare module 'mathjs' { + * interface MathJsStatic { + * hello(a: number): number; + * } + * } + * + * @param object An object with functions to be imported. + * @param options An object with import options. + */ + import(object: ImportObject | ImportObject[], options: ImportOptions): void; } interface Matrix { @@ -4542,4 +4560,14 @@ declare namespace math { */ typeof(): MathJsChain; } + + interface ImportOptions { + override?: boolean; + silent?: boolean; + wrap?: boolean; + } + + interface ImportObject { + [key: string]: any; + } } diff --git a/types/mathjs/mathjs-tests.ts b/types/mathjs/mathjs-tests.ts index babfa3ff37..0d21be817e 100644 --- a/types/mathjs/mathjs-tests.ts +++ b/types/mathjs/mathjs-tests.ts @@ -1,3 +1,6 @@ +// Import needed for mathjs.import functionality (declaring/extending module) +import * as math from 'mathjs'; + /* Basic usage examples */ @@ -392,3 +395,27 @@ JSON serialization/deserialization const parsed = JSON.parse(stringified, math.json.reviver); parsed.bigNumber === math.bignumber('1.5'); // true } + +/* +Extend functionality with import + */ + +declare module 'mathjs' { + interface MathJsStatic { + testFun(): number; + value: number; + } +} + +{ + const testFun = () => 5; + + math.import({ + testFun, + value: 10 + }, {}); + + math.testFun(); + + const a = math.value * 2; +} diff --git a/types/mcrypt/index.d.ts b/types/mcrypt/index.d.ts new file mode 100644 index 0000000000..945cb88e59 --- /dev/null +++ b/types/mcrypt/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for mcrypt 0.1 +// Project: https://github.com/tugrul/node-mcrypt +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +export function getAlgorithmNames(): string[]; +export function getModeNames(): string[]; + +export class MCrypt { + constructor(algorithm: string, mode: string); + open(key: string | Buffer, iv?: string | Buffer): void; + encrypt(plaintext: string | Buffer): Buffer; + decrypt(ciphertext: Buffer): Buffer; + generateIv(): Buffer; + validateKeySize(validate: boolean): void; + validateIvSize(validate: boolean): void; + selfTest(): boolean; + isBlockAlgorithmMode(): boolean; + isBlockAlgorithm(): boolean; + isBlockMode(): boolean; + getBlockSize(): number; + getKeySize(): number; + getSupportedKeySizes(): number[]; + getIvSize(): number; + hasIv(): boolean; + getAlgorithmName(): string; + getModeName(): string; +} diff --git a/types/mcrypt/mcrypt-tests.ts b/types/mcrypt/mcrypt-tests.ts new file mode 100644 index 0000000000..66614e08e3 --- /dev/null +++ b/types/mcrypt/mcrypt-tests.ts @@ -0,0 +1,51 @@ +import { getAlgorithmNames, getModeNames, MCrypt } from "mcrypt"; + +let plaintext: Buffer; +let ciphertext: Buffer; + +for (const algo of getAlgorithmNames()) { + console.log(algo.toUpperCase()); +} +for (const mode of getModeNames()) { + console.log(mode.toUpperCase()); +} + +const desEcb = new MCrypt("des", "ecb"); +desEcb.open("madepass"); + +ciphertext = desEcb.encrypt("too many secrets"); +console.log(ciphertext.toString("base64")); + +plaintext = desEcb.decrypt(ciphertext); +console.log(plaintext.toString()); + +const blowfishCfb = new MCrypt("blowfish", "cfb"); +const iv = blowfishCfb.generateIv(); +blowfishCfb.open("somekey", iv); +ciphertext = blowfishCfb.encrypt("sometext"); +console.log(Buffer.concat([iv, ciphertext]).toString("base64")); + +const bfEcb = new MCrypt("blowfish", "ecb"); +bfEcb.validateKeySize(false); +bfEcb.open("typeconfig.sys^_-"); + +const rjCbc = new MCrypt("rijndael-256", "cbc"); +rjCbc.validateIvSize(false); +rjCbc.open("$verysec$retkey$", "foobar"); + +console.log(blowfishCfb.getBlockSize() * 8); +console.log(blowfishCfb.getKeySize() * 8); +console.log(blowfishCfb.getSupportedKeySizes().map(v => v * 8)); +console.log(blowfishCfb.getIvSize() * 8); +console.log(blowfishCfb.getAlgorithmName().toUpperCase()); +console.log(blowfishCfb.getModeName().toUpperCase()); + +function assertBool(value: boolean) { + return value; +} + +assertBool(blowfishCfb.selfTest()); +assertBool(blowfishCfb.isBlockAlgorithmMode()); +assertBool(blowfishCfb.isBlockAlgorithm()); +assertBool(blowfishCfb.isBlockMode()); +assertBool(blowfishCfb.hasIv()); diff --git a/types/mcrypt/tsconfig.json b/types/mcrypt/tsconfig.json new file mode 100644 index 0000000000..1bb1454ce5 --- /dev/null +++ b/types/mcrypt/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mcrypt-tests.ts"] +} diff --git a/types/mcrypt/tslint.json b/types/mcrypt/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mcrypt/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mdast/index.d.ts b/types/mdast/index.d.ts index d7761bd38f..c1fcadec97 100644 --- a/types/mdast/index.d.ts +++ b/types/mdast/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/syntax-tree/mdast // Definitions by: Jun Lu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 3.0 import { Parent as UnistParent, Literal as UnistLiteral, Node } from 'unist'; diff --git a/types/meteor/test/globals/meteor-tests.ts b/types/meteor/test/globals/meteor-tests.ts index b902019aca..e3a3e750bb 100644 --- a/types/meteor/test/globals/meteor-tests.ts +++ b/types/meteor/test/globals/meteor-tests.ts @@ -371,19 +371,19 @@ Comments.find({ viewNumber: { $gt: 100 } }); Comments.find({ viewNumber: { $not: { $lt: 100, $gt: 1000 } } }); Comments.find({ tags: { $in: [ "tag-1", "tag-2", "tag-3" ] } }); Comments.find({ $or: [ { text: "hello" }, { text: "world" } ] }); -Comments.find({ $or: [ - { text: "hello" }, - { text: "world", viewNumber: { $gt: 0 } } +Comments.find({ $or: [ + { text: "hello" }, + { text: "world", viewNumber: { $gt: 0 } } ], authorId: "test-author-id" }); -Comments.find({ $and: [ - { $or: [{ authorId: "author-id-1" }, { authorId: "author-id-2" }] }, +Comments.find({ $and: [ + { $or: [{ authorId: "author-id-1" }, { authorId: "author-id-2" }] }, { $or: [{ tags: "tag-1" }, { tags: "tag-2" }] } ]}); Comments.find({ $query: {inlineLinks: { $exists: true, $type: "array" } } }); -Comments.find({ inlineLinks: { $elemMatch: { - objectType: InlineObjectType.Image, - objectUrl: { $regex: "https://(www\.?)youtube\.com" } +Comments.find({ inlineLinks: { $elemMatch: { + objectType: InlineObjectType.Image, + objectUrl: { $regex: "https://(www\.?)youtube\.com" } } } }); Comments.find({ "inlineLinks.objectType": InlineObjectType.Person }); Comments.find({ tags: "tag-1" }); @@ -697,7 +697,7 @@ Accounts.onPageLoadLogin(function () { }); // Covers this PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/8065 -var loginOpts = { +var loginOpts = { requestPermissions: ["a", "b"], requestOfflineToken: true, loginUrlParameters: { asdf: 1, qwer: "1234" }, @@ -705,7 +705,7 @@ var loginOpts = { loginStyle: "Bold and powerful", redirectUrl: "popup", profile: "asdfasdf" -}; +} as Meteor.LoginWithExternalServiceOptions; Meteor.loginWithMeteorDeveloperAccount(loginOpts, function (error: Meteor.Error) { }); Accounts.emailTemplates.siteName = "AwesomeSite"; @@ -748,7 +748,7 @@ const deeperPrivateSetting = Meteor.settings['somePrivateSettings']['deeperSetti // Covers https://github.com/meteor-typings/meteor/issues/9 -const username = (Template.instance().find('#username')).value; +const username = (Template.instance().find('#username') as HTMLInputElement).value; // Covers https://github.com/meteor-typings/meteor/issues/3 diff --git a/types/meteor/test/meteor-tests.ts b/types/meteor/test/meteor-tests.ts index 4901e810c5..63f83ef79d 100644 --- a/types/meteor/test/meteor-tests.ts +++ b/types/meteor/test/meteor-tests.ts @@ -383,19 +383,19 @@ Comments.find({ viewNumber: { $gt: 100 } }); Comments.find({ viewNumber: { $not: { $lt: 100, $gt: 1000 } } }); Comments.find({ tags: { $in: [ "tag-1", "tag-2", "tag-3" ] } }); Comments.find({ $or: [ { text: "hello" }, { text: "world" } ] }); -Comments.find({ $or: [ - { text: "hello" }, - { text: "world", viewNumber: { $gt: 0 } } +Comments.find({ $or: [ + { text: "hello" }, + { text: "world", viewNumber: { $gt: 0 } } ], authorId: "test-author-id" }); -Comments.find({ $and: [ - { $or: [{ authorId: "author-id-1" }, { authorId: "author-id-2" }] }, +Comments.find({ $and: [ + { $or: [{ authorId: "author-id-1" }, { authorId: "author-id-2" }] }, { $or: [{ tags: "tag-1" }, { tags: "tag-2" }] } ]}); Comments.find({ $query: { inlineLinks: { $exists: true, $type: "array" } } }); -Comments.find({ inlineLinks: { $elemMatch: { - objectType: InlineObjectType.Image, - objectUrl: { $regex: "https://(www\.?)youtube\.com" } +Comments.find({ inlineLinks: { $elemMatch: { + objectType: InlineObjectType.Image, + objectUrl: { $regex: "https://(www\.?)youtube\.com" } } } }); Comments.find({ "inlineLinks.objectType": InlineObjectType.Person }); Comments.find({ tags: "tag-1" }); @@ -709,7 +709,7 @@ Accounts.onPageLoadLogin(function () { }); // Covers this PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/8065 -var loginOpts = { +var loginOpts = { requestPermissions: ["a", "b"], requestOfflineToken: true, loginUrlParameters: { asdf: 1, qwer: "1234" }, @@ -717,7 +717,7 @@ var loginOpts = { loginStyle: "Bold and powerful", redirectUrl: "popup", profile: "asdfasdf" -}; +} as Meteor.LoginWithExternalServiceOptions; Meteor.loginWithMeteorDeveloperAccount(loginOpts, function (error: Meteor.Error) { }); Accounts.emailTemplates.siteName = "AwesomeSite"; @@ -760,7 +760,7 @@ const deeperPrivateSetting = Meteor.settings['somePrivateSettings']['deeperSetti // Covers https://github.com/meteor-typings/meteor/issues/9 -const username = (Template.instance().find('#username')).value; +const username = (Template.instance().find('#username') as HTMLInputElement).value; // Covers https://github.com/meteor-typings/meteor/issues/3 diff --git a/types/mirrorx/index.d.ts b/types/mirrorx/index.d.ts index 443712c325..e2fa0ee465 100644 --- a/types/mirrorx/index.d.ts +++ b/types/mirrorx/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mirrorjs/mirror // Definitions by: Aaronphy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import * as H from 'history'; diff --git a/types/mochaccino/index.d.ts b/types/mochaccino/index.d.ts index 4dbc62b7d9..3d5d9570a8 100644 --- a/types/mochaccino/index.d.ts +++ b/types/mochaccino/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/pawelgalazka/mochaccino#readme // Definitions by: Thomas-P // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 import * as Sinon from 'sinon'; export interface Expect { not: Expect; diff --git a/types/mockingoose/index.d.ts b/types/mockingoose/index.d.ts new file mode 100644 index 0000000000..a1597bd4e5 --- /dev/null +++ b/types/mockingoose/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for mockingoose 2.11 +// Project: https://github.com/alonronin/mockingoose#readme +// Definitions by: Hiroshi Ioka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +type Op = + | 'find' + | 'findOne' + | 'count' + | 'countDocuments' + | 'estimatedDocumentCount' + | 'distinct' + | 'findOneAndUpdate' + | 'findOneAndRemove' + | 'remove' + | 'update' + | 'deleteOne' + | 'deleteMany' + | 'save'; + +declare class Mock { + toReturn(expected: any, op?: Op): this; + reset(op: Op): this; + toJSON(): any; +} + +interface Target { + __mocks: any; + resetAll(): void; + toJSON(): any; +} + +type Proxy = Target & { + [index: string]: Mock; +}; + +declare const mockingoose: Proxy; + +export default mockingoose; diff --git a/types/mockingoose/mockingoose-tests.ts b/types/mockingoose/mockingoose-tests.ts new file mode 100644 index 0000000000..09a00ad274 --- /dev/null +++ b/types/mockingoose/mockingoose-tests.ts @@ -0,0 +1,9 @@ +import mockingoose from 'mockingoose'; + +mockingoose.User + .toReturn({ name: 'name' }) + .toReturn({ name: 'a name too' }, 'findOne') + .toReturn({ name: 'another name' }, 'save') + .reset('find'); + +mockingoose.resetAll(); diff --git a/types/mockingoose/tsconfig.json b/types/mockingoose/tsconfig.json new file mode 100644 index 0000000000..a6f171944a --- /dev/null +++ b/types/mockingoose/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mockingoose-tests.ts" + ] +} diff --git a/types/mockingoose/tslint.json b/types/mockingoose/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mockingoose/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mockjs/index.d.ts b/types/mockjs/index.d.ts index 9be645b791..25d6cac833 100644 --- a/types/mockjs/index.d.ts +++ b/types/mockjs/index.d.ts @@ -198,7 +198,7 @@ declare namespace mockjs { city(prefix?: B): S; // Random.county - country(prefix?: B): S; + county(prefix?: B): S; // Random.zip zip(prefix?: B): S; diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index ab4d2f4c02..feb12923aa 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -19,6 +19,7 @@ // Mikael Lirbank // Hector Ribes // Florian Richter +// Erik Christensen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -44,10 +45,7 @@ export class MongoClient extends EventEmitter { static connect(uri: string, callback: MongoCallback): void; static connect(uri: string, options?: MongoClientOptions): Promise; static connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; - /** - * @deprecated - * http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#connect - */ + /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#connect */ connect(): Promise; connect(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#close */ @@ -79,7 +77,7 @@ export interface ClientSession extends EventEmitter { /** The server id associated with this session */ id: any; /** - * Aborts the currently active transaction in this session. + * Aborts the currently active transaction in this session. * @param {MongoCallback} [cb] Optional callback for completion of this operation */ abortTransaction(cb?: MongoCallback): Promise; @@ -89,7 +87,7 @@ export interface ClientSession extends EventEmitter { */ advanceOperationTime(operamtionTime: Timestamp): void; /** - * Commits the currently active transaction in this session. + * Commits the currently active transaction in this session. * @param {MongoCallback} [cb] Optional callback for completion of this operation */ commitTransaction(cb?: MongoCallback): Promise; @@ -110,7 +108,7 @@ export interface ClientSession extends EventEmitter { * Used to determine if this session equals another * * @param {ClientSession} session A class representing a client session on the server - * @returns {boolean} if the sessions are equal + * @returns {boolean} if the sessions are equal */ equals(session: ClientSession): boolean; @@ -118,13 +116,13 @@ export interface ClientSession extends EventEmitter { incrementTransactionNumber(): void; /** - * @returns {boolean} this session is currently in a transaction or not + * @returns {boolean} this session is currently in a transaction or not */ inTransaction(): boolean; /** * Starts a new transaction with the given options. - * @param {TransactionOptions} options + * @param {TransactionOptions} options * @memberof ClientSession */ startTransaction(options?: TransactionOptions): void; @@ -219,10 +217,10 @@ export class MongoError extends Error { * client/user (eg. "Email address must be unique" instead of "Both email * address and username must be unique") - which caters for a better (app) * user experience. - * + * * Details: https://github.com/Automattic/mongoose/issues/2129 (issue for * mongoose, but the same applies for the native mongodb driver) - * + * * Note that in mongoose (the link above) the prop in question is called * 'message' while in mongodb it is called 'errmsg'. This can be seen in * multiple places in the source code, for example here: @@ -231,6 +229,7 @@ export class MongoError extends Error { errmsg?: string; } + /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#.connect */ export interface MongoClientOptions extends DbCreateOptions, @@ -240,57 +239,120 @@ export interface MongoClientOptions extends SocketOptions, SSLOptions, HighAvailabilityOptions { - // The logging level (error/warn/info/debug) + + /** + * The logging level (error/warn/info/debug) + */ loggerLevel?: string; - // Custom logger object - logger?: Object; - // Default: false; + + /** + * Custom logger object + */ + logger?: Object | log; + + /** + * Validate MongoClient passed in options for correctness. + * Default: false + */ validateOptions?: Object; - // The name of the application that created this MongoClient instance. + + /** + * The name of the application that created this MongoClient instance. + */ appname?: string; + + /** + * Authentifikation credentials + */ auth?: { + /** + * The username for auth + */ user: string; + /** + * The password for auth + */ password: string; - }, - // Determines whether or not to use the new url parser - useNewUrlParser?: boolean + }; + + /** + * Determines whether or not to use the new url parser + */ + useNewUrlParser?: boolean; + + /** + * Mechanism for authentication: DEFAULT, GSSAPI, PLAIN, MONGODB-X509, 'MONGODB-CR', SCRAM-SHA-1 or SCRAM-SHA-256 + */ + authMechanism?: 'DEFAULT' | 'GSSAPI' | 'PLAIN' | 'MONGODB-X509' | 'MONGODB-CR' | 'SCRAM-SHA-1' | 'SCRAM-SHA-256' | string; } export interface SSLOptions { - // Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + /** + * Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + */ ciphers?: string; - // Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + /** + * Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + */ ecdhCurve?: string; - // Default:5; Number of connections for each server instance + /** + * Default:5; Number of connections for each server instance + */ poolSize?: number; - // If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + /** + * If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + */ minSize?: number; - // Use ssl connection (needs to have a mongod server with ssl support) + /** + * Use ssl connection (needs to have a mongod server with ssl support) + */ ssl?: boolean; - // Default: true; Validate mongod server certificate against ca (mongod server >=2.4 with ssl support required) + /** + * Default: true; Validate mongod server certificate against ca (mongod server >=2.4 with ssl support required) + */ sslValidate?: boolean; - // Default: true; Server identity checking during SSL + /** + * Default: true; Server identity checking during SSL + */ checkServerIdentity?: boolean | Function; - // Array of valid certificates either as Buffers or Strings + /** + * Array of valid certificates either as Buffers or Strings + */ sslCA?: Array; - // SSL Certificate revocation list binary buffer + /** + * SSL Certificate revocation list binary buffer + */ sslCRL?: Array; - // SSL Certificate binary buffer + /** + * SSL Certificate binary buffer + */ sslCert?: Buffer | string; - // SSL Key file binary buffer + /** + * SSL Key file binary buffer + */ sslKey?: Buffer | string; - // SSL Certificate pass phrase + /** + * SSL Certificate pass phrase + */ sslPass?: Buffer | string; - // String containing the server name requested via TLS SNI. + /** + * String containing the server name requested via TLS SNI. + */ servername?: string; } export interface HighAvailabilityOptions { - // Default: true; Turn on high availability monitoring. + /** + * Default: true; Turn on high availability monitoring. + */ ha?: boolean; - // Default: 10000; The High availability period for replicaset inquiry + /** + * Default: 10000; The High availability period for replicaset inquiry + */ haInterval?: number; - // Default: false; + /** + * Default: false; + */ domainsEnabled?: boolean; } @@ -299,7 +361,12 @@ export class ReadPreference { constructor(mode: string, tags: Object); mode: string; tags: any; - options: { maxStalenessSeconds?: number }; // Max Secondary Read Stalleness in Seconds + options: { + /** + * Max Secondary Read Stalleness in Seconds + */ + maxStalenessSeconds?: number + }; static PRIMARY: string; static PRIMARY_PREFERRED: string; static SECONDARY: string; @@ -311,86 +378,156 @@ export class ReadPreference { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html */ export interface DbCreateOptions extends CommonOptions { - // If the database authentication is dependent on another databaseName. + /** + * If the database authentication is dependent on another databaseName. + */ authSource?: string; - // Default: false; Force server to create _id fields instead of client. + /** + * Default: false; Force server to create _id fields instead of client. + */ forceServerObjectId?: boolean; - // Default: false; Use c++ bson parser. + /** + * Default: false; Use c++ bson parser. + */ native_parser?: boolean; - // Serialize functions on any object. + /** + * Serialize functions on any object. + */ serializeFunctions?: boolean; - // Specify if the BSON serializer should ignore undefined fields. + /** + * Specify if the BSON serializer should ignore undefined fields. + */ ignoreUndefined?: boolean; - // Return document results as raw BSON buffers. + /** + * Return document results as raw BSON buffers. + */ raw?: boolean; - // Default: true; Promotes Long values to number if they fit inside the 53 bits resolution. + /** + * Default: true; Promotes Long values to number if they fit inside the 53 bits resolution. + */ promoteLongs?: boolean; - // Default: false; Promotes Binary BSON values to native Node Buffers + /** + * Default: false; Promotes Binary BSON values to native Node Buffers + */ promoteBuffers?: boolean; - // the prefered read preference. use 'ReadPreference' class. + /** + * the prefered read preference. use 'ReadPreference' class. + */ readPreference?: ReadPreference | string; - // Default: true; Promotes BSON values to native types where possible, set to false to only receive wrapper types. + /** + * Default: true; Promotes BSON values to native types where possible, set to false to only receive wrapper types. + */ promoteValues?: Object; - // Custom primary key factory to generate _id values (see Custom primary keys). + /** + * Custom primary key factory to generate _id values (see Custom primary keys). + */ pkFactory?: Object; - // ES6 compatible promise constructor + /** + * ES6 compatible promise constructor + */ promiseLibrary?: Object; - /** https://docs.mongodb.com/manual/reference/read-concern/#read-concern */ + /** + * https://docs.mongodb.com/manual/reference/read-concern/#read-concern + **/ readConcern?: ReadConcern; - // Sets a cap on how many operations the driver will buffer up before giving up on getting a - // working connection, default is -1 which is unlimited. + /** + * Sets a cap on how many operations the driver will buffer up before giving up on getting a + * working connection, default is -1 which is unlimited. + */ bufferMaxEntries?: number; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Server.html */ export interface SocketOptions { - // Reconnect on error. default:false + /** + * Reconnect on error. default:false + */ autoReconnect?: boolean; - // TCP Socket NoDelay option. default:true + /** + * TCP Socket NoDelay option. default:true + */ noDelay?: boolean; - // TCP KeepAlive enabled on the socket. default:true + /** + * TCP KeepAlive enabled on the socket. default:true + */ keepAlive?: boolean; - // TCP KeepAlive initial delay before sending first keep-alive packet when idle. default:300000 + /** + * TCP KeepAlive initial delay before sending first keep-alive packet when idle. default:300000 + */ keepAliveInitialDelay?: number; - // TCP Connection timeout setting. default 0 + /** + * TCP Connection timeout setting. default 0 + */ connectTimeoutMS?: number; - // Version of IP stack. Can be 4, 6 or null. default: null. - // If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - // refer to http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html + /** + * Version of IP stack. Can be 4, 6 or null. default: null. + * + * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + * refer to http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html + */ family?: 4 | 6 | null; - // TCP Socket timeout setting. default 0 + /** + * TCP Socket timeout setting. default 0 + */ socketTimeoutMS?: number; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Server.html */ export interface ServerOptions extends SSLOptions { - // Default: 30; + /** + * Default: 30; + */ reconnectTries?: number; - // Default: 1000; + /** + * Default: 1000; + */ reconnectInterval?: number; - // Default: true; + /** + * Default: true; + */ monitoring?: boolean + + /** + * Socket Options + */ socketOptions?: SocketOptions; - // Default: 10000; The High availability period for replicaset inquiry + + /** + * Default: 10000; The High availability period for replicaset inquiry + */ haInterval?: number; - // Default: false; + /** + * Default: false; + */ domainsEnabled?: boolean; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Mongos.html */ export interface MongosOptions extends SSLOptions, HighAvailabilityOptions { - // Default: 15; Cutoff latency point in MS for MongoS proxy selection + /** + * Default: 15; Cutoff latency point in MS for MongoS proxy selection + */ acceptableLatencyMS?: number; + + /** + * Socket Options + */ socketOptions?: SocketOptions; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html */ export interface ReplSetOptions extends SSLOptions, HighAvailabilityOptions { - // The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); + /** + * The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); + */ maxStalenessSeconds?: number; - // The name of the replicaset to connect to. + /** + * The name of the replicaset to connect to. + */ replicaSet?: string; - // Default: 15 ; Range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + /** + * Default: 15 ; Range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + */ secondaryAcceptableLatencyMS?: number; connectWithNoPrimary?: boolean; socketOptions?: SocketOptions; @@ -450,7 +587,7 @@ export class Db extends EventEmitter { indexInformation(name: string, options?: { full?: boolean, readPreference?: ReadPreference | string }): Promise; indexInformation(name: string, options: { full?: boolean, readPreference?: ReadPreference | string }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#listCollections */ - listCollections(filter?: Object, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; + listCollections(filter?: Object, options?: { nameOnly?: boolean, batchSize?: number, readPreference?: ReadPreference | string, session?: ClientSession }): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#profilingInfo */ /** @deprecated Query the system.profile collection directly. */ profilingInfo(callback: MongoCallback): void; @@ -482,28 +619,40 @@ export interface CommonOptions extends WriteConcern { session?: ClientSession; } -// Deprecated http://mongodb.github.io/node-mongodb-native/3.1/api/Server.html +/** + * @deprecated + * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Server.html + */ export class Server extends EventEmitter { constructor(host: string, port: number, options?: ServerOptions); connections(): Array; } -// Deprecated http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html +/** + * @deprecated + * @see http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html + */ export class ReplSet extends EventEmitter { constructor(servers: Array, options?: ReplSetOptions); connections(): Array; } -// Deprecated http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html +/** + * @deprecated + * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Mongos.html + */ export class Mongos extends EventEmitter { constructor(servers: Array, options?: MongosOptions); connections(): Array; } -/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#addUser */ +/** + * @deprecated + * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#addUser + */ export interface DbAddUserOptions extends CommonOptions { customData?: Object; roles?: Object[]; @@ -528,7 +677,7 @@ export interface CollectionCreateOptions extends CommonOptions { indexOptionDefaults?: object; viewOn?: string; pipeline?: any[]; - collation?: object; + collation?: CollationDocument; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collection */ @@ -543,29 +692,50 @@ export interface DbCollectionOptions extends CommonOptions { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createIndex */ export interface IndexOptions extends CommonOptions { - // Creates an unique index. + /** + * Creates an unique index. + */ unique?: boolean; - // Creates a sparse index. + /** + * Creates a sparse index. + */ sparse?: boolean; - // Creates the index in the background, yielding whenever possible. + /** + * Creates the index in the background, yielding whenever possible. + */ background?: boolean; - // A unique index cannot be created on a key that has pre-existing duplicate values. - // If you would like to create the index anyway, keeping the first document the database indexes and - // deleting all subsequent documents that have duplicate value + /** + * A unique index cannot be created on a key that has pre-existing duplicate values. + * + * If you would like to create the index anyway, keeping the first document the database indexes and + * deleting all subsequent documents that have duplicate value + */ dropDups?: boolean; - // For geo spatial indexes set the lower bound for the co-ordinates. + /** + * For geo spatial indexes set the lower bound for the co-ordinates. + */ min?: number; - // For geo spatial indexes set the high bound for the co-ordinates. + /** + * For geo spatial indexes set the high bound for the co-ordinates. + */ max?: number; - // Specify the format version of the indexes. + /** + * Specify the format version of the indexes. + */ v?: number; - // Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + /** + * Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + */ expireAfterSeconds?: number; - // Override the auto generated index name (useful if the resulting name is larger than 128 bytes) + /** + * Override the auto generated index name (useful if the resulting name is larger than 128 bytes) + */ name?: string; - // Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + /** + * Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + */ partialFilterExpression?: any; - collation?: Object; + collation?: CollationDocument; default_language?: string } @@ -619,17 +789,27 @@ export interface FSyncOptions extends CommonOptions { fsync?: boolean } -// Documentation : http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html +/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html */ export interface Collection { - // Get the collection name. + /** + * Get the collection name. + */ collectionName: string; - // Get the full collection namespace. + /** + * Get the full collection namespace. + */ namespace: string; - // The current write concern values. + /** + * The current write concern values. + */ writeConcern: any; - // The current read concern values. + /** + * The current read concern values. + */ readConcern: ReadConcern; - // Get current index hint for collection. + /** + * Get current index hint for collection. + */ hint: any; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#aggregate */ aggregate(callback: MongoCallback>): AggregationCursor; @@ -657,9 +837,9 @@ export interface Collection { createIndex(fieldOrSpec: string | any, options?: IndexOptions): Promise; createIndex(fieldOrSpec: string | any, options: IndexOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#createIndexes and http://docs.mongodb.org/manual/reference/command/createIndexes/ */ - createIndexes(indexSpecs: Object[], callback: MongoCallback): void; - createIndexes(indexSpecs: Object[], options?: { session?: ClientSession }): Promise; - createIndexes(indexSpecs: Object[], options: { session?: ClientSession }, callback: MongoCallback): void; + createIndexes(indexSpecs: IndexSpecification[], callback: MongoCallback): void; + createIndexes(indexSpecs: IndexSpecification[], options?: { session?: ClientSession }): Promise; + createIndexes(indexSpecs: IndexSpecification[], options: { session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany */ deleteMany(filter: FilterQuery, callback: MongoCallback): void; deleteMany(filter: FilterQuery, options?: CommonOptions): Promise; @@ -706,9 +886,9 @@ export interface Collection { findOneAndReplace(filter: FilterQuery, replacement: Object, options?: FindOneAndReplaceOption): Promise>; findOneAndReplace(filter: FilterQuery, replacement: Object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate */ - findOneAndUpdate(filter: FilterQuery, update: Object, callback: MongoCallback>): void; - findOneAndUpdate(filter: FilterQuery, update: Object, options?: FindOneAndUpdateOption): Promise>; - findOneAndUpdate(filter: FilterQuery, update: Object, options: FindOneAndUpdateOption, callback: MongoCallback>): void; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback>): void; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, options?: FindOneAndUpdateOption): Promise>; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, options: FindOneAndUpdateOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoHaystackSearch */ geoHaystackSearch(x: number, y: number, callback: MongoCallback): void; geoHaystackSearch(x: number, y: number, options?: GeoHaystackSearchOptions): Promise; @@ -880,40 +1060,70 @@ export type FilterQuery = { [P in keyof T]?: T[P] | Condition; } | { [key: string]: any }; -// Documentation: http://docs.mongodb.org/manual/reference/command/collStats/ +/** http://docs.mongodb.org/manual/reference/command/collStats/ */ export interface CollStats { - // Namespace. + /** + * Namespace. + */ ns: string; - // Number of documents. + /** + * Number of documents. + */ count: number; - // Collection size in bytes. + /** + * Collection size in bytes. + */ size: number; - // Average object size in bytes. + /** + * Average object size in bytes. + */ avgObjSize: number; - // (Pre)allocated space for the collection in bytes. + /** + * (Pre)allocated space for the collection in bytes. + */ storageSize: number; - // Number of extents (contiguously allocated chunks of datafile space). + /** + * Number of extents (contiguously allocated chunks of datafile space). + */ numExtents: number; - // Number of indexes. + /** + * Number of indexes. + */ nindexes: number; - // Size of the most recently created extent in bytes. + /** + * Size of the most recently created extent in bytes. + */ lastExtentSize: number; - // Padding can speed up updates if documents grow. + /** + * Padding can speed up updates if documents grow. + */ paddingFactor: number; - // A number that indicates the user-set flags on the collection. userFlags only appears when using the mmapv1 storage engine. + /** + * A number that indicates the user-set flags on the collection. userFlags only appears when using the mmapv1 storage engine. + */ userFlags?: number; - // Total index size in bytes. + /** + * Total index size in bytes. + */ totalIndexSize: number; - // Size of specific indexes in bytes. + /** + * Size of specific indexes in bytes. + */ indexSizes: { _id_: number; [index: string]: number; }; - // `true` if the collection is capped. + /** + * `true` if the collection is capped. + */ capped: boolean; - // The maximum number of documents that may be present in a capped collection. + /** + * The maximum number of documents that may be present in a capped collection. + */ max: number; - // The maximum size of a capped collection. + /** + * The maximum size of a capped collection. + */ maxSize: number; wiredTiger?: WiredTigerData; indexDetails?: any; @@ -1059,24 +1269,35 @@ export interface WiredTigerData { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#aggregate */ export interface CollectionAggregationOptions { readPreference?: ReadPreference | string; - // Return the query as cursor, on 2.6 > it returns as a real cursor - // on pre 2.6 it returns as an emulated cursor. + /** + * Return the query as cursor, on 2.6 > it returns as a real cursor + * on pre 2.6 it returns as an emulated cursor. + */ cursor?: { batchSize?: number }; - // Explain returns the aggregation execution plan (requires mongodb 2.6 >). + /** + * Explain returns the aggregation execution plan (requires mongodb 2.6 >). + */ explain?: boolean; - // lets the server know if it can use disk to store - // temporary results for the aggregation (requires mongodb 2.6 >). + /** + * Lets the server know if it can use disk to store + * temporary results for the aggregation (requires mongodb 2.6 >). + */ allowDiskUse?: boolean; - // specifies a cumulative time limit in milliseconds for processing operations - // on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + /** + * specifies a cumulative time limit in milliseconds for processing operations + * on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + */ maxTimeMS?: number; - // Allow driver to bypass schema validation in MongoDB 3.2 or higher. + /** + * Allow driver to bypass schema validation in MongoDB 3.2 or higher. + */ bypassDocumentValidation?: boolean; + hint?: string | object; raw?: boolean; promoteLongs?: boolean; promoteValues?: boolean; promoteBuffers?: boolean; - collation?: Object; + collation?: CollationDocument; comment?: string session?: ClientSession; @@ -1084,23 +1305,37 @@ export interface CollectionAggregationOptions { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertMany */ export interface CollectionInsertManyOptions extends CommonOptions { - // Serialize functions on any object. + /** + * Serialize functions on any object. + */ serializeFunctions?: boolean; - //Force server to assign _id values instead of driver. + /** + * Force server to assign _id values instead of driver. + */ forceServerObjectId?: boolean; - // Allow driver to bypass schema validation in MongoDB 3.2 or higher. + /** + * Allow driver to bypass schema validation in MongoDB 3.2 or higher. + */ bypassDocumentValidation?: boolean; - // If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. + /** + * If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. + */ ordered?: boolean; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#bulkWrite */ export interface CollectionBulkWriteOptions extends CommonOptions { - // Serialize functions on any object. + /** + * Serialize functions on any object. + */ serializeFunctions?: boolean; - // Execute write operation in ordered or unordered fashion. + /** + * Execute write operation in ordered or unordered fashion. + */ ordered?: boolean; - // Allow driver to bypass schema validation in MongoDB 3.2 or higher. + /** + * Allow driver to bypass schema validation in MongoDB 3.2 or higher. + */ bypassDocumentValidation?: boolean; //Force server to assign _id values instead of driver. forceServerObjectId?: boolean; @@ -1120,13 +1355,21 @@ export interface BulkWriteOpResultObject { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#count */ export interface MongoCountPreferences { - // The limit of documents to count. + /** + * The limit of documents to count. + */ limit?: number; - // The number of documents to skip for the count. + /** + * The number of documents to skip for the count. + */ skip?: boolean; - // An index name hint for the query. + /** + * An index name hint for the query. + */ hint?: string; - // The preferred read preference + /** + * The preferred read preference + */ readPreference?: ReadPreference | string; maxTimeMS?: number; session?: ClientSession; @@ -1292,7 +1535,10 @@ export interface FindOneOptions { limit?: number; sort?: Array | Object; projection?: Object; - fields?: Object; // Deprecated Use options.projection instead + /** + * @deprecated Use options.projection instead + */ + fields?: Object; skip?: number; hint?: Object; explain?: boolean; @@ -1313,7 +1559,7 @@ export interface FindOneOptions { readPreference?: ReadPreference | string; partial?: boolean; maxTimeMs?: number; - collation?: Object; + collation?: CollationDocument; session?: ClientSession; } @@ -1328,7 +1574,9 @@ export interface InsertWriteOpResult { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne */ export interface CollectionInsertOneOptions extends CommonOptions { - // Serialize functions on any object. + /** + * Serialize functions on any object. + */ serializeFunctions?: boolean; //Force server to assign _id values instead of driver. forceServerObjectId?: boolean; @@ -1432,7 +1680,7 @@ export class Cursor extends Readable { close(): Promise; close(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#collation */ - collation(value: Object): Cursor; + collation(value: CollationDocument): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#comment */ comment(value: string): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#count */ @@ -1578,24 +1826,30 @@ export class AggregationCursor extends Readable { unwind(field: string): AggregationCursor; } +/** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#~resultCallback */ +export type CommandCursorResult = any | void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html */ export class CommandCursor extends Readable { + /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#hasNext */ + hasNext(): Promise; + /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#hasNext */ + hasNext(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#batchSize */ batchSize(value: number): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#clone */ clone(): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#close */ - close(): Promise; - close(callback: MongoCallback): void; + close(): Promise; + close(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#each */ - each(callback: MongoCallback): void; + each(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#isClosed */ isClosed(): boolean; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#maxTimeMS */ maxTimeMS(value: number): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#next */ - next(): Promise; - next(callback: MongoCallback): void; + next(): Promise; + next(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#read */ read(size: number): string | Buffer | void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#rewind */ @@ -1683,17 +1937,29 @@ export class GridFSBucketWriteStream extends Writable { /** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketWriteStream.html */ export interface GridFSBucketWriteStreamOptions { - /** Custom file id for the GridFS file. */ + /** + * Custom file id for the GridFS file. + **/ id?: GridFSBucketWriteStreamId, - /** The chunk size to use, in bytes */ + /** + * The chunk size to use, in bytes + */ chunkSizeBytes?: number, - /** The write concern */ + /** + * The write concern + */ w?: number, - /** The write concern timeout */ + /** + * The write concern timeout + */ wtimeout?: number, - /** The journal write concern */ + /** + * The journal write concern + */ j?: number - /** Default false; If true, disables adding an md5 field to file data */ + /** + * Default false; If true, disables adding an md5 field to file data + */ disableMD5?: boolean } @@ -1725,15 +1991,21 @@ export interface ChangeStreamOptions { maxAwaitTimeMS?: number; resumeAfter?: Object; batchSize?: number; - collation?: Object; + collation?: CollationDocument; readPreference?: ReadPreference; } type GridFSBucketWriteStreamId = string | number | Object | ObjectID; export interface LoggerOptions { - loggerLevel?: string // Custom logger function - logger?: log // Override default global log level. + /** + * Custom logger function + */ + loggerLevel?: string + /** + * Override default global log level. + */ + logger?: log } export type log = (message?: string, state?: LoggerState) => void @@ -1749,30 +2021,90 @@ export interface LoggerState { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Logger.html */ export class Logger { constructor(className: string, options?: LoggerOptions) - // Log a message at the debug level + /** + * Log a message at the debug level + */ debug(message: string, state: LoggerState): void - // Log a message at the warn level + /** + * Log a message at the warn level + */ warn(message: string, state: LoggerState): void - // Log a message at the info level + /** + * Log a message at the info level + */ info(message: string, state: LoggerState): void - // Log a message at the error level + /** + * Log a message at the error level + */ error(message: string, state: LoggerState): void - // Is the logger set at info level + /** + * Is the logger set at info level + */ isInfo(): boolean - // Is the logger set at error level + /** + * Is the logger set at error level + */ isError(): boolean - // Is the logger set at error level + /** + * Is the logger set at error level + */ isWarn(): boolean - // Is the logger set at debug level + /** + * Is the logger set at debug level + */ isDebug(): boolean - // Resets the logger to default settings, error and no filtered classes + /** + * Resets the logger to default settings, error and no filtered classes + */ static reset(): void - // Get the current logger function + /** + * Get the current logger function + */ static currentLogger(): log //Set the current logger function static setCurrentLogger(log: log): void - // Set what classes to log. + /** + * Set what classes to log. + */ static filter(type: string, values: string[]): void - // Set the current log level + /** + * Set the current log level + */ static setLevel(level: string): void } + +/** https://docs.mongodb.com/manual/reference/collation/#collation-document-fields */ +export interface CollationDocument { + locale: string; + strength?: number; + caseLevel?: boolean; + caseFirst?: string; + numericOrdering?: boolean; + alternate?: string; + maxVariable?: string; + backwards?: boolean; + normalization?: boolean; + +} + +/** https://docs.mongodb.com/manual/reference/command/createIndexes/ */ +export interface IndexSpecification { + key: object; + name?: string; + background?: boolean; + unique?: boolean; + partialFilterExpression?: object; + sparse?: boolean; + expireAfterSeconds?: number; + storageEngine?: object; + weights?: object; + default_language?: string; + language_override?: string; + textIndexVersion?: number; + '2dsphereIndexVersion'?: number; + bits?: number; + min?: number; + max?: number; + bucketSize?: number; + collation?: CollationDocument; +} diff --git a/types/mongodb/mongodb-tests.ts b/types/mongodb/mongodb-tests.ts index b9b4a63c8d..ea755a8eb1 100644 --- a/types/mongodb/mongodb-tests.ts +++ b/types/mongodb/mongodb-tests.ts @@ -7,6 +7,7 @@ const connectionString = 'mongodb://127.0.0.1:27017/test'; var format = require('util').format; let options: mongodb.MongoClientOptions = { authSource: ' ', + loggerLevel: 'debug', w: 1, wtimeout: 300, j: true, @@ -21,7 +22,6 @@ let options: mongodb.MongoClientOptions = { reconnectTries: 123456, reconnectInterval: 123456, - ssl: true, sslValidate: false, checkServerIdentity: function () { }, @@ -31,12 +31,14 @@ let options: mongodb.MongoClientOptions = { sslKey: new Buffer(999), sslPass: new Buffer(999), promoteBuffers: false, - useNewUrlParser: false + useNewUrlParser: false, + authMechanism: 'SCRAM-SHA-1', + forceServerObjectId: false } MongoClient.connect(connectionString, options, function (err: mongodb.MongoError, client: mongodb.MongoClient) { if (err) throw err; const db = client.db('test'); - + var collection = db.collection('test_insert'); collection.insertOne({ a: 2 }, function (err: mongodb.MongoError, docs: any) { @@ -263,11 +265,11 @@ async function transfer(client: mongodb.MongoClient, from: any, to: any, amount: // `session.abortTransaction()` will undo the above `findOneAndUpdate()` throw new Error('Insufficient funds: ' + (A.balance + amount)); } - + const B = await db.collection('Account'). findOneAndUpdate({ name: to }, { $inc: { balance: amount } }, opts). then(res => res.value); - + await session.commitTransaction(); session.endSession(); return { from: A, to: B }; @@ -287,3 +289,4 @@ mongodb.connect(connectionString).then((client) => { ); }); + diff --git a/types/mongoose-paginate/mongoose-paginate-tests.ts b/types/mongoose-paginate/mongoose-paginate-tests.ts index 320077bc3a..d55f8a454e 100644 --- a/types/mongoose-paginate/mongoose-paginate-tests.ts +++ b/types/mongoose-paginate/mongoose-paginate-tests.ts @@ -40,7 +40,7 @@ let router: Router = Router(); router.get('/users.json', function(req: Request, res: Response) { let descending: boolean = true; - let options: PaginateOptions = {}; + let options: PaginateOptions = {} as PaginateOptions; options.select = 'email username'; options.sort = { 'username': (descending ? -1 : 1) }; options.populate = ''; diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 5963be87ed..87ce57f05c 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -280,6 +280,16 @@ declare module "mongoose" { collection?: string ): U; + /** + * Removes the model named `name` from this connection, if it exists. You can + * use this function to clean up any models you created in your tests to + * prevent OverwriteModelErrors. + * + * @param name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. + * @returns this + */ + deleteModel(name: string | RegExp): Connection; + /** Returns an array of model names created on this connection. */ modelNames(): string[]; @@ -414,6 +424,7 @@ declare module "mongoose" { */ autoIndex?: boolean; }; + autoIndex?: boolean; } /** See the node-mongodb-native driver instance for options that it understands. */ @@ -511,7 +522,7 @@ declare module "mongoose" { /** * section error/notFound.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.DocumentNotFoundError - * + * * An instance of this error class will be returned when `save()` fails * because the underlying * document was not found. The constructor takes one parameter, the @@ -524,7 +535,7 @@ declare module "mongoose" { /** * section error/cast.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.CastError - * + * * An instance of this error class will be returned when mongoose failed to * cast a value. */ @@ -544,7 +555,7 @@ declare module "mongoose" { /** * section error/validation.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidationError - * + * * An instance of this error class will be returned when [validation](http://mongoosejs.com/docs/validation.html) failed. */ export class ValidationError extends Error { @@ -565,7 +576,7 @@ declare module "mongoose" { /** * section error/validator.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidatorError - * + * * A `ValidationError` has a hash of `errors` that contain individual `ValidatorError` instances */ export class ValidatorError extends Error { @@ -585,7 +596,7 @@ declare module "mongoose" { /** * section error/version.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.VersionError - * + * * An instance of this error class will be returned when you call `save()` after * the document in the database was changed in a potentially unsafe way. See * the [`versionKey` option](http://mongoosejs.com/docs/guide.html#versionKey) for more information. @@ -600,7 +611,7 @@ declare module "mongoose" { /** * section error/parallelSave.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ParallelSaveError - * + * * An instance of this error class will be returned when you call `save()` multiple * times on the same document in parallel. See the [FAQ](http://mongoosejs.com/docs/faq.html) for more * information. @@ -612,7 +623,7 @@ declare module "mongoose" { /** * section error/overwriteModel.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.OverwriteModelError - * + * * Thrown when a model with the given name was already registered on the connection. * See [the FAQ about `OverwriteModelError`](http://mongoosejs.com/docs/faq.html#overwrite-model-error). */ @@ -623,7 +634,7 @@ declare module "mongoose" { /** * section error/missingSchema.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.MissingSchemaError - * + * * Thrown when you try to access a model that has not been registered yet */ export class MissingSchemaError extends Error { @@ -633,7 +644,7 @@ declare module "mongoose" { /** * section error/divergentArray.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.DivergentArrayError - * + * * An instance of this error will be returned if you used an array projection * and then modified the array in an unsafe way. */ @@ -811,11 +822,11 @@ declare module "mongoose" { * @param fn callback */ post(method: string, fn: ( - error: mongodb.MongoError, doc: T, next: (err?: NativeError) => void + doc: T, next: (err?: NativeError) => void ) => void): this; post(method: string, fn: ( - doc: T, next: (err?: NativeError) => void + error: mongodb.MongoError, doc: T, next: (err?: NativeError) => void ) => void): this; /** @@ -2011,6 +2022,30 @@ declare module "mongoose" { */ or(array: any[]): this; + /** + * Make this query throw an error if no documents match the given `filter`. + * This is handy for integrating with async/await, because `orFail()` saves you + * an extra `if` statement to check if no document was found. + * + * Example: + * + * // Throws if no doc returned + * await Model.findOne({ foo: 'bar' }).orFail(); + * + * // Throws if no document was updated + * await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail(); + * + * // Throws "No docs found!" error if no docs match `{ foo: 'bar' }` + * await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!')); + * + * // Throws "Not found" error if no document was found + * await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }). + * orFail(() => Error('Not found')); + * + * @param err optional error to throw if no docs match `filter` + */ + orFail(err?: Error | (() => Error)): this; + /** Specifies a $polygon condition */ polygon(...coordinatePairs: number[][]): this; polygon(path: string, ...coordinatePairs: number[][]): this; diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index c8873f85b3..7d23e6be6b 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -27,7 +27,8 @@ const connection2: Promise = mongoose.connect(connectUri, { bufferCommands: false, useNewUrlParser: true, useFindAndModify: true, - useCreateIndex: true + useCreateIndex: true, + autoIndex: true }); const connection3: null = mongoose.connect(connectUri, function (error) { error.stack; @@ -145,6 +146,7 @@ conn1.close(function (err) {}); conn1.close(true, function (err) {}); conn1.collection('name').$format(999); conn1.model('myModel', new mongoose.Schema({}), 'myCol').find(); +conn1.deleteModel('myModel'); conn1.models.myModel.findOne().exec(); interface IStatics { staticMethod1: (a: number) => string; @@ -491,12 +493,12 @@ preHookTestSchemaArr.push( ); schema -.post('save', function (error, doc, next) { +.post('save', function (error: mongoose.Error, doc: mongoose.Document, next: (err?: mongoose.NativeError) => void) { error.stack; doc.model; next.apply; }) -.post('save', function (doc: mongoose.Document, next: Function) { +.post('save', function (doc: mongoose.Document, next: (err?: mongoose.NativeError) => void) { doc.model; next(new Error()); }) @@ -1079,6 +1081,7 @@ query.find().where('age').in([20, 21]); query.find().in('age', [20, 21]); query.nor([{ color: 'green' }, { status: 'ok' }]).nor([]); query.or([{ color: 'red' }, { status: 'emergency' }]).or([]); +query.find({ color: 'blue' }).orFail(); query.where('loc').within().polygon([10,20], [13, 25], [7,15]); query.polygon('loc', [10,20], [13, 25], [7,15]); query.findOne().populate('owner').exec(function (err, kitten) { diff --git a/types/mongoose/v4/index.d.ts b/types/mongoose/v4/index.d.ts index ee3cd4c045..d8a9feb085 100644 --- a/types/mongoose/v4/index.d.ts +++ b/types/mongoose/v4/index.d.ts @@ -329,6 +329,16 @@ declare module "mongoose" { collection?: string ): U; + /** + * Removes the model named `name` from this connection, if it exists. You can + * use this function to clean up any models you created in your tests to + * prevent OverwriteModelErrors. + * + * @param name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. + * @returns this + */ + deleteModel(name: string | RegExp): Connection; + /** Returns an array of model names created on this connection. */ modelNames(): string[]; diff --git a/types/mongoose/v4/mongoose-tests.ts b/types/mongoose/v4/mongoose-tests.ts index b2d2a834fd..633d3438a8 100644 --- a/types/mongoose/v4/mongoose-tests.ts +++ b/types/mongoose/v4/mongoose-tests.ts @@ -133,6 +133,7 @@ conn1.openSet('mongodb://localhost/test', 'db', { conn1.close().catch(function (err) {}); conn1.collection('name').$format(999); conn1.model('myModel', new mongoose.Schema({}), 'myCol').find(); +conn1.deleteModel('myModel'); interface IStatics { staticMethod1: (a: number) => string; } diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index d4558737ba..891186f7ee 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -316,6 +316,7 @@ export declare class PreparedStatement extends events.EventEmitter { public parameters: IRequestParameters; public stream: any; public constructor(connection?: ConnectionPool); + public constructor(transaction: Transaction); public input(name: string, type: (() => ISqlType) | ISqlType): PreparedStatement; public output(name: string, type: (() => ISqlType) | ISqlType): PreparedStatement; public prepare(statement?: string): Promise; diff --git a/types/mssql/mssql-tests.ts b/types/mssql/mssql-tests.ts index 72bbc15126..18ad4b3ad9 100644 --- a/types/mssql/mssql-tests.ts +++ b/types/mssql/mssql-tests.ts @@ -189,6 +189,16 @@ function test_request_constructor() { var request4 = new sql.Request(); } +function test_prepared_statement_constructor() { + // Request can be constructed with a connection, preparedStatment, transaction or no arguments + var connection: sql.ConnectionPool = new sql.ConnectionPool(config); + var preparedStatment = new sql.PreparedStatement(connection); + var transaction = new sql.Transaction(connection); + + var preparedSatement1 = new sql.PreparedStatement(connection); + var preparedSatement2 = new sql.PreparedStatement(transaction); +} + function test_classes_extend_eventemitter() { var connection: sql.ConnectionPool = new sql.ConnectionPool(config); var transaction = new sql.Transaction(); diff --git a/types/multi-progress/index.d.ts b/types/multi-progress/index.d.ts new file mode 100644 index 0000000000..db15a15b1b --- /dev/null +++ b/types/multi-progress/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for multi-progress 2.0 +// Project: https://github.com/pitaj/multi-progress +// Definitions by: David Brett +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import ProgressBar, { ProgressBarOptions } from 'progress'; +import { Stream } from 'stream'; + +export default class MultiProgress { + /** + * Create a new @see MultiProgress with the given stream, or stderr by default + * @param stream A stream to write the progress bars to + */ + constructor(stream?: Stream) + + /** + * Add a new bar + */ + newBar: (format: string, options: ProgressBarOptions) => ProgressBar; + + /** + * Close all bars + */ + terminate: () => void; + + /** + * Render the given progress bar + */ + move: (index: number) => void; + + /** + * Move the bar indicated by index forward the number of steps indicated by value + */ + tick: (index: number, value: number, options?: any) => void; + + /** + * Update the bar indicated by index to the value given + */ + update: (index: number, value: number, options?: any) => void; +} diff --git a/types/multi-progress/multi-progress-tests.ts b/types/multi-progress/multi-progress-tests.ts new file mode 100644 index 0000000000..9dde27c16b --- /dev/null +++ b/types/multi-progress/multi-progress-tests.ts @@ -0,0 +1,18 @@ +/** + * Example from https://github.com/pitaj/multi-progress + */ + +// require the library +import MultiProgress from 'multi-progress'; + +// spawn an instance with the optional stream to write to +// use of `new` is optional +const multi = new MultiProgress(process.stderr); + +// create a progress bar +const bar = multi.newBar(' downloading [:bar] :percent :etas', { + complete: '=', + incomplete: ' ', + width: 30, + total: 20 +}); diff --git a/types/multi-progress/tsconfig.json b/types/multi-progress/tsconfig.json new file mode 100644 index 0000000000..3f0dc36371 --- /dev/null +++ b/types/multi-progress/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "multi-progress-tests.ts" + ] +} \ No newline at end of file diff --git a/types/multi-progress/tslint.json b/types/multi-progress/tslint.json new file mode 100644 index 0000000000..1a60b8a5dd --- /dev/null +++ b/types/multi-progress/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": { } +} diff --git a/types/mustache-express/index.d.ts b/types/mustache-express/index.d.ts new file mode 100644 index 0000000000..ff40de42d7 --- /dev/null +++ b/types/mustache-express/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for mustache-express 1.2 +// Project: https://github.com/bryanburgers/node-mustache-express#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Cache } from 'lru-cache'; + +export = mustacheExpress; + +declare function mustacheExpress( + partialsPath?: string, + partialsExt?: string +): mustacheExpress.ExpessEngine; + +declare namespace mustacheExpress { + interface ExpessEngine { + (path: string, options: any, cb: (...args: any[]) => any): any; + cache: TemplateCache; + } + + type TemplateCache = Cache; +} diff --git a/types/mustache-express/mustache-express-tests.ts b/types/mustache-express/mustache-express-tests.ts new file mode 100644 index 0000000000..9157798c7b --- /dev/null +++ b/types/mustache-express/mustache-express-tests.ts @@ -0,0 +1,10 @@ +import express = require('express'); +import mustacheExpress = require('mustache-express'); + +const app = express(); +app.engine('mustache', mustacheExpress()); +app.engine('mustache', mustacheExpress('/partials')); +app.engine('mustache', mustacheExpress('/partials', '.mst')); + +// $ExpectType Cache +mustacheExpress().cache; diff --git a/types/mustache-express/tsconfig.json b/types/mustache-express/tsconfig.json new file mode 100644 index 0000000000..9afb989b62 --- /dev/null +++ b/types/mustache-express/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mustache-express-tests.ts" + ] +} diff --git a/types/mustache-express/tslint.json b/types/mustache-express/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mustache-express/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mz/mz-tests.ts b/types/mz/mz-tests.ts index b873c98bbe..a4ec4667a7 100644 --- a/types/mz/mz-tests.ts +++ b/types/mz/mz-tests.ts @@ -136,7 +136,7 @@ describe('readline', function () { var input = new stream.PassThrough() var output = new stream.PassThrough() var bufferedOutput = '' - var rl = readline.createInterface( input, output, completer, true ) + var rl = readline.createInterface( input, output, completer as readline.Completer, true ) rl.question('a').then(function (answer: string) { assert.equal(answer, 'bTESTSTRING') @@ -174,12 +174,12 @@ describe('readline', function () { it('completer support sync', function (done) { function completer (line: string) { assert.equal(line, 'b') - return <[string[], string]>[['bTESTSTRING'], line] + return [['bTESTSTRING'], line] as [string[], string] } var input = new stream.PassThrough() var output = new stream.PassThrough() - var rl = readline.createInterface(input, output, completer, true) + var rl = readline.createInterface(input, output, completer as readline.Completer, true) rl.question('a').then(function (answer) { assert.ok(output.read().toString().match(/TESTSTRING/)) @@ -197,7 +197,7 @@ describe('readline', function () { var input = new stream.PassThrough() var output = new stream.PassThrough() - var rl = readline.createInterface(input, output, completer, true ) + var rl = readline.createInterface(input, output, completer as readline.Completer, true ) rl.question('a').then(function (answer) { assert.ok(output.read().toString().match(/TESTSTRING/)) diff --git a/types/netease-captcha/index.d.ts b/types/netease-captcha/index.d.ts new file mode 100644 index 0000000000..fbdfb03e7d --- /dev/null +++ b/types/netease-captcha/index.d.ts @@ -0,0 +1,73 @@ +// Type definitions for netease-captcha 2.1 +// Project: https://cstaticdun.126.net/load.min.js +// Definitions by: Minjie Shen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Window { + initNECaptcha?: NeteaseCaptcha.InitFunction; +} + +declare namespace NeteaseCaptcha { + type InitFunction = (config: Config, onLoad?: onLoad, onError?: onError) => void; + + interface Config { + /** + * Verification code id + */ + captchaId: string; + + /** + * Selector string or HTMLElement to render widget into + */ + element: string | HTMLElement; + + /** + * Defaults to 'float' on desktop, and 'popup' on mobile + */ + mode?: 'float' | 'embed' | 'popup'; + + /** + * Defaults to page protocol + */ + protocol?: 'http' | 'https'; + + /** + * Defaults to 'auto' + */ + width?: number | string; + + /** + * Defaults to 'zh-CN' + */ + lang?: 'zh-CN' | 'en'; + + onReady?(instance: Instance): void; + + onVerify?(error: any, data: Data): void; + } + + interface Instance { + /** + * Refresh the instance to get new verification information + */ + refresh(): void; + + /** + * Destroy the current instance + */ + destroy(): void; + + /** + * Available when the mode is set to 'popup' - opens the popup to accept verification + */ + popUp?(): void; + } + + interface Data { + validate: string; + } + + type onLoad = (instance: Instance) => void; + + type onError = (error: any) => void; +} diff --git a/types/netease-captcha/netease-captcha-tests.ts b/types/netease-captcha/netease-captcha-tests.ts new file mode 100644 index 0000000000..ee73302cc1 --- /dev/null +++ b/types/netease-captcha/netease-captcha-tests.ts @@ -0,0 +1,23 @@ +const config: NeteaseCaptcha.Config = { + captchaId: 'FAKE ID', + element: '#captcha', + mode: 'popup', + protocol: 'https', + width: '200px', + lang: 'en', + onVerify: (error: any, data?: NeteaseCaptcha.Data) => { + console.log(error, data); + } + }; + +const onLoad: NeteaseCaptcha.onLoad = (instance: NeteaseCaptcha.Instance) => { + instance.refresh(); + instance.destroy(); + if (instance.popUp) { + instance.popUp(); + } +}; + +if (window.initNECaptcha) { + window.initNECaptcha(config, onLoad); +} diff --git a/types/netease-captcha/tsconfig.json b/types/netease-captcha/tsconfig.json new file mode 100644 index 0000000000..11afad945f --- /dev/null +++ b/types/netease-captcha/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "netease-captcha-tests.ts" + ] +} diff --git a/types/netease-captcha/tslint.json b/types/netease-captcha/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/netease-captcha/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/netlify-identity-widget/index.d.ts b/types/netlify-identity-widget/index.d.ts new file mode 100644 index 0000000000..a231be53d2 --- /dev/null +++ b/types/netlify-identity-widget/index.d.ts @@ -0,0 +1,86 @@ +// Type definitions for netlify-identity-widget 1.4 +// Project: https://github.com/netlify/netlify-identity-widget +// Definitions by: Naveen Kumar Sangi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface InitOptions { + // The container to attach to. e.g.: '#some-query-selector' + container?: string; + + // Absolute url to endpoint. ONLY USE IN SPECIAL CASES! + // e.g. https://www.example.com/.netlify/functions/identity + // Generally avoid setting the APIUrl. You should only set this when + // your app is served from a domain that differs from where the + // identity endpoint is served.This is common for Cordova or Electron + // apps where you host from localhost or a file. + APIUrl?: string; +} + +export interface Token { + access_token: string; + expires_at: string | number; + expires_in: string | number; + refresh_token: string; + token_type: string; +} + +export interface User { + api: { + _sameOrigin?: boolean; + apiURL: string; + defaultHeaders: { + [header: string]: string | string[] | undefined; + }; + }; + app_metadata: { + provider: string; + }; + aud: string; + audience?: any; + confirmed_at: string; + created_at: string; + updated_at: string; + email: string; + id: string; + role: string; + token?: Token; + url: string; + user_metadata: { + avatar_url: string; + full_name: string; + }; +} + +/** + * Initialises the netlify identity widget. + */ +export function init(opts?: InitOptions): void; + +/** + * Opens the netlify login modal to the corresponding tab. + */ +export function open(tabName?: "signup" | "login"): void; + +/** + * Closes the netlify login modal. + */ +export function close(): void; + +/** + * Retrieves the current logged in user information. + */ +export function currentUser(): User | null; + +/** + * Registers callbacks to corresponding events on the widget. + */ +export function on(event: 'init', cb: (user: User | null) => void): void; +export function on(event: 'login', cb: (user: User) => void): void; +export function on(event: 'logout' | 'open' | 'close', cb: () => void): void; +export function on(event: 'error', cb: (err: Error) => void): void; + +/** + * Logs out the current user. Returns a Promise when a user is + * logged in, else returns undefined. + */ +export function logout(): Promise | undefined; diff --git a/types/netlify-identity-widget/netlify-identity-widget-tests.ts b/types/netlify-identity-widget/netlify-identity-widget-tests.ts new file mode 100644 index 0000000000..f44daaec37 --- /dev/null +++ b/types/netlify-identity-widget/netlify-identity-widget-tests.ts @@ -0,0 +1,69 @@ +import es6styleimport from 'netlify-identity-widget'; + +import NetlifyIdentityWidget = require('netlify-identity-widget'); + +// Type 0: es6styleimport test +es6styleimport.init(); + +// Type 1: Initialize without options +NetlifyIdentityWidget.init(); +NetlifyIdentityWidget.init({}); + +// Type 2: Initialize with container option +NetlifyIdentityWidget.init({ container: 'body' }); + +// Type 3: Initialize with a specific APIUrl +NetlifyIdentityWidget.init({ APIUrl: 'https://www.example.com/.netlify/functions/identity' }); + +// Type 4: Initialize with both the options specified +NetlifyIdentityWidget.init({ + APIUrl: 'https://www.example.com/.netlify/functions/identity', + container: 'body', +}); + +// Open widget modal to let users login +NetlifyIdentityWidget.open(); +NetlifyIdentityWidget.on('open', () => { + // Widget is open and ready to login +}); + +// Open wigdet modal with signup tab selected +NetlifyIdentityWidget.open('signup'); + +// Close the widget programmatically +NetlifyIdentityWidget.close(); +NetlifyIdentityWidget.on('close', () => { + // Widget is closed +}); + +// Event handling after login +NetlifyIdentityWidget.on('login', (user) => { + // You can now use User info after a successful login +}); + +// Event handling after logout +NetlifyIdentityWidget.on('logout', () => { + // You can now notify that the logout was successful +}); + +// Event handling after login on page refresh +NetlifyIdentityWidget.on('init', (user) => { + // Now the widget is ready to use + // If a user was already logged in, the value is returned else null is passed via callback +}); + +// Event handling on errors +NetlifyIdentityWidget.on('error', (err) => { + // The error occured during operation is passed in via callback +}); + +// Use the current logged in user +const user = NetlifyIdentityWidget.currentUser(); + +// If a user is logged in, logout returns a Promise +const logoutPromise = NetlifyIdentityWidget.logout(); +if (logoutPromise) { + logoutPromise.then(() => { + // You can now do clean up after successful logout + }); +} diff --git a/types/netlify-identity-widget/tsconfig.json b/types/netlify-identity-widget/tsconfig.json new file mode 100644 index 0000000000..8ded135467 --- /dev/null +++ b/types/netlify-identity-widget/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "allowSyntheticDefaultImports": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "netlify-identity-widget-tests.ts" + ] +} diff --git a/types/netlify-identity-widget/tslint.json b/types/netlify-identity-widget/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/netlify-identity-widget/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/newman/index.d.ts b/types/newman/index.d.ts index cd2801c375..7bd7aef744 100644 --- a/types/newman/index.d.ts +++ b/types/newman/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for newman 3.10 +// Type definitions for newman 3.11 // Project: https://github.com/postmanlabs/newman // Definitions by: Leonid Logvinov // Graham McGregor @@ -168,9 +168,12 @@ export interface NewmanRunExecutionAssertion { error: NewmanRunExecutionAssertionError; } export interface NewmanRunExecutionAssertionError { + name: string; + index: number; + test: string; message: string; -} -export interface NewmanRunFailure { + stack: string; +}export interface NewmanRunFailure { error: NewmanRunExecutionAssertionError; /** The event where the failure occurred */ at: string; diff --git a/types/next-redux-saga/index.d.ts b/types/next-redux-saga/index.d.ts index b7575fba16..0366868d97 100644 --- a/types/next-redux-saga/index.d.ts +++ b/types/next-redux-saga/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/bmealhouse/next-redux-saga // Definitions by: Leo Cavalcante // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { ComponentType } from "react"; diff --git a/types/next-redux-wrapper/index.d.ts b/types/next-redux-wrapper/index.d.ts index 16af858743..10fa2d44d1 100644 --- a/types/next-redux-wrapper/index.d.ts +++ b/types/next-redux-wrapper/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Steve // Jungwoo-An // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 /// @@ -19,6 +19,8 @@ declare namespace nextReduxWrapper { interface Options { storeKey?: string; debug?: boolean; + serializeState?: any; + deserializeState?: any; } interface StoreCreatorOptions extends Options { diff --git a/types/ng-cordova/tslint.json b/types/ng-cordova/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/ng-cordova/tslint.json +++ b/types/ng-cordova/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ng-flow/tslint.json b/types/ng-flow/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/ng-flow/tslint.json +++ b/types/ng-flow/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ng-grid/tslint.json b/types/ng-grid/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/ng-grid/tslint.json +++ b/types/ng-grid/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ngeohash/index.d.ts b/types/ngeohash/index.d.ts index 25c8f29e5b..7fa05a0f4e 100644 --- a/types/ngeohash/index.d.ts +++ b/types/ngeohash/index.d.ts @@ -12,7 +12,7 @@ declare namespace ngeohash { type GeographicBoundingBox = [number, number, number, number]; type NSEW = [number, number]; - function encode(latitude: number, longitude: number, precision?: number): string; + function encode(latitude: number | string, longitude: number | string, precision?: number): string; function decode(hashstring: string): GeographicPoint; function decode_bbox(hashstring: string): GeographicBoundingBox; function bboxes(minlat: number, minlon: number, maxlat: number, maxlon: number, precision?: number): Array; diff --git a/types/ngeohash/ngeohash-tests.ts b/types/ngeohash/ngeohash-tests.ts index 34ad34d7cf..5c77ae94df 100644 --- a/types/ngeohash/ngeohash-tests.ts +++ b/types/ngeohash/ngeohash-tests.ts @@ -1,6 +1,7 @@ import geohash = require('ngeohash'); console.log(geohash.encode(37.8324, 112.5584)); +console.log(geohash.encode('37.8324', '112.5584')); // prints ww8p1r4t8 var latlon = geohash.decode('ww8p1r4t8'); diff --git a/types/nightmare/nightmare-tests.ts b/types/nightmare/nightmare-tests.ts index d49d8b5932..5d6da26d2a 100644 --- a/types/nightmare/nightmare-tests.ts +++ b/types/nightmare/nightmare-tests.ts @@ -17,7 +17,7 @@ new Nightmare() .click('.searchsubmit') .wait('.url.breadcrumb') .evaluate(() => { - return (document.querySelector('.url.breadcrumb')).innerText; + return (document.querySelector('.url.breadcrumb') as HTMLElement).innerText; }, (breadcrumb: string) => { // expect(breadcrumb).to.equal('github.com'); }) @@ -165,7 +165,7 @@ new Nightmare() .goto('http://validator.w3.org/#validate_by_upload') .upload('#uploaded_file', 'test/files/jquery-2.1.1.min.js') .evaluate(function () { - return (document.getElementById('uploaded_file')).value; + return (document.getElementById('uploaded_file') as HTMLInputElement).value; }, function (value) { }) .run(done); @@ -214,7 +214,7 @@ new Nightmare() var seconds = function () { var gifs = document.querySelectorAll('img'); - var split = (gifs[gifs.length - 2]).src.split('.gif')[0]; + var split = (gifs[gifs.length - 2] as HTMLImageElement).src.split('.gif')[0]; var seconds = split.split('.com/c')[1]; return parseInt(seconds, 10); }; @@ -319,7 +319,7 @@ new Nightmare() .headers(headers) .goto('http://httpbin.org/headers') .evaluate(function () { - return (document.body.children[0]).innerHTML; + return (document.body.children[0] as HTMLElement).innerHTML; }, function (data: string) { }) .run(done); diff --git a/types/nise/index.d.ts b/types/nise/index.d.ts new file mode 100644 index 0000000000..f054bad373 --- /dev/null +++ b/types/nise/index.d.ts @@ -0,0 +1,282 @@ +// Type definitions for nise 1.4 +// Project: https://github.com/sinonjs/nise#readme +// Definitions by: Alexander T. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export interface FakeUploadProgress { + eventListeners: { + progress: any[]; + load: any[]; + abort: any[]; + error: any[]; + }; + + addEventListener(event: string, listener: (e: Event) => any): void; + removeEventListener(event: string, listener: (e: Event) => any): void; + dispatchEvent(event: Event): void; +} + +export interface FakeXMLHttpRequest { + /** + * The URL set on the request object. + */ + url: string; + /** + * The request method as a string. + */ + method: string; + /** + * An object of all request headers, i.e.: + */ + requestHeaders: any; + /** + * The request body + */ + requestBody: string; + /** + * The request’s status code. + * undefined if the request has not been handled (see respond below) + */ + status: number; + /** + * Only populated if the respond method is called (see below). + */ + statusText: string; + /** + * Whether or not the request is asynchronous. + */ + async: boolean; + /** + * Username, if any. + */ + username: string; + /** + * Password, if any. + */ + password: string; + withCredentials: boolean; + upload: FakeUploadProgress; + /** + * When using respond, this property is populated with a parsed document if response headers indicate as much (see the spec) + */ + responseXML: Document; + /** + * The value of the given response header, if the request has been responded to (see respond). + * @param header + */ + getResponseHeader(header: string): string; + /** + * All response headers as an object. + */ + getAllResponseHeaders(): any; + + /** + * Sets response headers (e.g. { "Content-Type": "text/html", ... }, updates the readyState property and fires onreadystatechange. + * @param headers + */ + setResponseHeaders(headers: any): void; + /** + * Sets the respond body, updates the readyState property and fires onreadystatechange. + * Additionally, populates responseXML with a parsed document if response headers indicate as much. + */ + setResponseBody(body: string): void; + /** + * Calls the above three methods. + */ + respond(status: number, headers?: any, body?: string): void; + autoRespond(ms: number): void; + /** + * Simulates a network error on the request. The onerror handler will be called and the status will be 0. + */ + error(): void; + + onloadstart(e: Event): void; + onprogress(e: Event): void; + ontimeout(e: Event): void; + onloadend(e: Event): void; + onerror(e: Event): void; + onabort(e: Event): void; + onload(e: Event): void; +} + +export interface FakeServerOptions { + /** + * When set to true, causes the server to automatically respond to incoming requests after a timeout. + * The default timeout is 10ms but you can control it through the autoRespondAfter property. + * Note that this feature is intended to help during mockup development, and is not suitable for use in tests. + */ + autoRespond: boolean; + /** + * When autoRespond is true, respond to requests after this number of milliseconds. Default is 10. + */ + autoRespondAfter: number; + /** + * If set to true, server will find _method parameter in POST body and recognize that as the actual method. + * Supports a pattern common to Ruby on Rails applications. For custom HTTP method faking, override server.getHTTPMethod(request). + */ + fakeHTTPMethods: boolean; + /** + * If set, the server will respond to every request immediately and synchronously. + * This is ideal for faking the server from within a test without having to call server.respond() after each request made in that test. + * As this is synchronous and immediate, this is not suitable for simulating actual network latency in tests or mockups. + * To simulate network latency with automatic responses, see server.autoRespond and server.autoRespondAfter. + */ + respondImmediately: boolean; +} + +export interface FakeServer extends FakeServerOptions { + lastRequest: FakeXMLHttpRequest | undefined; + firstRequest: FakeXMLHttpRequest | undefined; + secondRequest: FakeXMLHttpRequest | undefined; + thirdRequest: FakeXMLHttpRequest | undefined; + + /** + * Used internally to determine the HTTP method used with the provided request. + * By default this method simply returns request.method. + * When server.fakeHTTPMethods is true, the method will return the value of the _method parameter if the method is “POST”. + * This method can be overridden to provide custom behavior. + * @param request + */ + getHTTPMethod(request: FakeXMLHttpRequest): string; + + /** + * You can inspect the server.requests to verify request ordering, find unmatched requests or check that no requests has been done. + * server.requests is an array of all the FakeXMLHttpRequest objects that have been created. + */ + requests: FakeXMLHttpRequest[]; + + /** + * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. + * A String representing the response body + * An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"] + * A Function. + * Default status is 200 and default headers are none. + * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. + * @param body A String representing the response body + */ + respondWith(body: string): void; + /** + * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. + * Default status is 200 and default headers are none. + * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. + * @param response An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"] + */ + respondWith(response: any[]): void; + /** + * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. + * Default status is 200 and default headers are none. + * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. + * @param fn A Function. + */ + respondWith(fn: (xhr: FakeXMLHttpRequest) => void): void; + /** + * Responds to all requests to given URL, e.g. /posts/1. + */ + respondWith(url: string, body: string): void; + /** + * Responds to all requests to given URL, e.g. /posts/1. + */ + respondWith(url: string, response: any[]): void; + /** + * Responds to all requests to given URL, e.g. /posts/1. + */ + respondWith(url: string, fn: (xhr: FakeXMLHttpRequest) => void): void; + /** + * Responds to all method requests to the given URL with the given response. + * method is an HTTP verb. + */ + respondWith(method: string, url: string, body: string): void; + /** + * Responds to all method requests to the given URL with the given response. + * method is an HTTP verb. + */ + respondWith(method: string, url: string, response: any[]): void; + /** + * Responds to all method requests to the given URL with the given response. + * method is an HTTP verb. + */ + respondWith(method: string, url: string, fn: (xhr: FakeXMLHttpRequest) => void): void; + /** + * URL may be a regular expression, e.g. /\\/post\\//\\d+ + * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: + */ + respondWith(url: RegExp, body: string): void; + /** + * URL may be a regular expression, e.g. /\\/post\\//\\d+ + * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: + */ + respondWith(url: RegExp, response: any[]): void; + /** + * URL may be a regular expression, e.g. /\\/post\\//\\d+ + * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: + */ + respondWith(url: RegExp, fn: (xhr: FakeXMLHttpRequest) => void): void; + /** + * Responds to all method requests to URLs matching the regular expression. + */ + respondWith(method: string, url: RegExp, body: string): void; + /** + * Responds to all method requests to URLs matching the regular expression. + */ + respondWith(method: string, url: RegExp, response: any[]): void; + /** + * Responds to all method requests to URLs matching the regular expression. + */ + respondWith(method: string, url: RegExp, fn: (xhr: FakeXMLHttpRequest) => void): void; + respondWith(...args: any[]): void; + + /** + * Causes all queued asynchronous requests to receive a response. + * If none of the responses added through respondWith match, the default response is [404, {}, ""]. + * Synchronous requests are responded to immediately, so make sure to call respondWith upfront. + * If called with arguments, respondWith will be called with those arguments before responding to requests. + */ + respond(): void; + restore(): void; + + getRequest(): FakeXMLHttpRequest | undefined; + reset(): void; + resetBehavior(): void; + resetHistory(): void; +} + +export interface FakeXMLHttpRequestStatic { + new(): FakeXMLHttpRequest; + /** + * Default false. + * When set to true, Sinon will check added filters if certain requests should be “unfaked” + */ + useFilters: boolean; + /** + * Add a filter that will decide whether or not to fake a request. + * The filter will be called when xhr.open is called, with the exact same arguments (method, url, async, username, password). + * If the filter returns true, the request will not be faked. + * @param filter + */ + addFilter(filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean): void; + /** + * By assigning a function to the onCreate property of the returned object from useFakeXMLHttpRequest() + * you can subscribe to newly created FakeXMLHttpRequest objects. See below for the fake xhr object API. + * Using this observer means you can still reach objects created by e.g. jQuery.ajax (or other abstractions/frameworks). + * @param xhr + */ + onCreate(xhr: FakeXMLHttpRequest): void; + /** + * Restore original function(s). + */ + restore(): void; +} + +export interface FakeServerStatic { + create(options?: Partial): FakeServer; +} + +export interface FakeXHR { + useFakeXMLHttpRequest(): FakeXMLHttpRequestStatic; + FakeXMLHttpRequest: FakeXMLHttpRequestStatic; +} + +export const fakeServerWithClock: FakeServerStatic; +export const fakeServer: FakeServerStatic; +export const fakeXhr: FakeXHR; diff --git a/types/nise/nise-tests.ts b/types/nise/nise-tests.ts new file mode 100644 index 0000000000..827275fc55 --- /dev/null +++ b/types/nise/nise-tests.ts @@ -0,0 +1,56 @@ +import { fakeXhr, fakeServer, FakeServer, FakeXMLHttpRequest } from 'nise'; + +function testCreateFakeServer() { + fakeServer.create(); + fakeServer.create({ autoRespond: true, autoRespondAfter: 3, fakeHTTPMethods: true, respondImmediately: false }); + fakeServer.create({ autoRespond: true, autoRespondAfter: 3 }); +} + +function testFakeServer() { + const server: FakeServer = fakeServer.create(); + const respondWith = ['GET', 'http://test.com', [200, {}, '']]; + + server.requests; + server.autoRespond = true; + + server.respondWith((xhr: FakeXMLHttpRequest) => xhr.respond(200)); + server.respondWith('body'); + server.respondWith([]); + + server.respondWith('http://test.com', 'body'); + server.respondWith('http://test.com', []); + server.respondWith('http://test.com', (xhr: FakeXMLHttpRequest) => xhr.respond(200)); + + server.respondWith('GET', 'http://test.com', 'body'); + server.respondWith('GET', 'http://test.com', []); + server.respondWith('GET', 'http://test.com', (xhr: FakeXMLHttpRequest) => xhr.respond(200)); + + server.respondWith(/url/, ''); + server.respondWith(/url/, []); + server.respondWith(/url/, (xhr: FakeXMLHttpRequest) => xhr.respond(200)); + + server.respondWith('GET', /url/, ''); + server.respondWith('GET', /url/, []); + server.respondWith('GET', /url/, (xhr: FakeXMLHttpRequest) => xhr.respond(200)); + server.respondWith(...respondWith); + server.respond(); + server.restore(); +} + +function testFakeXMLHttpRequest() { + const xhr = new fakeXhr.FakeXMLHttpRequest(); + const headers = xhr.getAllResponseHeaders(); + const header = xhr.getResponseHeader('test'); + + xhr.setResponseHeaders({ Accept: 'application/json' }); + xhr.setResponseBody('body'); + xhr.respond(200, { Accept: 'application/json' }, 'body'); + xhr.error(); +} + +function testFakeXMLHttpRequestStatic() { + fakeXhr.FakeXMLHttpRequest.useFilters = true; + fakeXhr.FakeXMLHttpRequest.addFilter((method, url, async, user, pass) => true); + fakeXhr.FakeXMLHttpRequest.onCreate = (xhr: FakeXMLHttpRequest) => { }; + fakeXhr.FakeXMLHttpRequest.restore(); +} diff --git a/types/nise/tsconfig.json b/types/nise/tsconfig.json new file mode 100644 index 0000000000..1e535819c3 --- /dev/null +++ b/types/nise/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "noImplicitThis": true, + "noImplicitAny": true, + "module": "commonjs", + "noEmit": true, + "types": [], + "lib": ["es6", "dom"], + "baseUrl": "../", + "typeRoots": ["../"] + }, + + "files": [ + "nise-tests.ts", + "index.d.ts" + ] +} diff --git a/types/nise/tslint.json b/types/nise/tslint.json new file mode 100644 index 0000000000..08b1465cd6 --- /dev/null +++ b/types/nise/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } +} diff --git a/types/noble/index.d.ts b/types/noble/index.d.ts index 61ca1f2113..5b4af235e7 100644 --- a/types/noble/index.d.ts +++ b/types/noble/index.d.ts @@ -30,6 +30,8 @@ export declare function removeListener(event: "scanStop", listener: () => void): export declare function removeListener(event: "discover", listener: (peripheral: Peripheral) => void): events.EventEmitter; export declare function removeListener(event: string, listener: Function): events.EventEmitter; +export declare function removeAllListeners(event?: string): events.EventEmitter; + export declare var state:string; export declare class Peripheral extends events.EventEmitter { diff --git a/types/noble/noble-tests.ts b/types/noble/noble-tests.ts index 0c8dcf6c20..a4441eba6e 100644 --- a/types/noble/noble-tests.ts +++ b/types/noble/noble-tests.ts @@ -35,6 +35,12 @@ noble.removeListener("discover", (peripheral: noble.Peripheral): void => { peripheral.disconnect((): void => {}); }); +noble.removeAllListeners("stateChange"); +noble.removeAllListeners("scanStart"); +noble.removeAllListeners("scanStop"); +noble.removeAllListeners("discover"); +noble.removeAllListeners(); + var peripheral: noble.Peripheral = new noble.Peripheral(); peripheral.uuid = "12ad4e81"; peripheral.advertisement = { diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index d362eb1c27..d2fcddc2d9 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -7,6 +7,7 @@ // Beeno Tung // Joe Flateau // Nikita Koryabkin +// timhwang21 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -20,6 +21,15 @@ declare module "node-forge" { type Utf8 = string; type OID = string; + namespace jsbn { + class BigInteger { + data: number[]; + t: number; + s: number; + toString(): string; + } + } + namespace pem { interface EncodeOptions { @@ -40,40 +50,63 @@ declare module "node-forge" { } namespace pki { - type PEM = string; - type Key = any; + type PublicKey = rsa.PublicKey | ed25519.Key; + type PrivateKey = rsa.PrivateKey | ed25519.Key; interface KeyPair { publicKey: PublicKey; privateKey: PrivateKey; } - interface PublicKey { - encrypt(data: string, scheme?: string, schemeOptions?: number): Bytes - verify(digest: string, signature: string, scheme?: string): boolean - } - - interface PrivateKey { - decrypt(data: string, scheme?: string, schemeOptions?: number): string - sign(md: string, scheme?: string): Bytes - } - function pemToDer(pem: PEM): util.ByteStringBuffer; function privateKeyToPem(key: PrivateKey, maxline?: number): PEM; - function privateKeyInfoToPem(key: PrivateKey, maxline?: number): PEM; + function privateKeyInfoToPem(key: Bytes, maxline?: number): PEM; function publicKeyToPem(key: PublicKey, maxline?: number): PEM; function publicKeyFromPem(pem: PEM): PublicKey; function privateKeyFromPem(pem: PEM): PrivateKey; function certificateToPem(cert: Certificate, maxline?: number): PEM; function certificateFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate; + function createCaStore(): CAStore; + function verifyCertificateChain(caStore: CAStore, chain: Certificate[], customVerifyCallback?: (verified: boolean | string, depth: number, chain: Certificate[]) => boolean): boolean; interface oids { [key: string]: string; } var oids: oids; + namespace ed25519 { + type Key = ArrayBuffer; + } + namespace rsa { + type EncryptionScheme = 'RSAES-PKCS1-V1_5' | 'RSA-OAEP' | 'RAW' | 'NONE' | null; + type SignatureScheme = 'RSASSA-PKCS1-V1_5' | pss.PSS | 'NONE' | null; + + interface PublicKey { + n: jsbn.BigInteger; + e: jsbn.BigInteger; + encrypt(data: Bytes, scheme?: EncryptionScheme, schemeOptions?: any): Bytes; + verify(digest: Bytes, signature: Bytes, scheme?: SignatureScheme): boolean; + } + + interface PrivateKey { + n: jsbn.BigInteger; + e: jsbn.BigInteger; + d: jsbn.BigInteger; + p: jsbn.BigInteger; + q: jsbn.BigInteger; + dP: jsbn.BigInteger; + dQ: jsbn.BigInteger; + qInv: jsbn.BigInteger; + decrypt(data: Bytes, scheme?: EncryptionScheme, schemeOptions?: any): Bytes; + sign(md: md.MessageDigest, scheme?: SignatureScheme): Bytes; + } + + interface KeyPair { + publicKey: PublicKey; + privateKey: PrivateKey; + } interface GenerateKeyPairOptions { bits?: number; @@ -84,9 +117,9 @@ declare module "node-forge" { prng?: any; algorithm?: string; } - + function setPublicKey(n: any, e: any): any; - + function generateKeyPair(bits?: number, e?: number, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; function generateKeyPair(options?: GenerateKeyPairOptions, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; } @@ -160,8 +193,8 @@ declare module "node-forge" { hash: any; }; extensions: any[]; - privateKey: Key; - publicKey: Key; + privateKey: PrivateKey; + publicKey: PublicKey; md: any; /** * Sets the subject of this certificate. @@ -171,7 +204,7 @@ declare module "node-forge" { */ setSubject(attrs: CertificateField[], uniqueId?: string): void; /** - * Sets the subject of this certificate. + * Sets the issuer of this certificate. * * @param attrs the array of subject attributes to use. * @param uniqueId an optional a unique ID to use. @@ -200,7 +233,7 @@ declare module "node-forge" { * @param key the private key to sign with. * @param md the message digest object to use (defaults to forge.md.sha1). */ - sign(key: pki.Key, md: md.MessageDigest): void; + sign(key: pki.PrivateKey, md?: md.MessageDigest): void; /** * Attempts verify the signature on the passed certificate using this * certificate's public key. @@ -213,21 +246,41 @@ declare module "node-forge" { } + interface CAStore { + addCertificate(cert: Certificate | string): void; + hasCertificate(cert: Certificate | string): boolean; + removeCertificate(cert: Certificate | string): Certificate | null; + listAllCertificates(): pki.Certificate[]; + getIssuer(subject: Certificate): Certificate | null; + getBySubject(subject: string): Certificate | null; + } + function certificateFromAsn1(obj: asn1.Asn1, computeHash?: boolean): Certificate; - function decryptRsaPrivateKey(pem: PEM, passphrase?: string): Key; + function decryptRsaPrivateKey(pem: PEM, passphrase?: string): PrivateKey; function createCertificate(): Certificate; - + function certificationRequestToPem(cert: Certificate, maxline?: number): PEM; - + function certificationRequestFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate; - + function createCertificationRequest(): Certificate; - - function publicKeyToAsn1(publicKey: Key): any; - - function publicKeyToRSAPublicKey(publicKey: Key): any; + + function publicKeyToAsn1(publicKey: PublicKey): any; + + function publicKeyToRSAPublicKey(publicKey: PublicKey): any; + } + + namespace random { + function getBytes(count: number, callback?: (bytes: Bytes) => any): Bytes; + function getBytesSync(count: number): Bytes; + type CB = (_: any, seed: string) => void; + interface Random { + seedFileSync: (needed: number) => string; + seedFile: (needed: number, cb: CB) => void; + } + function createInstance(): Random; } namespace ssh { @@ -249,22 +302,22 @@ declare module "node-forge" { /** * @description Encodes a private RSA key as an OpenSSH file */ - function privateKeyToOpenSSH(privateKey: pki.Key, passphrase?: string): string; + function privateKeyToOpenSSH(privateKey: pki.PrivateKey, passphrase?: string): string; /** * @description Encodes (and optionally encrypts) a private RSA key as a Putty PPK file */ - function privateKeyToPutty(privateKey: pki.Key, passphrase?: string, comment?: string): string; + function privateKeyToPutty(privateKey: pki.PrivateKey, passphrase?: string, comment?: string): string; /** * @description Encodes a public RSA key as an OpenSSH file */ - function publicKeyToOpenSSH(publicKey: pki.Key, comment?: string): string | pki.PEM; + function publicKeyToOpenSSH(publicKey: pki.PublicKey, comment?: string): string | pki.PEM; /** * @description Gets the SSH fingerprint for the given public key */ - function getPublicKeyFingerprint(publicKey: pki.Key, options?: FingerprintOptions): util.ByteStringBuffer | Hex | string; + function getPublicKeyFingerprint(publicKey: pki.PublicKey, options?: FingerprintOptions): util.ByteStringBuffer | Hex | string; } namespace asn1 { @@ -377,7 +430,7 @@ declare module "node-forge" { function decodeUtf8(encoded: Utf8): string; function createBuffer(): ByteBuffer; - function createBuffer(input: string, encode: string): ByteBuffer; + function createBuffer(input: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer, encode: string): ByteBuffer; namespace binary { namespace raw { @@ -418,7 +471,7 @@ declare module "node-forge" { interface Bag { type: string; attributes: any; - key?: pki.Key; + key?: pki.PrivateKey; cert?: pki.Certificate; asn1: asn1.Asn1 } @@ -441,12 +494,12 @@ declare module "node-forge" { function pkcs12FromAsn1(obj: any, strict?: boolean, password?: string): Pkcs12Pfx; function pkcs12FromAsn1(obj: any, password?: string): Pkcs12Pfx; } - + namespace pkcs7 { interface PkcsSignedData { content?: string | util.ByteBuffer; contentInfo?: { value: any[] }; - + addCertificate(certificate: pki.Certificate): void; addSigner(options: { key: string; @@ -459,14 +512,16 @@ declare module "node-forge" { }): void; toAsn1(): asn1.Asn1; } - + function createSignedData(): PkcsSignedData; } namespace md { + type Encoding = "raw" | "utf8" + interface MessageDigest { - update(msg: string, encoding?: string): MessageDigest; + update(msg: string, encoding?: Encoding): MessageDigest; digest(): util.ByteStringBuffer; } @@ -477,7 +532,7 @@ declare module "node-forge" { namespace sha256 { function create(): MessageDigest; } - + namespace sha512 { function create(): MessageDigest; } @@ -513,18 +568,16 @@ declare module "node-forge" { tag: util.ByteStringBuffer; } } - + namespace pss { - function create(any: any): any; + type PSS = any; + + function create(any: any): PSS; } - + namespace mgf { namespace mgf1 { function create(any: any): any; } } - - namespace random { - function getBytesSync(length: number): Bytes; - } } diff --git a/types/node-forge/node-forge-tests.ts b/types/node-forge/node-forge-tests.ts index abc863f7ff..62f0718c21 100644 --- a/types/node-forge/node-forge-tests.ts +++ b/types/node-forge/node-forge-tests.ts @@ -8,9 +8,7 @@ let x: string = forge.ssh.privateKeyToOpenSSH(key); let pemKey: forge.pki.PEM = publicKeyPem; let publicKeyRsa = forge.pki.publicKeyFromPem(pemKey); let privateKeyRsa = forge.pki.privateKeyFromPem(privateKeyPem); -let privateKeyRsa2 = forge.pki.privateKeyInfoToPem(privateKeyRsa); let byteBufferString = forge.pki.pemToDer(privateKeyPem); -let certPem = forge.pki.certificateFromPem(pemKey); let cert = forge.pki.createCertificate(); { @@ -118,6 +116,7 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin } { + let key = forge.random.getBytesSync(24) let payload = { asd: 'asd' }; let cipher = forge.cipher.createCipher('3DES-ECB', forge.util.createBuffer(key, 'raw')); cipher.start(); @@ -133,7 +132,7 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin let decrypted = decipher.output as forge.util.ByteStringBuffer; let content = JSON.parse(forge.util.encodeUtf8(decrypted.getBytes())); - if (content.asd == payload.asd) throw Error('forge.cipher.createCipher failed'); + if (content.asd !== payload.asd) throw Error('forge.cipher.createCipher failed'); } { @@ -189,3 +188,37 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin // self-sign certificate cert.sign(keypair.privateKey, forge.md.sha256.create()); } + +{ + let md: forge.md.MessageDigest; + let hex: string; + let signature: forge.Bytes + + md = forge.md.sha256.create(); + md = md.update('Test'); + hex = md.digest().toHex(); + + signature = keypair.privateKey.sign(md) + if (!keypair.publicKey.verify(md.digest().bytes(), signature)) { + throw Error("rsa signature verification fail"); + } +} + +{ + const emptyStore = forge.pki.createCaStore(); + + const certificate = forge.pki.createCertificate(); + const pem = forge.pki.certificateToPem(certificate); + + const caStore = forge.pki.createCaStore(); + caStore.addCertificate(certificate); + caStore.removeCertificate(certificate); + + caStore.listAllCertificates(); + + caStore.removeCertificate(certificate); + + forge.pki.verifyCertificateChain(caStore, [certificate], (verified, depth, chain) => { + return true; + }); +} diff --git a/types/node-ral/node-ral-tests.ts b/types/node-ral/node-ral-tests.ts index a625c37da4..3c6f6cd9b1 100644 --- a/types/node-ral/node-ral-tests.ts +++ b/types/node-ral/node-ral-tests.ts @@ -17,7 +17,7 @@ class HashringBalance extends nodeRal.Balance { return 'hashring'; } fetchServer(balanceContext: nodeRal.Balance.BalanceContextClass, conf: {}, prevBackend: nodeRal.Server) { - return {}; + return {} as nodeRal.Server; } } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index fdda9e948a..f484e48703 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1126,10 +1126,10 @@ declare module "http" { 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; - 'authorization'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; + 'authorization'?: string; 'cache-control'?: string; 'connection'?: string; 'content-disposition'?: string; @@ -1139,14 +1139,24 @@ declare module "http" { 'content-location'?: string; 'content-range'?: string; 'content-type'?: string; + 'cookie'?: string; 'date'?: string; + 'expect'?: string; 'expires'?: string; + 'forwarded'?: string; + 'from'?: string; 'host'?: string; + 'if-match'?: string; + 'if-modified-since'?: string; + 'if-none-match'?: string; + 'if-unmodified-since'?: string; 'last-modified'?: string; 'location'?: string; 'pragma'?: string; 'proxy-authenticate'?: string; + 'proxy-authorization'?: string; 'public-key-pins'?: string; + 'range'?: string; 'referer'?: string; 'retry-after'?: string; 'set-cookie'?: string[]; @@ -1608,6 +1618,131 @@ declare module "cluster" { function eventNames(): string[]; } +declare module "worker_threads" { + import { EventEmitter } from "events"; + import { Readable, Writable } from "stream"; + + const isMainThread: boolean; + const parentPort: null | MessagePort; + const threadId: number; + const workerData: any; + + class MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; + } + + class MessagePort extends EventEmitter { + close(): void; + postMessage(value: any, transferList?: Array): void; + ref(): void; + unref(): void; + start(): void; + + addListener(event: "close", listener: () => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "message", value: any): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "close", listener: () => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface WorkerOptions { + eval?: boolean; + workerData?: any; + stdin?: boolean; + stdout?: boolean; + stderr?: boolean; + } + + class Worker extends EventEmitter { + readonly stdin: Writable | null; + readonly stdout: Readable; + readonly stderr: Readable; + readonly threadId: number; + + constructor(filename: string, options?: WorkerOptions); + + postMessage(value: any, transferList?: Array): void; + ref(): void; + unref(): void; + terminate(callback?: (err: any, exitCode: number) => void): void; + + addListener(event: "error", listener: (err: any) => void): this; + addListener(event: "exit", listener: (exitCode: number) => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: "online", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "error", err: any): boolean; + emit(event: "exit", exitCode: number): boolean; + emit(event: "message", value: any): boolean; + emit(event: "online"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "error", listener: (err: any) => void): this; + on(event: "exit", listener: (exitCode: number) => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: "online", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "error", listener: (err: any) => void): this; + once(event: "exit", listener: (exitCode: number) => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: "online", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "error", listener: (err: any) => void): this; + prependListener(event: "exit", listener: (exitCode: number) => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: "online", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "error", listener: (err: any) => void): this; + prependOnceListener(event: "exit", listener: (exitCode: number) => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: "online", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "error", listener: (err: any) => void): this; + removeListener(event: "exit", listener: (exitCode: number) => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: "online", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "error", listener: (err: any) => void): this; + off(event: "exit", listener: (exitCode: number) => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: "online", listener: () => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } +} + declare module "zlib" { import * as stream from "stream"; @@ -2501,7 +2636,9 @@ declare module "readline" { } declare module "vm" { - interface Context { } + interface Context { + [key: string]: any; + } interface BaseOptions { /** * Specifies the filename used in stack traces produced by this script. @@ -2655,6 +2792,7 @@ declare module "child_process" { windowsHide?: boolean; } + function spawn(command: string, options?: SpawnOptions): ChildProcess; function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; interface ExecOptions { @@ -6257,6 +6395,13 @@ declare module "tls" { * May be used to distinguish TLS sockets from regular ones. */ encrypted: boolean; + + /** + * String containing the selected ALPN protocol. + * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol?: string; + /** * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. * @returns Returns an object representing the cipher name @@ -8302,6 +8447,7 @@ declare module "http2" { peerMaxConcurrentStreams?: number; selectPadding?: (frameLen: number, maxFrameLen: number) => number; settings?: Settings; + createConnection?: (option: SessionOptions) => stream.Duplex; } export type ClientSessionOptions = SessionOptions; @@ -8987,3 +9133,65 @@ declare module "perf_hooks" { const performance: Performance; } + +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + export interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + + /** + * Creates and returns a Tracing object for the given set of categories. + */ + export function createTracing(options: CreateTracingOptions): Tracing; + + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is + * determined by the union of all currently-enabled `Tracing` objects and + * any categories enabled using the `--trace-event-categories` flag. + */ + export function getEnabledCategories(): string; +} diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 20159c70d9..37f8272e87 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -17,6 +17,7 @@ import * as path from "path"; import * as readline from "readline"; import * as childProcess from "child_process"; import * as cluster from "cluster"; +import * as workerThreads from "worker_threads"; import * as os from "os"; import * as vm from "vm"; import * as console2 from "console"; @@ -30,6 +31,7 @@ import * as async_hooks from "async_hooks"; import * as http2 from "http2"; import * as inspector from "inspector"; import * as perf_hooks from "perf_hooks"; +import * as trace_events from "trace_events"; import Module = require("module"); // Specifically test buffer module regression. @@ -2636,6 +2638,8 @@ async function asyncStreamPipelineFinished() { { childProcess.exec("echo test"); childProcess.exec("echo test", { windowsHide: true }); + childProcess.spawn("echo"); + childProcess.spawn("echo", { windowsHide: true }); childProcess.spawn("echo", ["test"], { windowsHide: true }); childProcess.spawn("echo", ["test"], { windowsHide: true, argv0: "echo-test" }); childProcess.spawn("echo", ["test"], { stdio: [0xdeadbeef, "inherit", undefined, "pipe"] }); @@ -2930,6 +2934,56 @@ async function asyncStreamPipelineFinished() { } } +////////////////////////////////////////////////////////////////////// +/// worker_threads tests: https://nodejs.org/api/worker_threads.html /// +////////////////////////////////////////////////////////////////////// + +{ + { + if (workerThreads.isMainThread) { + module.exports = async function parseJSAsync(script: string) { + return new Promise((resolve, reject) => { + const worker = new workerThreads.Worker(__filename, { + workerData: script + }); + worker.on('message', resolve); + worker.on('error', reject); + worker.on('exit', (code) => { + if (code !== 0) + reject(new Error(`Worker stopped with exit code ${code}`)); + }); + }); + }; + } else { + const script = workerThreads.workerData; + workerThreads.parentPort.postMessage(script); + } + } + + { + const { port1, port2 } = new workerThreads.MessageChannel(); + port1.on('message', (message) => console.log('received', message)); + port2.postMessage({ foo: 'bar' }); + } + + { + if (workerThreads.isMainThread) { + const worker = new workerThreads.Worker(__filename); + const subChannel = new workerThreads.MessageChannel(); + worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); + subChannel.port2.on('message', (value) => { + console.log('received:', value); + }); + } else { + workerThreads.parentPort.once('message', (value) => { + assert(value.hereIsYourPort instanceof MessagePort); + value.hereIsYourPort.postMessage('the worker is sending this'); + value.hereIsYourPort.close(); + }); + } + } +} + //////////////////////////////////////////////////// /// os tests : https://nodejs.org/api/os.html //////////////////////////////////////////////////// @@ -3675,6 +3729,12 @@ import * as p from "process"; function test() { throw new repl.Recoverable(new Error("test")); } + + _server.context['key0'] = 1; + _server.context['key1'] = ""; + _server.context['key2'] = true; + _server.context['key3'] = []; + _server.context['key4'] = {}; } } @@ -4668,6 +4728,19 @@ import * as constants from 'constants'; } } +/////////////////////////////////////////////////////////// +/// Trace Events Tests /// +/////////////////////////////////////////////////////////// + +{ + const enabledCategories: string = trace_events.getEnabledCategories(); + const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] }); + const categories: string = tracing.categories; + const enabled: boolean = tracing.enabled; + tracing.enable(); + tracing.disable(); +} + //////////////////////////////////////////////////// /// module tests : http://nodejs.org/api/modules.html //////////////////////////////////////////////////// diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 4678c59c74..3660d87725 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -2390,7 +2390,9 @@ declare module "readline" { } declare module "vm" { - export interface Context { } + export interface Context { + [key: string]: any; + } export interface ScriptOptions { filename?: string; lineOffset?: number; diff --git a/types/nw.js/nw.js-tests.ts b/types/nw.js/nw.js-tests.ts index 853feed3b8..b0387f97a4 100644 --- a/types/nw.js/nw.js-tests.ts +++ b/types/nw.js/nw.js-tests.ts @@ -164,7 +164,7 @@ nw.Screen.chooseDesktopMedia( ["window", "screen"], maxWidth: 1920, maxHeight: 1080 }, - optional: [] + optional: [] as any[] }; //navigator.webkitGetUserMedia( { audio: false, video: constraint }, success_func, fallback_func ); } diff --git a/types/oauth2-server/index.d.ts b/types/oauth2-server/index.d.ts index 27a863051f..a846c489a2 100644 --- a/types/oauth2-server/index.d.ts +++ b/types/oauth2-server/index.d.ts @@ -2,7 +2,8 @@ // Project: https://github.com/oauthjs/node-oauth2-server // Definitions by: Robbie Van Gorkom , // Charles Irick , -// Daniel Fischer +// Daniel Fischer , +// Vitor Santos // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -112,6 +113,56 @@ declare namespace OAuth2Server { redirect(url: string): void; } + abstract class AbstractGrantType { + /** + * Instantiates AbstractGrantType using the supplied options. + * + */ + constructor(options: TokenOptions) + + /** + * Generate access token. Calls Model#generateAccessToken() if implemented. + * + */ + generateAccessToken(client: Client, user: User, scope: string | string[]): Promise; + + /** + * Generate refresh token. Calls Model#generateRefreshToken() if implemented. + * + */ + generateRefreshToken(client: Client, user: User, scope: string | string[]): Promise; + + /** + * Get access token expiration date. + * + */ + getAccessTokenExpiresAt(): Date; + + /** + * Get refresh token expiration date. + * + */ + getRefreshTokenExpiresAt(): Date; + + /** + * Get scope from the request body. + * + */ + getScope(request: Request): string; + + /** + * Validate requested scope. Calls Model#validateScope() if implemented. + * + */ + validateScope(user: User, client: Client, scope: string | string[]): Promise; + + /** + * Retrieve info from the request and client and return token + * + */ + abstract handle(request: Request, client: Client): Promise; + } + interface ServerOptions extends AuthenticateOptions, AuthorizeOptions, TokenOptions { /** * Model object @@ -183,6 +234,11 @@ declare namespace OAuth2Server { * Always revoke the used refresh token and issue a new one for the refresh_token grant. */ alwaysIssueNewRefreshToken?: boolean; + + /** + * Additional supported grant types. + */ + extendedGrantTypes?: { [key: string]: typeof AbstractGrantType }; } /** diff --git a/types/oauth2orize/index.d.ts b/types/oauth2orize/index.d.ts index 798030c7d2..b3a62d01e4 100644 --- a/types/oauth2orize/index.d.ts +++ b/types/oauth2orize/index.d.ts @@ -99,6 +99,7 @@ export class OAuth2Server { decision(options: DecisionOptions, parse: DecisionParseFunction): MiddlewareFunction; decision(parse: DecisionParseFunction): MiddlewareFunction; + decision(): MiddlewareFunction; token(options?: any): MiddlewareFunction; diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index bbbaccf209..3e7f64375f 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -252,7 +252,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -288,7 +288,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
- * + * * * * @@ -326,7 +326,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
- * + * * * * @@ -356,7 +356,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
- * + * * * * @@ -390,7 +390,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
- * + * * * * @@ -421,7 +421,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
- * + * * * * @@ -476,7 +476,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
OneNote Y Y
- * + * * * * @@ -540,7 +540,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
OneNote Y Y
- * + * * * * @@ -596,7 +596,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
- * + * * * * @@ -651,7 +651,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
- * + * * * * @@ -688,9 +688,9 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
- * - * - * + * + * + * *
Office for iPad
Excel Y
Word Y
Office for iPad
Excel Y
Word Y
*/ commerceAllowed: boolean; @@ -713,7 +713,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -751,7 +751,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
- * + * * * * @@ -776,7 +776,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
- * + * * * * @@ -856,7 +856,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
- * + * * * * @@ -885,7 +885,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for iPad
Office for iPad
Excel Y
PowerPoint Y
Word Y
- * + * * * * @@ -936,8 +936,8 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
- * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Outlook Y (Mailbox 1.3)
Office for Windows desktop Office Online (in browser) Office for iPad
Outlook Y (Mailbox 1.3)
*/ source:Source; @@ -969,7 +969,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -1157,6 +1157,13 @@ declare namespace Office { * This is best for user experience and performance. */ displayInIframe?: boolean + /** + * Determines if the pop-up blocker dialog will be shown to the user. Defaults to true. + * + * `true` - The framework displays a pop-up to trigger the navigation and avoid the browser's pop-up blocker. + * `false` - The dialog will not be shown and the developer must handle pop-ups (by providing a user interface artifact to trigger the navigation). + */ + promptBeforeOpen?: boolean; /** * A user-defined item of any type that is returned, unchanged, in the asyncContext property of the AsyncResult object that is passed to a callback. */ @@ -1511,7 +1518,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Outlook Y (Mailbox 1.3)
PowerPoint Y Y Y
- * + * * * * @@ -1578,10 +1585,10 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop
Office for Windows desktop
Excel Y
Outlook Y (in preview)
PowerPoint Y
- * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y
*/ function select(expression: string, callback?: (result: AsyncResult) => void): Binding; @@ -1600,8 +1607,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
PowerPoint Y Y Y Y
*/ enum ActiveView { @@ -1628,10 +1635,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
*/ enum BindingType { @@ -1667,7 +1674,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -1716,7 +1723,7 @@ declare namespace Office { SlideRange, /** * Data is returned or set as an image stream. - * Note: Only applies to data in Excel, Word and PowerPoint. + * Note: Only applies to data in Excel, Word, and PowerPoint. */ Image } @@ -1737,11 +1744,11 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
- * - * - * - * - * + * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
PowerPoint Y Y Y Y
Project Y
Word Y Y Y
*/ enum DocumentMode { @@ -1770,8 +1777,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Word Y Y Y Y
*/ enum CustomXMLNodeType { @@ -1824,7 +1831,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -1846,7 +1853,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Outlook Y Y Y
PowerPoint Y Y
- * + * * *
Office for Windows desktop Office Online (in browser) Office for iPad
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
*/ @@ -1882,10 +1889,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
*/ BindingDataChanged, @@ -1905,10 +1912,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
*/ BindingSelectionChanged, @@ -1933,9 +1940,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
Word Y Y
*/ DocumentSelectionChanged, @@ -1994,7 +2001,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -2027,10 +2034,10 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
- * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
PowerPoint Y Y Y Y
Word Y Y Y Y
*/ enum FileType { @@ -2062,10 +2069,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum FilterType { @@ -2093,7 +2100,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -2141,7 +2148,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y
- * + * * *
Office for Windows desktop Office Online (in browser) Office for iPad
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
*/ @@ -2178,7 +2185,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -2213,10 +2220,10 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y
Word Y Y
- * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum ValueFormat { @@ -2234,7 +2241,7 @@ declare namespace Office { * Represents a binding to a section of the document. * * @remarks - *
Requirement SetsMatrixBinding, TableBinding, TextBinding
+ *
Requirement SetsMatrixBindings, TableBindings, TextBindings
* * The Binding object exposes the functionality possessed by all bindings regardless of type. * @@ -2254,10 +2261,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
*/ interface Binding { @@ -2541,10 +2548,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
*/ document: Document; @@ -2582,10 +2589,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
* @param itemName Name of the bindable object in the document. For Example 'MyExpenses' table in Excel." * @param bindingType The {@link Office.BindingType} for the data. The method returns null if the selected object cannot be coerced into the specified type. @@ -2613,9 +2620,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
* * @param bindingType Specifies the type of the binding object to create. Required. @@ -2648,10 +2655,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
* * @param bindingType Specifies the type of the binding object to create. Required. @@ -2677,10 +2684,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -2706,10 +2713,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
* * @param id Specifies the unique name of the binding object. Required. @@ -2736,10 +2743,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
* * @param id Specifies the unique name to be used to identify the binding object. Required. @@ -2764,8 +2771,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Word Y Y Y Y
*/ interface CustomXmlNode { @@ -2887,8 +2894,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Word Y Y Y Y
*/ interface CustomXmlPart { @@ -2979,8 +2986,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Word Y Y Y Y
*/ interface NodeDeletedEventArgs { @@ -3016,8 +3023,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Word Y Y Y Y
*/ interface NodeInsertedEventArgs { @@ -3047,8 +3054,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Word Y Y Y Y
*/ interface NodeReplacedEventArgs { @@ -3087,8 +3094,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Word Y Y Y
*/ interface CustomXmlParts { @@ -3138,8 +3145,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Word Y Y Y Y
*/ interface CustomXmlPrefixMappings { @@ -3208,10 +3215,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
PowerPoint Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
PowerPoint Y Y Y Y
Word Y Y Y Y
*/ bindings: Bindings; @@ -3230,8 +3237,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Word Y Y Y Y
*/ customXmlParts: CustomXmlParts; @@ -3250,11 +3257,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
PowerPoint Y Y Y Y
Word Y Y Y Y
*/ mode: DocumentMode; @@ -3273,11 +3280,12 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
OneNote Y
PowerPoint Y Y Y Y
Word Y Y Y Y
*/ settings: Settings; @@ -3296,7 +3304,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -3322,11 +3330,12 @@ declare namespace Office { * * *Supported hosts, by platform* *
Office for Windows desktop Office Online (in browser) Office for iPad
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y
- * - * - * - * - * + * + * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
OneNote Y
PowerPoint Y Y Y Y
Project Y
Word Y Y Y Y
* * @param eventType For a Document object event, the eventType parameter can be specified as `Office.EventType.Document.SelectionChanged` or @@ -3354,10 +3363,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
PowerPoint Y Y Y
Word Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
PowerPoint Y Y Y Y
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3381,13 +3388,13 @@ declare namespace Office { * The fileType parameter can be specified by using the {@link Office.FileType} enumeration or text values. But the possible values vary with * the host: * - * Excel Online, Win32, Mac, and iOS: `Office.FileType.Compressed` + * Excel for Windows desktop, iPad, and Excel Online: `Office.FileType.Compressed` + * + * Excel for Mac: `Office.FileType.Compressed`, `Office.FileType.Pdf` * - * PowerPoint on Windows desktop, Mac, and iPad, and PowerPoint Online: `Office.FileType.Compressed`, `Office.FileType.Pdf` + * PowerPoint for Windows desktop, Mac, iPad, and PowerPoint Online: `Office.FileType.Compressed`, `Office.FileType.Pdf` * - * Word on Windows desktop, Word on Mac, and Word Online: `Office.FileType.Compressed`, `Office.FileType.Pdf`, `Office.FileType.Text` - * - * Word on iPad: `Office.FileType.Compressed`, `Office.FileType.Text` + * Word for Windows desktop, Mac, iPad, and Word Online: `Office.FileType.Compressed`, `Office.FileType.Pdf`, `Office.FileType.Text` * * **Support details** * @@ -3399,10 +3406,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
PowerPoint Y Y Y
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
PowerPoint Y Y Y Y
Word Y Y Y Y
* * @param fileType The format in which the file will be returned @@ -3429,10 +3436,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
PowerPoint Y Y Y Y
Word Y Y Y Y
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3480,15 +3487,15 @@ declare namespace Office { * Supported coercionType * * - * Excel, Excel Online, PowerPoint, PowerPoint Online, Word, and Word Online + * Excel, PowerPoint, Project, and Word * `Office.CoercionType.Text` (string) * * - * Excel, Word, and Word Online + * Excel and Word * `Office.CoercionType.Matrix` (array of arrays) * * - * Access, Excel, Word, and Word Online + * Access, Excel, and Word * `Office.CoercionType.Table` (TableData object) * * @@ -3496,7 +3503,7 @@ declare namespace Office { * `Office.CoercionType.Html` * * - * Word and Word Online + * Word * `Office.CoercionType.Ooxml` (Office Open XML) * * @@ -3515,12 +3522,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * - * + * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Project Y Y
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
PowerPoint Y Y Y Y
Project Y
Word Y Y Y Y
* * @param coercionType The type of data structure to return. See the remarks section for each host's supported coercion types. @@ -3562,10 +3568,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
PowerPoint Y Y Y Y
Word Y Y Y
* * @param id The identifier of the object or location to go to. @@ -3591,10 +3597,12 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
OneNote Y
PowerPoint Y Y Y Y
Project Y
Word Y Y Y Y
* * @param eventType The event type. For document can be 'Document.SelectionChanged' or 'Document.ActiveViewChanged'. @@ -3643,15 +3651,15 @@ declare namespace Office { * Supported coercionType * * - * Excel, Excel Online, PowerPoint, PowerPoint Online, Word, and Word Online + * Excel, PowerPoint, Project, and Word * `Office.CoercionType.Text` (string) * * - * Excel, Word, and Word Online + * Excel and Word * `Office.CoercionType.Matrix` (array of arrays) * * - * Access, Excel, Word, and Word Online + * Access, Excel, and Word * `Office.CoercionType.Table` (TableData object) * * @@ -3659,7 +3667,7 @@ declare namespace Office { * `Office.CoercionType.Html` * * - * Word and Word Online + * Word * `Office.CoercionType.Ooxml` (Office Open XML) * * @@ -3678,11 +3686,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
PowerPoint Y Y Y Y
Project Y
Word Y Y Y Y
* * @param data The data to be set. Either a string or {@link Office.CoercionType} value, 2d array or TableData object. @@ -3734,8 +3742,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ getProjectFieldAsync(fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3759,8 +3767,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ getResourceFieldAsync(resourceId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3782,8 +3790,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ getSelectedResourceAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3805,8 +3813,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ getSelectedTaskAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3830,8 +3838,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ getSelectedViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3857,8 +3865,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ getTaskAsync(taskId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3882,8 +3890,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ getTaskFieldAsync(taskId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3907,8 +3915,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ getWSSUrlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3959,8 +3967,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ getMaxTaskIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3986,8 +3994,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ getResourceByIndexAsync(resourceIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -4013,8 +4021,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ getTaskByIndexAsync(taskIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -4041,8 +4049,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -4069,8 +4077,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -4104,9 +4112,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
PowerPoint Y Y Y Y
Word Y Y Y Y
*/ interface File { @@ -4222,9 +4231,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
Word Y Y Y Y
*/ interface MatrixBinding extends Binding { @@ -4317,8 +4326,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y
*/ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -4338,11 +4348,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
PowerPoint Y Y Y Y
Word Y Y Y Y
* * @param settingName The case-sensitive name of the setting to retrieve. @@ -4398,11 +4408,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * - * - * - * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
Excel Y Y
PowerPoint Y Y
Word Y Y
* * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -4431,11 +4441,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
PowerPoint Y Y Y Y
Word Y Y Y Y
* * @param settingName The case-sensitive name of the setting to remove. @@ -4467,10 +4477,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y
* * @param eventType Specifies the type of event to remove. Required. @@ -4524,11 +4533,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
PowerPoint Y Y Y Y
Word Y Y Y Y
* * @param options Provides options for saving settings. @@ -4560,11 +4569,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
PowerPoint Y Y Y Y
Word Y Y Y Y
* * @param settingName The case-sensitive name of the setting to set or create. @@ -4603,9 +4612,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
Word Y Y
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
Word Y Y
*/ interface SettingsChangedEventArgs { @@ -4636,7 +4645,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * *
Office for Windows desktop Office Online (in browser) Office for iPad
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
Word Y Y Y
@@ -4688,10 +4697,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
*/ columnCount: number; @@ -4710,10 +4719,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
*/ hasHeaders: boolean; @@ -4745,10 +4754,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
*/ rowCount: number; @@ -4778,15 +4787,16 @@ declare namespace Office { * * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. * An empty cell indicates that the Office host application doesn't support this method. - * + * * For more information about Office host application and server requirements, see * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. * * *Supported hosts, by platform* * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
* * @param tableData An array of arrays ("matrix") or a TableData object that contains one or more columns of data to add to the table. Required. @@ -4823,10 +4833,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
* * @param rows An array of arrays ("matrix") or a TableData object that contains one or more rows of data to add to the table. Required. @@ -4851,10 +4861,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Access Y
Excel Y Y Y Y
Word Y Y Y Y
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -4877,8 +4887,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5043,8 +5053,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
* * @param cellFormat An array that contains one or more JavaScript objects that specify which cells to target and the formatting to apply to them. @@ -5095,8 +5105,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
* * @param tableOptions An object literal containing a list of property name-value pairs that define the table options to apply. @@ -5173,8 +5183,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
*/ enum Table { @@ -5210,9 +5220,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * + * + * + * *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Word Y Y Y
Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
Excel Y Y Y Y
Word Y Y Y Y
*/ interface TextBinding extends Binding { } @@ -5233,8 +5243,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectProjectFields { @@ -5309,8 +5319,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectResourceFields { @@ -6136,8 +6146,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectTaskFields { @@ -7298,8 +7308,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
Office for Windows desktop Office Online (in browser)
Project Y
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectViewTypes { @@ -21755,18 +21765,19 @@ declare namespace Excel { interface BasicDataValidation { /** * - * Gets or sets the Formula1, i.e. minimum value or value depending of the operator. - When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). - When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. + * Specifies the right-hand operand when the operator property is set to a binary operator such as GreaterThan (the left-hand operand is the value the user tries to enter in the cell). With the ternary operators Between and NotBetween, specifies the lower bound operand. + * For example, setting formula1 to 10 and operator to GreaterThan means that valid data for the range must be greater than 10. + * When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). + * When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. * * [Api set: ExcelApi 1.8] */ formula1: string | number | Range; /** * - * Gets or sets the Formula2, i.e. maximum value or value depending of the operator. - When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). - When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. + * With the ternary operators Between and NotBetween, specifies the upper bound operand. Is not used with the binary operators, such as GreaterThan. + * When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). + * When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. * * [Api set: ExcelApi 1.8] */ @@ -21788,18 +21799,18 @@ declare namespace Excel { interface DateTimeDataValidation { /** * - * Gets or sets the Formula1, i.e. minimum value or value depending of the operator. - When setting the value, it can be passed in as a Date, a Range object, or a string formula (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). - When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. + * Specifies the right-hand operand when the operator property is set to a binary operator such as GreaterThan (the left-hand operand is the value the user tries to enter in the cell). With the ternary operators Between and NotBetween, specifies the lower bound operand. + * When setting the value, it can be passed in as a Date, a Range object, or a string formula (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). + * When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. * * [Api set: ExcelApi 1.8] */ formula1: string | Date | Range; /** * - * Gets or sets the Formula2, i.e. maximum value or value depending of the operator. - When setting the value, it can be passed in as a Date, a Range object, or a string (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). - When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. + * With the ternary operators Between and NotBetween, specifies the upper bound operand. Is not used with the binary operators, such as GreaterThan. + * When setting the value, it can be passed in as a Date, a Range object, or a string (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). + * When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. * * [Api set: ExcelApi 1.8] */ @@ -50826,7 +50837,7 @@ declare namespace Word { getRange(rangeLocation?: "Whole" | "Start" | "End" | "Before" | "After" | "Content"): Word.Range; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.2] * @@ -50836,7 +50847,7 @@ declare namespace Word { insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.2] * @@ -50853,7 +50864,7 @@ declare namespace Word { insertContentControl(): Word.ContentControl; /** * - * Inserts a document at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a document at the specified location. * * [Api set: WordApi 1.2] * @@ -50863,7 +50874,7 @@ declare namespace Word { insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation): Word.Range; /** * - * Inserts a document at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a document at the specified location. * * [Api set: WordApi 1.2] * @@ -50873,7 +50884,7 @@ declare namespace Word { insertFileFromBase64(base64File: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts HTML at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts HTML at the specified location. * * [Api set: WordApi 1.2] * @@ -50883,7 +50894,7 @@ declare namespace Word { insertHtml(html: string, insertLocation: Word.InsertLocation): Word.Range; /** * - * Inserts HTML at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts HTML at the specified location. * * [Api set: WordApi 1.2] * @@ -50913,7 +50924,7 @@ declare namespace Word { insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.InlinePicture; /** * - * Inserts OOXML at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts OOXML at the specified location. * * [Api set: WordApi 1.2] * @@ -50923,7 +50934,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: Word.InsertLocation): Word.Range; /** * - * Inserts OOXML at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts OOXML at the specified location. * * [Api set: WordApi 1.2] * @@ -50933,7 +50944,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.2] * @@ -50943,7 +50954,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.2] * @@ -50953,7 +50964,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * - * Inserts text at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts text at the specified location. * * [Api set: WordApi 1.2] * @@ -50963,7 +50974,7 @@ declare namespace Word { insertText(text: string, insertLocation: Word.InsertLocation): Word.Range; /** * - * Inserts text at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts text at the specified location. * * [Api set: WordApi 1.2] * @@ -51774,7 +51785,7 @@ declare namespace Word { getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.1] * @@ -51784,7 +51795,7 @@ declare namespace Word { insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.1] * @@ -51881,7 +51892,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.1] * @@ -51891,7 +51902,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.1] * @@ -51901,7 +51912,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -51913,7 +51924,7 @@ declare namespace Word { insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation, values?: string[][]): Word.Table; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -52352,7 +52363,7 @@ declare namespace Word { getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.1] * @@ -52362,7 +52373,7 @@ declare namespace Word { insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.1] * @@ -52459,7 +52470,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.1] * @@ -52469,7 +52480,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.1] * @@ -52479,7 +52490,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -52491,7 +52502,7 @@ declare namespace Word { insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation, values?: string[][]): Word.Table; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -53354,7 +53365,7 @@ declare namespace Word { insertContentControl(): Word.ContentControl; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.3] * @@ -53364,7 +53375,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.3] * @@ -53374,7 +53385,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -53386,7 +53397,7 @@ declare namespace Word { insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation, values?: string[][]): Word.Table; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * diff --git a/types/ol/ol-tests.ts b/types/ol/ol-tests.ts index ca099420cd..be19e61a2b 100644 --- a/types/ol/ol-tests.ts +++ b/types/ol/ol-tests.ts @@ -303,7 +303,7 @@ import VectorTile from 'ol/vectortile'; import View from 'ol/view'; // Map -const map: ol.Map = new Map( {}); +const map: ol.Map = new Map({} as any); declare const mapView: View; declare const layerBase: LayerBase; declare const control: ControlControl; @@ -320,6 +320,6 @@ declare const size: ol.Size; declare const position: ol.Pixel; view = map.getView(); view.getProjection(); -view.animate( {}); -view.calculateExtent( 'size'); +view.animate({} as any); +view.calculateExtent('size' as any); view.centerOn(coordinate, size, position); diff --git a/types/openapi-factory/index.d.ts b/types/openapi-factory/index.d.ts new file mode 100644 index 0000000000..e41958e6df --- /dev/null +++ b/types/openapi-factory/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for openapi-factory 4.2 +// Project: https://github.com/wparad/openapi-factory.js +// Definitions by: Daan Boerlage +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare namespace OpenApi { + interface ApiOptions { + requestMiddleware?: () => any; + responseMiddleware?: () => any; + errorMiddleware?: () => any; + } + + interface HttpMethodOptions { + rawBody?: boolean; + } + + interface HttpResponse { + statusCode?: number; + headers?: object; + body?: (object | string); + } +} + +declare class OpenApi { + constructor(options: OpenApi.ApiOptions, overrideLogger?: () => void); + + setAuthorizer(authorizerFunc: (req?: any) => Promise): void; + onEvent(onEventFunc: (req?: any) => Promise): void; + onSchedule(onScheduleFunc: (req?: any) => Promise): void; + + head(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + head(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: any) => any): void; + + get(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + get(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + post(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + post(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + put(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + put(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + patch(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + patch(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + delete(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + delete(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + options(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + options(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + any(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + any(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + handler(event: object, context: object): Promise; +} + +export = OpenApi; diff --git a/types/openapi-factory/openapi-factory-tests.ts b/types/openapi-factory/openapi-factory-tests.ts new file mode 100644 index 0000000000..8213104a44 --- /dev/null +++ b/types/openapi-factory/openapi-factory-tests.ts @@ -0,0 +1,29 @@ +import OpenApiFactory = require('openapi-factory'); + +const api = new OpenApiFactory({}); + +api.setAuthorizer((req: any) => req); +api.onEvent((req: any) => req); +api.onSchedule((req: any) => req); + +const testReponse = { + statusCode: 200 +}; + +api.head('/v1/test', () => testReponse); +api.get('/v1/test', () => testReponse); +api.post('/v1/test', () => testReponse); +api.put('/v1/test', () => testReponse); +api.patch('/v1/test', () => testReponse); +api.delete('/v1/test', () => testReponse); +api.options('/v1/test', () => testReponse); +api.any('/v1/test2', () => testReponse); + +api.head('/v2/test', { rawBody: true }, () => testReponse); +api.get('/v2/test', { rawBody: true }, () => testReponse); +api.post('/v2/test', { rawBody: true }, () => testReponse); +api.put('/v2/test', { rawBody: true }, () => testReponse); +api.patch('/v2/test', { rawBody: true }, () => testReponse); +api.delete('/v2/test', { rawBody: true }, () => testReponse); +api.options('/v2/test', { rawBody: true }, () => testReponse); +api.any('/v2/test2', { rawBody: true }, () => testReponse); diff --git a/types/openapi-factory/tsconfig.json b/types/openapi-factory/tsconfig.json new file mode 100644 index 0000000000..e9035817a2 --- /dev/null +++ b/types/openapi-factory/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "openapi-factory-tests.ts" + ] +} diff --git a/types/openapi-factory/tslint.json b/types/openapi-factory/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/openapi-factory/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/openfin/index.d.ts b/types/openfin/index.d.ts index 55ee5b6741..78b1801b0b 100644 --- a/types/openfin/index.d.ts +++ b/types/openfin/index.d.ts @@ -420,7 +420,7 @@ declare namespace fin { /** * The timeout for displaying a notification.Can be in milliseconds or "never". */ - duration?: number | "never"; + timeout?: number | "never"; /** * The url of the notification */ @@ -804,9 +804,9 @@ declare namespace fin { */ getSnapshot(callback?: (base64Snapshot: string) => void, errorCallback?: (reason: string) => void): void; /** - * Gets the current state ("minimized", "maximized", or "restored") of the window. + * Gets the current state ("minimized", "maximized", or "normal") of the window. */ - getState(callback?: (state: "minimized" | "maximized" | "restored") => void, errorCallback?: (reason: string) => void): void; + getState(callback?: (state: "minimized" | "maximized" | "normal") => void, errorCallback?: (reason: string) => void): void; /** * Returns the zoom level of the window. */ diff --git a/types/openfin/openfin-tests.ts b/types/openfin/openfin-tests.ts index 167a6c86be..e4430ff9c2 100644 --- a/types/openfin/openfin-tests.ts +++ b/types/openfin/openfin-tests.ts @@ -207,7 +207,7 @@ function test_notification() { notification.close(); // sendMessage notification = new fin.desktop.Notification({ - duration: 10, + timeout: 10, url: "http://localhost:5000/Account/Register", message: "Hello", onShow: () => { }, diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index 3214bad15c..b0356122e4 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -12494,6 +12494,7 @@ export namespace olx { renderer?: (ol.RendererType | Array<(ol.RendererType | string)> | string); target?: (Element | string); view?: ol.View; + moveTolerance?: number; } /** diff --git a/types/openlayers/openlayers-tests.ts b/types/openlayers/openlayers-tests.ts index d631a9e9bb..9fb6f0bb3b 100644 --- a/types/openlayers/openlayers-tests.ts +++ b/types/openlayers/openlayers-tests.ts @@ -175,7 +175,7 @@ loadingStrategy = ol.loadingstrategy.tile(tilegrid); // ol.geom.Circle // booleanValue = circle.intersectsExtent(extent); -circle = circle.transform(projectionLike, projectionLike); +circle = circle.transform(projectionLike, projectionLike) as ol.geom.Circle; // // diff --git a/types/openui5/tslint.json b/types/openui5/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/openui5/tslint.json +++ b/types/openui5/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/p-defer/index.d.ts b/types/p-defer/index.d.ts index 7eff607e7d..8386706d89 100644 --- a/types/p-defer/index.d.ts +++ b/types/p-defer/index.d.ts @@ -1,16 +1,17 @@ // Type definitions for p-defer 1.0 // Project: https://github.com/sindresorhus/p-defer // Definitions by: Sam Verschueren +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace pDefer { - interface DeferredPromise { - resolve(value?: U | PromiseLike): Promise; - reject(reason: any): Promise; - promise: Promise; - } -} +export = pDefer; declare function pDefer(): pDefer.DeferredPromise; -export = pDefer; +declare namespace pDefer { + interface DeferredPromise { + resolve(value?: T | PromiseLike): void; + reject(reason: any): void; + promise: Promise; + } +} diff --git a/types/p-defer/p-defer-tests.ts b/types/p-defer/p-defer-tests.ts index 9ea4647620..f61bce624b 100644 --- a/types/p-defer/p-defer-tests.ts +++ b/types/p-defer/p-defer-tests.ts @@ -1,13 +1,13 @@ import pDefer = require('p-defer'); -function delay(deferred: pDefer.DeferredPromise, ms: number) { +function delay(deferred: pDefer.DeferredPromise, ms: number) { setTimeout(deferred.resolve, ms, '🦄'); return deferred.promise; } -let s: string; -async function f() { s = await delay(pDefer(), 100); } +const s: Promise = delay(pDefer(), 100); -async function u() { - const u: Promise = pDefer().resolve(); -} +// $ExpectType void +pDefer().resolve(); +// $ExpectType void +pDefer().reject('oh no'); diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index 016581f16c..5709826f6a 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -1491,7 +1491,7 @@ declare module paper { /** * The color of the stroke. */ - strokeColor: Color | string; + strokeColor: Color | string | null; /** * The width of the stroke. @@ -1539,7 +1539,7 @@ declare module paper { /** * The fill color of the item. */ - fillColor: Color | string; + fillColor: Color | string | null; /** * The fill-rule with which the shape gets filled. Please note that only modern browsers support fill-rules other than 'nonzero'. @@ -1551,7 +1551,7 @@ declare module paper { /** * The shadow color. */ - shadowColor: Color | string; + shadowColor: Color | string | null; /** * The shadow’s blur radius. @@ -4865,7 +4865,7 @@ declare module paper { /** * The current scale factor of the view, as described by its matrix. */ - scaling: number; + scaling: Point; /** * The view’s transformation matrix, defining the view onto the project’s contents (position, zoom level, rotation, etc). diff --git a/types/paper/paper-tests.ts b/types/paper/paper-tests.ts index 165c64b2d8..1d1bc32abe 100644 --- a/types/paper/paper-tests.ts +++ b/types/paper/paper-tests.ts @@ -79,6 +79,8 @@ hitTestResults = paper.project.hitTestAll(hitTestPoint, hitOptionsInterfaceEmpty hitTestResults = paper.project.hitTestAll(hitTestPoint, hitOptionsInterfacePartial); hitTestResults = paper.project.hitTestAll(hitTestPoint, hitOptionsInterfaceFull); +paper.view.scaling = new paper.Point(1, 1); + function Examples() { function BooleanOperations(){ let text = new paper.PointText({ diff --git a/types/passport-azure-ad/bearer-strategy.d.ts b/types/passport-azure-ad/bearer-strategy.d.ts index 30751720f3..6ea48809c1 100644 --- a/types/passport-azure-ad/bearer-strategy.d.ts +++ b/types/passport-azure-ad/bearer-strategy.d.ts @@ -21,7 +21,7 @@ export interface IBearerStrategyOptionWithRequest extends IBearerStrategyOption passReqToCallback: true; } -export class BearerStrategy extends passport.Strategy { +export class BearerStrategy implements passport.Strategy { constructor( options: IBearerStrategyOptionWithRequest, verify: VerifyBearerFunctionWithReq @@ -31,4 +31,4 @@ export class BearerStrategy extends passport.Strategy { name: string; authenticate(req: Request, options?: object): void; -} \ No newline at end of file +} diff --git a/types/passport-azure-ad/oidc-strategy.d.ts b/types/passport-azure-ad/oidc-strategy.d.ts index ac4d984ea2..672694d5a9 100644 --- a/types/passport-azure-ad/oidc-strategy.d.ts +++ b/types/passport-azure-ad/oidc-strategy.d.ts @@ -52,7 +52,7 @@ export type VerifyOIDCFunctionWithReq = ((req: Request, iss: string, sub: string, profile: IProfile, access_token: string, refresh_token: string, params: any, done: VerifyCallback) => void) | ((req: Request, iss: string, sub: string, profile: IProfile, jwtClaims: any, access_token: string, refresh_token: string, params: any, done: VerifyCallback) => void); -export class OIDCStrategy extends passport.Strategy { +export class OIDCStrategy implements passport.Strategy { constructor( options: IOIDCStrategyOptionWithRequest, verify: VerifyOIDCFunction @@ -62,4 +62,4 @@ export class OIDCStrategy extends passport.Strategy { name: string; authenticate(req: Request, options?: object): void; -} \ No newline at end of file +} diff --git a/types/passport-bnet/index.d.ts b/types/passport-bnet/index.d.ts new file mode 100644 index 0000000000..e7ffaaedce --- /dev/null +++ b/types/passport-bnet/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for passport-bnet 2.0 +// Project: https://github.com/Blizzard/passport-bnet#readme +// Definitions by: Ivan Fernandes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Strategy as OAuth2Strategy, VerifyFunction, VerifyFunctionWithRequest, _StrategyOptionsBase } from 'passport-oauth2'; + +declare class BnetStrategy extends OAuth2Strategy { + constructor(options: BnetStrategy.StrategyOptions, verify: VerifyFunction); + constructor(options: BnetStrategy.StrategyOptionsWithRequest, verify: VerifyFunctionWithRequest); +} + +declare namespace BnetStrategy { + // passport--bnet accepts any options that passport-oauth2 accepts, but add the option region and makes authorizationURL and tokenURL optional + interface _BaseBnetOptions extends Partial<_StrategyOptionsBase> { + clientID: string; + clientSecret: string; + + region?: string; + } + + interface StrategyOptions extends _BaseBnetOptions { + passReqToCallback?: false; + } + + interface StrategyOptionsWithRequest extends _BaseBnetOptions { + passReqToCallback: true; + } + + function getHost(region: string): string; + + type Strategy = BnetStrategy; + const Strategy: typeof BnetStrategy; +} + +export = BnetStrategy; diff --git a/types/passport-bnet/passport-bnet-tests.ts b/types/passport-bnet/passport-bnet-tests.ts new file mode 100644 index 0000000000..b02cf40519 --- /dev/null +++ b/types/passport-bnet/passport-bnet-tests.ts @@ -0,0 +1,62 @@ +// Based on passport-oauth2/passport-oauth2-tests.ts + +import BnetStrategy = require("passport-bnet"); +import { Strategy, StrategyOptions, StrategyOptionsWithRequest } from "passport-bnet"; +import { Strategy as OAuth2Strategy, VerifyCallback } from "passport-oauth2"; +import { Request } from "express"; + +const strategyOptions1: StrategyOptions = { + callbackURL: 'http://www.example.com/callback', + clientID: 'dummy', + clientSecret: 'secret', + region: 'us', + scope: "email", + scopeSeparator: ' ', + customHeaders: {} +}; + +function verifyFunction1(_accessToken: string, _refreshToken: string, _profile: any, verifyCallback: VerifyCallback) { + verifyCallback(new Error('unimplemented')); +} + +function verifyFunction2(_accessToken: string, _refreshToken: string, _results: any, _profile: any, verifyCallback: VerifyCallback) { + verifyCallback(new Error('unimplemented')); +} + +const strategy1: BnetStrategy = new BnetStrategy(strategyOptions1, verifyFunction1); + +const strategy2: Strategy = new BnetStrategy(strategyOptions1, verifyFunction2); + +function verifyFunction3(_req: Request, _accessToken: string, _refreshToken: string, _profile: any, verifyCallback: VerifyCallback) { + verifyCallback(undefined, { userid: '1' }); +} + +function verifyFunction4(_req: Request, _accessToken: string, _refreshToken: string, _results: any, _profile: any, verifyCallback: VerifyCallback) { + verifyCallback(undefined, { userid: '1' }); +} + +const strategyOptions2: StrategyOptionsWithRequest = { + authorizationURL: 'http://www.example.com/auth', + callbackURL: 'http://www.example.com/callback', + clientID: 'dummy', + clientSecret: 'secret', + tokenURL: 'http://www.example.com/token', + region: 'us', + scope: "email", + scopeSeparator: ' ', + customHeaders: {}, + passReqToCallback: true +}; + +const strategy3: OAuth2Strategy = new BnetStrategy +(strategyOptions2, verifyFunction3); + +const strategy4: Strategy = new Strategy(strategyOptions2, verifyFunction4); + +class MyStrategy extends BnetStrategy { + useProtectedProperty() { + this._oauth2.get('http://www.example.com/profile', 'token', err => err.statusCode); + this._oauth2.get('http://www.example.com/profile', 'token', (err, result) => result); + this._oauth2.get('http://www.example.com/profile', 'token', (err, result, response) => response); + } +} diff --git a/types/passport-bnet/tsconfig.json b/types/passport-bnet/tsconfig.json new file mode 100644 index 0000000000..28da7a7a65 --- /dev/null +++ b/types/passport-bnet/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "passport-bnet-tests.ts" + ] +} \ No newline at end of file diff --git a/types/passport-bnet/tslint.json b/types/passport-bnet/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/passport-bnet/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/passport-github2/index.d.ts b/types/passport-github2/index.d.ts index 0b2c1f6a5d..4ca8e93124 100644 --- a/types/passport-github2/index.d.ts +++ b/types/passport-github2/index.d.ts @@ -3,12 +3,14 @@ // Definitions by: Yasunori Ohoka // Maarten Mulders // Christoph Werner +// Ivan Fernandes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import passport = require('passport'); import oauth2 = require('passport-oauth2'); import express = require('express'); +import { OutgoingHttpHeaders } from 'http'; export interface Profile extends passport.Profile { profileUrl: string; @@ -25,7 +27,7 @@ export interface StrategyOption extends passport.AuthenticateOptions { authorizationURL?: string; tokenURL?: string; scopeSeparator?: string; - customHeaders?: string; + customHeaders?: OutgoingHttpHeaders; userProfileURL?: string; } @@ -46,7 +48,7 @@ export interface _StrategyOptionsBase extends OAuth2StrategyOptionsWithoutRequir authorizationURL?: string; tokenURL?: string; scopeSeparator?: string; - customHeaders?: string; + customHeaders?: OutgoingHttpHeaders; userProfileURL?: string; } diff --git a/types/passport-oauth2/index.d.ts b/types/passport-oauth2/index.d.ts index d985852bd6..28a1a06348 100644 --- a/types/passport-oauth2/index.d.ts +++ b/types/passport-oauth2/index.d.ts @@ -3,12 +3,14 @@ // Definitions by: Pasi Eronen // Wang Zishi // Eduardo AC +// Ivan Fernandes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import { Request } from 'express'; import { Strategy } from 'passport'; import { OAuth2 } from 'oauth'; +import { OutgoingHttpHeaders } from 'http'; declare class OAuth2Strategy extends Strategy { name: string; @@ -32,6 +34,23 @@ declare class OAuth2Strategy extends Strategy { } declare namespace OAuth2Strategy { + interface Metadata { + authorizationURL: string; + tokenURL: string; + clientID: string; + } + + type StateStoreStoreCallback = (err: Error | null, state: any) => void; + type StateStoreVerifyCallback = (err: Error, ok: boolean, state: any) => void; + + interface StateStore { + store(req: Request, callback: StateStoreStoreCallback): void; + store(req: Request, meta: Metadata, callback: StateStoreStoreCallback): void; + + verify(req: Request, state: string, callback: StateStoreVerifyCallback): void; + verify(req: Request, state: string, meta: Metadata, callback: StateStoreVerifyCallback): void; + } + type VerifyCallback = (err?: Error | null, user?: object, info?: object) => void; type VerifyFunction = @@ -47,6 +66,12 @@ declare namespace OAuth2Strategy { clientID: string; clientSecret: string; callbackURL?: string; + customHeaders?: OutgoingHttpHeaders; + scope?: string | string[]; + scopeSeparator?: string; + sessionKey?: string; + store?: StateStore; + state?: any; } interface StrategyOptions extends _StrategyOptionsBase { passReqToCallback?: false; diff --git a/types/passport-oauth2/passport-oauth2-tests.ts b/types/passport-oauth2/passport-oauth2-tests.ts index 864b2cb9d6..30faeebda0 100644 --- a/types/passport-oauth2/passport-oauth2-tests.ts +++ b/types/passport-oauth2/passport-oauth2-tests.ts @@ -1,5 +1,6 @@ import OAuth2Strategy = require('passport-oauth2'); -import { Strategy, StrategyOptions, StrategyOptionsWithRequest, VerifyCallback, AuthorizationError, TokenError, InternalOAuthError } from 'passport-oauth2'; +import { Strategy, StrategyOptions, StrategyOptionsWithRequest, VerifyCallback, AuthorizationError, TokenError, + InternalOAuthError, Metadata, StateStore, StateStoreStoreCallback, StateStoreVerifyCallback } from 'passport-oauth2'; import { Strategy as PassportStrategy } from 'passport'; import { Request } from 'express'; @@ -56,3 +57,34 @@ class MyStrategy extends OAuth2Strategy { this._oauth2.get('http://www.example.com/profile', 'token', (err, result, response) => response); } } + +const metadata: Metadata = { + authorizationURL: 'http://www.example.com/auth', + clientID: 'dummy', + tokenURL: 'http://www.example.com/token' +}; + +class MyStore implements StateStore { + store(req: Request, meta: StateStoreStoreCallback | Metadata, callback?: StateStoreStoreCallback): void {} + verify(req: Request, state: string, meta: StateStoreVerifyCallback | Metadata, callback?: StateStoreVerifyCallback): void {} +} + +const myStore = new MyStore(); + +const strategyOptions3: StrategyOptions = { + authorizationURL: 'http://www.example.com/auth', + clientID: 'dummy', + clientSecret: 'secret', + tokenURL: 'http://www.example.com/token', + callbackURL: 'http://www.example.com/callback', + customHeaders: { + 'content-type': 'text/html' + }, + scope: ['scope1', 'scope2'], + scopeSeparator: ' ', + sessionKey: 'oauth', + state: {id: 1}, + store: myStore +}; + +const strategy5: Strategy = new Strategy(strategyOptions3, verifyFunction2); diff --git a/types/passport-saml/index.d.ts b/types/passport-saml/index.d.ts index cc2faafe5c..9338b88deb 100644 --- a/types/passport-saml/index.d.ts +++ b/types/passport-saml/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/bergie/passport-saml // Definitions by: Chris Barth // Damian Assennato +// Karol Samborski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/passport-saml/multiSamlStrategy.d.ts b/types/passport-saml/multiSamlStrategy.d.ts new file mode 100644 index 0000000000..405c7264dc --- /dev/null +++ b/types/passport-saml/multiSamlStrategy.d.ts @@ -0,0 +1,10 @@ +import express = require('express'); +import { Strategy, SamlConfig, VerifyWithRequest, VerifyWithoutRequest } from './index'; + +export interface MultiSamlConfig extends SamlConfig { + getSamlOptions(req: express.Request, callback: (err: Error | null, samlOptions: SamlConfig) => void): void; +} + +export class MultiSamlStrategy extends Strategy { + constructor(config: MultiSamlConfig, verify: VerifyWithRequest | VerifyWithoutRequest); +} diff --git a/types/passport-saml/passport-saml-tests.ts b/types/passport-saml/passport-saml-tests.ts index 615c1b7320..b22421fe81 100644 --- a/types/passport-saml/passport-saml-tests.ts +++ b/types/passport-saml/passport-saml-tests.ts @@ -1,6 +1,7 @@ import express = require('express'); import passport = require('passport'); import SamlStrategy = require('passport-saml'); +import MultiSamlStrategy = require('passport-saml/multiSamlStrategy'); import fs = require('fs'); const samlStrategy = new SamlStrategy.Strategy( @@ -33,3 +34,27 @@ passport.use(samlStrategy); passport.authenticate('samlCustomName', {failureRedirect: '/', failureFlash: true}); const metadata = samlStrategy.generateServiceProviderMetadata("decryptionCert"); + +const multiSamlStrategy = new MultiSamlStrategy.MultiSamlStrategy( + { + name: 'samlCustomName', + path: '/login/callback', + entryPoint: 'https://openidp.feide.no/simplesaml/saml2/idp/SSOService.php', + issuer: 'passport-saml', + getSamlOptions(req: express.Request, callback: (err: Error | null, samlOptions: SamlStrategy.SamlConfig) => void) { + callback(null, { + name: 'samlCustomName', + path: '/login/callback2', + entryPoint: 'https://openidp.feide.no/simplesaml/saml2/idp/SSOService.php', + issuer: 'passport-saml', + }); + } + }, + (profile: {}, done: (err: Error | null, user: {}, info?: {}) => void) => { + const user = {}; + done(null, user); + } +); + +passport.use(multiSamlStrategy); +passport.authenticate('samlCustomName', {failureRedirect: '/', failureFlash: true}); diff --git a/types/passport-saml/tsconfig.json b/types/passport-saml/tsconfig.json index 0809dbbaf7..39283fa663 100644 --- a/types/passport-saml/tsconfig.json +++ b/types/passport-saml/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "multiSamlStrategy.d.ts", "passport-saml-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/physijs/test/collisions.ts b/types/physijs/test/collisions.ts index 20493189e0..41f09e351d 100644 --- a/types/physijs/test/collisions.ts +++ b/types/physijs/test/collisions.ts @@ -90,7 +90,7 @@ spawnBox = (function() { var box_geometry = new THREE.BoxGeometry( 4, 4, 4 ), handleCollision = function( collided_with ) { - var target = this; + var target = this as any; target.collisions = 0; switch (++target.collisions) { @@ -168,4 +168,4 @@ render = function() { render_stats.update(); }; -window.onload = initScene; \ No newline at end of file +window.onload = initScene; diff --git a/types/physijs/test/vehicle.ts b/types/physijs/test/vehicle.ts index b8643de3b0..37f32279a8 100644 --- a/types/physijs/test/vehicle.ts +++ b/types/physijs/test/vehicle.ts @@ -186,11 +186,11 @@ initScene = function() { ); } - input = { + input = { power: null, direction: null, steering: 0 - }; + } as any; document.addEventListener('keydown', function( ev ) { switch ( ev.keyCode ) { case 37: // left diff --git a/types/pigpio/index.d.ts b/types/pigpio/index.d.ts index 79d0ebe0f9..8eaa6491bb 100644 --- a/types/pigpio/index.d.ts +++ b/types/pigpio/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for pigpio 0.4 +// Type definitions for pigpio 1.2 // Project: https://github.com/fivdi/pigpio -// Definitions by: ManerFan +// Definitions by: ManerFan , erikma // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -424,3 +424,27 @@ export function configureClock(microseconds: number, peripheral: number): void; * @param port an unsigned integer specifying the pigpio socket port number */ export function configureSocketPort(port: number): void; + +/** + * Returns the Raspberry Pi hardware revision as an unsigned integer. Returns 0 + * if the hardware revision can not be determined. + */ +export function hardwareRevision(): number; + +/** + * Gets the current unsigned 32-bit integer value of the number of microseconds + * since system boot. This value wraps around the 32-bit space in just over an hour. + * Use tickDiff() to get the difference between two tick values, to + * ensure the correct JavaScript operations are used to account for the possibility + * of overflow. + */ +export function getTick(): number; + +/** + * Returns the difference in microseconds between the end and start tick counts. + * The tick counts can be retrieved using getTick(), or may be passed + * in a GPIO event callback. + * @param startTick The start of the measured interval. An unsigned integer tick value. + * @param endTick The end of the measured interval. An unsigned integer tick value. + */ +export function tickDiff(startTick: number, endTick: number): number; diff --git a/types/pigpio/pigpio-tests.ts b/types/pigpio/pigpio-tests.ts index 90e7d4485d..f756058b03 100644 --- a/types/pigpio/pigpio-tests.ts +++ b/types/pigpio/pigpio-tests.ts @@ -880,6 +880,15 @@ import * as assert from 'assert'; }, 2000); })(); +(function tickAndTickDiff(): void { + const startTick: number = pigpio.getTick(); + setTimeout(() => { + const endTick: number = pigpio.getTick(); + const diff: number = pigpio.tickDiff(startTick, endTick); + assert.ok(diff > 0, 'expected tick count to increase across a timer call'); + }, 50); +})(); + (function gpio_glitch_filter(): void { const Gpio = pigpio.Gpio; const input = new Gpio(7, { diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index bea9987832..8efaa85d33 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -5,6 +5,7 @@ // Christian Rackerseder // GP // Alex Ferrando +// Oleksandr Sidko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -243,13 +244,12 @@ declare namespace P { interface PrettyOptions { /** - * If set to true, it will only covert the unix timestamp to ISO 8601 date format, and reserialize the JSON (equivalent to pino -t). + * Translate the epoch time value into a human readable date and time string. + * This flag also can set the format string to apply when translating the date to human readable format. + * The default format is yyyy-mm-dd HH:MM:ss.l o in UTC. + * For a list of available pattern letters see the {@link https://www.npmjs.com/package/dateformat|dateformat documentation}. */ - timeTransOnly?: boolean; - /** - * A custom function to format the line, is passed the JSON object as an argument and should return a string value. - */ - formatter?(log: LogDescriptor): string; + translateTime?: boolean | string; /** * If set to true, it will print the name of the log level as the first field in the log line. Default: `false`. */ @@ -261,7 +261,24 @@ declare namespace P { /** * If set to true, will add color information to the formatted output message. Default: `false`. */ - forceColor?: boolean; + colorize?: boolean; + /** + * Appends carriage return and line feed, instead of just a line feed, to the formatted log line. + */ + crlf?: boolean; + /** + * Define the log keys that are associated with error like objects. Default: ["err", "error"] + */ + errorLikeObjectKeys?: string[]; + /** + * When formatting an error object, display this list of properties. + * The list should be a comma separated list of properties. Default: '' + */ + errorProps?: string; + /** + * Specify a search pattern according to {@link http://jmespath.org|jmespath} + */ + search?: string; } type Level = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'; diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index d3203b5dd4..3a6283c3e4 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -123,3 +123,16 @@ anotherRedacted.info({ msg: 'another logged with redacted properties', anotherPath: 'Not shown' }); + +const pretty = pino({ + prettyPrint: { + colorize: true, + crlf: false, + errorLikeObjectKeys: ['err', 'error'], + errorProps: '', + levelFirst: false, + messageKey: 'msg', + translateTime: 'UTC:h:MM:ss TT Z', + search: 'foo == `bar`' + } +}); diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index 7c05701e75..4d86533fed 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -1585,7 +1585,7 @@ declare namespace PIXI { constructor( vertexSrc?: string, fragmentSrc?: string, - uniforms?: UniformDataMap + uniformData?: UniformDataMap ); protected _blendMode: number; @@ -2312,7 +2312,7 @@ declare namespace PIXI { ); baseTexture: BaseTexture; - animations: { [key: string]: Texture }; + animations: { [key: string]: Texture[] }; textures: { [key: string]: Texture }; data: any; resolution: number; @@ -3346,6 +3346,7 @@ declare namespace PIXI { spineAtlas: any; spineData: any; textures?: TextureDictionary; + spritesheet?: Spritesheet; } const shared: Loader; } diff --git a/types/pixi.js/pixi.js-tests.ts b/types/pixi.js/pixi.js-tests.ts index 48581e67fe..c311c1281b 100644 --- a/types/pixi.js/pixi.js-tests.ts +++ b/types/pixi.js/pixi.js-tests.ts @@ -1508,7 +1508,7 @@ function filters() { maggot.scale.set(1 + Math.random() * 0.3); //tslint:disable-next-line:whitespace - maggot.original = (maggot.scale).clone(); + maggot.original = (maggot.scale as PIXI.Point).clone(); this.maggots.push(maggot); } diff --git a/types/pollyjs__adapter-fetch/index.d.ts b/types/pollyjs__adapter-fetch/index.d.ts index 3d93435d51..d38313db9d 100644 --- a/types/pollyjs__adapter-fetch/index.d.ts +++ b/types/pollyjs__adapter-fetch/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/adapter-fetch 1.2 +// Type definitions for @pollyjs/adapter-fetch 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/pollyjs__adapter/index.d.ts b/types/pollyjs__adapter/index.d.ts index b3810a67bb..0bc49fd73b 100644 --- a/types/pollyjs__adapter/index.d.ts +++ b/types/pollyjs__adapter/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/adapter 1.2 +// Type definitions for @pollyjs/adapter 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/pollyjs__core/index.d.ts b/types/pollyjs__core/index.d.ts index 83b6b933b9..4f6d308d0d 100644 --- a/types/pollyjs__core/index.d.ts +++ b/types/pollyjs__core/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/core 1.2 +// Type definitions for @pollyjs/core 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -12,8 +12,10 @@ export const Timing: { fixed(ms: number): () => Promise; relative(ratio: number): (ms: number) => Promise; }; + +export type MatchBy = (input: T) => R; export interface PollyConfig { - mode?: MODES; + mode?: MODES | string; adapters?: Array; adapterOptions?: any; @@ -34,20 +36,20 @@ export interface PollyConfig { timing?: ((ms: number) => Promise) | (() => Promise); matchRequestsBy?: { - method?: boolean; - headers?: any; - body?: boolean; + method?: boolean | MatchBy; + headers?: boolean | { exclude: string[] } | MatchBy>; + body?: boolean | MatchBy; order?: boolean; url?: { - protocol?: boolean; - username?: boolean; - password?: boolean; - hostname?: boolean; - port?: boolean; - pathname?: boolean; - query?: boolean; - hash?: boolean; + protocol?: boolean | MatchBy; + username?: boolean | MatchBy; + password?: boolean | MatchBy; + hostname?: boolean | MatchBy; + port?: boolean | MatchBy; + pathname?: boolean | MatchBy; + query?: boolean | MatchBy; + hash?: boolean | MatchBy; }; }; } diff --git a/types/pollyjs__core/pollyjs__core-tests.ts b/types/pollyjs__core/pollyjs__core-tests.ts index 22f5516646..0644eff7f4 100644 --- a/types/pollyjs__core/pollyjs__core-tests.ts +++ b/types/pollyjs__core/pollyjs__core-tests.ts @@ -6,7 +6,74 @@ const polly = new Polly('test recording', { recordFailedRequests: true, adapters: ['xhr', 'fetch'], persister: 'rest', - timing: Timing.relative(3) + timing: Timing.relative(3), + matchRequestsBy: { + method: true, + headers: true, + body: true, + order: true, + + url: { + protocol: true, + username: true, + password: true, + hostname: true, + port: true, + pathname: true, + query: true, + hash: false + } + } +}); + +new Polly('test recording', { + mode: 'replay', + recordFailedRequests: true, + adapters: ['xhr', 'fetch'], + persister: 'rest', + timing: Timing.relative(3), + matchRequestsBy: { + method(method) { + return method.toLowerCase(); + }, + headers: 1 === 1 ? { exclude: ['X-Auth'] } : (headers) => { + delete headers['X-Auth']; + return headers; + }, + body(body) { + const json = JSON.parse(body); + + delete json.email; + return JSON.stringify(json); + }, + + url: { + protocol(protocol) { + return protocol === 'http' ? 'https:' : protocol; + }, + username(username) { + return username === 'johndoe' ? 'username' : username; + }, + password(password) { + return password || 'password'; + }, + hostname(hostname) { + return hostname.replace('.com', '.net'); + }, + port(port) { + return port > 80 ? 3000 : 433; + }, + pathname(pathname) { + return pathname.replace('/api/v1', '/api'); + }, + query(query) { + return { ...query, token: '' }; + }, + hash(hash) { + return hash.replace(/token=[0-9]+/, ''); + } + } + } }); function log(_: string) { diff --git a/types/pollyjs__persister-fs/index.d.ts b/types/pollyjs__persister-fs/index.d.ts index 3d97b382f7..fc7f9ad656 100644 --- a/types/pollyjs__persister-fs/index.d.ts +++ b/types/pollyjs__persister-fs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/persister-fs 1.2 +// Type definitions for @pollyjs/persister-fs 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/pollyjs__persister/index.d.ts b/types/pollyjs__persister/index.d.ts index 45fc1fc250..87e1c27f5b 100644 --- a/types/pollyjs__persister/index.d.ts +++ b/types/pollyjs__persister/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/persister 1.2 +// Type definitions for @pollyjs/persister 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/pollyjs__utils/index.d.ts b/types/pollyjs__utils/index.d.ts index e87392fcee..ca3e7735ef 100644 --- a/types/pollyjs__utils/index.d.ts +++ b/types/pollyjs__utils/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/utils 1.2 +// Type definitions for @pollyjs/utils 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/postcss-url/index.d.ts b/types/postcss-url/index.d.ts new file mode 100644 index 0000000000..361b69f1c7 --- /dev/null +++ b/types/postcss-url/index.d.ts @@ -0,0 +1,148 @@ +// Type definitions for postcss-url 8.0 +// Project: https://github.com/postcss/postcss-url +// Definitions by: Silas Rech +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +import { Plugin } from 'postcss'; + +declare namespace url { + type CustomTransformFunction = ( + asset: { + /** + * Original URL. + */ + url: string; + + /** + * URL pathname. + */ + pathname?: string; + + /** + * Absolute path to asset. + */ + absolutePath?: string; + + /** + * Current relative path to asset. + */ + relativePath?: string; + + /** + * Querystring from URL. + */ + search?: string; + + /** + * Hash from URL. + */ + hash?: string; + }, + dir: { + /** + * PostCSS from option. + */ + from?: string; + + /** + * PostCSS to option. + */ + to?: string; + + /** + * File path. + */ + file?: string; + }, + ) => string; + type CustomHashFunction = (file: Buffer) => string; + type CustomFilterFunction = (file: string) => boolean; + + interface Options { + /** + * URL rewriting mechanism. + * + * @default 'rebase' + */ + url?: 'copy' | 'inline' | 'rebase' | CustomTransformFunction; + + /** + * Specify the maximum file size to inline (in kilobytes). + */ + maxSize?: number; + + /** + * Do not warn when an SVG URL with a fragment is inlined. + * PostCSS-URL does not support partial inlining. + * The entire SVG file will be inlined. + * By default a warning will be issued when this occurs. + * + * @default false + */ + ignoreFragmentWarning?: boolean; + + /** + * Determine wether a file should be inlined. + */ + filter?: RegExp | CustomFilterFunction | string; + + /** + * Specifies whether the URL's fragment identifer value, if present, will be added to the inlined data URI. + * + * @default false + */ + includeUriFragment?: boolean; + + /** + * The fallback method to use if the maximum size is exceeded or the URL contains a hash. + */ + fallback?: CustomTransformFunction; + + /** + * Specify the base path or list of base paths where to search images from. + */ + basePath?: string | string[]; + + /** + * The assets files will be copied in that destination. + * + * @default false + */ + assetsPath?: boolean | string; + + /** + * Rename the path of the files by a hash name. + * + * @default false + */ + useHash?: boolean; + + /** + * Hash options + */ + hashOptions?: { + /** + * Hashing method or custom function. + */ + method?: 'xxhash32' | 'xxhash64' | CustomHashFunction; + + /** + * Shrink hast to certain length. + */ + shrink?: number; + + /** + * Append the original filename in resulting filename. + */ + append?: boolean; + }; + } + + type Url = Plugin; +} + +declare const url: url.Url; +export = url; diff --git a/types/postcss-url/package.json b/types/postcss-url/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-url/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-url/postcss-url-tests.ts b/types/postcss-url/postcss-url-tests.ts new file mode 100644 index 0000000000..a258b49be4 --- /dev/null +++ b/types/postcss-url/postcss-url-tests.ts @@ -0,0 +1,17 @@ +import * as postcss from 'postcss'; +import * as url from 'postcss-url'; + +const standard: postcss.Transformer = url(); + +const single: postcss.Transformer = url({ url: 'copy', assetsPath: 'img', useHash: true }); + +const multiple: postcss.Transformer = url([ + { filter: '**/assets/copy/*.png', url: 'copy', assetsPath: 'img', useHash: true }, + { filter: '**/assets/inline/*.svg', url: 'inline' }, + { filter: '**/assets/**/*.gif', url: 'rebase' }, + { filter: 'cdn/**/*', url: (asset) => `https://cdn.url/${asset.url}` }, +]); + +postcss().use(standard); +postcss().use(single); +postcss().use(multiple); diff --git a/types/postcss-url/tsconfig.json b/types/postcss-url/tsconfig.json new file mode 100644 index 0000000000..c7759ba2d3 --- /dev/null +++ b/types/postcss-url/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "postcss-url-tests.ts" + ] +} diff --git a/types/postcss-url/tslint.json b/types/postcss-url/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-url/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pouchdb-core/pouchdb-core-tests.ts b/types/pouchdb-core/pouchdb-core-tests.ts index c4c1e0e408..911a21e2f7 100644 --- a/types/pouchdb-core/pouchdb-core-tests.ts +++ b/types/pouchdb-core/pouchdb-core-tests.ts @@ -50,7 +50,7 @@ function testBulkDocs() { const isError = ( result: PouchDB.Core.Response | PouchDB.Core.Error ): result is PouchDB.Core.Error => { - return !!( result).error; + return !!(result as PouchDB.Core.Error).error; }; db.bulkDocs([model, model2]).then((result) => { diff --git a/types/pouchdb-upsert/pouchdb-upsert-tests.ts b/types/pouchdb-upsert/pouchdb-upsert-tests.ts index be36580bf7..0f718bb033 100644 --- a/types/pouchdb-upsert/pouchdb-upsert-tests.ts +++ b/types/pouchdb-upsert/pouchdb-upsert-tests.ts @@ -15,7 +15,7 @@ function testUpsert_WithPromise_AndReturnDoc() { // `doc` may be empty if the document didn't already exist, so we have to // cast it to the type containing the required fields. If the document type // had all optional fields, the cast would not be necessary. - return doc; + return doc as UpsertDocModel; }).then((res: PouchDB.UpsertResponse) => { }); } @@ -25,7 +25,7 @@ function testUpsert_WithPromise_AndReturnFalsey() { if (doc.readonly) return false; // Make some updates.... - return doc; + return doc as UpsertDocModel; }).then((res: PouchDB.UpsertResponse) => { }); } @@ -41,7 +41,7 @@ function testUpsert_WithPromise_AndReturnNewObject() { function testUpsert_WithCallback_AndReturnDoc() { db.upsert(docToUpsert._id, (doc) => { // Make some updates.... - return doc; + return doc as UpsertDocModel; }, (error: PouchDB.Core.Error, res: PouchDB.UpsertResponse) => {}); } @@ -51,7 +51,7 @@ function testUpsert_WithCallback_AndReturnFalsey() { if (doc.readonly) return false; // Make some updates.... - return doc; + return doc as UpsertDocModel; }, (error: PouchDB.Core.Error, res: PouchDB.UpsertResponse) => {}); } diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts index 3a64129364..6cef2ef27a 100644 --- a/types/prettier/index.d.ts +++ b/types/prettier/index.d.ts @@ -256,7 +256,7 @@ export function clearConfigCache(): void; export interface SupportLanguage { name: string; since?: string; - parsers: string[]; + parsers: BuiltInParserName[] | string[]; group?: string; tmScope: string; aceMode: string; diff --git a/types/pretty-ms/index.d.ts b/types/pretty-ms/index.d.ts index b1e151cd65..ca9bf663e2 100644 --- a/types/pretty-ms/index.d.ts +++ b/types/pretty-ms/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for pretty-ms 3.2 +// Type definitions for pretty-ms 4.0 // Project: https://github.com/sindresorhus/pretty-ms#readme // Definitions by: BendingBender // ocboogie +// silh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = prettyMs; @@ -14,6 +15,9 @@ declare namespace prettyMs { msDecimalDigits?: number; keepDecimalsOnWholeSeconds?: boolean; compact?: boolean; + unitCount?: number; verbose?: boolean; + separateMs?: boolean; + formatSubMs?: boolean; } } diff --git a/types/pretty-ms/pretty-ms-tests.ts b/types/pretty-ms/pretty-ms-tests.ts index ae5e8120b2..bb5e8a69ec 100644 --- a/types/pretty-ms/pretty-ms-tests.ts +++ b/types/pretty-ms/pretty-ms-tests.ts @@ -7,4 +7,7 @@ str = prettyMs(1335669000, {verbose: true}); str = prettyMs(1335669000, {keepDecimalsOnWholeSeconds: true}); str = prettyMs(1335669000, {secDecimalDigits: 1}); str = prettyMs(1335669000, {msDecimalDigits: 2}); +str = prettyMs(1335669000, {unitCount: 2}); +str = prettyMs(1335669000, {separateMs: true}); +str = prettyMs(1335669000, {formatSubMs: true}); str = prettyMs(new Date(2014, 0, 1, 10, 40).getTime() - new Date(2014, 0, 1, 10, 5).getTime()); diff --git a/types/pretty-ms/v3/index.d.ts b/types/pretty-ms/v3/index.d.ts new file mode 100644 index 0000000000..b1e151cd65 --- /dev/null +++ b/types/pretty-ms/v3/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for pretty-ms 3.2 +// Project: https://github.com/sindresorhus/pretty-ms#readme +// Definitions by: BendingBender +// ocboogie +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = prettyMs; + +declare function prettyMs(input: number, options?: prettyMs.PrettyMsOptions): string; + +declare namespace prettyMs { + interface PrettyMsOptions { + secDecimalDigits?: number; + msDecimalDigits?: number; + keepDecimalsOnWholeSeconds?: boolean; + compact?: boolean; + verbose?: boolean; + } +} diff --git a/types/pretty-ms/v3/pretty-ms-tests.ts b/types/pretty-ms/v3/pretty-ms-tests.ts new file mode 100644 index 0000000000..ae5e8120b2 --- /dev/null +++ b/types/pretty-ms/v3/pretty-ms-tests.ts @@ -0,0 +1,10 @@ +import prettyMs = require('pretty-ms'); + +let str: string; +str = prettyMs(133); +str = prettyMs(1337, {compact: true}); +str = prettyMs(1335669000, {verbose: true}); +str = prettyMs(1335669000, {keepDecimalsOnWholeSeconds: true}); +str = prettyMs(1335669000, {secDecimalDigits: 1}); +str = prettyMs(1335669000, {msDecimalDigits: 2}); +str = prettyMs(new Date(2014, 0, 1, 10, 40).getTime() - new Date(2014, 0, 1, 10, 5).getTime()); diff --git a/types/pretty-ms/v3/tsconfig.json b/types/pretty-ms/v3/tsconfig.json new file mode 100644 index 0000000000..5d4f2d4c31 --- /dev/null +++ b/types/pretty-ms/v3/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "pretty-ms": [ + "pretty-ms/v3" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pretty-ms-tests.ts" + ] +} diff --git a/types/pretty-ms/v3/tslint.json b/types/pretty-ms/v3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pretty-ms/v3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/progress/index.d.ts b/types/progress/index.d.ts index 74596c4c13..6f6e2ea33d 100644 --- a/types/progress/index.d.ts +++ b/types/progress/index.d.ts @@ -10,22 +10,22 @@ /** * These are keys in the options object you can pass to the progress bar along with total as seen in the example above. */ -interface ProgressBarOptions { +export interface ProgressBarOptions { /** * Total number of ticks to complete. */ total: number; - + /** * current completed index */ - curr?: number; - + curr?: number; + /** * head character defaulting to complete character */ - head?: string; - + head?: string; + /** * The displayed width of the progress bar defaulting to total. */ @@ -120,7 +120,7 @@ declare class ProgressBar { * overall completion to. */ update(ratio: number, tokens?: any): void; - + /** * "interrupt" the progress bar and write a message above it. */ @@ -128,7 +128,7 @@ declare class ProgressBar { /** * Terminates a progress bar. - */ + */ terminate(): void; /** @@ -138,4 +138,4 @@ declare class ProgressBar { } declare namespace ProgressBar { } -export = ProgressBar; +export default ProgressBar; diff --git a/types/proj4/index.d.ts b/types/proj4/index.d.ts index afba494556..d7d4cf1ae5 100644 --- a/types/proj4/index.d.ts +++ b/types/proj4/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for proj4 2.3 +// Type definitions for proj4 2.5 // Project: https://github.com/proj4js/proj4js // Definitions by: Denis Carriere +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace proj4 { @@ -21,9 +22,9 @@ declare namespace proj4 { ep2: number; } - interface Static { - forward(coordinates: TemplateCoordinates): number[]; - inverse(coordinates: TemplateCoordinates): number[]; + interface Converter { + forward(coordinates: T): T; + inverse(coordinates: T): T; } interface InterfaceProjection { @@ -38,6 +39,39 @@ declare namespace proj4 { inverse(coordinates: TemplateCoordinates): number[]; } + interface ProjectionDefinition { + title: string; + projName?: string; + ellps?: string; + datum?: string; + datumName?: string; + rf?: number; + lat0?: number; + lat1?: number; + lat2?: number; + lat_ts?: number; + long0?: number; + long1?: number; + long2?: number; + alpha?: number; + longc?: number; + x0?: number; + y0?: number; + k0?: number; + a?: number; + b?: number; + R_A?: true; + zone?: number; + utmSouth?: true; + datum_params?: string | number[]; + to_meter?: number; + units?: string; + from_greenwich?: number; + datumCode?: string; + natGrids?: string; + axis?: string; + } + const defaultDatum: string; function Proj(srsCode: any, callback?: any): InterfaceProjection; @@ -45,23 +79,38 @@ declare namespace proj4 { const WGS84: any; /** - * Depecrated v3 + * @deprecated v3 */ function Point(x: number, y: number, z?: number): InterfaceCoordinates; function Point(coordinates: TemplateCoordinates | string): InterfaceCoordinates; function toPoint(array: number[]): InterfaceCoordinates; - function defs(name: string, projection?: string): any; - function defs(name: string[][]): any; + function defs(name: string, projection: string | ProjectionDefinition): void; + function defs(name: string[][]): undefined[]; + function defs(name: string): ProjectionDefinition; - function transform(source: InterfaceProjection, dest: InterfaceProjection, point: TemplateCoordinates): any; + function transform( + source: InterfaceProjection, + dest: InterfaceProjection, + point: TemplateCoordinates + ): any; function mgrs(coordinates: number[], accuracy: number): string; const version: string; } -declare function proj4(fromProjection: string, toProjection?: string, coordinates?: proj4.TemplateCoordinates): proj4.Static; -declare function proj4(fromProjection: string, coordinates: proj4.TemplateCoordinates): number[]; +declare function proj4(fromProjection: string, toProjection?: string): proj4.Converter; +declare function proj4( + toProjection: string, + coordinates: T +): T; +declare function proj4( + fromProjection: string, + toProjection: string, + coordinates: T +): T; + export = proj4; +export as namespace proj4; diff --git a/types/proj4/proj4-tests.ts b/types/proj4/proj4-tests.ts index 3d1ab1ab9b..7df09014db 100644 --- a/types/proj4/proj4-tests.ts +++ b/types/proj4/proj4-tests.ts @@ -3,31 +3,55 @@ import proj4 = require('proj4'); /////////////////////////////////////////// // Tests data initialisation /////////////////////////////////////////// -const name = 'WGS84'; const epsg = { 4269: '+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees', 4326: '+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees', }; -const point1 = [-71, 41]; -const point2 = {x: 2, y: 5}; -const mgrs = "24XWT783908"; +const firstProjection = epsg[4269]; +const secondProjection = epsg[4326]; + +const pointArr = [-71, 41]; +const pointObj = { x: 2, y: 5 }; /////////////////////////////////////////// // Tests Measurement /////////////////////////////////////////// -proj4(epsg['4269'], epsg['4326'], point1); -proj4(epsg['4269'], point1); -proj4(epsg['4269'], epsg['4326']).forward(point2); -proj4(epsg['4269'], epsg['4326']).inverse(point2); +proj4(firstProjection, secondProjection, pointArr); +proj4(firstProjection, pointArr); + +// $ExpectType number[] +proj4(firstProjection, secondProjection, pointArr); +// $ExpectType { x: number; y: number; } +proj4(firstProjection, secondProjection, pointObj); + +// $ExpectType number[] +proj4(firstProjection, pointArr); +// $ExpectType { x: number; y: number; } +proj4(firstProjection, pointObj); + +// $ExpectType Converter +proj4(firstProjection, secondProjection); +// $ExpectType Converter +proj4(firstProjection); + +// $ExpectType number[] +proj4(firstProjection, secondProjection).forward(pointArr); +// $ExpectType { x: number; y: number; } +proj4(firstProjection, secondProjection).forward(pointObj); +// $ExpectType number[] +proj4(firstProjection, secondProjection).inverse(pointArr); +// $ExpectType { x: number; y: number; } +proj4(firstProjection, secondProjection).inverse(pointObj); /////////////////////////////////// // Named Projections /////////////////////////////////// -proj4.defs('WGS84', epsg['4326']); -proj4.defs([ - ['EPSG:4326', epsg['4326']], - ['EPSG:4269', epsg['4269']] -]); + +// $ExpectType ProjectionDefinition +proj4.defs('WGS84'); +proj4.defs('WGS84', secondProjection); +// $ExpectType undefined[] +proj4.defs([['EPSG:4326', secondProjection], ['EPSG:4269', firstProjection]]); proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')); /////////////////////////////////// diff --git a/types/proj4/tsconfig.json b/types/proj4/tsconfig.json index a55659d52c..02713475d5 100644 --- a/types/proj4/tsconfig.json +++ b/types/proj4/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "proj4-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/promised-ldap/index.d.ts b/types/promised-ldap/index.d.ts new file mode 100644 index 0000000000..8b0182bea6 --- /dev/null +++ b/types/promised-ldap/index.d.ts @@ -0,0 +1,95 @@ +// Type definitions for promised-ldap 0.3 +// Project: https://github.com/stewartml/promised-ldap +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { EventEmitter } from "events"; +import * as ldap from "ldapjs"; + +declare class Client extends EventEmitter { + constructor({ url }: { url: string }); + + search( + base: string, + options: ldap.SearchOptions, + controls?: ldap.Control | ldap.Control[] + ): Promise<{ + entries: any[]; + references: any[]; + }>; + + authenticate(base: string, dn: string, password: string): Promise; + authenticateUser( + base: string, + dn: string, + password: string + ): Promise<{ name: string; email: string; groups: string[] } | null>; + + bind( + dn: string, + password: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + add( + name: string, + entry: object, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + compare( + name: string, + attr: string, + value: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + del(name: string, controls?: ldap.Control | ldap.Control[]): Promise; + + exop( + name: string, + value: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + modify( + name: string, + change: ldap.Change | ldap.Change[], + controls?: ldap.Control | ldap.Control[] + ): Promise; + + modifyDN( + name: string, + newName: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + _search( + base: string, + options: ldap.SearchOptions, + controls?: ldap.Control | ldap.Control[], + _bypass?: boolean + ): Promise; + _search( + base: string, + options: ldap.SearchOptions, + _bypass: boolean + ): Promise; + + starttls( + options: object, + controls: ldap.Control | ldap.Control[], + _bypass?: boolean + ): Promise; + + unbind(): Promise; + + destroy(err?: any): void; +} + +declare namespace Client { + type SearchOptions = ldap.SearchOptions; +} + +export = Client; diff --git a/types/promised-ldap/promised-ldap-tests.ts b/types/promised-ldap/promised-ldap-tests.ts new file mode 100644 index 0000000000..b61f7ef6fc --- /dev/null +++ b/types/promised-ldap/promised-ldap-tests.ts @@ -0,0 +1,39 @@ +import ldap = require("promised-ldap"); +import ldapjs = require("ldapjs"); + +const client = new ldap({ + url: "ldap://127.0.0.1:1389" +}); + +client.authenticate("test", "cn=root", "secret").then((res: any) => { + console.log(res); +}); + +client.authenticateUser("test", "cn=root", "secret").then((res: any) => { + console.log(res); +}); + +client.bind("cn=root", "secret").catch((err: Error) => { + console.error(err); +}); + +const opts: ldap.SearchOptions = { + filter: "(&(l=Seattle)(email=*@foo.com))", + scope: "sub", + attributes: ["dn", "sn", "cn"] +}; + +client._search("o=example", opts).then((res: NodeJS.EventEmitter) => { + console.log(res); +}); + +const change = new ldapjs.Change({ + operation: "add", + modification: { + pets: ["cat", "dog"] + } +}); + +client.modify("cn=foo, o=example", change).catch((err: Error) => { + console.error(err); +}); diff --git a/types/promised-ldap/tsconfig.json b/types/promised-ldap/tsconfig.json new file mode 100644 index 0000000000..89b60715eb --- /dev/null +++ b/types/promised-ldap/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "promised-ldap-tests.ts"] +} diff --git a/types/promised-ldap/tslint.json b/types/promised-ldap/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/promised-ldap/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/prop-types/index.d.ts b/types/prop-types/index.d.ts index 3b0a1164d6..5f95d354dd 100644 --- a/types/prop-types/index.d.ts +++ b/types/prop-types/index.d.ts @@ -5,11 +5,15 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 +export type ReactComponentLike = + | string + | ((props: any, context?: any) => any) + | (new (props: any, context?: any) => any); + export interface ReactElementLike { - type: string | ((...args: any[]) => ReactElementLike); + type: ReactComponentLike; props: any; key: string | number | null; - children?: ReactNodeLike; } export interface ReactNodeArray extends Array {} @@ -28,9 +32,9 @@ export const nominalTypeHack: unique symbol; export type IsOptional = undefined | null extends T ? true : undefined extends T ? true : null extends T ? true : false; -export type RequiredKeys = { [K in keyof V]: V[K] extends Validator ? IsOptional extends true ? never : K : never }[keyof V]; +export type RequiredKeys = { [K in keyof V]-?: Exclude extends Validator ? IsOptional extends true ? never : K : never }[keyof V]; export type OptionalKeys = Exclude>; -export type InferPropsInner = { [K in keyof V]: InferType; }; +export type InferPropsInner = { [K in keyof V]-?: InferType; }; export interface Validator { (props: object, propName: string, componentName: string, location: string, propFullName: string): Error | null; @@ -41,7 +45,7 @@ export interface Requireable extends Validator { isRequired: Validator>; } -export type ValidationMap = { [K in keyof T]-?: Validator }; +export type ValidationMap = { [K in keyof T]?: Validator }; export type InferType = V extends Validator ? T : any; export type InferProps = diff --git a/types/prop-types/prop-types-tests.ts b/types/prop-types/prop-types-tests.ts index a9bde3af00..baf210fdeb 100644 --- a/types/prop-types/prop-types-tests.ts +++ b/types/prop-types/prop-types-tests.ts @@ -129,35 +129,26 @@ type ExtractedPartialProps = PropTypes.InferProps; type ExtractedPropsWithoutAnnotation = PropTypes.InferProps; type ExtractedPropsFromOuterPropsWithoutAnnotation = PropTypes.InferProps['props']; -// $ExpectType: true +// $ExpectType true type ExtractPropsMatch = ExtractedProps extends ExtractedPropsWithoutAnnotation ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractPropsMatch2 = ExtractedPropsWithoutAnnotation extends ExtractedProps ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractPropsMatch3 = ExtractedProps extends Props ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractPropsMatch4 = Props extends ExtractedPropsWithoutAnnotation ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractFromOuterPropsMatch = ExtractedPropsFromOuterProps extends ExtractedPropsFromOuterPropsWithoutAnnotation ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractFromOuterPropsMatch2 = ExtractedPropsFromOuterPropsWithoutAnnotation extends ExtractedPropsFromOuterProps ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractFromOuterPropsMatch3 = ExtractedPropsFromOuterProps extends Props ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractFromOuterPropsMatch4 = Props extends ExtractedPropsFromOuterPropsWithoutAnnotation ? true : false; -// $ExpectType: false +// $ExpectType false type ExtractPropsMismatch = ExtractedPartialProps extends Props ? true : false; -// $ExpectType: {} -type UnmatchedPropKeys = Pick>; -// $ExpectType: {} -type UnmatchedPropKeys2 = Pick>; - PropTypes.checkPropTypes({ xs: PropTypes.array }, { xs: [] }, 'location', 'componentName'); // This would be the type that JSX sees @@ -189,7 +180,7 @@ const componentDefaultProps = { type DefaultizedProps = Defaultize, typeof componentDefaultProps>; type UndefaultizedProps = Undefaultize, typeof componentDefaultProps>; -// $ExpectType: true +// $ExpectType true type DefaultizedPropsTest = { fi?: (...args: any[]) => any; foo?: string | null; @@ -197,7 +188,7 @@ type DefaultizedPropsTest = { baz?: boolean | null; bat?: ReactNode; } extends DefaultizedProps ? true : false; -// $ExpectType: true +// $ExpectType true type UndefaultizedPropsTest = { fi: (...args: any[]) => any; foo?: string | null; diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 8337acfbe4..257ca3cd44 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -1,8 +1,9 @@ // Type definitions for pubnub 4.0 // Project: https://github.com/pubnub/javascript -// Definitions by: bitbankinc , rollymaduk , vitosamson +// Definitions by: bitbankinc , rollymaduk , vitosamson , FlorianDr // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @see https://www.pubnub.com/docs/web-javascript/api-reference-configuration +// TypeScript Version: 2.2 declare class Pubnub { constructor(config: Pubnub.PubnubConfig); @@ -88,6 +89,18 @@ declare class Pubnub { setState( params: Pubnub.SetStateParameters ): Promise; + + encrypt( + data: string, + customCipherKey?: string, + options?: Pubnub.CryptoParameters, + ): any; + + decrypt( + data: object, + customCipherKey?: string, + options?: Pubnub.CryptoParameters + ): any; } declare namespace Pubnub { @@ -296,6 +309,14 @@ declare namespace Pubnub { }; } + // encrypt & decrypt + interface CryptoParameters { + encryptKey?: boolean; + keyEncoding?: string; + keyLength?: number; + mode?: string; + } + interface Categories { PNNetworkUpCategory: string; PNNetworkDownCategory: string; diff --git a/types/pubnub/pubnub-tests.ts b/types/pubnub/pubnub-tests.ts index 1d8b2bb1ca..50660bd942 100644 --- a/types/pubnub/pubnub-tests.ts +++ b/types/pubnub/pubnub-tests.ts @@ -86,3 +86,15 @@ pubnub.setState({ channels: [] }, (status, res) => { pubnub.setState({ channels: [] }).then(res => { console.log(res.state); }); + +const cryptoOptions = { + encryptKey: true, + keyEncoding: 'utf8', + keyLength: 256, + mode: 'cbc' +}; +const mySecret = { + message: 'Hi!', +}; +pubnub.decrypt(mySecret, undefined, cryptoOptions); +pubnub.encrypt('egrah5rwgrehwqh5eh3hwfwef', undefined, cryptoOptions); diff --git a/types/punycode/index.d.ts b/types/punycode/index.d.ts new file mode 100644 index 0000000000..a3048a5e28 --- /dev/null +++ b/types/punycode/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for punycode 2.1 +// Project: https://mths.be/punycode +// Definitions by: Dmitry Guketlev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function decode(input: string): string; +export function encode(input: string): string; +export function toUnicode(input: string): string; +export function toASCII(input: string): string; + +export namespace ucs2 { + function decode(string: string): number[]; + function encode(array: ReadonlyArray): string; +} + +export const version: string; diff --git a/types/punycode/punycode-tests.ts b/types/punycode/punycode-tests.ts new file mode 100644 index 0000000000..4de954fbc7 --- /dev/null +++ b/types/punycode/punycode-tests.ts @@ -0,0 +1,11 @@ +import punycode = require('punycode'); + +const result1: string = punycode.decode('x'); +const result2: string = punycode.encode('x'); +const result3: string = punycode.toASCII('x'); +const result4: string = punycode.toUnicode('x'); + +const ucs2result1: number[] = punycode.ucs2.decode('x'); +const ucs2result2: string = punycode.ucs2.encode([1, 2, 3]); + +const version: string = punycode.version; diff --git a/types/punycode/tsconfig.json b/types/punycode/tsconfig.json new file mode 100644 index 0000000000..0474c0a874 --- /dev/null +++ b/types/punycode/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "punycode-tests.ts" + ] +} diff --git a/types/punycode/tslint.json b/types/punycode/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/punycode/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/puppeteer/DeviceDescriptors.d.ts b/types/puppeteer/DeviceDescriptors.d.ts new file mode 100644 index 0000000000..e457748fda --- /dev/null +++ b/types/puppeteer/DeviceDescriptors.d.ts @@ -0,0 +1,22 @@ +declare namespace devices { + interface Viewport { + width: number; + height: number; + deviceScaleFactor: number; + isMobile: boolean; + hasTouch: boolean; + isLandscape: boolean; + } + + interface Device { + name: string; + userAgent: string; + viewport: Viewport; + } +} + +declare const devices: { + [key: string]: devices.Device; +}; + +export = devices; diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index bfd14d9c35..2051603f69 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for puppeteer 1.10 +// Type definitions for puppeteer 1.11 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch @@ -398,6 +398,8 @@ export interface Cookie { path: string; /** The cookie Unix expiration time in seconds. */ expires: number; + /** The cookie size */ + size: number; /** The cookie http only flag. */ httpOnly: boolean; /** The session cookie flag. */ @@ -414,7 +416,6 @@ export interface DeleteCookie { url?: string; domain?: string; path?: string; - secure?: boolean; } export interface SetCookie { @@ -512,6 +513,9 @@ export interface DirectNavigationOptions extends NavigationOptions { referer?: string; } +/** Accepts values labeled with units. If number, treat as pixels. */ +export type LayoutDimension = string | number; + export type PDFFormat = | "Letter" | "Legal" @@ -579,22 +583,21 @@ export interface PDFOptions { * @default 'Letter' */ format?: PDFFormat; - /** Paper width, accepts values labeled with units. */ - width?: string; - /** Paper height, accepts values labeled with units. */ - height?: string; - /** Paper margins, defaults to none. */ + /** Paper width. */ + width?: LayoutDimension; + /** Paper height. */ + height?: LayoutDimension; + /** Paper margins, defaults to none. */ margin?: { - /** Top margin, accepts values labeled with units. */ - top?: string; - /** Right margin, accepts values labeled with units. */ - right?: string; - /** Bottom margin, accepts values labeled with units. */ - bottom?: string; - /** Left margin, accepts values labeled with units. */ - left?: string; + /** Top margin. */ + top?: LayoutDimension; + /** Right margin. */ + right?: LayoutDimension; + /** Bottom margin. */ + bottom?: LayoutDimension; + /** Left margin. */ + left?: LayoutDimension; }; - /** * Give any CSS @page size declared in the page priority over what is declared in width and * height or format options. @@ -968,7 +971,7 @@ export interface Request { /** * @returns The `Frame` object that initiated the request, or `null` if navigating to error pages */ - frame(): Promise; + frame(): Frame | null; /** * An object with HTTP headers associated with the request. @@ -1177,8 +1180,9 @@ export interface FrameBase extends Evalable { /** * Sets the page content. * @param html HTML markup to assign to the page. + * @param options The navigation parameters. */ - setContent(html: string): Promise; + setContent(html: string, options?: NavigationOptions): Promise; /** * This method fetches an element with `selector`, scrolls it into view if needed, @@ -1395,11 +1399,11 @@ export interface AXNode { /** * Whether the checkbox is checked, or "mixed". */ - checked: boolean | string; + checked: boolean | "mixed"; /** * Whether the toggle button is checked, or "mixed". */ - pressed: boolean | string; + pressed: boolean | "mixed"; /** * The level of a heading. */ @@ -1620,9 +1624,9 @@ export interface Page extends EventEmitter, FrameBase { /** * Determines whether cache is enabled on the page. - * @param enabled Whether or not to enable cache on the page. + * @param [enabled=true] Whether or not to enable cache on the page. */ - setCacheEnabled(enabled: boolean): Promise; + setCacheEnabled(enabled?: boolean): Promise; /** * Sets the cookies on the page. @@ -1715,7 +1719,7 @@ export interface Page extends EventEmitter, FrameBase { } export interface TargetAwaiter { - waitForTarget(predicate: (target: Target) => boolean, options: Timeoutable): Promise; + waitForTarget(predicate: (target: Target) => boolean, options?: Timeoutable): Promise; } /** A Browser is created when Puppeteer connects to a Chromium instance, either through puppeteer.launch or puppeteer.connect. */ @@ -1933,27 +1937,7 @@ export interface Target { url(): string; } -export interface LaunchOptions extends Timeoutable { - /** - * Whether to open chrome in appMode. - * @default false - */ - appMode?: boolean; - /** - * Whether to ignore HTTPS errors during navigation. - * @default false - */ - ignoreHTTPSErrors?: boolean; - /** - * Do not use `puppeteer.defaultArgs()` for launching Chromium. - * @default false - */ - ignoreDefaultArgs?: boolean | string[]; - /** - * Whether to run Chromium in headless mode. - * @default true - */ - headless?: boolean; +export interface LaunchOptions extends ChromeArgOptions, BrowserOptions, Timeoutable { /** * Path to a Chromium executable to run instead of bundled Chromium. If * executablePath is a relative path, then it is resolved relative to current @@ -1961,10 +1945,73 @@ export interface LaunchOptions extends Timeoutable { */ executablePath?: string; /** - * Slows down Puppeteer operations by the specified amount of milliseconds. - * Useful so that you can see what is going on. + * Do not use `puppeteer.defaultArgs()` for launching Chromium. + * @default false */ - slowMo?: number; + ignoreDefaultArgs?: boolean | string[]; + /** + * Close chrome process on Ctrl-C. + * @default true + */ + handleSIGINT?: boolean; + /** + * Close chrome process on SIGTERM. + * @default true + */ + handleSIGTERM?: boolean; + /** + * Close chrome process on SIGHUP. + * @default true + */ + handleSIGHUP?: boolean; + /** + * Whether to pipe browser process stdout and stderr into process.stdout and + * process.stderr. + * @default false + */ + dumpio?: boolean; + /** + * Specify environment variables that will be visible to Chromium. + * @default `process.env`. + */ + env?: { + [key: string]: string | boolean | number; + }; + /** + * Connects to the browser over a pipe instead of a WebSocket. + * @default false + */ + pipe?: boolean; +} + +export interface ChromeArgOptions { + /** + * Whether to run browser in headless mode. + * @default true unless the devtools option is true. + */ + headless?: boolean; + /** + * Additional arguments to pass to the browser instance. + * The list of Chromium flags can be found here. + */ + args?: string[]; + /** + * Path to a User Data Directory. + */ + userDataDir?: string; + /** + * Whether to auto-open a DevTools panel for each tab. + * If this option is true, the headless option will be set false. + */ + devtools?: boolean; +} + +export interface BrowserOptions { + /** + * Whether to ignore HTTPS errors during navigation. + * @default false + */ + ignoreHTTPSErrors?: boolean; /** * Sets a consistent viewport for each page. Defaults to an 800x600 viewport. null disables the default viewport. */ @@ -1988,7 +2035,6 @@ export interface LaunchOptions extends Timeoutable { */ isMobile?: boolean; /** - * * Specifies if viewport supports touch events. * @default false */ @@ -1998,83 +2044,28 @@ export interface LaunchOptions extends Timeoutable { * @default false */ isLandscape?: boolean; - }; + } | null; /** - * Additional arguments to pass to the Chromium instance. List of Chromium - * flags can be found here. + * Slows down Puppeteer operations by the specified amount of milliseconds. + * Useful so that you can see what is going on. */ - args?: string[]; - /** - * Close chrome process on Ctrl-C. - * @default true - */ - handleSIGINT?: boolean; - /** - * Close chrome process on SIGTERM. - * @default true - */ - handleSIGTERM?: boolean; - /** - * Close chrome process on SIGHUP. - * @default true - */ - handleSIGHUP?: boolean; - /** - * Whether to pipe browser process stdout and stderr into process.stdout and - * process.stderr. - * @default false - */ - dumpio?: boolean; - /** Path to a User Data Directory. */ - userDataDir?: string; - /** - * Specify environment variables that will be visible to Chromium. - * @default `process.env`. - */ - env?: { - [key: string]: string | boolean | number; - }; - /** - * Whether to auto-open DevTools panel for each tab. If this option is true, the headless option will be set false. - */ - devtools?: boolean; - /** - * Connects to the browser over a pipe instead of a WebSocket. - * @default false - */ - pipe?: boolean; + slowMo?: number; } -export interface DefaultArgsOptions { - /** - * Whether to run browser in headless mode. - * @default true unless the devtools option is true. - */ - headless?: boolean; - /** - * Additional arguments to pass to the browser instance. - * The list of Chromium flags can be found here. - */ - args?: string[]; - /** - * Path to a User Data Directory. - */ - userDataDir?: string; - /** - * Whether to auto-open a DevTools panel for each tab. - * If this option is true, the headless option will be set false. - */ - devtools?: boolean; -} - -export interface ConnectOptions { +export interface ConnectOptions extends BrowserOptions { /** A browser websocket endpoint to connect to. */ browserWSEndpoint?: string; /** - * Whether to ignore HTTPS errors during navigation. - * @default false + * **Experimental** Specify a custom transport object for Puppeteer to use. */ - ignoreHTTPSErrors?: boolean; + transport?: ConnectionTransport; +} + +export interface ConnectionTransport { + send(message: string): void; + close(): void; + onmessage?(message: string): void; + onclose?(): void; } export interface CDPSession extends EventEmitter { @@ -2119,7 +2110,7 @@ export interface CoverageEntry { /** Attaches Puppeteer to an existing Chromium instance */ export function connect(options?: ConnectOptions): Promise; /** The default flags that Chromium will be launched with */ -export function defaultArgs(options?: DefaultArgsOptions): string[]; +export function defaultArgs(options?: ChromeArgOptions): string[]; /** Path where Puppeteer expects to find bundled Chromium */ export function executablePath(): string; /** The method launches a browser instance with given arguments. The browser will be closed when the parent node.js process is closed. */ diff --git a/types/puppeteer/puppeteer-tests.ts b/types/puppeteer/puppeteer-tests.ts index b708f1bc0c..e2a559d8e6 100644 --- a/types/puppeteer/puppeteer-tests.ts +++ b/types/puppeteer/puppeteer-tests.ts @@ -1,5 +1,6 @@ import * as puppeteer from "puppeteer"; import { TimeoutError } from "puppeteer/Errors"; +import * as Devices from "puppeteer/DeviceDescriptors"; // Accessibility @@ -118,6 +119,7 @@ puppeteer.launch().then(async browser => { }); await page.emulateMedia("screen"); + await page.emulate(Devices['test']); await page.pdf({ path: "page.pdf" }); await page.setRequestInterception(true); @@ -200,6 +202,13 @@ puppeteer.launch().then(async browser => { browser.close(); })(); +// Launching with default viewport disabled +(async () => { + await puppeteer.launch({ + defaultViewport: null + }); +})(); + // Test v0.12 features (async () => { const browser = await puppeteer.launch({ diff --git a/types/puppeteer/tsconfig.json b/types/puppeteer/tsconfig.json index f253604e14..57b57e65aa 100644 --- a/types/puppeteer/tsconfig.json +++ b/types/puppeteer/tsconfig.json @@ -21,6 +21,7 @@ }, "files": [ "Errors.d.ts", + "DeviceDescriptors.d.ts", "index.d.ts", "puppeteer-tests.ts" ] diff --git a/types/q/tslint.json b/types/q/tslint.json index 0bded8e292..4af8abbc8d 100644 --- a/types/q/tslint.json +++ b/types/q/tslint.json @@ -7,6 +7,7 @@ "no-unnecessary-type-assertion": false, "prefer-declare-function": false, "strict-export-declare-modifiers": false, - "unified-signatures": false + "unified-signatures": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/q/v0/tslint.json b/types/q/v0/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/q/v0/tslint.json +++ b/types/q/v0/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/qhistory/index.d.ts b/types/qhistory/index.d.ts index 84bd4e6d83..6269c25e82 100644 --- a/types/qhistory/index.d.ts +++ b/types/qhistory/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for qhistory 1.0 // Project: https://github.com/pshrmn/qhistory#readme -// Definitions by: Diogo Franco +// Definitions by: Jessica Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/qtip2/tslint.json b/types/qtip2/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/qtip2/tslint.json +++ b/types/qtip2/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/rabbitmq-schema/index.d.ts b/types/rabbitmq-schema/index.d.ts new file mode 100644 index 0000000000..3c607115ab --- /dev/null +++ b/types/rabbitmq-schema/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for rabbitmq-schema 2.0 +// Project: https://github.com/tjmehta/rabbitmq-schema +// Definitions by: Alex Duka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +interface Binding { + destination: Exchange | Queue; + source: Exchange; + args?: object; + routingPattern?: string; +} + +interface TopicBinding extends Binding { + routingPattern: string; +} + +interface DirectBinding extends Binding { + routingPattern: string; +} + +interface Topology { + options?: object; +} + +interface Exchange extends Topology { + exchange: string; + type: string; + bindings: Binding[]; +} + +interface FanoutExchange extends Exchange { + type: 'fanout'; +} + +interface TopicExchange extends Exchange { + type: 'topic'; + bindings: TopicBinding[]; +} + +interface DirectExchange extends Exchange { + type: 'direct'; + bindings: DirectBinding[]; +} + +interface Queue extends Topology { + queue: string; + messageSchema: object; +} + +declare class RabbitMQSchema { + constructor(schema: Topology | Topology[], parentPath?: string); + + getExchanges(): Exchange[]; + + getBindings(): Binding[]; + + getQueues(): Queue[]; + + getDirectBindings(): DirectBinding[]; + + validate(schema: Topology | Topology[], parentPath?: string): void; + + validateMessage(exchangeName: string, routingPattern: string, message: T): T; + + getQueueByName(name: string): Queue | void; + + getExchangeByName(name: string): Exchange | void; +} + +export = RabbitMQSchema; diff --git a/types/rabbitmq-schema/rabbitmq-schema-tests.ts b/types/rabbitmq-schema/rabbitmq-schema-tests.ts new file mode 100644 index 0000000000..067c9c3c5a --- /dev/null +++ b/types/rabbitmq-schema/rabbitmq-schema-tests.ts @@ -0,0 +1,16 @@ +import RabbitMqSchema = require('rabbitmq-schema'); + +const topology = {}; + +const rabbitSchema = new RabbitMqSchema({}, ''); + +rabbitSchema.getExchanges(); +rabbitSchema.getBindings(); +rabbitSchema.getQueues(); +rabbitSchema.getDirectBindings(); + +rabbitSchema.getQueueByName('images.jpeg.get'); +rabbitSchema.getExchangeByName('images'); + +rabbitSchema.validate(topology); +rabbitSchema.validateMessage('images', 'images.jpeg.get', {testMsg: 'ok'}); diff --git a/types/rabbitmq-schema/tsconfig.json b/types/rabbitmq-schema/tsconfig.json new file mode 100644 index 0000000000..81e519bb47 --- /dev/null +++ b/types/rabbitmq-schema/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "strictFunctionTypes": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "rabbitmq-schema-tests.ts" + ] +} diff --git a/types/rabbitmq-schema/tslint.json b/types/rabbitmq-schema/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rabbitmq-schema/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/radix64/index.d.ts b/types/radix64/index.d.ts new file mode 100644 index 0000000000..f376184fce --- /dev/null +++ b/types/radix64/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for radix64 1.1 +// Project: https://github.com/maxired/radix64 +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type MethodsString = 'base64' | 'base64URL' | 'base64URLNaturalSort' | 'base64URLASCIISort'; + +interface MethodsEnum { + BASE64: MethodsString; + BASE64URL: MethodsString; + BASE64NATURAL: MethodsString; + BASE64ASCII: MethodsString; + DEFAULT: MethodsString; +} + +interface Radix { + radix64: (number: number, method?: MethodsString) => string; + ascii64: (number: number, pad?: number) => string; + methods: MethodsEnum; +} + +declare const radix: Radix; +export = radix; diff --git a/types/radix64/radix64-tests.ts b/types/radix64/radix64-tests.ts new file mode 100644 index 0000000000..a77554c238 --- /dev/null +++ b/types/radix64/radix64-tests.ts @@ -0,0 +1,11 @@ +import radix64 = require("radix64"); + +const num: string = radix64.radix64(42); + +const numAndEnum: string = radix64.radix64(1337, radix64.methods.BASE64NATURAL); + +const numAndString: string = radix64.radix64(1337, 'base64URL'); + +const asciiNum: string = radix64.ascii64(42); + +const asciiNumAndPad: string = radix64.ascii64(42, 25); diff --git a/types/radix64/tsconfig.json b/types/radix64/tsconfig.json new file mode 100644 index 0000000000..362ad6d26e --- /dev/null +++ b/types/radix64/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "radix64-tests.ts" + ] +} diff --git a/types/radix64/tslint.json b/types/radix64/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/radix64/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index a3bc51c8ca..48888c6ee5 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -777,6 +777,7 @@ declare namespace R { * matches, fn returns undefined. */ cond(fns: ReadonlyArray<[Pred, (...a: any[]) => any]>): (...a: any[]) => any; + cond(fns: ReadonlyArray<[SafePred, (...a: A[]) => B]>): (...a: A[]) => B; /** * Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 2f68808d17..2bd9a55d2f 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1306,14 +1306,21 @@ type Pair = KeyValuePair; }; () => { - const fn = R.cond([ - [R.equals(0), R.always("water freezes at 0°C")], - [R.equals(100), R.always("water boils at 100°C")], - [R.T, (temp: number) => `nothing special happens at ${temp}°C`] + const f = R.cond([ + [x => x === 0, () => "a"], + [() => true, () => "b"], ]); - const a: string = fn(0); // => 'water freezes at 0°C' - const b: string = fn(50); // => 'nothing special happens at 50°C' - const c: string = fn(100); // => 'water boils at 100°C' + f(0); // $ExpectType string + f(""); // $ExpectError + f(1, 2); // $ExpectType string + + const g = R.cond([ + [(a, b) => a === b, () => "a"], + [() => true, () => "b"], + ]); + g(0); + g(""); + g(1, ""); }; () => { diff --git a/types/random-boolean/index.d.ts b/types/random-boolean/index.d.ts new file mode 100644 index 0000000000..3390da9317 --- /dev/null +++ b/types/random-boolean/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for random-boolean 1.0 +// Project: https://github.com/arthurvr/random-boolean#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomBoolean; + +declare function randomBoolean(): boolean; diff --git a/types/random-boolean/random-boolean-tests.ts b/types/random-boolean/random-boolean-tests.ts new file mode 100644 index 0000000000..8ac983e111 --- /dev/null +++ b/types/random-boolean/random-boolean-tests.ts @@ -0,0 +1,4 @@ +import randomBoolean = require('random-boolean'); + +// $ExpectType boolean +randomBoolean(); diff --git a/types/random-boolean/tsconfig.json b/types/random-boolean/tsconfig.json new file mode 100644 index 0000000000..7392190732 --- /dev/null +++ b/types/random-boolean/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "random-boolean-tests.ts" + ] +} diff --git a/types/random-boolean/tslint.json b/types/random-boolean/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-boolean/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-float/index.d.ts b/types/random-float/index.d.ts new file mode 100644 index 0000000000..646d263128 --- /dev/null +++ b/types/random-float/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for random-float 1.0 +// Project: https://github.com/sindresorhus/random-float +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomFloat; + +declare function randomFloat(max: number): number; +declare function randomFloat(min: number, max: number): number; // tslint:disable-line unified-signatures diff --git a/types/random-float/random-float-tests.ts b/types/random-float/random-float-tests.ts new file mode 100644 index 0000000000..663190ce81 --- /dev/null +++ b/types/random-float/random-float-tests.ts @@ -0,0 +1,6 @@ +import randomFloat = require('random-float'); + +// $ExpectType number +randomFloat(5); +// $ExpectType number +randomFloat(10, 100); diff --git a/types/random-float/tsconfig.json b/types/random-float/tsconfig.json new file mode 100644 index 0000000000..faefa13645 --- /dev/null +++ b/types/random-float/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "random-float-tests.ts" + ] +} diff --git a/types/random-float/tslint.json b/types/random-float/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-float/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-int/index.d.ts b/types/random-int/index.d.ts new file mode 100644 index 0000000000..6f7f421976 --- /dev/null +++ b/types/random-int/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for random-int 1.0 +// Project: https://github.com/sindresorhus/random-int +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomInt; + +declare function randomInt(max: number): number; +declare function randomInt(min: number, max: number): number; // tslint:disable-line unified-signatures diff --git a/types/random-int/random-int-tests.ts b/types/random-int/random-int-tests.ts new file mode 100644 index 0000000000..68165e9c5d --- /dev/null +++ b/types/random-int/random-int-tests.ts @@ -0,0 +1,6 @@ +import randomInt = require('random-int'); + +// $ExpectType number +randomInt(5); +// $ExpectType number +randomInt(10, 100); diff --git a/types/random-int/tsconfig.json b/types/random-int/tsconfig.json new file mode 100644 index 0000000000..e1a576d337 --- /dev/null +++ b/types/random-int/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "random-int-tests.ts" + ] +} diff --git a/types/random-int/tslint.json b/types/random-int/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-int/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-item/index.d.ts b/types/random-item/index.d.ts new file mode 100644 index 0000000000..3fbbaca074 --- /dev/null +++ b/types/random-item/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for random-item 1.0 +// Project: https://github.com/sindresorhus/random-item +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomItem; + +declare function randomItem(input: T[]): T; diff --git a/types/random-item/random-item-tests.ts b/types/random-item/random-item-tests.ts new file mode 100644 index 0000000000..12185a0ad2 --- /dev/null +++ b/types/random-item/random-item-tests.ts @@ -0,0 +1,6 @@ +import randomItem = require('random-item'); + +// $ExpectType string +randomItem(['pony', 'unicorn', 'rainbow']); +// $ExpectType string | number +randomItem(['pony', 'unicorn', 'rainbow', 1]); diff --git a/types/random-item/tsconfig.json b/types/random-item/tsconfig.json new file mode 100644 index 0000000000..279aba16b5 --- /dev/null +++ b/types/random-item/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "random-item-tests.ts" + ] +} diff --git a/types/random-item/tslint.json b/types/random-item/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-item/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-obj-key/index.d.ts b/types/random-obj-key/index.d.ts new file mode 100644 index 0000000000..dfe12ca6f6 --- /dev/null +++ b/types/random-obj-key/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for random-obj-key 1.0 +// Project: https://github.com/sindresorhus/random-obj-key +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = randomObjKey; + +declare function randomObjKey(input: TObj): keyof TObj; diff --git a/types/random-obj-key/random-obj-key-tests.ts b/types/random-obj-key/random-obj-key-tests.ts new file mode 100644 index 0000000000..b12cf282ea --- /dev/null +++ b/types/random-obj-key/random-obj-key-tests.ts @@ -0,0 +1,4 @@ +import randomObjKey = require('random-obj-key'); + +// $ExpectType "foo" | "bar" +randomObjKey({ foo: true, bar: true }); diff --git a/types/random-obj-key/tsconfig.json b/types/random-obj-key/tsconfig.json new file mode 100644 index 0000000000..aaaf33ba98 --- /dev/null +++ b/types/random-obj-key/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "random-obj-key-tests.ts" + ] +} diff --git a/types/random-obj-key/tslint.json b/types/random-obj-key/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-obj-key/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-obj-prop/index.d.ts b/types/random-obj-prop/index.d.ts new file mode 100644 index 0000000000..f9aca5624f --- /dev/null +++ b/types/random-obj-prop/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for random-obj-prop 1.0 +// Project: https://github.com/sindresorhus/random-obj-prop +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomObjProp; + +declare function randomObjProp(input: { [key: string]: T }): T; diff --git a/types/random-obj-prop/random-obj-prop-tests.ts b/types/random-obj-prop/random-obj-prop-tests.ts new file mode 100644 index 0000000000..7dd2fcd67d --- /dev/null +++ b/types/random-obj-prop/random-obj-prop-tests.ts @@ -0,0 +1,4 @@ +import randomObjProp = require('random-obj-prop'); + +// $ExpectType string | number +randomObjProp({ foo: 'pony', bar: 1 }); diff --git a/types/random-obj-prop/tsconfig.json b/types/random-obj-prop/tsconfig.json new file mode 100644 index 0000000000..f155cfc211 --- /dev/null +++ b/types/random-obj-prop/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "random-obj-prop-tests.ts" + ] +} diff --git a/types/random-obj-prop/tslint.json b/types/random-obj-prop/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-obj-prop/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/randombytes/index.d.ts b/types/randombytes/index.d.ts new file mode 100644 index 0000000000..049f893870 --- /dev/null +++ b/types/randombytes/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for randombytes 2.0 +// Project: https://github.com/crypto-browserify/randombytes +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { randomBytes as _randomBytes } from 'crypto'; + +export = randomBytes; + +declare const randomBytes: typeof _randomBytes; diff --git a/types/randombytes/randombytes-tests.ts b/types/randombytes/randombytes-tests.ts new file mode 100644 index 0000000000..583fa685ec --- /dev/null +++ b/types/randombytes/randombytes-tests.ts @@ -0,0 +1,11 @@ +import randomBytes = require('randombytes'); + +// $ExpectType Buffer +randomBytes(16); +// $ExpectType void +randomBytes(16, (err, resp) => { + // $ExpectType Error | null + err; + // $ExpectType Buffer + resp; +}); diff --git a/types/randombytes/tsconfig.json b/types/randombytes/tsconfig.json new file mode 100644 index 0000000000..31ecde389d --- /dev/null +++ b/types/randombytes/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "randombytes-tests.ts" + ] +} diff --git a/types/randombytes/tslint.json b/types/randombytes/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/randombytes/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/range-parser/index.d.ts b/types/range-parser/index.d.ts index a1bcf4c9dc..e8e6ae4451 100644 --- a/types/range-parser/index.d.ts +++ b/types/range-parser/index.d.ts @@ -4,11 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** - * Returns `-1` when unsatisfiable and `-2` when syntactically invalid. - * * When ranges are returned, the array has a "type" property which is the type of * range that is required (most commonly, "bytes"). Each array element is an object * with a "start" and "end" property for the portion of the range. + * + * @returns `-1` when unsatisfiable and `-2` when syntactically invalid, ranges otherwise. */ declare function RangeParser(size: number, str: string, options?: RangeParser.Options): RangeParser.Result | RangeParser.Ranges; @@ -27,10 +27,9 @@ declare namespace RangeParser { */ combine?: boolean; } - const enum Result { - invaild = -2, - unsatisifiable = -1, - } + type ResultUnsatisfiable = -1; + type ResultInvalid = -2; + type Result = ResultUnsatisfiable | ResultInvalid; } export = RangeParser; diff --git a/types/range-parser/range-parser-tests.ts b/types/range-parser/range-parser-tests.ts index ec1ffa6e4e..2c18e3f9dc 100644 --- a/types/range-parser/range-parser-tests.ts +++ b/types/range-parser/range-parser-tests.ts @@ -2,8 +2,8 @@ import RangeParser = require('range-parser'); declare var console: { assert(b: boolean): void }; -console.assert(RangeParser(200, `malformed`) === RangeParser.Result.invaild); -console.assert(RangeParser(200, `bytes=500-20`) === RangeParser.Result.unsatisifiable); +console.assert(RangeParser(200, `malformed`) === -2); +console.assert(RangeParser(200, `bytes=500-20`) === -1); const range = RangeParser(1000, `bytes=0-499`); diff --git a/types/range-parser/tsconfig.json b/types/range-parser/tsconfig.json index 15585886a9..dc6de494bf 100644 --- a/types/range-parser/tsconfig.json +++ b/types/range-parser/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "range-parser-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/rc-tooltip/index.d.ts b/types/rc-tooltip/index.d.ts index e752404f21..78a1fb63fb 100644 --- a/types/rc-tooltip/index.d.ts +++ b/types/rc-tooltip/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for rc-tooltip v3.4.2 +// Type definitions for rc-tooltip 3.7 // Project: https://github.com/react-component/tooltip -// Definitions by: rhysd -// ahstro +// Definitions by: rhysd +// ahstro +// vsaarinen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -24,6 +25,7 @@ declare namespace RCTooltip { prefixCls?: string; transitionName?: string; onVisibleChange?: (visible?: boolean) => void; + afterVisibleChange?: (visible?: boolean) => void; visible?: boolean; defaultVisible?: boolean; placement?: Placement | Object; @@ -33,6 +35,7 @@ declare namespace RCTooltip { arrowContent?: React.ReactNode; getTooltipContainer?: () => Element; destroyTooltipOnHide?: boolean; + id?: string; } } diff --git a/types/rc-tooltip/rc-tooltip-tests.tsx b/types/rc-tooltip/rc-tooltip-tests.tsx index 06b230a55b..7219d8579b 100644 --- a/types/rc-tooltip/rc-tooltip-tests.tsx +++ b/types/rc-tooltip/rc-tooltip-tests.tsx @@ -28,12 +28,14 @@ ReactDOM.render( prefixCls="my-" transitionName="cool-transition" onVisibleChange={() => console.log('visible changed')} + afterVisibleChange={() => console.log('after visible changed')} visible defaultVisible onPopupAlign={(popup, align) => console.log('aligned:', popup, align)} arrowContent={
} getTooltipContainer={() => document.querySelector('.foo')} destroyTooltipOnHide + id="tooltip-id" > hover , diff --git a/types/rc-tooltip/tslint.json b/types/rc-tooltip/tslint.json index a41bf5d19a..a0357daa61 100644 --- a/types/rc-tooltip/tslint.json +++ b/types/rc-tooltip/tslint.json @@ -7,7 +7,6 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, diff --git a/types/react-addons-test-utils/index.d.ts b/types/react-addons-test-utils/index.d.ts index 0531c5e3f6..19df32f3dc 100644 --- a/types/react-addons-test-utils/index.d.ts +++ b/types/react-addons-test-utils/index.d.ts @@ -160,11 +160,11 @@ declare namespace TestUtils { root: Component, tagName: string): Element; - export function scryRenderedComponentsWithType, C extends ComponentClass<{}>>( + export function scryRenderedComponentsWithType, C extends ComponentClass>( root: Component, type: ClassType): T[]; - export function findRenderedComponentWithType, C extends ComponentClass<{}>>( + export function findRenderedComponentWithType, C extends ComponentClass>( root: Component, type: ClassType): T; diff --git a/types/react-albus/index.d.ts b/types/react-albus/index.d.ts index be546011d4..ccc0ac8582 100644 --- a/types/react-albus/index.d.ts +++ b/types/react-albus/index.d.ts @@ -9,13 +9,13 @@ import * as React from "react"; import { History } from "history"; -export interface WizardStepObject { +export interface StepObject { id: string; } export interface WizardContext { - step: WizardStepObject; - steps: WizardStepObject[]; + step: StepObject; + steps: StepObject[]; history: History; next: () => void; previous: () => void; @@ -42,13 +42,24 @@ export interface WizardProps { export const Wizard: React.ComponentType; export interface StepsProps { - step?: WizardStepObject; + step?: StepObject; } export const Steps: React.ComponentType; -export type StepProps = { id: string } & ( +export type StepProps = StepObject & ( | { render?: (wizard: WizardContext) => React.ReactNode } | { children: (wizard: WizardContext) => React.ReactNode }); +/** + * In addition to id, any additional props added to will be available on each step object. + * This can be used to add names, descriptions, or other metadata to each step. + * To use this feature globally in your project you need to augment the StepObject + * @example + * declare module "react-albus" { + * interface StepObject { + * propName: string; + * } + * } + */ export const Step: React.ComponentType; diff --git a/types/react-albus/react-albus-tests.tsx b/types/react-albus/react-albus-tests.tsx index 2f31733b1d..57fe8147d1 100644 --- a/types/react-albus/react-albus-tests.tsx +++ b/types/react-albus/react-albus-tests.tsx @@ -1,6 +1,12 @@ import * as React from "react"; import { Wizard, Step, Steps, withWizard } from "react-albus"; +declare module "react-albus" { + interface StepObject { + quote?: string; + } +} + const Example = () => ( ( (

Merlin

@@ -28,6 +35,7 @@ const Example = () => ( /> (

Gandalf

diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index bbfd7047ec..89e6f0eead 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -5,14 +5,23 @@ // Krzysztof Bezrąk // Sebastian Silbermann // Paul Potsides +// janb87 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { Validator } from 'prop-types'; import * as React from 'react'; +export type DayPropGetter = (date: Date) => { className?: string, style?: React.CSSProperties }; +export type EventPropGetter = (event: T, start: stringOrDate, end: stringOrDate, isSelected: boolean) => { className?: string, style?: React.CSSProperties }; +export type SlotPropGetter = (date: Date) => { className?: string, style?: React.CSSProperties }; export type stringOrDate = string | Date; export type ViewKey = 'MONTH' | 'WEEK' | 'WORK_WEEK' | 'DAY' | 'AGENDA'; export type View = 'month' | 'week' | 'work_week' | 'day' | 'agenda'; +export type Views = View[] | { + month: boolean | React.SFC | React.Component, + week: boolean | React.SFC | React.Component, + myweek: boolean | React.SFC | React.Component, +}; export type Navigate = 'PREV' | 'NEXT' | 'TODAY' | 'DATE'; export type Event = object; @@ -70,7 +79,7 @@ export interface Formats { /** * Toolbar header format for the Agenda view, e.g. "4/1/2015 — 5/1/2015" */ - agendaHeaderFormat?: DateFormat; + agendaHeaderFormat?: DateRangeFormatFunction; /** * A time range format for selecting time slots, e.g "8:00am — 2:00pm" @@ -105,14 +114,14 @@ export interface HeaderProps { export interface Components { event?: React.SFC | React.Component | React.ComponentClass | JSX.Element; - eventWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + eventWrapper?: React.ComponentType; dayWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dateCellWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; /** * component used as a header for each column in the TimeGridHeader */ header?: React.ComponentType; - toolbar?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + toolbar?: React.ComponentType; agenda?: { date?: React.SFC | React.Component | React.ComponentClass | JSX.Element; time?: React.SFC | React.Component | React.ComponentClass | JSX.Element; @@ -133,6 +142,42 @@ export interface Components { }; } +export interface ToolbarProps { + date: Date; + view: View; + views: Views; + label: string; + localizer: { messages: Messages }; + onNavigate: (navigate: Navigate, date?: Date) => void; + onView: (view: View) => void; + children?: React.ReactNode; +} + +export interface EventWrapperProps { + // https://github.com/intljusticemission/react-big-calendar/blob/27a2656b40ac8729634d24376dff8ea781a66d50/src/TimeGridEvent.js#L28 + style?: React.CSSProperties & { xOffset: number }; + className: string; + event: T; + isRtl: boolean; + getters: { + eventProp?: EventPropGetter; + slotProp?: SlotPropGetter; + dayProp?: DayPropGetter; + }; + onClick: (e: React.MouseEvent) => void; + onDoubleClick: (e: React.MouseEvent) => void; + accessors: { + title?: (event: T) => string; + tooltip?: (event: T) => string; + end?: (event: T) => Date; + start?: (event: T) => Date; + }; + selected: boolean; + label: string; + continuesEarlier: boolean; + continuesLater: boolean; +} + export interface Messages { date?: string; time?: string; @@ -171,26 +216,22 @@ export class DateLocalizer { format(value: FormatInput, format: string, culture: Culture): string; } -export interface BigCalendarProps extends React.Props> { +export interface BigCalendarProps extends React.Props> { localizer: DateLocalizer; date?: stringOrDate; now?: Date; view?: View; - events?: T[]; - onNavigate?: (newDate: Date, action: Navigate) => void; + events?: TEvent[]; + onNavigate?: (newDate: Date, view: View, action: Navigate) => void; onView?: (view: View) => void; onDrillDown?: (date: Date, view: View) => void; onSelectSlot?: (slotInfo: { start: stringOrDate, end: stringOrDate, slots: Date[] | string[], action: 'select' | 'click' | 'doubleClick' }) => void; - onDoubleClickEvent?: (event: T, e: React.SyntheticEvent) => void; - onSelectEvent?: (event: T, e: React.SyntheticEvent) => void; + onDoubleClickEvent?: (event: TEvent, e: React.SyntheticEvent) => void; + onSelectEvent?: (event: TEvent, e: React.SyntheticEvent) => void; onSelecting?: (range: { start: stringOrDate, end: stringOrDate }) => boolean | undefined | null; selected?: any; - views?: View[] | { - month: boolean | React.SFC | React.Component, - week: boolean | React.SFC | React.Component, - myweek: boolean | React.SFC | React.Component, - }; + views?: Views; drilldownView?: View | null; getDrilldownView?: ((targetDate: Date, currentViewName: View, configuredViewNames: View[]) => void) | null; length?: number; @@ -202,9 +243,9 @@ export interface BigCalendarProps extends React.Props { className?: string, style?: React.CSSProperties }; - slotPropGetter?: (date: Date) => { className?: string, style?: object }; - dayPropGetter?: (date: Date) => { className?: string, style?: object }; + eventPropGetter?: EventPropGetter; + slotPropGetter?: SlotPropGetter; + dayPropGetter?: DayPropGetter; showMultiDayTimes?: boolean; min?: stringOrDate; max?: stringOrDate; @@ -213,14 +254,14 @@ export interface BigCalendarProps extends React.Props string); - allDayAccessor?: keyof T | ((event: T) => boolean); - startAccessor?: keyof T | ((event: T) => Date); - endAccessor?: keyof T | ((event: T) => Date); - resourceAccessor?: keyof T | ((event: T) => any); - resources?: any[]; - resourceIdAccessor?: keyof T | ((event: T) => any); - resourceTitleAccessor?: keyof T | ((event: T) => string); + titleAccessor?: keyof TEvent | ((event: TEvent) => string); + allDayAccessor?: keyof TEvent | ((event: TEvent) => boolean); + startAccessor?: keyof TEvent | ((event: TEvent) => Date); + endAccessor?: keyof TEvent | ((event: TEvent) => Date); + resourceAccessor?: keyof TEvent | ((event: TEvent) => any); + resources?: TResource[]; + resourceIdAccessor?: keyof TResource | ((resource: TResource) => any); + resourceTitleAccessor?: keyof TResource | ((resource: TResource) => string); defaultView?: View; defaultDate?: Date; className?: string; @@ -237,7 +278,7 @@ export interface MoveOptions { today: Date; } -export default class BigCalendar extends React.Component> { +export default class BigCalendar extends React.Component> { components: { dateCellWrapper: React.ComponentType, dayWrapper: React.ComponentType, diff --git a/types/react-big-calendar/react-big-calendar-tests.tsx b/types/react-big-calendar/react-big-calendar-tests.tsx index e1b561901e..fd1e70f929 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; -import BigCalendar, { BigCalendarProps, Navigate, View, DateRange, DateLocalizer } from "react-big-calendar"; +import BigCalendar, { BigCalendarProps, Navigate, View, DateRange, DateLocalizer, ToolbarProps, EventWrapperProps } from "react-big-calendar"; // Don't want to add this as a dependency, because it is only used for tests. declare const globalize: any; @@ -17,13 +17,25 @@ class CalendarEvent { start: Date; end: Date; desc: string; + resourceId?: string; - constructor(_title: string, _start: Date, _end: Date, _allDay?: boolean, _desc?: string) { + constructor(_title: string, _start: Date, _end: Date, _allDay?: boolean, _desc?: string, _resourceId?: string) { this.title = _title; this.allDay = _allDay || false; this.start = _start; this.end = _end; this.desc = _desc || ''; + this.resourceId = _resourceId; + } +} + +class CalendarResource { + title: string; + id: string; + + constructor(id: string, title: string) { + this.id = id; + this.title = title; } } @@ -49,64 +61,70 @@ class CalendarEvent { } { + class MyCalendar extends BigCalendar {} + // Full API Example Test - based on API Documentation // http://intljusticemission.github.io/react-big-calendar/examples/index.html#api - class FullAPIExample extends React.Component> { + class FullAPIExample extends React.Component> { render() { return ( - { }} - onView={(view: View) => { }} - onSelectSlot={(slotInfo) => { - const start = slotInfo.start; - const end = slotInfo.end; - const slots = slotInfo.slots; - }} - onSelectEvent={(event) => { }} - onSelecting={(slotInfo) => { - const start = slotInfo.start; - const end = slotInfo.end; - return true; - }} - views={['day']} - toolbar={true} - popup={true} - popupOffset={20} - selectable={true} - step={20} - rtl={true} - eventPropGetter={(event, start, end, isSelected) => ({ className: 'some-class' })} - titleAccessor={'title'} - allDayAccessor={(event: any) => !!event.allDay} - startAccessor={'start'} - endAccessor={(event: any) => event.end || event.start} - min={new Date()} - max={new Date()} - scrollToTime={new Date()} - formats={{ - dateFormat: "h a", - agendaDateFormat: (date: Date, culture?: string, localizer?: object) => "some-format", - dayRangeHeaderFormat: (range: DateRange, culture?: string, localizer?: object) => "some-format" - }} - messages={{}} - timeslots={24} - defaultView={'month'} - className={'my-calendar'} - elementProps={{ id: 'myCalendar' }} - components={{ - event: Event, - agenda: { - event: EventAgenda - } - }} - dayPropGetter={customDayPropGetter} - slotPropGetter={customSlotPropGetter} - defaultDate={new Date()} - /> + { }} + onView={(view: View) => { }} + onSelectSlot={(slotInfo) => { + const start = slotInfo.start; + const end = slotInfo.end; + const slots = slotInfo.slots; + }} + onSelectEvent={(event) => { }} + onSelecting={(slotInfo) => { + const start = slotInfo.start; + const end = slotInfo.end; + return true; + }} + views={['day']} + toolbar={true} + popup={true} + popupOffset={20} + selectable={true} + step={20} + rtl={true} + eventPropGetter={(event, start, end, isSelected) => ({ className: 'some-class' })} + titleAccessor={'title'} + allDayAccessor={(event: CalendarEvent) => !!event.allDay} + startAccessor={'start'} + endAccessor={(event: CalendarEvent) => event.end || event.start} + min={new Date()} + max={new Date()} + scrollToTime={new Date()} + formats={{ + dateFormat: "h a", + agendaDateFormat: (date: Date, culture?: string, localizer?: object) => "some-format", + dayRangeHeaderFormat: (range: DateRange, culture?: string, localizer?: object) => "some-format" + }} + messages={{}} + timeslots={24} + defaultView={'month'} + className={'my-calendar'} + elementProps={{ id: 'myCalendar' }} + components={{ + event: Event, + agenda: { + event: EventAgenda + }, + toolbar: Toolbar, + eventWrapper: EventWrapper, + }} + dayPropGetter={customDayPropGetter} + slotPropGetter={customSlotPropGetter} + defaultDate={new Date()} + resources={getResources()} + resourceAccessor={event => event.resourceId} + resourceIdAccessor={resource => resource.id} + resourceTitleAccessor={resource => resource.title} /> ); } } @@ -130,10 +148,19 @@ function getEvents(): CalendarEvent[] { new CalendarEvent('Happy Hour', new Date(2015, 3, 12, 17, 0, 0, 0), new Date(2015, 3, 12, 17, 30, 0, 0), undefined, 'Most important meal of the day'), new CalendarEvent('Dinner', new Date(2015, 3, 12, 20, 0, 0, 0), new Date(2015, 3, 12, 21, 0, 0, 0)), new CalendarEvent('Birthday Party', new Date(2015, 3, 13, 7, 0, 0), new Date(2015, 3, 13, 10, 30, 0)), + new CalendarEvent('Alice\'s break', new Date(2015, 3, 14, 20, 0, 0, 0), new Date(2015, 3, 14, 21, 0, 0, 0), undefined, undefined, "alice"), + new CalendarEvent('Bob\'s break', new Date(2015, 3, 15, 7, 0, 0), new Date(2015, 3, 15, 10, 30, 0), undefined, undefined, "bob"), ]; return events; } +function getResources(): CalendarResource[] { + return [ + new CalendarResource('alice', 'Alice'), + new CalendarResource('bob', 'Bob') + ]; +} + class EventAgenda extends React.Component { render() { // const { label } = this.props; @@ -172,3 +199,25 @@ function Event(event: any) { ); } + +class EventWrapper extends React.Component { + render() { + const { continuesEarlier, label, accessors = {}, style } = this.props; + return ( +
+
{continuesEarlier}-{label}-{accessors.title && event && accessors.title(event)}}
+
+ ); + } +} + +class Toolbar extends React.Component { + render() { + const { date, label, view } = this.props; + return ( +
+
{date.toJSON()}-{label}-{view}}
+
+ ); + } +} diff --git a/types/react-burger-menu/index.d.ts b/types/react-burger-menu/index.d.ts index 85d49494c2..544dd84aec 100644 --- a/types/react-burger-menu/index.d.ts +++ b/types/react-burger-menu/index.d.ts @@ -16,6 +16,7 @@ export interface Styles { bmCross: Partial; bmCrossButton: Partial; bmItemList: Partial; + bmMenuWrap: Partial; bmMenu: Partial; bmMorphShape: Partial; bmOverlay: Partial; diff --git a/types/react-css-collapse/index.d.ts b/types/react-css-collapse/index.d.ts new file mode 100644 index 0000000000..e454d5946b --- /dev/null +++ b/types/react-css-collapse/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for react-css-collapse 3.6 +// Project: https://github.com/SparebankenVest/react-css-collapse +// Definitions by: Daniel Ford +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +declare module 'react-css-collapse' { + interface Props { + isOpen: boolean; + className?: string | null; + onRest?: () => void; + transition?: string | null; + } + class Collapse extends React.Component { + render(): React.ReactElement; + } + export default Collapse; +} diff --git a/types/react-css-collapse/react-css-collapse-tests.tsx b/types/react-css-collapse/react-css-collapse-tests.tsx new file mode 100644 index 0000000000..3b699b530d --- /dev/null +++ b/types/react-css-collapse/react-css-collapse-tests.tsx @@ -0,0 +1,14 @@ +import * as React from "react"; +import { SFC } from "react"; +import { render } from "react-dom"; +import Collapse from "react-css-collapse"; + +const TestOpen: SFC = () => ( + +
+ i am open +
+
+); + +render(, document.getElementById("main")); diff --git a/types/react-css-collapse/tsconfig.json b/types/react-css-collapse/tsconfig.json new file mode 100644 index 0000000000..efb2921718 --- /dev/null +++ b/types/react-css-collapse/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-css-collapse-tests.tsx" + ] +} diff --git a/types/react-css-collapse/tslint.json b/types/react-css-collapse/tslint.json new file mode 100644 index 0000000000..9e934cc4fe --- /dev/null +++ b/types/react-css-collapse/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-single-declare-module": false, + "no-declare-current-package": false, + "no-duplicate-imports": false + } +} diff --git a/types/react-data-grid/index.d.ts b/types/react-data-grid/index.d.ts index b41c2c2501..94d8af72d9 100644 --- a/types/react-data-grid/index.d.ts +++ b/types/react-data-grid/index.d.ts @@ -583,7 +583,7 @@ declare namespace AdazzleReactDataGrid { declare namespace AdazzleReactDataGridPlugins { interface AutoCompleteEditorProps { onCommit?: () => void; - options?: Array<{ id: number; title: string }>; + options?: Array<{ id: any; title: string }>; label?: any; value?: any; height?: number; diff --git a/types/react-datepicker/index.d.ts b/types/react-datepicker/index.d.ts index 23e542d322..e727155520 100644 --- a/types/react-datepicker/index.d.ts +++ b/types/react-datepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-datepicker 1.1 +// Type definitions for react-datepicker 2.0 // Project: https://github.com/Hacker0x01/react-datepicker // Definitions by: Rajab Shakirov , // Andrey Balokha , @@ -7,11 +7,12 @@ // Roy Xue // Koala Human // Sean Kelley +// Justin Grant +// Jake Boone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from "react"; -import * as moment from "moment"; import * as Popper from "popper.js"; export interface ReactDatePickerProps { @@ -20,59 +21,65 @@ export interface ReactDatePickerProps { autoComplete?: string; autoFocus?: boolean; calendarClassName?: string; + calendarContainer?(props: { children: React.ReactNode[] }): React.ReactNode; children?: React.ReactNode; className?: string; customInput?: React.ReactNode; customInputRef?: string; dateFormat?: string | string[]; dateFormatCalendar?: string; - dayClassName?(date: moment.Moment): string | null; + dayClassName?(date: Date): string | null; disabled?: boolean; disabledKeyboardNavigation?: boolean; dropdownMode?: 'scroll' | 'select'; - endDate?: moment.Moment; - excludeDates?: moment.Moment[]; - excludeTimes?: moment.Moment[]; - filterDate?(date: moment.Moment): boolean; + endDate?: Date; + excludeDates?: Date[]; + excludeTimes?: Date[]; + filterDate?(date: Date): boolean; fixedHeight?: boolean; forceShowMonthNavigation?: boolean; - formatWeekNumber?(date: moment.Moment): string | number; - highlightDates?: moment.Moment[]; + formatWeekNumber?(date: Date): string | number; + highlightDates?: Date[]; id?: string; - includeDates?: moment.Moment[]; - includeTimes?: moment.Moment[]; + includeDates?: Date[]; + includeTimes?: Date[]; + injectTimes?: Date[]; inline?: boolean; isClearable?: boolean; locale?: string; - maxDate?: moment.Moment; - maxTime?: moment.Moment; - minDate?: moment.Moment; - minTime?: moment.Moment; + maxDate?: Date; + maxTime?: Date; + minDate?: Date; + minTime?: Date; monthsShown?: number; name?: string; onBlur?(event: React.FocusEvent): void; - onChange(date: moment.Moment | null, event: React.SyntheticEvent | undefined): void; + onChange(date: Date | null, event: React.SyntheticEvent | undefined): void; onChangeRaw?(event: React.FocusEvent): void; onClickOutside?(event: React.MouseEvent): void; onFocus?(event: React.FocusEvent): void; onKeyDown?(event: React.KeyboardEvent): void; - onMonthChange?(date: moment.Moment): void; - onSelect?(date: moment.Moment, event: React.SyntheticEvent | undefined): void; - onWeekSelect?(firstDayOfWeek: moment.Moment, weekNumber: string | number, event: React.SyntheticEvent | undefined): void; - onYearChange?(date: moment.Moment): void; - openToDate?: moment.Moment; + onMonthChange?(date: Date): void; + onSelect?(date: Date, event: React.SyntheticEvent | undefined): void; + onWeekSelect?(firstDayOfWeek: Date, weekNumber: string | number, event: React.SyntheticEvent | undefined): void; + onInputClick?(): void; + onYearChange?(date: Date): void; + onInputError?(err: {code: number; msg: string}): void; + open?: boolean; + openToDate?: Date; peekNextMonth?: boolean; placeholderText?: string; popperClassName?: string; popperContainer?(props: { children: React.ReactNode[] }): React.ReactNode; popperModifiers?: Popper.Modifiers; popperPlacement?: string; + popperProps?: {}; preventOpenOnFocus?: boolean; readOnly?: boolean; required?: boolean; scrollableMonthYearDropdown?: boolean; scrollableYearDropdown?: boolean; - selected?: moment.Moment | null; + selected?: Date | null; selectsEnd?: boolean; selectsStart?: boolean; shouldCloseOnSelect?: boolean; @@ -83,21 +90,34 @@ export interface ReactDatePickerProps { showTimeSelectOnly?: boolean; showWeekNumbers?: boolean; showYearDropdown?: boolean; - startDate?: moment.Moment; + startDate?: Date; startOpen?: boolean; tabIndex?: number; timeCaption?: string; timeFormat?: string; timeIntervals?: number; title?: string; - todayButton?: string; + todayButton?: React.ReactNode; useShortMonthInDropdown?: boolean; useWeekdaysShort?: boolean; - utcOffset?: number; value?: string; weekLabel?: string; withPortal?: boolean; yearDropdownItemNumber?: number; + formatWeekDay?(date: Date): string; + clearButtonTitle?: string; + previousMonthButtonLabel?: string; + nextMonthButtonLabel?: string; + renderCustomHeader?(params: { + date: Date; + changeYear(year: number): void; + changeMonth(month: number): void; + decreaseMonth(): void; + increaseMonth(): void; + prevMonthButtonDisabled: boolean; + nextMonthButtonDisabled: boolean; + }): React.ReactNode; + renderDayContents?(dayOfMonth: number): React.ReactNode; } declare const ReactDatePicker: React.ClassicComponentClass; export default ReactDatePicker; diff --git a/types/react-datepicker/package.json b/types/react-datepicker/package.json index fc763e4d4b..245f69cd2c 100644 --- a/types/react-datepicker/package.json +++ b/types/react-datepicker/package.json @@ -1,7 +1,6 @@ { "private": true, "dependencies": { - "moment": ">=2.14.0", "popper.js": "^1.14.1" } } diff --git a/types/react-datepicker/react-datepicker-tests.tsx b/types/react-datepicker/react-datepicker-tests.tsx index 1414672684..4a3fd93cac 100644 --- a/types/react-datepicker/react-datepicker-tests.tsx +++ b/types/react-datepicker/react-datepicker-tests.tsx @@ -1,17 +1,16 @@ import * as React from 'react'; -import * as moment from 'moment'; import DatePicker from 'react-datepicker'; {}} - onYearChange={(date: moment.Moment) => {}} + selected={new Date()} + onChange={(date: Date | null) => {}} + onYearChange={(date: Date) => {}} popperModifiers={{ flip: { enabled: false } }} - includeTimes={[moment()]} + includeTimes={[new Date()]} >
diff --git a/types/react-dates/index.d.ts b/types/react-dates/index.d.ts index 05058b2ca9..9e96538f7d 100644 --- a/types/react-dates/index.d.ts +++ b/types/react-dates/index.d.ts @@ -55,6 +55,7 @@ declare namespace ReactDates { screenReaderInputMessage?: string, showClearDates?: boolean, showDefaultInputIcon?: boolean, + inputIconPosition?: IconPositionShape, customInputIcon?: string | JSX.Element, customArrowIcon?: string | JSX.Element, customCloseIcon?: string | JSX.Element, diff --git a/types/react-dom/react-dom-tests.tsx b/types/react-dom/react-dom-tests.tsx index ff5ef5850e..c7ccb0052d 100644 --- a/types/react-dom/react-dom-tests.tsx +++ b/types/react-dom/react-dom-tests.tsx @@ -7,7 +7,7 @@ import * as ReactTestUtils from 'react-dom/test-utils'; declare function describe(desc: string, f: () => void): void; declare function it(desc: string, f: () => void): void; -class TestComponent extends React.Component { } +class TestComponent extends React.Component<{x: string}> { } describe('ReactDOM', () => { it('render', () => { diff --git a/types/react-dom/server/index.d.ts b/types/react-dom/server/index.d.ts index 53bbca7250..ef42606717 100644 --- a/types/react-dom/server/index.d.ts +++ b/types/react-dom/server/index.d.ts @@ -1,4 +1,10 @@ -/// +// forward declarations +declare global { + namespace NodeJS { + // tslint:disable-next-line:no-empty-interface + interface ReadableStream {} + } +} import { ReactElement } from 'react'; diff --git a/types/react-dom/test-utils/index.d.ts b/types/react-dom/test-utils/index.d.ts index caa5605ef5..f60d088515 100644 --- a/types/react-dom/test-utils/index.d.ts +++ b/types/react-dom/test-utils/index.d.ts @@ -59,7 +59,7 @@ export interface SyntheticEventData extends OptionalEventProperties { export type EventSimulator = (element: Element | Component, eventData?: SyntheticEventData) => void; export interface MockedComponentClass { - new (props: {}): any; + new (props: any): any; } export interface ShallowRenderer { @@ -160,8 +160,12 @@ export function renderIntoDocument( element: DOMElement): T; export function renderIntoDocument( element: SFCElement): void; -export function renderIntoDocument>( - element: CElement): T; +// If we replace `P` with `any` in this overload, then some tests fail because +// calls to `renderIntoDocument` choose the last overload on the +// subtype-relation pass and get an undesirably broad return type. Using `P` +// allows this overload to match on the subtype-relation pass. +export function renderIntoDocument>( + element: CElement): T; export function renderIntoDocument

( element: ReactElement

): Component

| Element | void; @@ -257,7 +261,7 @@ export function findRenderedDOMComponentWithTag( /** * Finds all instances of components with type equal to `componentClass`. */ -export function scryRenderedComponentsWithType( +export function scryRenderedComponentsWithType, C extends ComponentClass>( root: Component, type: ClassType): T[]; @@ -266,7 +270,7 @@ export function scryRenderedComponentsWithType( +export function findRenderedComponentWithType, C extends ComponentClass>( root: Component, type: ClassType): T; diff --git a/types/react-dom/tsconfig.json b/types/react-dom/tsconfig.json index 0d21b07029..f63325026f 100644 --- a/types/react-dom/tsconfig.json +++ b/types/react-dom/tsconfig.json @@ -15,7 +15,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/react-facebook-login/index.d.ts b/types/react-facebook-login/index.d.ts index 82672660a8..419761974e 100644 --- a/types/react-facebook-login/index.d.ts +++ b/types/react-facebook-login/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-facebook-login 3.6 +// Type definitions for react-facebook-login 4.1 // Project: https://github.com/keppelen/react-facebook-login // Definitions by: Alexandre Paré , Jan Karres // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,7 @@ import * as React from "react"; -interface ReactFacebookLoginProps { +export interface ReactFacebookLoginProps { appId: string; callback(userInfo: ReactFacebookLoginInfo): void; onFailure?(response: ReactFacebookFailureResponse): void; @@ -18,7 +18,7 @@ interface ReactFacebookLoginProps { cssClass?: string; disableMobileRedirect?: boolean; fields?: string; - icon?: string | React.ReactNode; + icon?: React.ReactNode; isDisabled?: boolean; language?: string; onClick?(event: React.MouseEvent): void; @@ -32,6 +32,10 @@ interface ReactFacebookLoginProps { xfbml?: boolean; isMobile?: boolean; tag?: Node | React.Component; + returnScopes?: boolean; + state?: string; + authType?: string; + responseType?: string; } export interface ReactFacebookFailureResponse { @@ -45,14 +49,12 @@ export interface ReactFacebookLoginInfo { email?: string; } -interface ReactFacebookLoginState { +export interface ReactFacebookLoginState { isSdkLoaded?: boolean; isProcessing?: boolean; } -declare class ReactFacebookLogin extends React.Component< +export default class ReactFacebookLogin extends React.Component< ReactFacebookLoginProps, ReactFacebookLoginState > {} - -export default ReactFacebookLogin; diff --git a/types/react-facebook-login/react-facebook-login-tests.tsx b/types/react-facebook-login/react-facebook-login-tests.tsx index d7b2ebcde8..a52c955596 100644 --- a/types/react-facebook-login/react-facebook-login-tests.tsx +++ b/types/react-facebook-login/react-facebook-login-tests.tsx @@ -1,7 +1,6 @@ import * as React from 'react'; import * as ReactDOM from 'react-dom'; - -import FacebookLogin, { ReactFacebookLoginInfo, ReactFacebookFailureResponse } from 'react-facebook-login'; +import FacebookLogin, { ReactFacebookFailureResponse, ReactFacebookLoginInfo, ReactFacebookLoginProps } from 'react-facebook-login'; const responseFacebook = (response: ReactFacebookLoginInfo) => { console.log(response); @@ -106,3 +105,9 @@ class MyComponent2 extends React.Component { ); } } + +type FacebookLoginWrapperProps = ReactFacebookLoginProps & { className?: string }; + +export const FacebookLoginWrapper = ({ className, ...props }: FacebookLoginWrapperProps) => ( + +); diff --git a/types/react-flatpickr/index.d.ts b/types/react-flatpickr/index.d.ts index a0a9725ccd..c867527b06 100644 --- a/types/react-flatpickr/index.d.ts +++ b/types/react-flatpickr/index.d.ts @@ -1,18 +1,25 @@ -// Type definitions for react-flatpickr 3.2 +// Type definitions for react-flatpickr 3.6 // Project: https://github.com/coderhaoxin/react-flatpickr // Definitions by: begincalendar +// snaveevans // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import { Component } from 'react'; -import flatpickr from 'flatpickr'; +import { Component } from "react"; +import flatpickr from "flatpickr"; export interface DateTimePickerProps { defaultValue?: string; options?: flatpickr.Options.Options; onChange?: flatpickr.Options.Hook; - value?: string; - className?: string; + onOpen?: flatpickr.Options.Hook; + onClose?: flatpickr.Options.Hook; + onMonthChange?: flatpickr.Options.Hook; + onYearChange?: flatpickr.Options.Hook; + onReady?: flatpickr.Options.Hook; + onValueUpdate?: flatpickr.Options.Hook; + onDayCreate?: flatpickr.Options.Hook; + value?: string | Date | number | ReadonlyArray; } export default class DatePicker extends Component {} diff --git a/types/react-flatpickr/react-flatpickr-tests.tsx b/types/react-flatpickr/react-flatpickr-tests.tsx index 452d8529b4..7a1c64c266 100644 --- a/types/react-flatpickr/react-flatpickr-tests.tsx +++ b/types/react-flatpickr/react-flatpickr-tests.tsx @@ -1,22 +1,42 @@ -import flatpickr from 'flatpickr'; -import * as React from 'react'; -import DatePicker from 'react-flatpickr'; +import flatpickr from "flatpickr"; +import * as React from "react"; +import DatePicker from "react-flatpickr"; -const noParamsElement = ; +const noParamsElement = ; -const defaultValueElement = ; +const defaultValueElement = ; const options = { - dateFormat: 'YYYY-MM-DD' + dateFormat: "YYYY-MM-DD" }; -const optionsElement = ; +const optionsElement = ; -const onChange = ( - selectedDates: Date[], dateStr: string, instance: flatpickr.Instance, +const hook = ( + selectedDates: Date[], + dateStr: string, + instance: flatpickr.Instance, elem: HTMLElement ) => null; -const onChangeElement = ; +const onChangeElement = ; +const onOpenElement = ; +const onCloseElement = ; +const onMonthChangeElement = ; +const onYearChangeElement = ; +const onReadyElement = ; +const onValueUpdateElement = ; +const onDayCreateElement = ; -const valueElement = ; - -const classNameElement = ; +const valueStringElement = ; +const valueDateElement = ; +const valueNumberElement = ; +const valueStringArrayElement = ( + +); +const valueDateArrayElement = ( + +); +const valueNumberArrayElement = ( + +); diff --git a/types/react-gravatar/index.d.ts b/types/react-gravatar/index.d.ts index b2962edc8d..56e48b3b9b 100644 --- a/types/react-gravatar/index.d.ts +++ b/types/react-gravatar/index.d.ts @@ -25,7 +25,7 @@ declare namespace Gravatar { type DefaultImage = "404" | "mm" | "identicon" | "monsterid" | "wavatar" | "retro" | "blank"; type Rating = "g" | "pg" | "r" | "x"; - interface Props { + interface Props extends Partial { /** * The email address used to look up the Gravatar image. * If you wish to avoid sending an email address to the client, you can compute the md5 hash on the server and diff --git a/types/react-infinite-calendar/index.d.ts b/types/react-infinite-calendar/index.d.ts index 2110d4dbd0..ac09df7bf4 100644 --- a/types/react-infinite-calendar/index.d.ts +++ b/types/react-infinite-calendar/index.d.ts @@ -6,16 +6,33 @@ import * as React from 'react'; +export type DateType = Date | string | number; + +export enum EVENT_TYPE { + START = 1, + HOVER, + END +} + +export interface RangedSelection { + eventType: EVENT_TYPE; + start: Date; + end: Date; +} + +export type RangedSelectFunction = (rangedDate: RangedSelection) => void; +export type DateSelectFunction = (date: Date) => void; + export interface ReactInfiniteCalendarProps { - selected?: Date | boolean; - width?: number | 'auto'; + selected?: DateType | false | { start: DateType; end: DateType }; + width?: number | 'auto' | '100%'; height?: number | 'auto'; - min?: Date; - max?: Date; - minDate?: Date; - maxDate?: Date; + min?: DateType; + max?: DateType; + minDate?: DateType; + maxDate?: DateType; disabledDays?: Array<0 | 1 | 2 | 3 | 4 | 5 | 6>; - disabledDates?: Date[]; + disabledDates?: DateType[]; display?: 'days' | 'years'; displayOptions?: { hideYearsOnSelect?: boolean; @@ -55,12 +72,22 @@ export interface ReactInfiniteCalendarProps { weekdayColor?: string; }; className?: string; - onSelect?: (date: string) => void; + onSelect?: DateSelectFunction | RangedSelectFunction; onScroll?: (scrollTop: number) => void; onScrollEnd?: (scrollTop: number) => void; rowHeight?: number; autoFocus?: boolean; tabIndex?: number; + Component?: CalendarClass; } +export class Calendar extends React.Component {} +export type CalendarClass = React.ComponentClass; + +export function withRange(component: CalendarClass): CalendarClass; +export function withDateSelection(component: CalendarClass): CalendarClass; +export function withMultipleDates(component: CalendarClass): CalendarClass; +export function withKeyboardSupport(component: CalendarClass): CalendarClass; +export function defaultMultipleDateInterpolation(component: CalendarClass): CalendarClass; + export default class ReactInfiniteCalendar extends React.Component {} diff --git a/types/react-infinite-calendar/react-infinite-calendar-tests.tsx b/types/react-infinite-calendar/react-infinite-calendar-tests.tsx index ff1918d539..ba4b6a0ec7 100644 --- a/types/react-infinite-calendar/react-infinite-calendar-tests.tsx +++ b/types/react-infinite-calendar/react-infinite-calendar-tests.tsx @@ -1,5 +1,11 @@ import * as React from 'react'; -import ReactInfiniteCalendar from 'react-infinite-calendar'; +import ReactInfiniteCalendar, { + Calendar, + withRange, + withKeyboardSupport, + withMultipleDates, + withDateSelection +} from 'react-infinite-calendar'; const test: React.SFC = () => ( ( tabIndex={1} /> ); + +const testWithRange = withRange(Calendar); +const testWithDateSelection = withDateSelection(Calendar); +const testWithKeyboardSupport = withKeyboardSupport(Calendar); +const testWithMultipleDate = withMultipleDates(Calendar); diff --git a/types/react-instantsearch-core/index.d.ts b/types/react-instantsearch-core/index.d.ts index e76be4ee08..bceb91ca85 100644 --- a/types/react-instantsearch-core/index.d.ts +++ b/types/react-instantsearch-core/index.d.ts @@ -128,7 +128,52 @@ export class Configure extends React.Component {} export function connectAutoComplete(Composed: React.ComponentType): React.ComponentClass; export function connectBreadcrumb(Composed: React.ComponentType): React.ComponentClass; export function connectConfigure(Composed: React.ComponentType): React.ComponentClass; -export function connectCurrentRefinements(Composed: React.ComponentType): React.ComponentClass; + +export type Refinement = { + label: string; + attribute: string; + index: string; + id: string; + value: RefinementValue; +} & ({ + currentRefinement: string; +} | { + items: Array<{ label: string, value: RefinementValue }>; + currentRefinement: string[]; +}); + +export type RefinementValue = (searchState: SearchState) => SearchState; + +export interface CurrentRefinementsExposed { + /** + * Function to modify the items being displayed, e.g. for filtering or sorting them. + * Takes an items as parameter and expects it back in return. + */ + transformItems?: (...args: any[]) => any; + /** Pass true to also clear the search query */ + clearsQuery?: boolean; +} + +export interface CurrentRefinementsProvided { + /** a function to remove a single filter */ + refine: (refinement: RefinementValue | RefinementValue[]) => void; + /** + * all the filters, the value is to pass to the refine function for removing all currentrefinements, + * label is for the display. When existing several refinements for the same atribute name, then you + * get a nested items object that contains a label and a value function to use to remove a single filter. + * attribute and currentRefinement are metadata containing row values. + */ + items: Refinement[]; + /** the search query */ + query: string; +} + +export function connectCurrentRefinements( + stateless: React.StatelessComponent, +): React.ComponentClass; +export function connectCurrentRefinements>( + Composed: React.ComponentType, +): ConnectedComponentClass; export interface NESW { northEast: { lat: number, lng: number }; @@ -263,13 +308,16 @@ export function connectRange(Composed: React.ComponentType): React.Componen export interface RefinementListProvided { /** a function to toggle a refinement */ - refine: (...args: any[]) => any; + refine: (value: string[]) => any; /** a function to generate a URL for the corresponding search state */ createURL: (...args: any[]) => any; /** the refinement currently applied */ currentRefinement: string[]; - /** the list of items the RefinementList can display. */ - items: Array>; + /** + * The list of items the RefinementList can display. + * If isFromSearch is false, the hit properties like _highlightResult are undefined + */ + items: Array>; /** a function to toggle a search inside items values */ searchForItems: (...args: any[]) => any; /** a boolean that says if the items props contains facet values from the global search or from the search inside items. */ @@ -455,12 +503,18 @@ export interface SearchResults { */ export type Hit = TDoc & { objectID: string; + /** + * Contains the searchable attributes within the document and shows which part of the + * attribute was matched by the search terms. Note that if the index has defined + * any searchable attributes, this object will only contain those keys and others + * will not exist. + */ '_highlightResult': HighlightResult; }; export type HighlightResult = TDoc extends { [k: string]: any } ? - { [K in keyof TDoc]: HighlightResultField } : + { [K in keyof TDoc]?: HighlightResultField } : never; type HighlightResultField = diff --git a/types/react-instantsearch-core/react-instantsearch-core-tests.tsx b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx index 62bf99e3d4..e39a9f53e6 100644 --- a/types/react-instantsearch-core/react-instantsearch-core-tests.tsx +++ b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx @@ -7,7 +7,11 @@ import { connectStateResults, SearchBoxProvided, connectSearchBox, - connectRefinementList + connectRefinementList, + CurrentRefinementsProvided, + connectCurrentRefinements, + RefinementListProvided, + Refinement } from 'react-instantsearch-core'; () => { @@ -100,9 +104,7 @@ import {

{additionalProp}

{searchResults.hits.map((h) => { // $ExpectType string - const compound = h._highlightResult.field3.compound.value; - // $ExpectType never - const field2 = h._highlightResult.field2; + const compound = h._highlightResult.field3!.compound!.value; return {compound}; })}
; @@ -119,7 +121,7 @@ import {

{additionalProp}

{searchResults.hits.map((h) => { // $ExpectType string[] - const words = h._highlightResult.field3.compound.matchedWords; + const words = h._highlightResult.field3!.compound!.matchedWords; return {h.field2}: {words.join(',')}; })}
; @@ -153,3 +155,67 @@ import { // reading and manipulating the current query of the search. const ConnectedSearchBox = connectSearchBox(MySearchBox); }; + +() => { + const MyCurrentRefinements = ({refine, items, query}: CurrentRefinementsProvided) => + <> + {items.map((refinement) => ( +
refine(refinement.value) }> + +
+ ))} + ; + + const ConnectedCurrentRefinements = connectCurrentRefinements(MyCurrentRefinements); + + item} />; +}; + +() => { + function renderRefinement( + label: string, + value: Refinement['value'], + refine: CurrentRefinementsProvided['refine'], + ) { + return ; + } + + const MyCurrentRefinements = connectCurrentRefinements(({refine, items, query}: CurrentRefinementsProvided) => { + return <> + {items.map((refinement) => { + let str: string = refinement.currentRefinement; // $ExpectError + /* + * When existing several refinements for the same atribute name, then you get a + * nested items object that contains a label and a value function to use to remove a single filter. + * https://community.algolia.com/react-instantsearch/connectors/connectCurrentRefinements.html + */ + if ('items' in refinement) { + str = refinement.currentRefinement; // $ExpectError + return <> + {refinement.items.map((i) => renderRefinement(i.label, i.value, refine))} + ; + } + + console.log(refinement.items); // $ExpectError + return renderRefinement(refinement.currentRefinement, refinement.value, refine); + })} + ; + }); +}; + +() => { + const MyRefinementList = ({items, refine}: RefinementListProvided) => + <> + {items.map((item) => ( + + ))} + ; + const ConnectedRefinementList = connectRefinementList(MyRefinementList); + + ; +}; diff --git a/types/react-instantsearch-dom/index.d.ts b/types/react-instantsearch-dom/index.d.ts index f1dec59118..6ecb03c981 100644 --- a/types/react-instantsearch-dom/index.d.ts +++ b/types/react-instantsearch-dom/index.d.ts @@ -118,8 +118,9 @@ export interface SearchBoxProps extends CommonWidgetProps { reset?: JSX.Element; loadingIndicator?: JSX.Element; - onSubmit?: (...args: any[]) => any; - onReset?: (...args: any[]) => any; + onSubmit?: (event: React.SyntheticEvent) => any; + onReset?: (event: React.SyntheticEvent) => any; + onChange?: (event: React.SyntheticEvent) => any; } /** * The SearchBox component displays a search box that lets the user search for a specific query. diff --git a/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx b/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx index 6d9b7b55f8..e10d3fde08 100644 --- a/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx +++ b/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx @@ -216,6 +216,21 @@ import { Hit, connectRefinementList, connectMenu } from 'react-instantsearch-cor ; }; +(() => { + function onSearchBoxChange(event: React.SyntheticEvent) { + } + + function onSearchBoxReset(event: React.SyntheticEvent) { + } + + function onSearchBoxSubmit(event: React.SyntheticEvent) { + } + + } />; +}); + import { createInstantSearch } from 'react-instantsearch-dom/server'; // import { createServer } from 'http'; declare function createServer(handler: (req: any, res: any) => any): any; diff --git a/types/react-instantsearch/react-instantsearch-tests.tsx b/types/react-instantsearch/react-instantsearch-tests.tsx index 82672b7a60..9abf91c0ef 100644 --- a/types/react-instantsearch/react-instantsearch-tests.tsx +++ b/types/react-instantsearch/react-instantsearch-tests.tsx @@ -348,7 +348,7 @@ import { createInstantSearch } from "react-instantsearch-core"; : item.label; return ( -
  • +
  • props.refine(item.value)}> {label} {item.isRefined ? '- selected' : ''} diff --git a/types/react-intl-redux/index.d.ts b/types/react-intl-redux/index.d.ts index 9d9e805df9..4410e7c019 100644 --- a/types/react-intl-redux/index.d.ts +++ b/types/react-intl-redux/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ratson/react-intl-redux // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { Action, AnyAction } from "redux" import { Provider as ReduxProvider } from "react-redux" diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index 17e738bb2a..aaba74820b 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -9,6 +9,7 @@ // Krister Kari // Martin Raedlinger // Kanitkorn Sujautra +// obedm503 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -46,6 +47,7 @@ declare namespace ReactIntl { messages: React.Requireable; defaultLocale: React.Requireable; defaultFormats: React.Requireable; + onError: React.Requireable; } interface IntlFormat { @@ -78,6 +80,7 @@ declare namespace ReactIntl { defaultLocale: string; defaultFormats: any; now(): number; + onError(error: string): void; } interface InjectedIntlProps { @@ -197,6 +200,7 @@ declare namespace ReactIntl { defaultFormats?: any; textComponent?: any; initialNow?: any; + onError?: (error: string) => void; } } diff --git a/types/react-intl/react-intl-tests.tsx b/types/react-intl/react-intl-tests.tsx index b3b23bb38f..63af762e61 100644 --- a/types/react-intl/react-intl-tests.tsx +++ b/types/react-intl/react-intl-tests.tsx @@ -401,7 +401,15 @@ class TestApp extends React.Component { hello: "Hello, {name}!" }; return ( - + console.error(error)} + > diff --git a/types/react-jsonschema-form/index.d.ts b/types/react-jsonschema-form/index.d.ts index 7e1e1df7e3..c17bda1a94 100644 --- a/types/react-jsonschema-form/index.d.ts +++ b/types/react-jsonschema-form/index.d.ts @@ -2,7 +2,6 @@ // Project: https://github.com/mozilla-services/react-jsonschema-form // Definitions by: Dan Fox // Ivan Jiang -// Kurt Preston // Philippe Bourdages // Lucian Buzzo // Sylvain Thénault diff --git a/types/react-leaflet-markercluster/index.d.ts b/types/react-leaflet-markercluster/index.d.ts new file mode 100644 index 0000000000..5db583d409 --- /dev/null +++ b/types/react-leaflet-markercluster/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for react-leaflet-markercluster 2.0 +// Project: https://github.com/YUzhva/react-leaflet-markercluster +// Definitions by: Adam Binford +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// +import * as Leaflet from 'leaflet'; +import * as ReactLeaflet from 'react-leaflet'; + +export type MarkerClusterGroupProps = ReactLeaflet.MapLayerProps & Leaflet.MarkerClusterGroupOptions; + +export default class MarkerClusterGroup

    extends ReactLeaflet.MapLayer

    { } diff --git a/types/react-leaflet-markercluster/react-leaflet-markercluster-tests.tsx b/types/react-leaflet-markercluster/react-leaflet-markercluster-tests.tsx new file mode 100644 index 0000000000..9fc901c527 --- /dev/null +++ b/types/react-leaflet-markercluster/react-leaflet-markercluster-tests.tsx @@ -0,0 +1,30 @@ +import * as React from 'react'; +import * as Leaflet from 'leaflet'; +import MarkerClusterGroup from 'react-leaflet-markercluster'; + +const MarkerCluster = ( + Leaflet.divIcon({ html: `${cluster.getChildCount()}` }) }/> +); diff --git a/types/react-leaflet-markercluster/tsconfig.json b/types/react-leaflet-markercluster/tsconfig.json new file mode 100644 index 0000000000..071c9c734d --- /dev/null +++ b/types/react-leaflet-markercluster/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-leaflet-markercluster-tests.tsx" + ] +} diff --git a/types/react-leaflet-markercluster/tslint.json b/types/react-leaflet-markercluster/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-leaflet-markercluster/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-lifecycle-component/index.d.ts b/types/react-lifecycle-component/index.d.ts index 315d04f7fb..bb6dc65dd8 100644 --- a/types/react-lifecycle-component/index.d.ts +++ b/types/react-lifecycle-component/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/JamieDixon/react-lifecycle-component // Definitions by: Alexander Fisher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { ComponentLifecycle, Component, ComponentClass } from 'react'; import { Connect } from 'react-redux'; diff --git a/types/react-loadable/index.d.ts b/types/react-loadable/index.d.ts index b27a4de764..bf8af8e794 100644 --- a/types/react-loadable/index.d.ts +++ b/types/react-loadable/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-loadable 5.4 // Project: https://github.com/thejameskyle/react-loadable#readme -// Definitions by: Diogo Franco +// Definitions by: Jessica Franco // Oden S. // Ian Ker-Seymer // Tomek Łaziuk diff --git a/types/react-lottie/index.d.ts b/types/react-lottie/index.d.ts index 8e4f3b717b..a57da91307 100644 --- a/types/react-lottie/index.d.ts +++ b/types/react-lottie/index.d.ts @@ -7,7 +7,7 @@ import * as React from 'react'; -interface Options { +export interface Options { /** * Defines if the animation should play only once or repeatedly in an endless loop */ @@ -41,7 +41,7 @@ interface Options { }; } -interface EventListener { +export interface EventListener { /** * The event sent by Lottie */ @@ -61,7 +61,7 @@ interface EventListener { callback: () => void; } -interface LottieProps { +export interface LottieProps { /** * Object representing animation settings */ diff --git a/types/react-map-gl/index.d.ts b/types/react-map-gl/index.d.ts index 136f9352bb..3fea6a3ea9 100644 --- a/types/react-map-gl/index.d.ts +++ b/types/react-map-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-map-gl 3.3 +// Type definitions for react-map-gl 4.0 // Project: https://github.com/uber/react-map-gl#readme // Definitions by: Robert Imig // Fabio Berta @@ -9,16 +9,18 @@ import * as React from 'react'; import * as MapboxGL from 'mapbox-gl'; import * as GeoJSON from 'geojson'; -export interface Viewport { +export interface ViewState { latitude: number; longitude: number; zoom: number; bearing?: number; pitch?: number; + altitude?: number; } export interface MapError { - message: string; + error?: { message: string; status: number }; + status: number; } export interface MapRequest { @@ -27,31 +29,37 @@ export interface MapRequest { credentials?: string; } -export interface MapboxProps extends Partial { - container?: {}; +export interface MapboxProps extends Partial { + container?: object; + gl?: object; mapboxApiAccessToken?: string; attributionControl?: boolean; preserveDrawingBuffer?: boolean; + reuseMaps?: boolean; + transformRequest?: (url?: string, resourceType?: string) => MapRequest; + mapOptions?: object; + mapStyle?: string | object; + visible?: boolean; onLoad?: () => void; onError?: (e: MapError) => void; - reuseMaps?: boolean; reuseMap?: boolean; - transformRequest?: (url?: string, resourceType?: string) => MapRequest; - - mapStyle?: string | {}; - - width: number; - height: number; - - viewState?: Viewport; - - altitude?: number; // Note: Non-public API, see https://github.com/mapbox/mapbox-gl-js/issues/1137 + width: number | string; + height: number | string; + viewState?: ViewState; } export interface StaticMapProps extends MapboxProps { + onResize?: (dimensions: { width: number; height: number }) => void; preventStyleDiffing?: boolean; - visible?: boolean; + disableTokenWarning?: boolean; className?: string; + style?: object; + visibilityConstraints?: { + minZoom?: number; + maxZoom?: number; + minPitch?: number; + maxPitch?: number; + }; } export interface QueryRenderedFeaturesParams { @@ -64,14 +72,71 @@ export class StaticMap extends React.Component { queryRenderedFeatures(geometry?: MapboxGL.PointLike | MapboxGL.PointLike[], parameters?: QueryRenderedFeaturesParams): Array>; } -export interface InteractiveMapState { +export interface ExtraState { isDragging: boolean; isHovering: boolean; } -export interface MapEvent { - lngLat: [number, number]; - features: Array<{}>; +export interface PositionInput { + pos: [number, number]; +} + +export interface MapControllerOptions { + onViewportChange?: (viewState: ViewState) => void; + onStateChange?: (state: MapState) => void; + eventManager?: any; + isInteractive: boolean; + scrollZoom?: boolean; + dragPan?: boolean; + dragRotate?: boolean; + doubleClickZoom?: boolean; + touchZoom?: boolean; + touchRotate?: boolean; + keyboard?: boolean; +} + +export interface ViewportProps { + width: number; + height: number; + latitude: number; + longitude: number; + zoom: number; + bearing: number; + pitch: number; + altitude: number; + maxZoom: number; + minZoom: number; + maxPitch: number; + minPitch: number; + transitionDuration?: number; + transitionInterpolator?: TransitionInterpolator; + transitionInterruption?: TRANSITION_EVENTS; + transitionEasing?: EasingFunction; +} + +export interface InteractiveState { + startPanLngLat?: [number, number]; + startZoomLngLat?: [number, number]; + startBearing?: number; + startPitch?: number; + startZoom?: number; +} + +export type MapStateProps = Partial; + +export class MapState { + constructor(props: MapStateProps); + getViewportProps(): ViewportProps; + getInteractiveState(): InteractiveState; + panStart(input: PositionInput): MapState; + pan(input: PositionInput & { startPos?: [number, number] }): MapState; + panEnd(): MapState; + rotateStart(input: PositionInput): MapState; + rotate(input: { deltaScaleX?: number; deltaScaleY?: number }): MapState; + rotateEnd(): MapState; + zoomStart(input: PositionInput): MapState; + zoom(input: PositionInput & { scale: number; startPos?: [number, number] }): MapState; + zoomEnd(): MapState; } export interface Center { @@ -93,11 +158,30 @@ export interface MapControlEvent { delta?: number; } -export interface BaseMapControls { +export interface BaseMapController { events: string[]; handleEvent(event: MapControlEvent): void; } +export class MapController implements BaseMapController { + events: string[]; + handleEvent(event: MapControlEvent): void; + getMapState(overrides: Partial): MapState; + setOptions(options: MapControllerOptions): void; + setState(newState: MapState): void; + updateViewport(newMapState: MapState, extraProps: any, extraState: ExtraState): void; +} + +export interface PointerEvent { + type: string; + point: [number, number]; + lngLat: [number, number]; + target: any; + srcEvent: any; + // backward compatibility: v3 interface + features: any[]; +} + export type EasingFunction = (t: number) => number; export enum TRANSITION_EVENTS { @@ -115,7 +199,7 @@ export class LinearInterpolator extends TransitionInterpolator { export class FlyToInterpolator extends TransitionInterpolator {} export interface ViewStateChangeInfo { - viewState: Viewport; + viewState: ViewState; } export interface InteractiveMapProps extends StaticMapProps { @@ -123,10 +207,9 @@ export interface InteractiveMapProps extends StaticMapProps { minZoom?: number; maxPitch?: number; minPitch?: number; - - onViewportChange?: (viewport: Viewport) => void; onViewStateChange?: (info: ViewStateChangeInfo) => void; - + onViewportChange?: (viewState: ViewState) => void; + onInteractionStateChange?: (state: ExtraState) => void; transitionDuration?: number; transitionInterpolator?: TransitionInterpolator; transitionInterruption?: TRANSITION_EVENTS; @@ -134,7 +217,6 @@ export interface InteractiveMapProps extends StaticMapProps { onTransitionStart?: () => void; onTransitionInterrupt?: () => void; onTransitionEnd?: () => void; - scrollZoom?: boolean; dragPan?: boolean; dragRotate?: boolean; @@ -142,26 +224,25 @@ export interface InteractiveMapProps extends StaticMapProps { touchZoom?: boolean; touchRotate?: boolean; keyboard?: boolean; - - onHover?: (event: MapEvent) => void; - onClick?: (event: MapEvent) => void; - - onContextMenu?: (event: MapEvent) => void; - + onHover?: (event: PointerEvent) => void; + onClick?: (event: PointerEvent) => void; + onDblClick?: (event: PointerEvent) => void; + onContextMenu?: (event: PointerEvent) => void; + onMouseDown?: (event: PointerEvent) => void; + onMouseMove?: (event: PointerEvent) => void; + onMouseUp?: (event: PointerEvent) => void; + onTouchStart?: (event: PointerEvent) => void; + onTouchMove?: (event: PointerEvent) => void; + onTouchEnd?: (event: PointerEvent) => void; + onMouseEnter?: (event: PointerEvent) => void; + onMouseLeave?: (event: PointerEvent) => void; + onMouseOut?: (event: PointerEvent) => void; + onWheel?: (event: PointerEvent) => void; touchAction?: string; - clickRadius?: number; - - getCursor?: (state: InteractiveMapState) => void; - - visibilityConstraints?: { - minZoom?: number; - maxZoom?: number; - minPitch?: number; - maxPitch?: number; - }; - - mapControls?: BaseMapControls; + interactiveLayerIds?: string[]; + getCursor?: (state: ExtraState) => void; + controller?: MapController; } export class InteractiveMap extends React.Component { @@ -180,12 +261,21 @@ export interface BaseControlProps { export class BaseControl extends React.Component {} +export interface DragEvent { + lngLat: [number, number]; + [key: string]: any; +} + export interface MarkerProps extends BaseControlProps { className?: string; longitude: number; latitude: number; offsetLeft?: number; offsetTop?: number; + draggable?: boolean; + onDrag?: (event: DragEvent) => void; + onDragEnd?: (event: DragEvent) => void; + onDragStart?: (event: DragEvent) => void; } export class Marker extends BaseControl {} @@ -194,6 +284,7 @@ export interface PopupProps extends BaseControlProps { className?: string; longitude: number; latitude: number; + altitude?: number; offsetLeft?: number; offsetTop?: number; tipSize?: number; @@ -201,6 +292,7 @@ export interface PopupProps extends BaseControlProps { closeOnClick?: boolean; anchor?: 'top' | 'top-left' | 'top-right' | 'bottom' | 'bottom-left' | 'bottom-right' | 'left' | 'right'; dynamicPosition?: boolean; + sortByDepth?: boolean; onClose?: () => void; } @@ -209,13 +301,22 @@ export class Popup extends BaseControl {} export interface NavigationControlProps extends BaseControlProps { className?: string; onViewStateChange: (info: ViewStateChangeInfo) => void; - onViewportChange: (viewport: Viewport) => void; + onViewportChange: (viewport: ViewState) => void; showCompass?: boolean; showZoom?: boolean; } export class NavigationControl extends BaseControl {} +export interface DraggableControlProps extends BaseControlProps { + draggable?: boolean; + onDrag?: (event: DragEvent) => void; + onDragEnd?: (event: DragEvent) => void; + onDragStart?: (event: DragEvent) => void; +} + +export class DraggableControl extends BaseControl {} + export interface HTMLRedrawOptions { width: number; height: number; @@ -248,61 +349,3 @@ export interface SVGOverlayProps extends BaseControlProps { } export class SVGOverlay extends BaseControl {} - -export namespace experimental { - interface Options { - // TODO(deprecate): remove this when `onChangeViewport` gets deprecated - onChangeViewport?: (viewport: Viewport) => void; - // TODO(deprecate): remove this when `touchZoomRotate` gets deprecated - touchZoomRotate?: boolean; - - onViewStateChange?: (info: ViewStateChangeInfo) => void; - onViewportChange?: (viewport: Viewport) => void; - onStateChange?: (state: MapState) => void; - eventManager?: any; - scrollZoom?: boolean; - dragPan?: boolean; - dragRotate?: boolean; - doubleClickZoom?: boolean; - touchZoom?: boolean; - touchRotate?: boolean; - keyboard?: boolean; - } - - class MapState implements Viewport { - width: number; - height: number; - latitude: number; - longitude: number; - zoom: number; - bearing?: number; - pitch?: number; - altitude?: number; - - maxZoom?: number; - minZoom?: number; - maxPitch?: number; - minPitch?: number; - - transitionDuration?: number; - transitionInterpolator?: TransitionInterpolator; - transitionInterruption?: TRANSITION_EVENTS; - transitionEasing?: EasingFunction; - - startPanLngLat?: [number, number]; - startZoomLngLat?: [number, number]; - startBearing?: number; - startPitch?: number; - startZoom?: number; - } - - class MapControls implements BaseMapControls { - events: string[]; - - handleEvent(event: MapControlEvent): void; - getMapState(overrides: Partial): MapState; - setOptions(options: Options): void; - setState(newState: MapState): void; - updateViewport(newMapState: MapState, extraProps: any, extraState: InteractiveMapState): void; - } -} diff --git a/types/react-map-gl/react-map-gl-tests.tsx b/types/react-map-gl/react-map-gl-tests.tsx index 7eb5bfd590..c9024287c9 100644 --- a/types/react-map-gl/react-map-gl-tests.tsx +++ b/types/react-map-gl/react-map-gl-tests.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import { - Viewport, + ViewState, InteractiveMap, CanvasOverlay, SVGOverlay, @@ -13,12 +13,12 @@ import { import * as MapboxGL from "mapbox-gl"; interface State { - viewport: Viewport; + viewState: ViewState; } class MyMap extends React.Component<{}, State> { readonly state: State = { - viewport: { + viewState: { bearing: 0, latitude: 0, longitude: 0, @@ -31,14 +31,14 @@ class MyMap extends React.Component<{}, State> { return (

    { + redraw={opts => { const { ctx, height, @@ -51,7 +51,7 @@ class MyMap extends React.Component<{}, State> { }} /> {}} + redraw={opts => {}} captureScroll={true} captureDrag={true} captureClick={true} @@ -61,7 +61,7 @@ class MyMap extends React.Component<{}, State> { redraw={() => {}} /> { + redraw={opts => { const { height, project, @@ -79,7 +79,7 @@ class MyMap extends React.Component<{}, State> { redraw={() => {}} /> { + redraw={opts => { const { height, project, @@ -98,7 +98,7 @@ class MyMap extends React.Component<{}, State> { /> +// Stack Builders +// Esteban Ibarra // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -32,7 +34,7 @@ interface ButtonProps { interface ContainerProps { blurComponentIOS?: ReactNode; - children: JSX.Element[]; + children: React.ReactNode[]; /** * default: false */ diff --git a/types/react-native-dialog/react-native-dialog-tests.tsx b/types/react-native-dialog/react-native-dialog-tests.tsx index 151ee14af5..544025051c 100644 --- a/types/react-native-dialog/react-native-dialog-tests.tsx +++ b/types/react-native-dialog/react-native-dialog-tests.tsx @@ -2,6 +2,24 @@ import Dialog from "react-native-dialog"; import { createRef, Component } from "react"; class Example extends Component { + dynamicButtons() { + const buttonFunc = () => console.log('click'); + const buttons = [ + { label: 'Button 1', action: buttonFunc }, + { label: 'Button 2', action: buttonFunc }, + ]; + return buttons.map(({ label , action }) => + + ); + } + + singleButton() { + return ( null} />); + } + render() { const ref = createRef(); @@ -23,6 +41,8 @@ class Example extends Component { label="Validate" onPress={() => console.log("test")} /> + {this.dynamicButtons()} + {this.singleButton()} ); } diff --git a/types/react-native-draggable-flatlist/index.d.ts b/types/react-native-draggable-flatlist/index.d.ts new file mode 100644 index 0000000000..0b96f0b3cd --- /dev/null +++ b/types/react-native-draggable-flatlist/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for react-native-draggable-flatlist 1.1 +// Project: https://github.com/computerjazz/react-native-draggable-flatlist#readme +// Definitions by: Stack Builders +// Esteban Ibarra +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { VirtualizedListWithoutRenderItemProps } from "react-native"; +import { Component } from "react"; + +export interface RenderItemInfo { + item: ItemR; + index: number; + move: () => void; + moveEnd: () => void; + isActive: boolean; +} + +export interface OnMoveEndInfo { + data: ReadonlyArray | null; + to: number; + from: number; + row: ItemM; +} + +interface DraggableFlatListProps extends VirtualizedListWithoutRenderItemProps { + /** + * Items to be rendered. + */ + data: ReadonlyArray | null; + + /** + * Function that returns updated ordering of data + */ + onMoveEnd?: (info: OnMoveEndInfo) => void; + + /** + * Function that is called when row becomes active. + */ + onMoveBegin?: (index: number) => void; + + /** + * Sets where scrolling begins. + * + * Default is 5 + */ + scrollPercent?: number; + + /** + * Function that calls move when the row should become active (in an onPress, onLongPress, etc). Calls moveEnd when the gesture is complete (in onPressOut). + */ + renderItem: (info: RenderItemInfo) => React.ReactElement | null; +} + +declare class DraggableFlatList extends Component> { + constructor(props: DraggableFlatListProps); +} + +export default DraggableFlatList; diff --git a/types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx b/types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx new file mode 100644 index 0000000000..40d613e4ea --- /dev/null +++ b/types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx @@ -0,0 +1,44 @@ +import * as React from 'react'; +import { TouchableOpacity, Text } from 'react-native'; +import DraggableFlatList, { RenderItemInfo } from 'react-native-draggable-flatlist'; + +interface Item { + name: string; + mail: string; +} + +class Example extends React.Component { + state = { + data: [ + { name: 'Esteban', mail: 'foo@foo.com' }, + { name: 'Xavier', mail: 'foo2@foo.com' }, + ] + }; + + renderItem({ item, index, move, moveEnd, isActive }: RenderItemInfo) { + return ( + + {index} + {item.name} + {item.mail} + + ); + } + + render() { + const { data } = this.state; + return ( + `draggable-item-${index}`} + scrollPercent={10} + onMoveEnd={({ data }) => this.setState({ data })} + ListFooterComponent={{'Hello'}} + /> + ); + } +} diff --git a/types/react-native-draggable-flatlist/tsconfig.json b/types/react-native-draggable-flatlist/tsconfig.json new file mode 100644 index 0000000000..b3c009feac --- /dev/null +++ b/types/react-native-draggable-flatlist/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react-native" + }, + "files": [ + "index.d.ts", + "react-native-draggable-flatlist-tests.tsx" + ] +} diff --git a/types/react-native-draggable-flatlist/tslint.json b/types/react-native-draggable-flatlist/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-draggable-flatlist/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-safe-area/index.d.ts b/types/react-native-safe-area/index.d.ts new file mode 100644 index 0000000000..fd38aec0a5 --- /dev/null +++ b/types/react-native-safe-area/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for react-native-safe-area 0.5 +// Project: https://github.com/miyabi/react-native-safe-area#readme +// Definitions by: Pavlos Vinieratos +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +import { EmitterSubscription } from 'react-native'; + +// from `TypeDefinition.js` +export interface SafeAreaInsets { top: number; left: number; bottom: number; right: number; } + +// from `SafeArea.[ios|android].js` +declare namespace SafeArea { + function getSafeAreaInsetsForRootView(): Promise<{ safeAreaInsets: SafeAreaInsets }>; + function addEventListener(eventType: string, listener: (...args: any[]) => any, context?: any): EmitterSubscription; + function removeEventListener(eventType: string, listener: (...args: any[]) => any): void; +} +export default SafeArea; + +// from `withSafeArea.js` +export type Direction = + | 'top' + | 'bottom' + | 'left' + | 'right' + | 'topLeft' // DEPRECATED + | 'topAndLeft' + | 'topRight' // DEPRECATED + | 'topAndRight' + | 'bottomLeft' // DEPRECATED + | 'bottomAndLeft' + | 'bottomRight' // DEPRECATED + | 'bottomAndRight' + | 'vertical' + | 'horizontal' + | 'verticalAndLeft' + | 'verticalAndRight' + | 'horizontalAndTop' + | 'horizontalAndBottom' + | 'all'; + +export function withSafeArea( + WrappedComponent: React.ComponentType, + applyTo?: 'margin' | 'padding' | 'absolutePosition' | 'contentInset', + direction?: Direction, +): React.ComponentType; diff --git a/types/react-native-safe-area/react-native-safe-area-tests.ts b/types/react-native-safe-area/react-native-safe-area-tests.ts new file mode 100644 index 0000000000..0dc931d026 --- /dev/null +++ b/types/react-native-safe-area/react-native-safe-area-tests.ts @@ -0,0 +1,4 @@ +import { View } from 'react-native'; +import { withSafeArea } from 'react-native-safe-area'; + +const SafeAreaView = withSafeArea(View); diff --git a/types/react-native-safe-area/tsconfig.json b/types/react-native-safe-area/tsconfig.json new file mode 100644 index 0000000000..6a88cd1448 --- /dev/null +++ b/types/react-native-safe-area/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-native-safe-area-tests.ts" + ] +} diff --git a/types/react-native-safe-area/tslint.json b/types/react-native-safe-area/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-safe-area/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-scrollable-tab-view/index.d.ts b/types/react-native-scrollable-tab-view/index.d.ts index 9be23aa66c..d992012856 100644 --- a/types/react-native-scrollable-tab-view/index.d.ts +++ b/types/react-native-scrollable-tab-view/index.d.ts @@ -125,7 +125,7 @@ export default class ScrollableTabView extends React.Component = T & { - tabLabel: React.ReactType; + tabLabel: React.ReactChild; }; export interface DefaultTabBarProps { diff --git a/types/react-native-video/index.d.ts b/types/react-native-video/index.d.ts index 190d731394..63d0ff6c89 100644 --- a/types/react-native-video/index.d.ts +++ b/types/react-native-video/index.d.ts @@ -1,13 +1,11 @@ -// Type definitions for react-native-video 2.0 +// Type definitions for react-native-video 3.1 // Project: https://github.com/react-native-community/react-native-video // Definitions by: HuHuanming // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; -import { - ViewProps -} from 'react-native'; +import { ViewProps } from 'react-native'; export interface OnLoadData { canPlayFastForward: boolean; @@ -32,75 +30,92 @@ export interface LoadError { }; } +export const TextTrackType: { + SRT: 'application/x-subrip'; + TTML: 'application/ttml+xml'; + VTT: 'text/vtt'; +}; + export interface VideoProperties extends ViewProps { - /* Native only */ - src?: any; - seek?: number; - fullscreen?: boolean; - onVideoLoadStart?(): void; - onVideoLoad?(): void; - onVideoBuffer?(): void; - onVideoError?(): void; - onVideoProgress?(): void; - onVideoSeek?(): void; - onVideoEnd?(): void; - onTimedMetadata?(): void; - onVideoFullscreenPlayerWillPresent?(): void; - onVideoFullscreenPlayerDidPresent?(): void; - onVideoFullscreenPlayerWillDismiss?(): void; - onVideoFullscreenPlayerDidDismiss?(): void; + /* Native only */ + src?: any; + seek?: number; + fullscreen?: boolean; + onVideoLoadStart?(): void; + onVideoLoad?(): void; + onVideoBuffer?(): void; + onVideoError?(): void; + onVideoProgress?(): void; + onVideoSeek?(): void; + onVideoEnd?(): void; + onTimedMetadata?(): void; + onVideoFullscreenPlayerWillPresent?(): void; + onVideoFullscreenPlayerDidPresent?(): void; + onVideoFullscreenPlayerWillDismiss?(): void; + onVideoFullscreenPlayerDidDismiss?(): void; - /* Wrapper component */ - // Opaque type returned by require('./video.mp4') - source: { uri?: string } | number; - resizeMode?: string; - poster?: string; - repeat?: boolean; - paused?: boolean; - muted?: boolean; - volume?: number; - rate?: number; - playInBackground?: boolean; - playWhenInactive?: boolean; - ignoreSilentSwitch?: 'ignore' | 'obey'; - disableFocus?: boolean; - controls?: boolean; - currentTime?: number; - progressUpdateInterval?: number; - useTextureView?: boolean; - allowsExternalPlayback?: boolean; - onLoadStart?(): void; - onLoad?(data: OnLoadData): void; - onBuffer?(): void; - onError?(error: LoadError): void; - onProgress?(data: { - currentTime: number; - playableDuration: number; - seekableDuration: number; - }): void; - onSeek?(): void; - onEnd?(): void; - onFullscreenPlayerWillPresent?(): void; - onFullscreenPlayerDidPresent?(): void; - onFullscreenPlayerWillDismiss?(): void; - onFullscreenPlayerDidDismiss?(): void; - onReadyForDisplay?(): void; - onPlaybackStalled?(): void; - onPlaybackResume?(): void; - onPlaybackRateChange?(): void; - onAudioFocusChanged?(): void; - onAudioBecomingNoisy?(): void; + /* Wrapper component */ + // Opaque type returned by require('./video.mp4') + source: { uri?: string } | number; + resizeMode?: string; + poster?: string; + repeat?: boolean; + paused?: boolean; + muted?: boolean; + volume?: number; + rate?: number; + playInBackground?: boolean; + playWhenInactive?: boolean; + ignoreSilentSwitch?: 'ignore' | 'obey'; + disableFocus?: boolean; + controls?: boolean; + currentTime?: number; + progressUpdateInterval?: number; + useTextureView?: boolean; + allowsExternalPlayback?: boolean; - /* Required by react-native */ - scaleX?: number; - scaleY?: number; - translateX?: number; - translateY?: number; - rotation?: number; + onLoadStart?(): void; + onLoad?(data: OnLoadData): void; + onBuffer?(): void; + onError?(error: LoadError): void; + onProgress?(data: { + currentTime: number; + playableDuration: number; + seekableDuration: number; + }): void; + onSeek?(): void; + onEnd?(): void; + onFullscreenPlayerWillPresent?(): void; + onFullscreenPlayerDidPresent?(): void; + onFullscreenPlayerWillDismiss?(): void; + onFullscreenPlayerDidDismiss?(): void; + onReadyForDisplay?(): void; + onPlaybackStalled?(): void; + onPlaybackResume?(): void; + onPlaybackRateChange?(): void; + onAudioFocusChanged?(): void; + onAudioBecomingNoisy?(): void; + selectedTextTrack?: { + type: 'system' | 'disabled' | 'title' | 'language' | 'index'; + value?: string | number; + }; + textTracks?: Array<{ + title?: string; + language?: string; + type: 'application/x-subrip' | 'application/ttml+xml' | 'text/vtt'; + uri: string; + }>; + + /* Required by react-native */ + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; + rotation?: number; } export default class Video extends React.Component { - seek(time: number, tolerance?: number): void; - presentFullscreenPlayer(): void; - dismissFullscreenPlayer(): void; + seek(time: number, tolerance?: number): void; + presentFullscreenPlayer(): void; + dismissFullscreenPlayer(): void; } diff --git a/types/react-native/globals.d.ts b/types/react-native/globals.d.ts index f5dcb25382..39723fcde1 100644 --- a/types/react-native/globals.d.ts +++ b/types/react-native/globals.d.ts @@ -119,3 +119,92 @@ type HeadersInit_ = Headers | string[][] | { [key: string]: string }; type RequestCredentials_ = "omit" | "same-origin" | "include"; type RequestMode_ = "navigate" | "same-origin" | "no-cors" | "cors"; type ResponseType_ = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; + +// +// XMLHttpRequest +// + +interface XMLHttpRequestEventMap extends XMLHttpRequestEventTargetEventMap { + "readystatechange": Event; +} + +interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { +// msCaching: string; + onreadystatechange: ((this: XMLHttpRequest, ev: Event) => any) | null; + readonly readyState: number; + readonly response: any; + readonly responseText: string; + responseType: XMLHttpRequestResponseType; + readonly responseURL: string; + readonly responseXML: Document | null; + readonly status: number; + readonly statusText: string; + timeout: number; + readonly upload: XMLHttpRequestUpload; + withCredentials: boolean; + abort(): void; + getAllResponseHeaders(): string; + getResponseHeader(header: string): string | null; +// msCachingEnabled(): boolean; + open(method: string, url: string, async?: boolean, user?: string | null, password?: string | null): void; + overrideMimeType(mime: string): void; + send(data?: any): void; + setRequestHeader(header: string, value: string): void; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; + addEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any): void; +// addEventListener(type: string, listener: EventListenerOrEventListenerObject): void; + removeEventListener(type: K, listener: (this: XMLHttpRequest, ev: XMLHttpRequestEventMap[K]) => any): void; +// removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void; +} + +declare var XMLHttpRequest: { + prototype: XMLHttpRequest; + new(): XMLHttpRequest; + readonly DONE: number; + readonly HEADERS_RECEIVED: number; + readonly LOADING: number; + readonly OPENED: number; + readonly UNSENT: number; +}; + +interface XMLHttpRequestEventTargetEventMap { + "abort": Event; + "error": Event; + "load": Event; + "loadend": Event; + "loadstart": Event; + "progress": Event; + "timeout": Event; +} + +interface XMLHttpRequestEventTarget { + onabort: ((this: XMLHttpRequest, ev: Event) => any) | null; + onerror: ((this: XMLHttpRequest, ev: Event) => any) | null; + onload: ((this: XMLHttpRequest, ev: Event) => any) | null; + onloadend: ((this: XMLHttpRequest, ev: Event) => any) | null; + onloadstart: ((this: XMLHttpRequest, ev: Event) => any) | null; + onprogress: ((this: XMLHttpRequest, ev: Event) => any) | null; + ontimeout: ((this: XMLHttpRequest, ev: Event) => any) | null; + addEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any): void; +// addEventListener(type: string, listener: EventListenerOrEventListenerObject): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestEventTarget, ev: XMLHttpRequestEventTargetEventMap[K]) => any): void; +// removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void; +} + +interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget { + addEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any): void; +// addEventListener(type: string, listener: EventListenerOrEventListenerObject): void; + removeEventListener(type: K, listener: (this: XMLHttpRequestUpload, ev: XMLHttpRequestEventTargetEventMap[K]) => any): void; +// removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void; +} + +declare var XMLHttpRequestUpload: { + prototype: XMLHttpRequestUpload; + new(): XMLHttpRequestUpload; +}; + +type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text"; diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 2386fc71c2..ae3127bc1d 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -3629,6 +3629,18 @@ interface ImagePropsAndroid { * Duration of fade in animation. */ fadeDuration?: number; + + /** + * Required if loading images via 'uri' from drawable folder on Android. + * Explanation: https://medium.com/@adamjacobb/react-native-performance-images-adf5843e120 + */ + width?: number; + + /** + * Required if loading images via 'uri' from drawable folder on Android + * Explanation: https://medium.com/@adamjacobb/react-native-performance-images-adf5843e120 + */ + height?: number; } /** @@ -6325,6 +6337,12 @@ export interface ScrollViewProps */ horizontal?: boolean; + /** + * If sticky headers should stick at the bottom instead of the top of the + * ScrollView. This is usually used with inverted ScrollViews. + */ + invertStickyHeaders?: boolean; + /** * Determines whether the keyboard gets dismissed in response to a drag. * - 'none' (the default) drags do not dismiss the keyboard. @@ -8177,6 +8195,13 @@ export interface SwitchProps extends SwitchPropsIOS { * Default value is false. */ value?: boolean; + + /** + * On iOS, custom color for the background. + * Can be seen when the switch value is false or when the switch is disabled. + */ + ios_backgroundColor?: string; + style?: StyleProp; } @@ -9023,34 +9048,18 @@ export const Platform: PlatformStatic; export const PlatformIOS: PlatformIOSStatic; export const PixelRatio: PixelRatioStatic; -export interface ComponentInterface

    { - name?: string; - displayName?: string; - propTypes: PropTypes.ValidationMap

    ; -} - /** - * Used to create React components that directly wrap native component - * implementations. Config information is extracted from data exported from the - * UIManager module. You should also wrap the native component in a - * hand-written component with full propTypes definitions and other - * documentation - pass the hand-written component in as `componentInterface` to - * verify all the native props are documented via `propTypes`. + * Creates values that can be used like React components which represent native + * view managers. You should create JavaScript modules that wrap these values so + * that the results are memoized. Example: * - * If some native props shouldn't be exposed in the wrapper interface, you can - * pass null for `componentInterface` and call `verifyPropTypes` directly - * with `nativePropsToIgnore`; + * const View = requireNativeComponent('RCTView'); * - * Common types are lined up with the appropriate prop differs with - * `TypeToDifferMap`. Non-scalar types not in the map default to `deepDiffer`. + * The concrete return type of `requireNativeComponent` is a string, but the declared type is + * `any` because TypeScript assumes anonymous JSX intrinsics (`string` instead of `"div", for + * example) not to have any props. */ -export function requireNativeComponent( - viewName: string, - componentInterface?: ComponentInterface

    , - extraConfig?: { nativeOnly?: NP } -): React.ComponentClass< - Partial>> & { [K in keyof NP]?: any} ->; +export function requireNativeComponent(viewName: string): any; export function findNodeHandle( componentOrHandle: null | number | React.Component | React.ComponentClass diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 56d6b7035b..79c5a111ca 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -430,6 +430,7 @@ class ScrollerListComponentTest extends React.Component< ( diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index ada96b802f..8e743465c6 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -27,6 +27,8 @@ // Alec Hill // Lachlan Young // Jason Killian +// Jeroen Vervaeke +// Fellipe Chagas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -94,6 +96,9 @@ export interface NavigationState { */ index: number; routes: NavigationRoute[]; + isTransitioning: boolean; + key: string; + params: NavigationParams; } export interface DrawerNavigationState extends NavigationState { @@ -129,6 +134,14 @@ export interface NavigationLeafRoute { * e.g. `{ car_id: 123 }` in a route that displays a car. */ params?: Params; + /** + * Array containing the navigator's routes + */ + routes: NavigationRoute[]; + /** + * Flag that indicates the transition state of the route + */ + isTransitioning: boolean; } export type NavigationStateRoute< @@ -280,28 +293,28 @@ export interface NavigationInitAction extends NavigationInitActionPayload { } export interface NavigationReplaceActionPayload { - key?: string; - newKey?: string; - routeName: string; - params?: NavigationParams; - action?: NavigationNavigateAction; + key?: string; + newKey?: string; + routeName: string; + params?: NavigationParams; + action?: NavigationNavigateAction; } export interface NavigationReplaceAction { - type: 'Navigation/REPLACE'; - key: string; - routeName: string; - params?: NavigationParams; - action?: NavigationNavigateAction; + type: 'Navigation/REPLACE'; + key: string; + routeName: string; + params?: NavigationParams; + action?: NavigationNavigateAction; } export interface NavigationCompleteTransitionActionPayload { - key?: string; + key?: string; } export interface NavigationCompleteTransitionAction { - type: 'Navigation/COMPLETE_TRANSITION'; - key: string; + type: 'Navigation/COMPLETE_TRANSITION'; + key: string; } export interface NavigationResetActionPayload { @@ -343,33 +356,33 @@ export interface NavigationPopToTopAction } export interface NavigationPushActionPayload { - routeName: string; - params?: NavigationParams; - action?: NavigationNavigateAction; - key?: string; + routeName: string; + params?: NavigationParams; + action?: NavigationNavigateAction; + key?: string; } export interface NavigationPushAction { - type: 'Navigation/PUSH'; - routeName: string; - params?: NavigationParams; - action?: NavigationNavigateAction; - key?: string; + type: 'Navigation/PUSH'; + routeName: string; + params?: NavigationParams; + action?: NavigationNavigateAction; + key?: string; } export interface NavigationOpenDrawerAction { - key?: string; - type: 'Navigation/OPEN_DRAWER'; + key?: string; + type: 'Navigation/OPEN_DRAWER'; } export interface NavigationCloseDrawerAction { - key?: string; - type: 'Navigation/CLOSE_DRAWER'; + key?: string; + type: 'Navigation/CLOSE_DRAWER'; } export interface NavigationToggleDrawerAction { - key?: string; - type: 'Navigation/TOGGLE_DRAWER'; + key?: string; + type: 'Navigation/TOGGLE_DRAWER'; } export interface NavigationStackViewConfig { @@ -379,6 +392,7 @@ export interface NavigationStackViewConfig { headerTransitionPreset?: 'fade-in-place' | 'uikit'; headerLayoutPreset?: 'left' | 'center'; cardStyle?: StyleProp; + transparentCard?: boolean; transitionConfig?: ( transitionProps: NavigationTransitionProps, prevTransitionProps: NavigationTransitionProps, @@ -657,9 +671,12 @@ export interface NavigationScreenProp { pop: (n?: number, params?: { immediate?: boolean }) => boolean; popToTop: (params?: { immediate?: boolean }) => boolean; isFocused: () => boolean; + router?: NavigationRouter; + dangerouslyGetParent: () => NavigationScreenProp | undefined; } export interface NavigationNavigatorProps { + detached?: boolean; navigation?: NavigationProp; screenProps?: { [key: string]: any }; navigationOptions?: O; @@ -730,6 +747,9 @@ export interface NavigationTransitionSpec { easing?: (t: number) => number; // A timing function such as `Animated.timing`. timing?: (value: AnimatedValue, config: any) => any; + friction?: number; + tension?: number; + useNativeDriver?: boolean; } /** @@ -876,7 +896,37 @@ export function createSwitchNavigator( ): NavigationContainer; // DrawerItems -export const DrawerItems: React.ReactType; +export const DrawerItems: React.ComponentType; + +export interface DrawerItemsProps { + navigation: NavigationScreenProp; + items: NavigationRoute[]; + activeItemKey?: string; + activeTintColor?: string; + activeBackgroundColor?: string; + inactiveTintColor?: string; + inactiveBackgroundColor?: string; + getLabel: (scene: DrawerScene) => React.ReactNode | string; + renderIcon: (scene: DrawerScene) => React.ReactNode; + onItemPress: (info: DrawerItem) => void; + itemsContainerStyle?: StyleProp; + itemStyle?: StyleProp; + labelStyle?: StyleProp; + activeLabelStyle?: StyleProp; + inactiveLabelStyle?: StyleProp; + iconContainerStyle?: StyleProp; + drawerPosition: 'left' | 'right'; +} +export interface DrawerScene { + route: NavigationRoute; + focused: boolean; + index: number; + tintColor?: string; +} +export interface DrawerItem { + route: NavigationRoute; + focused: boolean; +} /** * Drawer Navigator @@ -885,7 +935,7 @@ export interface DrawerViewConfig { drawerBackgroundColor?: string; drawerWidth?: number; drawerPosition?: 'left' | 'right'; - contentComponent?: React.ReactType; + contentComponent?: React.ComponentType; contentOptions?: any; style?: StyleProp; } @@ -1068,41 +1118,41 @@ export namespace NavigationActions { * DrawerActions */ export namespace DrawerActions { - const OPEN_DRAWER: 'Navigation/OPEN_DRAWER'; - const CLOSE_DRAWER: 'Navigation/CLOSE_DRAWER'; - const TOGGLE_DRAWER: 'Navigation/TOGGLE_DRAWER'; + const OPEN_DRAWER: 'Navigation/OPEN_DRAWER'; + const CLOSE_DRAWER: 'Navigation/CLOSE_DRAWER'; + const TOGGLE_DRAWER: 'Navigation/TOGGLE_DRAWER'; - function openDrawer(): NavigationOpenDrawerAction; - function closeDrawer(): NavigationCloseDrawerAction; - function toggleDrawer(): NavigationToggleDrawerAction; + function openDrawer(): NavigationOpenDrawerAction; + function closeDrawer(): NavigationCloseDrawerAction; + function toggleDrawer(): NavigationToggleDrawerAction; } /** * StackActions */ export namespace StackActions { - const POP: 'Navigation/POP'; - const POP_TO_TOP: 'Navigation/POP_TO_TOP'; - const PUSH: 'Navigation/PUSH'; - const RESET: 'Navigation/RESET'; - const REPLACE: 'Navigation/REPLACE'; - const COMPLETE_TRANSITION: 'Navigation/COMPLETE_TRANSITION'; + const POP: 'Navigation/POP'; + const POP_TO_TOP: 'Navigation/POP_TO_TOP'; + const PUSH: 'Navigation/PUSH'; + const RESET: 'Navigation/RESET'; + const REPLACE: 'Navigation/REPLACE'; + const COMPLETE_TRANSITION: 'Navigation/COMPLETE_TRANSITION'; - function pop(options: NavigationPopActionPayload): NavigationPopAction; - function popToTop( - options: NavigationPopToTopActionPayload - ): NavigationPopToTopAction; + function pop(options: NavigationPopActionPayload): NavigationPopAction; + function popToTop( + options: NavigationPopToTopActionPayload + ): NavigationPopToTopAction; - function push(options: NavigationPushActionPayload): NavigationPushAction; - function reset(options: NavigationResetActionPayload): NavigationResetAction; + function push(options: NavigationPushActionPayload): NavigationPushAction; + function reset(options: NavigationResetActionPayload): NavigationResetAction; - function replace( - options: NavigationReplaceActionPayload - ): NavigationReplaceAction; + function replace( + options: NavigationReplaceActionPayload + ): NavigationReplaceAction; - function completeTransition( - payload: NavigationCompleteTransitionActionPayload - ): NavigationCompleteTransitionAction; + function completeTransition( + payload: NavigationCompleteTransitionActionPayload + ): NavigationCompleteTransitionAction; } /** @@ -1127,6 +1177,7 @@ export interface TransitionerProps { transitionProps: NavigationTransitionProps, prevTransitionProps?: NavigationTransitionProps ) => any; + descriptors?: { [key: string]: NavigationDescriptor }; style?: StyleProp; } @@ -1177,6 +1228,8 @@ export interface NavigationDescriptor { export type NavigationView = React.ComponentType<{ descriptors: { [key: string]: NavigationDescriptor }; + navigationConfig: O; + screenProps?: { [key: string]: any }; } & NavigationInjectedProps>; export function createNavigator( @@ -1251,17 +1304,17 @@ export interface NavigationInjectedProps

    { } // If the wrapped component is a class, we can get a ref to it -export function withNavigation>( - Component: T, -): React.ComponentType, keyof NavigationInjectedProps> & { onRef?: React.Ref> }>; +export function withNavigation

    >( + Component: T & React.ComponentClass

    , +): React.ComponentType & { onRef?: React.Ref> }>; -export function withNavigation>( - Component: T, -): React.ComponentType, keyof NavigationInjectedProps>>; +export function withNavigation

    ( + Component: React.ComponentType

    , +): React.ComponentType>; // For backwards compatibility export function withNavigation( - Component: React.ComponentType)>, + Component: React.ComponentType>, ): React.ComponentType>> }>; export interface NavigationFocusInjectedProps

    extends NavigationInjectedProps

    { @@ -1269,13 +1322,13 @@ export interface NavigationFocusInjectedProps

    extends Navi } // If the wrapped component is a class, we can get a ref to it -export function withNavigationFocus>( - Component: T, -): React.ComponentType, keyof NavigationFocusInjectedProps> & { onRef?: React.Ref> }>; +export function withNavigationFocus

    >( + Component: T & React.ComponentClass

    , +): React.ComponentType & { onRef?: React.Ref> }>; -export function withNavigationFocus>( - Component: T, -): React.ComponentType, keyof NavigationFocusInjectedProps>>; +export function withNavigationFocus

    ( + Component: React.ComponentType

    , +): React.ComponentType>; // For backwards compatibility export function withNavigationFocus( diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx index 116ae92c56..aaa69bc35b 100644 --- a/types/react-navigation/react-navigation-tests.tsx +++ b/types/react-navigation/react-navigation-tests.tsx @@ -8,6 +8,8 @@ import { import { createDrawerNavigator, createBottomTabNavigator, + DrawerItems, + DrawerItemsProps, DrawerNavigatorConfig, NavigationAction, NavigationActions, @@ -360,6 +362,17 @@ const BasicDrawerNavigator = createDrawerNavigator( stackNavigatorConfig, ); +const Drawer = (props: DrawerItemsProps) => ( + +); + +const DrawerNavigatorWithCustomDrawer = createDrawerNavigator( + routeConfigMap, + { + contentComponent: Drawer, + } +); + function renderBasicDrawerNavigator(): JSX.Element { return ( /> ); } - _render = (props: NavigationTransitionProps, prevProps: NavigationTransitionProps): React.ReactElement => { + _render = (props: NavigationTransitionProps, prevProps?: NavigationTransitionProps): React.ReactElement => { return ( ); } _configureTransition = ( _transitionProps: NavigationTransitionProps, - _prevTransitionProps: NavigationTransitionProps + _prevTransitionProps?: NavigationTransitionProps ) => { return {}; } diff --git a/types/react-navigation/tsconfig.json b/types/react-navigation/tsconfig.json index b0cf7029db..bc49bee237 100644 --- a/types/react-navigation/tsconfig.json +++ b/types/react-navigation/tsconfig.json @@ -7,7 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "jsx": "react", "typeRoots": [ diff --git a/types/react-paginate/index.d.ts b/types/react-paginate/index.d.ts index 83a03ac838..4b73f0cf14 100644 --- a/types/react-paginate/index.d.ts +++ b/types/react-paginate/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for react-paginate 5.2 +// Type definitions for react-paginate 6.0 // Project: https://github.com/AdeleD/react-paginate // Definitions by: Simon Hartcher // Wouter Hardeman // pegel03 // Simon Archer // Yasunori Ohoka +// Shingo Sato // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -29,22 +30,22 @@ interface ReactPaginateProps { /** * Label for the `previous` button. */ - previousLabel?: string | JSX.Element; + previousLabel?: React.ReactNode; /** * Label for the `next` button. */ - nextLabel?: string | JSX.Element; + nextLabel?: React.ReactNode; /** * Label for ellipsis. */ - breakLabel?: string | JSX.Element; + breakLabel?: string | React.ReactNode; /** * The classname on tag `li` of the ellipsis element. */ - breakClassName?: string | JSX.Element; + breakClassName?: string; /** * The method to call when a page is clicked. Exposes the current page object as an argument. @@ -86,6 +87,11 @@ interface ReactPaginateProps { */ activeClassName?: string; + /** + * The classname for the active link. + */ + activeLinkClassName?: string; + /** * The classname on tag `li` of the `previous` button. */ diff --git a/types/react-paginate/react-paginate-tests.tsx b/types/react-paginate/react-paginate-tests.tsx index a98e8702a4..90a8718c52 100644 --- a/types/react-paginate/react-paginate-tests.tsx +++ b/types/react-paginate/react-paginate-tests.tsx @@ -20,6 +20,7 @@ class Test extends React.Component { pageClassName={'page-li'} pageLinkClassName={'page-a'} activeClassName={'active'} + activeLinkClassName={'active'} previousClassName={'previous-li'} nextClassName={'next-li'} previousLinkClassName={'previous-a'} diff --git a/types/react-paginate/v5/index.d.ts b/types/react-paginate/v5/index.d.ts new file mode 100644 index 0000000000..83a03ac838 --- /dev/null +++ b/types/react-paginate/v5/index.d.ts @@ -0,0 +1,126 @@ +// Type definitions for react-paginate 5.2 +// Project: https://github.com/AdeleD/react-paginate +// Definitions by: Simon Hartcher +// Wouter Hardeman +// pegel03 +// Simon Archer +// Yasunori Ohoka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +interface ReactPaginateProps { + /** + * The total number of pages. + */ + pageCount: number; + + /** + * The range of pages displayed. + */ + pageRangeDisplayed: number; + + /** + * The number of pages to display for margins. + */ + marginPagesDisplayed: number; + + /** + * Label for the `previous` button. + */ + previousLabel?: string | JSX.Element; + + /** + * Label for the `next` button. + */ + nextLabel?: string | JSX.Element; + + /** + * Label for ellipsis. + */ + breakLabel?: string | JSX.Element; + + /** + * The classname on tag `li` of the ellipsis element. + */ + breakClassName?: string | JSX.Element; + + /** + * The method to call when a page is clicked. Exposes the current page object as an argument. + */ + onPageChange?(selectedItem: { selected: number }): void; + + /** + * The initial page selected. + */ + initialPage?: number; + + /** + * To override selected page with parent prop. + */ + forcePage?: number; + + /** + * Disable onPageChange callback with initial page. Default: false + */ + disableInitialCallback?: boolean; + + /** + * The classname of the pagination container. + */ + containerClassName?: string; + + /** + * The classname on tag `li` of each page element. + */ + pageClassName?: string; + + /** + * The classname on tag `a` of each page element. + */ + pageLinkClassName?: string; + + /** + * The classname for the active page. + */ + activeClassName?: string; + + /** + * The classname on tag `li` of the `previous` button. + */ + previousClassName?: string; + + /** + * The classname on tag `li` of the `next` button. + */ + nextClassName?: string; + + /** + * The classname on tag `a` of the `previous` button. + */ + previousLinkClassName?: string; + + /** + * The classname on tag `a` of the `next` button. + */ + nextLinkClassName?: string; + + /** + * The classname for disabled `previous` and `next` buttons. + */ + disabledClassName?: string; + + /** + * The method is called to generate the href attribute value on tag a of each page element. + */ + hrefBuilder?(pageIndex: number): void; + + /** + * Extra context to add to the aria-label HTML attribute. + */ + extraAriaContext?: string; +} + +declare const ReactPaginate: React.ComponentClass; +export default ReactPaginate; diff --git a/types/react-paginate/v5/react-paginate-tests.tsx b/types/react-paginate/v5/react-paginate-tests.tsx new file mode 100644 index 0000000000..a98e8702a4 --- /dev/null +++ b/types/react-paginate/v5/react-paginate-tests.tsx @@ -0,0 +1,33 @@ +import * as React from 'react'; +import ReactPaginate from 'react-paginate'; + +class Test extends React.Component { + render() { + return ( + null} + initialPage={2} + forcePage={3} + disableInitialCallback={false} + containerClassName={'container'} + pageClassName={'page-li'} + pageLinkClassName={'page-a'} + activeClassName={'active'} + previousClassName={'previous-li'} + nextClassName={'next-li'} + previousLinkClassName={'previous-a'} + nextLinkClassName={'next-a'} + disabledClassName={'disabled'} + hrefBuilder={(pageIndex: number) => null} + extraAriaContext={'aria'} + /> + ); + } +} diff --git a/types/react-paginate/v5/tsconfig.json b/types/react-paginate/v5/tsconfig.json new file mode 100644 index 0000000000..9ff370a729 --- /dev/null +++ b/types/react-paginate/v5/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "react-paginate": [ + "react-paginate/v5" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-paginate-tests.tsx" + ] + } diff --git a/types/react-paginate/v5/tslint.json b/types/react-paginate/v5/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-paginate/v5/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index 62e3d93a1d..e24e479be8 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for react-places-autocomplete 6.1 +// Type definitions for react-places-autocomplete 7.2 // Project: https://github.com/kenny-hibino/react-places-autocomplete/ // Definitions by: Guilherme Hübner // Andrew Makarov +// Nokky Goren // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 // @@ -15,13 +16,10 @@ export interface formattedSuggestionType { } export interface PropTypes { - inputProps: { - value: string; - onChange: (value: string) => void; + inputProps?: { type?: string; name?: string; placeholder?: string; - onBlur?: (event: React.FocusEvent) => void; disabled?: boolean; }; onError?: (status: string, clearSuggestion: () => void) => void; @@ -41,7 +39,7 @@ export interface PropTypes { autocompleteItem?: React.CSSProperties; autocompleteItemActive?: React.CSSProperties; }; - options?: { + searchOptions?: { bounds?: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral; componentRestrictions?: google.maps.GeocoderComponentRestrictions; location?: google.maps.LatLng | google.maps.LatLngLiteral; @@ -49,6 +47,9 @@ export interface PropTypes { radius?: number | string; types?: string[]; }; + value?: string; + onChange?: (value: string) => void; + onBlur?: (event: React.FocusEvent) => void; debounce?: number; highlightFirstSuggestion?: boolean; diff --git a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx index 41e6ff37b4..a7a7816d99 100644 --- a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx +++ b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx @@ -45,7 +45,7 @@ class Test extends React.Component { return (

    - + ); } diff --git a/types/react-qr-reader/index.d.ts b/types/react-qr-reader/index.d.ts index de426667c0..908960f25c 100644 --- a/types/react-qr-reader/index.d.ts +++ b/types/react-qr-reader/index.d.ts @@ -6,11 +6,7 @@ import * as React from "react"; -export as namespace QrReader; - -export default QrReader; - -export namespace QrReader { +declare namespace QrReader { interface props { onScan: (data: string | null) => void; onError: (err: any) => void; @@ -26,5 +22,8 @@ export namespace QrReader { } } -declare class QrReader extends React.Component { -} +export as namespace QrReader; + +declare class QrReader extends React.Component {} + +export = QrReader; diff --git a/types/react-qr-reader/react-qr-reader-tests.tsx b/types/react-qr-reader/react-qr-reader-tests.tsx index 20632f8029..0a6796bfd9 100644 --- a/types/react-qr-reader/react-qr-reader-tests.tsx +++ b/types/react-qr-reader/react-qr-reader-tests.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import QrReader from "react-qr-reader"; +import * as QrReader from "react-qr-reader"; export class Test extends React.Component { render() { diff --git a/types/react-redux-toastr/index.d.ts b/types/react-redux-toastr/index.d.ts index fc11da9c43..9a7a115725 100644 --- a/types/react-redux-toastr/index.d.ts +++ b/types/react-redux-toastr/index.d.ts @@ -4,7 +4,7 @@ // Artyom Stukans // Mika Kuitunen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { Component } from 'react'; import { Action, Reducer } from 'redux'; diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index 5cbde2e8db..bcbcced0bd 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-redux 6.0.4 +// Type definitions for react-redux 6.0 // Project: https://github.com/reduxjs/react-redux // Definitions by: Qubo , // Kenzie Togami , @@ -11,8 +11,9 @@ // Valentin Descamps // Johann Rakotoharisoa // Anatoli Papirovski +// Boris Sergeyev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 // Known Issue: // There is a known issue in TypeScript, which doesn't allow decorators to change the signature of the classes @@ -42,15 +43,14 @@ import { } from 'redux'; // Omit taken from https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html -type Omit = Pick>; +export type Omit = Pick>; export interface DispatchProp { dispatch: Dispatch; } -interface AdvancedComponentDecorator { - (component: ComponentType): ComponentClass; -} +export type AdvancedComponentDecorator = + (component: ComponentType) => ComponentClass; /** * A property P will be present if: @@ -64,12 +64,12 @@ interface AdvancedComponentDecorator { * - if property P is present in InjectedProps but does not extend the * DecorationTargetProps[P] definition, its definition will be that of InjectedProps[P] */ -type Matching = { - [P in keyof DecorationTargetProps]: P extends keyof InjectedProps - ? InjectedProps[P] extends DecorationTargetProps[P] - ? DecorationTargetProps[P] - : InjectedProps[P] - : DecorationTargetProps[P]; +export type Matching = { + [P in keyof DecorationTargetProps]: P extends keyof InjectedProps + ? InjectedProps[P] extends DecorationTargetProps[P] + ? DecorationTargetProps[P] + : InjectedProps[P] + : DecorationTargetProps[P]; }; /** @@ -82,7 +82,7 @@ type Matching = { * required by the decorated (right hand side) component. * But any property required by the decorated component must be satisfied by the injected property. */ -type Shared< +export type Shared< InjectedProps, DecorationTargetProps extends Shared > = { @@ -90,28 +90,46 @@ type Shared< }; // Infers prop type from component C -type GetProps = C extends ComponentType ? P : never; +export type GetProps = C extends ComponentType ? P : never; // Applies LibraryManagedAttributes (proper handling of defaultProps // and propTypes), as well as defines WrappedComponent. -type ConnectedComponentClass = ComponentClass> & { - WrappedComponent: C; -} +export type ConnectedComponentClass = ComponentClass> & { + WrappedComponent: C; +}; // Injects props and removes them from the prop requirements. // Will not pass through the injected props if they are passed in during // render. Also adds new prop requirements from TNeedsProps. -export interface InferableComponentEnhancerWithProps { - >>>( - component: C - ): ConnectedComponentClass, keyof Shared>> & TNeedsProps> -} +export type InferableComponentEnhancerWithProps = + >>>( + component: C + ) => ConnectedComponentClass, keyof Shared>> & TNeedsProps>; // Injects props and removes them from the prop requirements. // Will not pass through the injected props if they are passed in during // render. export type InferableComponentEnhancer = - InferableComponentEnhancerWithProps + InferableComponentEnhancerWithProps; + +export type InferThunkActionCreatorType any> = + TActionCreator extends (...args: infer TParams) => (...args: any[]) => infer TReturn + ? (...args: TParams) => TReturn + : TActionCreator; + +export type HandleThunkActionCreator = + TActionCreator extends (...args: any[]) => any + ? InferThunkActionCreatorType + : TActionCreator; + +// redux-thunk middleware returns thunk's return value from dispatch call +// https://github.com/reduxjs/redux-thunk#composition +export type ResolveThunks = + TDispatchProps extends { [key: string]: any } + ? { + [C in keyof TDispatchProps]: HandleThunkActionCreator + } + : TDispatchProps; /** * Connects a React component to a Redux store. @@ -133,6 +151,7 @@ export type InferableComponentEnhancer = * @param options */ export interface Connect { + // tslint:disable:no-unnecessary-generics (): InferableComponentEnhancer; ( @@ -141,14 +160,30 @@ export interface Connect { ( mapStateToProps: null | undefined, - mapDispatchToProps: MapDispatchToPropsParam + mapDispatchToProps: MapDispatchToPropsNonObject ): InferableComponentEnhancerWithProps; + ( + mapStateToProps: null | undefined, + mapDispatchToProps: TDispatchProps, + ): InferableComponentEnhancerWithProps< + ResolveThunks, + TOwnProps + >; + ( mapStateToProps: MapStateToPropsParam, - mapDispatchToProps: MapDispatchToPropsParam + mapDispatchToProps: MapDispatchToPropsNonObject ): InferableComponentEnhancerWithProps; + ( + mapStateToProps: MapStateToPropsParam, + mapDispatchToProps: TDispatchProps, + ): InferableComponentEnhancerWithProps< + TStateProps & ResolveThunks, + TOwnProps + >; + ( mapStateToProps: MapStateToPropsParam, mapDispatchToProps: null | undefined, @@ -171,6 +206,7 @@ export interface Connect { mapStateToProps: MapStateToPropsParam, mapDispatchToProps: MapDispatchToPropsParam, mergeProps: MergeProps, + options?: Options ): InferableComponentEnhancerWithProps; ( @@ -182,59 +218,70 @@ export interface Connect { ( mapStateToProps: null | undefined, - mapDispatchToProps: MapDispatchToPropsParam, + mapDispatchToProps: MapDispatchToPropsNonObject, mergeProps: null | undefined, options: Options<{}, TStateProps, TOwnProps> ): InferableComponentEnhancerWithProps; + ( + mapStateToProps: null | undefined, + mapDispatchToProps: TDispatchProps, + mergeProps: null | undefined, + options: Options<{}, TStateProps, TOwnProps> + ): InferableComponentEnhancerWithProps< + ResolveThunks, + TOwnProps + >; + ( mapStateToProps: MapStateToPropsParam, - mapDispatchToProps: MapDispatchToPropsParam, + mapDispatchToProps: MapDispatchToPropsNonObject, mergeProps: null | undefined, options: Options ): InferableComponentEnhancerWithProps; - ( + ( mapStateToProps: MapStateToPropsParam, - mapDispatchToProps: MapDispatchToPropsParam, - mergeProps: MergeProps, - options: Options - ): InferableComponentEnhancerWithProps; + mapDispatchToProps: TDispatchProps, + mergeProps: null | undefined, + options: Options + ): InferableComponentEnhancerWithProps< + TStateProps & ResolveThunks, + TOwnProps + >; + // tslint:enable:no-unnecessary-generics } /** * The connect function. See {@type Connect} for details. */ -export declare const connect: Connect; +export const connect: Connect; -interface MapStateToProps { - (state: State, ownProps: TOwnProps): TStateProps; -} +export type MapStateToProps = + (state: State, ownProps: TOwnProps) => TStateProps; -interface MapStateToPropsFactory { - (initialState: State, ownProps: TOwnProps): MapStateToProps; -} +export type MapStateToPropsFactory = + (initialState: State, ownProps: TOwnProps) => MapStateToProps; -type MapStateToPropsParam = MapStateToPropsFactory | MapStateToProps | null | undefined; +export type MapStateToPropsParam = MapStateToPropsFactory | MapStateToProps | null | undefined; -interface MapDispatchToPropsFunction { - (dispatch: Dispatch, ownProps: TOwnProps): TDispatchProps; -} +export type MapDispatchToPropsFunction = + (dispatch: Dispatch, ownProps: TOwnProps) => TDispatchProps; -type MapDispatchToProps = +export type MapDispatchToProps = MapDispatchToPropsFunction | TDispatchProps; -interface MapDispatchToPropsFactory { - (dispatch: Dispatch, ownProps: TOwnProps): MapDispatchToProps; -} +export type MapDispatchToPropsFactory = + (dispatch: Dispatch, ownProps: TOwnProps) => MapDispatchToPropsFunction; -type MapDispatchToPropsParam = MapDispatchToPropsFactory | MapDispatchToProps; +export type MapDispatchToPropsParam = MapDispatchToPropsFactory | MapDispatchToProps; -interface MergeProps { - (stateProps: TStateProps, dispatchProps: TDispatchProps, ownProps: TOwnProps): TMergedProps; -} +export type MapDispatchToPropsNonObject = MapDispatchToPropsFactory | MapDispatchToPropsFunction; -interface Options extends ConnectOptions { +export type MergeProps = + (stateProps: TStateProps, dispatchProps: TDispatchProps, ownProps: TOwnProps) => TMergedProps; + +export interface Options extends ConnectOptions { /** * If true, implements shouldComponentUpdate and shallowly compares the result of mergeProps, * preventing unnecessary updates, assuming that the component is a “pure” component @@ -275,11 +322,12 @@ interface OptionsselectorFactory in the factoryOptions argument. */ -export declare function connectAdvanced( +export function connectAdvanced( + // tslint:disable-next-line no-unnecessary-generics selectorFactory: SelectorFactory, connectOptions?: ConnectOptions & TFactoryOptions ): AdvancedComponentDecorator; @@ -292,13 +340,10 @@ export declare function connectAdvancedselector to return that * previous object when appropriate. */ -export interface SelectorFactory { - (dispatch: Dispatch, factoryOptions: TFactoryOptions): Selector -} +export type SelectorFactory = + (dispatch: Dispatch, factoryOptions: TFactoryOptions) => Selector; -export interface Selector { - (state: S, ownProps: TOwnProps): TProps -} +export type Selector = (state: S, ownProps: TOwnProps) => TProps; export interface ConnectOptions { /** @@ -308,13 +353,13 @@ export interface ConnectOptions { * @default name => 'ConnectAdvanced('+name+')' * @param componentName */ - getDisplayName?: (componentName: string) => string + getDisplayName?: (componentName: string) => string; /** * Shown in error messages. Usually overridden by wrapper functions. * * @default 'connectAdvanced' */ - methodName?: string + methodName?: string; /** * If defined, a property named this value will be added to the props passed to the wrapped component. Its value * will be the number of times the component has been rendered, which can be useful for tracking down unnecessary @@ -322,27 +367,27 @@ export interface ConnectOptions { * * @default undefined */ - renderCountProp?: string + renderCountProp?: string; /** * Controls whether the connector component subscribes to redux store state changes. If set to false, it will only * re-render on componentWillReceiveProps. * * @default true */ - shouldHandleStateChanges?: boolean + shouldHandleStateChanges?: boolean; /** * The key of props/context to get the store. You probably only need this if you are in the inadvisable position of * having multiple stores. * * @default 'store' */ - storeKey?: string + storeKey?: string; /** * If true, stores a ref to the wrapped component instance and makes it available via getWrappedInstance() method. * * @default false */ - withRef?: boolean + withRef?: boolean; } export interface ProviderProps { @@ -364,4 +409,4 @@ export class Provider extends Component {} + class TestComponent extends React.Component {} - const Test = connect()(TestComponent) + const Test = connect()(TestComponent); - const verify = + const verify = ; } -namespace MapState { - interface OwnProps { foo: string } - interface StateProps { bar: number } +function MapState() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapStateToProps = (_: any) => ({ bar: 1 - }) + }); const Test = connect( mapStateToProps - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapStateWithDispatchProp { - interface OwnProps { foo: string } - interface StateProps { bar: number, dispatch: Dispatch } +function MapStateWithDispatchProp() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; dispatch: Dispatch; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapStateToProps = (_: any) => ({ bar: 1 - }) + }); const Test = connect( mapStateToProps - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapStateFactory { - interface OwnProps { foo: string } - interface StateProps { bar: number } +function MapStateFactory() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapStateToProps = () => () => ({ bar: 1 - }) + }); const Test = connect( mapStateToProps - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapDispatch { - interface OwnProps { foo: string } - interface DispatchProps { onClick: () => void } +function MapDispatch() { + interface OwnProps { foo: string; } + interface DispatchProps { onClick: () => void; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapDispatchToProps = () => ({ onClick: () => {} - }) + }); const TestNull = connect( null, mapDispatchToProps, - )(TestComponent) + )(TestComponent); - const verifyNull = + const verifyNull = ; const TestUndefined = connect( undefined, mapDispatchToProps, - )(TestComponent) + )(TestComponent); - const verifyUndefined = + const verifyUndefined = ; } -namespace MapStateAndDispatchObject { - interface ClickPayload { count: number } +function MapDispatchWithThunkActionCreators() { + const simpleAction = (payload: boolean) => ({ + type: 'SIMPLE_ACTION', + payload, + }); + const thunkAction = (param1: number, param2: string) => ( + async (dispatch: Dispatch, { foo }: OwnProps) => { + return foo; + } + ); + interface OwnProps { + foo: string; + } + interface TestComponentProps extends OwnProps { + simpleAction: typeof simpleAction; + thunkAction(param1: number, param2: string): Promise; + } + class TestComponent extends React.Component {} + + const mapStateToProps = ({ foo }: { foo: string }) => ({ foo }); + const mapDispatchToProps = { simpleAction, thunkAction }; + + const Test1 = connect(null, mapDispatchToProps)(TestComponent); + const Test2 = connect(mapStateToProps, mapDispatchToProps)(TestComponent); + const Test3 = connect( + null, mapDispatchToProps, null, { storeKey: 'somekey' } + )(TestComponent); + const Test4 = connect( + mapStateToProps, mapDispatchToProps, null, { storeKey: 'somekey' } + )(TestComponent); + const verify =
    + ; + + ; + +
    ; +} + +function MapManualDispatchThatLooksLikeThunk() { + interface OwnProps { + foo: string; + } + interface TestComponentProps extends OwnProps { + remove: (item: string) => () => object; + } + class TestComponent extends React.Component { + render() { + return
    ; + } + } + + const mapStateToProps = ({ foo }: { foo: string }) => ({ foo }); + function mapDispatchToProps(dispatch: Dispatch) { + return { + remove(item: string) { + return () => dispatch({ type: 'REMOVE_ITEM', item }); + } + }; + } + + const Test1 = connect(null, mapDispatchToProps)(TestComponent); + const Test2 = connect(mapStateToProps, mapDispatchToProps)(TestComponent); + const Test3 = connect( + null, mapDispatchToProps, null, { storeKey: 'somekey' } + )(TestComponent); + const Test4 = connect( + mapStateToProps, mapDispatchToProps, null, { storeKey: 'somekey' } + )(TestComponent); + const verify =
    + ; + + ; + +
    ; +} + +function MapStateAndDispatchObject() { + interface ClickPayload { count: number; } const onClick: ActionCreator = () => ({ count: 1 }); const dispatchToProps = { onClick, }; - interface OwnProps { foo: string } - interface StateProps { bar: number } - interface DispatchProps { onClick: ActionCreator } + interface OwnProps { foo: string; } + interface StateProps { bar: number; } + interface DispatchProps { onClick: ActionCreator; } const mapStateToProps = (_: any, __: OwnProps): StateProps => ({ bar: 1 - }) + }); - class TestComponent extends Component {} + class TestComponent extends React.Component {} const Test = connect( mapStateToProps, dispatchToProps, - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapDispatchFactory { - interface OwnProps { foo: string } - interface DispatchProps { onClick: () => void } +function MapDispatchFactory() { + interface OwnProps { foo: string; } + interface DispatchProps { onClick: () => void; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapDispatchToPropsFactory = () => () => ({ onClick: () => {} - }) + }); const TestNull = connect( null, mapDispatchToPropsFactory, - )(TestComponent) + )(TestComponent); - const verifyNull = + const verifyNull = ; const TestUndefined = connect( undefined, mapDispatchToPropsFactory, - )(TestComponent) + )(TestComponent); - const verifyUndefined = + const verifyUndefined = ; } -namespace MapStateAndDispatch { - interface OwnProps { foo: string } - interface StateProps { bar: number } - interface DispatchProps { onClick: () => void } +function MapStateAndDispatch() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; } + interface DispatchProps { onClick: () => void; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapStateToProps = () => ({ bar: 1 - }) + }); const mapDispatchToProps = () => ({ onClick: () => {} - }) + }); const Test = connect( mapStateToProps, mapDispatchToProps, - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapStateFactoryAndDispatch { - interface OwnProps { foo: string } - interface StateProps { bar: number } - interface DispatchProps { onClick: () => void } +function MapStateFactoryAndDispatch() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; } + interface DispatchProps { onClick: () => void; } - const mapStateToPropsFactory = () => () =>({ + const mapStateToPropsFactory = () => () => ({ bar: 1 - }) + }); const mapDispatchToProps = () => ({ onClick: () => {} - }) + }); - class TestComponent extends Component {} + class TestComponent extends React.Component {} const Test = connect( mapStateToPropsFactory, mapDispatchToProps, - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapStateFactoryAndDispatchFactory { - interface OwnProps { foo: string } - interface StateProps { bar: number } - interface DispatchProps { onClick: () => void } +function MapStateFactoryAndDispatchFactory() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; } + interface DispatchProps { onClick: () => void; } - const mapStateToPropsFactory = () => () =>({ + const mapStateToPropsFactory = () => () => ({ bar: 1 - }) + }); const mapDispatchToPropsFactory = () => () => ({ onClick: () => {} - }) + }); - class TestComponent extends Component {} + class TestComponent extends React.Component {} const Test = connect( mapStateToPropsFactory, mapDispatchToPropsFactory, - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapStateAndDispatchAndMerge { - interface OwnProps { foo: string } - interface StateProps { bar: number } - interface DispatchProps { onClick: () => void } +function MapStateAndDispatchAndMerge() { + interface OwnProps { foo: string; } + interface StateProps { bar: number; } + interface DispatchProps { onClick: () => void; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapStateToProps = () => ({ bar: 1 - }) + }); const mapDispatchToProps = () => ({ onClick: () => {} - }) + }); const mergeProps = (stateProps: StateProps, dispatchProps: DispatchProps) => ( - Object.assign({}, stateProps, dispatchProps) - ) + { ...stateProps, ...dispatchProps } + ); const Test = connect( mapStateToProps, mapDispatchToProps, mergeProps, - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } -namespace MapStateAndOptions { +function MapStateAndOptions() { interface State { state: string; } - interface OwnProps { foo: string } - interface StateProps { bar: number } - interface DispatchProps { dispatch: Dispatch } + interface OwnProps { foo: string; } + interface StateProps { bar: number; } + interface DispatchProps { dispatch: Dispatch; } - class TestComponent extends Component {} + class TestComponent extends React.Component {} const mapStateToProps = (state: State) => ({ bar: 1 - }) + }); const areStatePropsEqual = (next: StateProps, current: StateProps) => true; @@ -268,17 +346,17 @@ namespace MapStateAndOptions { pure: true, areStatePropsEqual, } - )(TestComponent) + )(TestComponent); - const verify = + const verify = ; } interface CounterState { counter: number; } -declare var increment: Function; +declare var increment: () => { type: string }; -class Counter extends Component { +class Counter extends React.Component { render() { return (